contract_name
stringlengths
1
61
file_path
stringlengths
5
50.4k
contract_address
stringlengths
42
42
language
stringclasses
1 value
class_name
stringlengths
1
61
class_code
stringlengths
4
330k
class_documentation
stringlengths
0
29.1k
class_documentation_type
stringclasses
6 values
func_name
stringlengths
0
62
func_code
stringlengths
1
303k
func_documentation
stringlengths
2
14.9k
func_documentation_type
stringclasses
4 values
compiler_version
stringlengths
15
42
license_type
stringclasses
14 values
swarm_source
stringlengths
0
71
meta
dict
__index_level_0__
int64
0
60.4k
HooToken
HooToken.sol
0xaa52c04c7b18c2ebdba34627bde40c0bf241065c
Solidity
Ownable
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(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _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 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 onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } }
transferOwnership
function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); }
/** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */
NatSpecMultiLine
v0.5.17+commit.d19bba13
None
bzzr://5557e44db2bc84bd03fea4f1d2b0b06530c4cdb00ab9534e3b33839b7d78bfff
{ "func_code_index": [ 1603, 1717 ] }
2,600
HooToken
HooToken.sol
0xaa52c04c7b18c2ebdba34627bde40c0bf241065c
Solidity
Ownable
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(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _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 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 onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } }
_transferOwnership
function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; }
/** * @dev Transfers ownership of the contract to a new account (`newOwner`). */
NatSpecMultiLine
v0.5.17+commit.d19bba13
None
bzzr://5557e44db2bc84bd03fea4f1d2b0b06530c4cdb00ab9534e3b33839b7d78bfff
{ "func_code_index": [ 1818, 2052 ] }
2,601
HooToken
HooToken.sol
0xaa52c04c7b18c2ebdba34627bde40c0bf241065c
Solidity
Pausable
contract Pausable is PauserRole { event Paused(address account); event Unpaused(address account); bool private _paused; constructor () internal { _paused = false; } /** * @return True if the contract is paused, false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @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 a pauser to pause, triggers stopped state. */ function pause() public onlyPauser whenNotPaused { _paused = true; emit Paused(msg.sender); } /** * @dev Called by a pauser to unpause, returns to normal state. */ function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(msg.sender); } }
/** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */
NatSpecMultiLine
paused
function paused() public view returns (bool) { return _paused; }
/** * @return True if the contract is paused, false otherwise. */
NatSpecMultiLine
v0.5.17+commit.d19bba13
None
bzzr://5557e44db2bc84bd03fea4f1d2b0b06530c4cdb00ab9534e3b33839b7d78bfff
{ "func_code_index": [ 289, 372 ] }
2,602
HooToken
HooToken.sol
0xaa52c04c7b18c2ebdba34627bde40c0bf241065c
Solidity
Pausable
contract Pausable is PauserRole { event Paused(address account); event Unpaused(address account); bool private _paused; constructor () internal { _paused = false; } /** * @return True if the contract is paused, false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @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 a pauser to pause, triggers stopped state. */ function pause() public onlyPauser whenNotPaused { _paused = true; emit Paused(msg.sender); } /** * @dev Called by a pauser to unpause, returns to normal state. */ function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(msg.sender); } }
/** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */
NatSpecMultiLine
pause
function pause() public onlyPauser whenNotPaused { _paused = true; emit Paused(msg.sender); }
/** * @dev Called by a pauser to pause, triggers stopped state. */
NatSpecMultiLine
v0.5.17+commit.d19bba13
None
bzzr://5557e44db2bc84bd03fea4f1d2b0b06530c4cdb00ab9534e3b33839b7d78bfff
{ "func_code_index": [ 825, 946 ] }
2,603
HooToken
HooToken.sol
0xaa52c04c7b18c2ebdba34627bde40c0bf241065c
Solidity
Pausable
contract Pausable is PauserRole { event Paused(address account); event Unpaused(address account); bool private _paused; constructor () internal { _paused = false; } /** * @return True if the contract is paused, false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @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 a pauser to pause, triggers stopped state. */ function pause() public onlyPauser whenNotPaused { _paused = true; emit Paused(msg.sender); } /** * @dev Called by a pauser to unpause, returns to normal state. */ function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(msg.sender); } }
/** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */
NatSpecMultiLine
unpause
function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(msg.sender); }
/** * @dev Called by a pauser to unpause, returns to normal state. */
NatSpecMultiLine
v0.5.17+commit.d19bba13
None
bzzr://5557e44db2bc84bd03fea4f1d2b0b06530c4cdb00ab9534e3b33839b7d78bfff
{ "func_code_index": [ 1036, 1159 ] }
2,604
HooToken
HooToken.sol
0xaa52c04c7b18c2ebdba34627bde40c0bf241065c
Solidity
Lockable
contract Lockable is PauserRole{ mapping (address => bool) private lockers; event LockAccount(address account, bool islock); /** * @dev Check if the account is locked. * @param account specific account address. */ function isLock(address account) public view returns (bool) { return lockers[account]; } /** * @dev Lock or thaw account address * @param account specific account address. * @param islock true lock, false thaw. */ function lock(address account, bool islock) public onlyPauser { lockers[account] = islock; emit LockAccount(account, islock); } }
/** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */
NatSpecMultiLine
isLock
function isLock(address account) public view returns (bool) { return lockers[account]; }
/** * @dev Check if the account is locked. * @param account specific account address. */
NatSpecMultiLine
v0.5.17+commit.d19bba13
None
bzzr://5557e44db2bc84bd03fea4f1d2b0b06530c4cdb00ab9534e3b33839b7d78bfff
{ "func_code_index": [ 276, 383 ] }
2,605
HooToken
HooToken.sol
0xaa52c04c7b18c2ebdba34627bde40c0bf241065c
Solidity
Lockable
contract Lockable is PauserRole{ mapping (address => bool) private lockers; event LockAccount(address account, bool islock); /** * @dev Check if the account is locked. * @param account specific account address. */ function isLock(address account) public view returns (bool) { return lockers[account]; } /** * @dev Lock or thaw account address * @param account specific account address. * @param islock true lock, false thaw. */ function lock(address account, bool islock) public onlyPauser { lockers[account] = islock; emit LockAccount(account, islock); } }
/** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */
NatSpecMultiLine
lock
function lock(address account, bool islock) public onlyPauser { lockers[account] = islock; emit LockAccount(account, islock); }
/** * @dev Lock or thaw account address * @param account specific account address. * @param islock true lock, false thaw. */
NatSpecMultiLine
v0.5.17+commit.d19bba13
None
bzzr://5557e44db2bc84bd03fea4f1d2b0b06530c4cdb00ab9534e3b33839b7d78bfff
{ "func_code_index": [ 544, 700 ] }
2,606
HooToken
HooToken.sol
0xaa52c04c7b18c2ebdba34627bde40c0bf241065c
Solidity
HooToken
contract HooToken is ERC20, ERC20Detailed, ERC20Pausable, Ownable { // metadata string public constant tokenName = "HooToken"; string public constant tokenSymbol = "HOO"; uint8 public constant decimalUnits = 8; uint256 public constant initialSupply = 1000000000; // address private _owner; constructor(address _addr) ERC20Pausable() ERC20Detailed(tokenName, tokenSymbol, decimalUnits) ERC20() Ownable() public { require(initialSupply > 0); _mint(_addr, initialSupply * (10 ** uint256(decimals()))); } function mint(uint256 value) public whenNotPaused onlyOwner{ _mint(msg.sender, value * (10 ** uint256(decimals()))); } /** * @dev Burns a specific amount of tokens. * @param value The amount of token to be burned. */ function burn(uint256 value) public whenNotPaused { require(!isLock(msg.sender)); _burn(msg.sender, value); } /** * @dev Freeze a specific amount of tokens. * @param value The amount of token to be Freeze. */ function freeze(uint256 value) public whenNotPaused { require(!isLock(msg.sender)); _freeze(value); } /** * @dev unFreeze a specific amount of tokens. * @param value The amount of token to be unFreeze. */ function unfreeze(uint256 value) public whenNotPaused { require(!isLock(msg.sender)); _unfreeze(value); } }
burn
function burn(uint256 value) public whenNotPaused { require(!isLock(msg.sender)); _burn(msg.sender, value); }
/** * @dev Burns a specific amount of tokens. * @param value The amount of token to be burned. */
NatSpecMultiLine
v0.5.17+commit.d19bba13
None
bzzr://5557e44db2bc84bd03fea4f1d2b0b06530c4cdb00ab9534e3b33839b7d78bfff
{ "func_code_index": [ 839, 976 ] }
2,607
HooToken
HooToken.sol
0xaa52c04c7b18c2ebdba34627bde40c0bf241065c
Solidity
HooToken
contract HooToken is ERC20, ERC20Detailed, ERC20Pausable, Ownable { // metadata string public constant tokenName = "HooToken"; string public constant tokenSymbol = "HOO"; uint8 public constant decimalUnits = 8; uint256 public constant initialSupply = 1000000000; // address private _owner; constructor(address _addr) ERC20Pausable() ERC20Detailed(tokenName, tokenSymbol, decimalUnits) ERC20() Ownable() public { require(initialSupply > 0); _mint(_addr, initialSupply * (10 ** uint256(decimals()))); } function mint(uint256 value) public whenNotPaused onlyOwner{ _mint(msg.sender, value * (10 ** uint256(decimals()))); } /** * @dev Burns a specific amount of tokens. * @param value The amount of token to be burned. */ function burn(uint256 value) public whenNotPaused { require(!isLock(msg.sender)); _burn(msg.sender, value); } /** * @dev Freeze a specific amount of tokens. * @param value The amount of token to be Freeze. */ function freeze(uint256 value) public whenNotPaused { require(!isLock(msg.sender)); _freeze(value); } /** * @dev unFreeze a specific amount of tokens. * @param value The amount of token to be unFreeze. */ function unfreeze(uint256 value) public whenNotPaused { require(!isLock(msg.sender)); _unfreeze(value); } }
freeze
function freeze(uint256 value) public whenNotPaused { require(!isLock(msg.sender)); _freeze(value); }
/** * @dev Freeze a specific amount of tokens. * @param value The amount of token to be Freeze. */
NatSpecMultiLine
v0.5.17+commit.d19bba13
None
bzzr://5557e44db2bc84bd03fea4f1d2b0b06530c4cdb00ab9534e3b33839b7d78bfff
{ "func_code_index": [ 1105, 1234 ] }
2,608
HooToken
HooToken.sol
0xaa52c04c7b18c2ebdba34627bde40c0bf241065c
Solidity
HooToken
contract HooToken is ERC20, ERC20Detailed, ERC20Pausable, Ownable { // metadata string public constant tokenName = "HooToken"; string public constant tokenSymbol = "HOO"; uint8 public constant decimalUnits = 8; uint256 public constant initialSupply = 1000000000; // address private _owner; constructor(address _addr) ERC20Pausable() ERC20Detailed(tokenName, tokenSymbol, decimalUnits) ERC20() Ownable() public { require(initialSupply > 0); _mint(_addr, initialSupply * (10 ** uint256(decimals()))); } function mint(uint256 value) public whenNotPaused onlyOwner{ _mint(msg.sender, value * (10 ** uint256(decimals()))); } /** * @dev Burns a specific amount of tokens. * @param value The amount of token to be burned. */ function burn(uint256 value) public whenNotPaused { require(!isLock(msg.sender)); _burn(msg.sender, value); } /** * @dev Freeze a specific amount of tokens. * @param value The amount of token to be Freeze. */ function freeze(uint256 value) public whenNotPaused { require(!isLock(msg.sender)); _freeze(value); } /** * @dev unFreeze a specific amount of tokens. * @param value The amount of token to be unFreeze. */ function unfreeze(uint256 value) public whenNotPaused { require(!isLock(msg.sender)); _unfreeze(value); } }
unfreeze
function unfreeze(uint256 value) public whenNotPaused { require(!isLock(msg.sender)); _unfreeze(value); }
/** * @dev unFreeze a specific amount of tokens. * @param value The amount of token to be unFreeze. */
NatSpecMultiLine
v0.5.17+commit.d19bba13
None
bzzr://5557e44db2bc84bd03fea4f1d2b0b06530c4cdb00ab9534e3b33839b7d78bfff
{ "func_code_index": [ 1371, 1504 ] }
2,609
PAaveIntegration
contracts/peripheral/Aave/IAaveIncentivesController.sol
0x4094aec22f40f11c29941d144c3dc887b33f5504
Solidity
IAaveIncentivesController
interface IAaveIncentivesController { /** * @dev Claims reward for an user, on all the assets of the lending pool, accumulating the pending rewards * @param amount Amount of rewards to claim * @param to Address that will be receiving the rewards * @return Rewards claimed **/ function claimRewards( address[] calldata assets, uint256 amount, address to ) external returns (uint256); /** * @dev Returns the total of rewards of an user, already accrued + not yet accrued * @param user The address of the user * @return The rewards **/ function getRewardsBalance(address[] calldata assets, address user) external view returns (uint256); /** * @dev returns the unclaimed rewards of the user * @param user the address of the user * @return the unclaimed user rewards */ function getUserUnclaimedRewards(address user) external view returns (uint256); }
claimRewards
function claimRewards( address[] calldata assets, uint256 amount, address to ) external returns (uint256);
/** * @dev Claims reward for an user, on all the assets of the lending pool, accumulating the pending rewards * @param amount Amount of rewards to claim * @param to Address that will be receiving the rewards * @return Rewards claimed **/
NatSpecMultiLine
v0.8.6+commit.11564f7e
{ "func_code_index": [ 305, 443 ] }
2,610
PAaveIntegration
contracts/peripheral/Aave/IAaveIncentivesController.sol
0x4094aec22f40f11c29941d144c3dc887b33f5504
Solidity
IAaveIncentivesController
interface IAaveIncentivesController { /** * @dev Claims reward for an user, on all the assets of the lending pool, accumulating the pending rewards * @param amount Amount of rewards to claim * @param to Address that will be receiving the rewards * @return Rewards claimed **/ function claimRewards( address[] calldata assets, uint256 amount, address to ) external returns (uint256); /** * @dev Returns the total of rewards of an user, already accrued + not yet accrued * @param user The address of the user * @return The rewards **/ function getRewardsBalance(address[] calldata assets, address user) external view returns (uint256); /** * @dev returns the unclaimed rewards of the user * @param user the address of the user * @return the unclaimed user rewards */ function getUserUnclaimedRewards(address user) external view returns (uint256); }
getRewardsBalance
function getRewardsBalance(address[] calldata assets, address user) external view returns (uint256);
/** * @dev Returns the total of rewards of an user, already accrued + not yet accrued * @param user The address of the user * @return The rewards **/
NatSpecMultiLine
v0.8.6+commit.11564f7e
{ "func_code_index": [ 619, 747 ] }
2,611
PAaveIntegration
contracts/peripheral/Aave/IAaveIncentivesController.sol
0x4094aec22f40f11c29941d144c3dc887b33f5504
Solidity
IAaveIncentivesController
interface IAaveIncentivesController { /** * @dev Claims reward for an user, on all the assets of the lending pool, accumulating the pending rewards * @param amount Amount of rewards to claim * @param to Address that will be receiving the rewards * @return Rewards claimed **/ function claimRewards( address[] calldata assets, uint256 amount, address to ) external returns (uint256); /** * @dev Returns the total of rewards of an user, already accrued + not yet accrued * @param user The address of the user * @return The rewards **/ function getRewardsBalance(address[] calldata assets, address user) external view returns (uint256); /** * @dev returns the unclaimed rewards of the user * @param user the address of the user * @return the unclaimed user rewards */ function getUserUnclaimedRewards(address user) external view returns (uint256); }
getUserUnclaimedRewards
function getUserUnclaimedRewards(address user) external view returns (uint256);
/** * @dev returns the unclaimed rewards of the user * @param user the address of the user * @return the unclaimed user rewards */
NatSpecMultiLine
v0.8.6+commit.11564f7e
{ "func_code_index": [ 904, 987 ] }
2,612
Zunami
contracts/Zunami.sol
0x9b43e47bec96a9345cd26fdde7efa5f8c06e126c
Solidity
Zunami
contract Zunami is ERC20, Pausable, AccessControl { using SafeERC20 for IERC20Metadata; bytes32 public constant OPERATOR_ROLE = keccak256('OPERATOR_ROLE'); struct PendingWithdrawal { uint256 lpShares; uint256[3] minAmounts; } struct PoolInfo { IStrategy strategy; uint256 startTime; uint256 lpShares; } uint8 public constant POOL_ASSETS = 3; uint256 public constant FEE_DENOMINATOR = 1000; uint256 public constant MIN_LOCK_TIME = 1 days; uint256 public constant FUNDS_DENOMINATOR = 10_000; uint8 public constant ALL_WITHDRAWAL_TYPES_MASK = uint8(7); // Binary 111 = 2^0 + 2^1 + 2^2; PoolInfo[] internal _poolInfo; uint256 public defaultDepositPid; uint256 public defaultWithdrawPid; uint8 public availableWithdrawalTypes; address[POOL_ASSETS] public tokens; uint256[POOL_ASSETS] public decimalsMultipliers; mapping(address => uint256[POOL_ASSETS]) public pendingDeposits; mapping(address => PendingWithdrawal) public pendingWithdrawals; uint256 public totalDeposited = 0; uint256 public managementFee = 100; // 10% bool public launched = false; event CreatedPendingDeposit(address indexed depositor, uint256[POOL_ASSETS] amounts); event CreatedPendingWithdrawal( address indexed withdrawer, uint256[POOL_ASSETS] amounts, uint256 lpShares ); event Deposited(address indexed depositor, uint256[POOL_ASSETS] amounts, uint256 lpShares); event Withdrawn(address indexed withdrawer, IStrategy.WithdrawalType withdrawalType, uint256[POOL_ASSETS] tokenAmounts, uint256 lpShares, uint128 tokenIndex); event AddedPool(uint256 pid, address strategyAddr, uint256 startTime); event FailedDeposit(address indexed depositor, uint256[POOL_ASSETS] amounts, uint256 lpShares); event FailedWithdrawal(address indexed withdrawer, uint256[POOL_ASSETS] amounts, uint256 lpShares); event SetDefaultDepositPid(uint256 pid); event SetDefaultWithdrawPid(uint256 pid); event ClaimedAllManagementFee(uint256 feeValue); event AutoCompoundAll(); modifier startedPool() { require(_poolInfo.length != 0, 'Zunami: pool not existed!'); require( block.timestamp >= _poolInfo[defaultDepositPid].startTime, 'Zunami: default deposit pool not started yet!' ); require( block.timestamp >= _poolInfo[defaultWithdrawPid].startTime, 'Zunami: default withdraw pool not started yet!' ); _; } constructor(address[POOL_ASSETS] memory _tokens) ERC20('ZunamiLP', 'ZLP') { tokens = _tokens; _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(OPERATOR_ROLE, msg.sender); for (uint256 i; i < POOL_ASSETS; i++) { uint256 decimals = IERC20Metadata(tokens[i]).decimals(); if (decimals < 18) { decimalsMultipliers[i] = 10**(18 - decimals); } else { decimalsMultipliers[i] = 1; } } availableWithdrawalTypes = ALL_WITHDRAWAL_TYPES_MASK; } function poolInfo(uint256 pid) external view returns (PoolInfo memory) { return _poolInfo[pid]; } function pause() external onlyRole(DEFAULT_ADMIN_ROLE) { _pause(); } function unpause() external onlyRole(DEFAULT_ADMIN_ROLE) { _unpause(); } function setAvailableWithdrawalTypes(uint8 newAvailableWithdrawalTypes) external onlyRole(DEFAULT_ADMIN_ROLE) { require(newAvailableWithdrawalTypes <= ALL_WITHDRAWAL_TYPES_MASK, 'Zunami: wrong available withdrawal types'); availableWithdrawalTypes = newAvailableWithdrawalTypes; } /** * @dev update managementFee, this is a Zunami commission from protocol profit * @param newManagementFee - minAmount 0, maxAmount FEE_DENOMINATOR - 1 */ function setManagementFee(uint256 newManagementFee) external onlyRole(DEFAULT_ADMIN_ROLE) { require(newManagementFee < FEE_DENOMINATOR, 'Zunami: wrong fee'); managementFee = newManagementFee; } /** * @dev Returns managementFee for strategy's when contract sell rewards * @return Returns commission on the amount of profit in the transaction * @param amount - amount of profit for calculate managementFee */ function calcManagementFee(uint256 amount) external view returns (uint256) { return (amount * managementFee) / FEE_DENOMINATOR; } /** * @dev Claims managementFee from all active strategies */ function claimAllManagementFee() external { uint256 feeTotalValue; for (uint256 i = 0; i < _poolInfo.length; i++) { feeTotalValue += _poolInfo[i].strategy.claimManagementFees(); } emit ClaimedAllManagementFee(feeTotalValue); } function autoCompoundAll() external { for (uint256 i = 0; i < _poolInfo.length; i++) { _poolInfo[i].strategy.autoCompound(); } emit AutoCompoundAll(); } /** * @dev Returns total holdings for all pools (strategy's) * @return Returns sum holdings (USD) for all pools */ function totalHoldings() public view returns (uint256) { uint256 length = _poolInfo.length; uint256 totalHold = 0; for (uint256 pid = 0; pid < length; pid++) { totalHold += _poolInfo[pid].strategy.totalHoldings(); } return totalHold; } /** * @dev Returns price depends on the income of users * @return Returns currently price of ZLP (1e18 = 1$) */ function lpPrice() external view returns (uint256) { return (totalHoldings() * 1e18) / totalSupply(); } /** * @dev Returns number of pools * @return number of pools */ function poolCount() external view returns (uint256) { return _poolInfo.length; } /** * @dev in this func user sends funds to the contract and then waits for the completion * of the transaction for all users * @param amounts - array of deposit amounts by user */ function delegateDeposit(uint256[3] memory amounts) external whenNotPaused { for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] > 0) { IERC20Metadata(tokens[i]).safeTransferFrom(_msgSender(), address(this), amounts[i]); pendingDeposits[_msgSender()][i] += amounts[i]; } } emit CreatedPendingDeposit(_msgSender(), amounts); } /** * @dev in this func user sends pending withdraw to the contract and then waits * for the completion of the transaction for all users * @param lpAmount - amount of ZLP for withdraw * @param minAmounts - array of amounts stablecoins that user want minimum receive */ function delegateWithdrawal(uint256 lpAmount, uint256[3] memory minAmounts) external whenNotPaused { PendingWithdrawal memory withdrawal; address userAddr = _msgSender(); require(lpAmount > 0, 'Zunami: lpAmount must be higher 0'); withdrawal.lpShares = lpAmount; withdrawal.minAmounts = minAmounts; pendingWithdrawals[userAddr] = withdrawal; emit CreatedPendingWithdrawal(userAddr, minAmounts, lpAmount); } /** * @dev Zunami protocol owner complete all active pending deposits of users * @param userList - dev send array of users from pending to complete */ function completeDeposits(address[] memory userList) external onlyRole(OPERATOR_ROLE) startedPool { IStrategy strategy = _poolInfo[defaultDepositPid].strategy; uint256 currentTotalHoldings = totalHoldings(); uint256 newHoldings = 0; uint256[3] memory totalAmounts; uint256[] memory userCompleteHoldings = new uint256[](userList.length); for (uint256 i = 0; i < userList.length; i++) { newHoldings = 0; for (uint256 x = 0; x < totalAmounts.length; x++) { uint256 userTokenDeposit = pendingDeposits[userList[i]][x]; totalAmounts[x] += userTokenDeposit; newHoldings += userTokenDeposit * decimalsMultipliers[x]; } userCompleteHoldings[i] = newHoldings; } newHoldings = 0; for (uint256 y = 0; y < POOL_ASSETS; y++) { uint256 totalTokenAmount = totalAmounts[y]; if (totalTokenAmount > 0) { newHoldings += totalTokenAmount * decimalsMultipliers[y]; IERC20Metadata(tokens[y]).safeTransfer(address(strategy), totalTokenAmount); } } uint256 totalDepositedNow = strategy.deposit(totalAmounts); require(totalDepositedNow > 0, 'Zunami: too low deposit!'); uint256 lpShares = 0; uint256 addedHoldings = 0; uint256 userDeposited = 0; for (uint256 z = 0; z < userList.length; z++) { userDeposited = (totalDepositedNow * userCompleteHoldings[z]) / newHoldings; address userAddr = userList[z]; if (totalSupply() == 0) { lpShares = userDeposited; } else { lpShares = (totalSupply() * userDeposited) / (currentTotalHoldings + addedHoldings); } addedHoldings += userDeposited; _mint(userAddr, lpShares); _poolInfo[defaultDepositPid].lpShares += lpShares; emit Deposited(userAddr, pendingDeposits[userAddr], lpShares); // remove deposit from list delete pendingDeposits[userAddr]; } totalDeposited += addedHoldings; } /** * @dev Zunami protocol owner complete all active pending withdrawals of users * @param userList - array of users from pending withdraw to complete */ function completeWithdrawals(address[] memory userList) external onlyRole(OPERATOR_ROLE) startedPool { require(userList.length > 0, 'Zunami: there are no pending withdrawals requests'); IStrategy strategy = _poolInfo[defaultWithdrawPid].strategy; address user; PendingWithdrawal memory withdrawal; for (uint256 i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; if (balanceOf(user) >= withdrawal.lpShares) { if ( !( strategy.withdraw( user, withdrawal.lpShares * 1e18 / _poolInfo[defaultWithdrawPid].lpShares, withdrawal.minAmounts, IStrategy.WithdrawalType.Base, 0 ) ) ) { emit FailedWithdrawal(user, withdrawal.minAmounts, withdrawal.lpShares); delete pendingWithdrawals[user]; continue; } uint256 userDeposit = (totalDeposited * withdrawal.lpShares) / totalSupply(); _burn(user, withdrawal.lpShares); _poolInfo[defaultWithdrawPid].lpShares -= withdrawal.lpShares; totalDeposited -= userDeposit; emit Withdrawn(user, IStrategy.WithdrawalType.Base, withdrawal.minAmounts, withdrawal.lpShares, 0); } delete pendingWithdrawals[user]; } } function completeWithdrawalsOptimized(address[] memory userList) external onlyRole(OPERATOR_ROLE) startedPool { require(userList.length > 0, 'Zunami: there are no pending withdrawals requests'); IStrategy strategy = _poolInfo[defaultWithdrawPid].strategy; uint256 lpSharesTotal; uint256[POOL_ASSETS] memory minAmountsTotal; uint256 i; address user; PendingWithdrawal memory withdrawal; for (i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; if (balanceOf(user) < withdrawal.lpShares) { emit FailedWithdrawal(user, withdrawal.minAmounts, withdrawal.lpShares); delete pendingWithdrawals[user]; continue; } lpSharesTotal += withdrawal.lpShares; minAmountsTotal[0] += withdrawal.minAmounts[0]; minAmountsTotal[1] += withdrawal.minAmounts[1]; minAmountsTotal[2] += withdrawal.minAmounts[2]; emit Withdrawn(user, IStrategy.WithdrawalType.Base, withdrawal.minAmounts, withdrawal.lpShares, 0); } require( lpSharesTotal <= _poolInfo[defaultWithdrawPid].lpShares, "Zunami: Insufficient pool LP shares"); uint256[POOL_ASSETS] memory prevBalances; for (i = 0; i < 3; i++) { prevBalances[i] = IERC20Metadata(tokens[i]).balanceOf(address(this)); } if( !strategy.withdraw(address(this), lpSharesTotal * 1e18 / _poolInfo[defaultWithdrawPid].lpShares, minAmountsTotal, IStrategy.WithdrawalType.Base, 0) ) { //TODO: do we really need to remove delegated requests for (i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; emit FailedWithdrawal(user, withdrawal.minAmounts, withdrawal.lpShares); delete pendingWithdrawals[user]; } return; } uint256[POOL_ASSETS] memory diffBalances; for (i = 0; i < 3; i++) { diffBalances[i] = IERC20Metadata(tokens[i]).balanceOf(address(this)) - prevBalances[i]; } for (i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; uint256 userDeposit = (totalDeposited * withdrawal.lpShares) / totalSupply(); _burn(user, withdrawal.lpShares); _poolInfo[defaultWithdrawPid].lpShares -= withdrawal.lpShares; totalDeposited -= userDeposit; for (uint256 j = 0; j < 3; j++) { IERC20Metadata(tokens[j]).safeTransfer( user, (diffBalances[j] * withdrawal.lpShares) / lpSharesTotal ); } delete pendingWithdrawals[user]; } } /** * @dev deposit in one tx, without waiting complete by dev * @return Returns amount of lpShares minted for user * @param amounts - user send amounts of stablecoins to deposit */ function deposit(uint256[POOL_ASSETS] memory amounts) external whenNotPaused startedPool returns (uint256) { IStrategy strategy = _poolInfo[defaultDepositPid].strategy; uint256 holdings = totalHoldings(); for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] > 0) { IERC20Metadata(tokens[i]).safeTransferFrom( _msgSender(), address(strategy), amounts[i] ); } } uint256 newDeposited = strategy.deposit(amounts); require(newDeposited > 0, 'Zunami: too low deposit!'); uint256 lpShares = 0; if (totalSupply() == 0) { lpShares = newDeposited; } else { lpShares = (totalSupply() * newDeposited) / holdings; } _mint(_msgSender(), lpShares); _poolInfo[defaultDepositPid].lpShares += lpShares; totalDeposited += newDeposited; emit Deposited(_msgSender(), amounts, lpShares); return lpShares; } /** * @dev withdraw in one tx, without waiting complete by dev * @param lpShares - amount of ZLP for withdraw * @param tokenAmounts - array of amounts stablecoins that user want minimum receive */ function withdraw( uint256 lpShares, uint256[POOL_ASSETS] memory tokenAmounts, IStrategy.WithdrawalType withdrawalType, uint128 tokenIndex ) external whenNotPaused startedPool { require( checkBit(availableWithdrawalTypes, uint8(withdrawalType)), 'Zunami: withdrawal type not available' ); IStrategy strategy = _poolInfo[defaultWithdrawPid].strategy; address userAddr = _msgSender(); require(balanceOf(userAddr) >= lpShares, 'Zunami: not enough LP balance'); require( strategy.withdraw(userAddr, lpShares * 1e18 / _poolInfo[defaultWithdrawPid].lpShares, tokenAmounts, withdrawalType, tokenIndex), 'Zunami: user lps share should be at least required' ); uint256 userDeposit = (totalDeposited * lpShares) / totalSupply(); _burn(userAddr, lpShares); _poolInfo[defaultWithdrawPid].lpShares -= lpShares; totalDeposited -= userDeposit; emit Withdrawn(userAddr, withdrawalType, tokenAmounts, lpShares, tokenIndex); } /** * @dev add a new pool, deposits in the new pool are blocked for one day for safety * @param _strategyAddr - the new pool strategy address */ function addPool(address _strategyAddr) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_strategyAddr != address(0), 'Zunami: zero strategy addr'); uint256 startTime = block.timestamp + (launched ? MIN_LOCK_TIME : 0); _poolInfo.push( PoolInfo({ strategy: IStrategy(_strategyAddr), startTime: startTime, lpShares: 0 }) ); emit AddedPool(_poolInfo.length - 1, _strategyAddr, startTime); } /** * @dev set a default pool for deposit funds * @param _newPoolId - new pool id */ function setDefaultDepositPid(uint256 _newPoolId) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_newPoolId < _poolInfo.length, 'Zunami: incorrect default deposit pool id'); defaultDepositPid = _newPoolId; emit SetDefaultDepositPid(_newPoolId); } /** * @dev set a default pool for withdraw funds * @param _newPoolId - new pool id */ function setDefaultWithdrawPid(uint256 _newPoolId) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_newPoolId < _poolInfo.length, 'Zunami: incorrect default withdraw pool id'); defaultWithdrawPid = _newPoolId; emit SetDefaultWithdrawPid(_newPoolId); } function launch() external onlyRole(DEFAULT_ADMIN_ROLE) { launched = true; } /** * @dev dev can transfer funds from few strategy's to one strategy for better APY * @param _strategies - array of strategy's, from which funds are withdrawn * @param withdrawalsPercents - A percentage of the funds that should be transfered * @param _receiverStrategyId - number strategy, to which funds are deposited */ function moveFundsBatch( uint256[] memory _strategies, uint256[] memory withdrawalsPercents, uint256 _receiverStrategyId ) external onlyRole(DEFAULT_ADMIN_ROLE) { require( _strategies.length == withdrawalsPercents.length, 'Zunami: incorrect arguments for the moveFundsBatch' ); require(_receiverStrategyId < _poolInfo.length, 'Zunami: incorrect a reciver strategy ID'); uint256[POOL_ASSETS] memory tokenBalance; for (uint256 y = 0; y < POOL_ASSETS; y++) { tokenBalance[y] = IERC20Metadata(tokens[y]).balanceOf(address(this)); } uint256 pid; uint256 zunamiLp; for (uint256 i = 0; i < _strategies.length; i++) { pid = _strategies[i]; zunamiLp += _moveFunds(pid, withdrawalsPercents[i]); } uint256[POOL_ASSETS] memory tokensRemainder; for (uint256 y = 0; y < POOL_ASSETS; y++) { tokensRemainder[y] = IERC20Metadata(tokens[y]).balanceOf(address(this)) - tokenBalance[y]; if (tokensRemainder[y] > 0) { IERC20Metadata(tokens[y]).safeTransfer( address(_poolInfo[_receiverStrategyId].strategy), tokensRemainder[y] ); } } _poolInfo[_receiverStrategyId].lpShares += zunamiLp; require( _poolInfo[_receiverStrategyId].strategy.deposit(tokensRemainder) > 0, 'Zunami: Too low amount!' ); } function _moveFunds(uint256 pid, uint256 withdrawAmount) private returns (uint256) { uint256 currentLpAmount; if (withdrawAmount == FUNDS_DENOMINATOR) { _poolInfo[pid].strategy.withdrawAll(); currentLpAmount = _poolInfo[pid].lpShares; _poolInfo[pid].lpShares = 0; } else { currentLpAmount = (_poolInfo[pid].lpShares * withdrawAmount) / FUNDS_DENOMINATOR; uint256[POOL_ASSETS] memory minAmounts; _poolInfo[pid].strategy.withdraw( address(this), currentLpAmount * 1e18 / _poolInfo[pid].lpShares, minAmounts, IStrategy.WithdrawalType.Base, 0 ); _poolInfo[pid].lpShares = _poolInfo[pid].lpShares - currentLpAmount; } return currentLpAmount; } /** * @dev user remove his active pending deposit */ function pendingDepositRemove() external { for (uint256 i = 0; i < POOL_ASSETS; i++) { if (pendingDeposits[_msgSender()][i] > 0) { IERC20Metadata(tokens[i]).safeTransfer( _msgSender(), pendingDeposits[_msgSender()][i] ); } } delete pendingDeposits[_msgSender()]; } /** * @dev governance can withdraw all stuck funds in emergency case * @param _token - IERC20Metadata token that should be fully withdraw from Zunami */ function withdrawStuckToken(IERC20Metadata _token) external onlyRole(DEFAULT_ADMIN_ROLE) { uint256 tokenBalance = _token.balanceOf(address(this)); _token.safeTransfer(_msgSender(), tokenBalance); } /** * @dev governance can add new operator for complete pending deposits and withdrawals * @param _newOperator - address that governance add in list of operators */ function updateOperator(address _newOperator) external onlyRole(DEFAULT_ADMIN_ROLE) { _grantRole(OPERATOR_ROLE, _newOperator); } // Get bit value at position function checkBit(uint8 mask, uint8 bit) internal pure returns (bool) { return mask & (0x01 << bit) != 0; } }
/** * * @title Zunami Protocol * * @notice Contract for Convex&Curve protocols optimize. * Users can use this contract for optimize yield and gas. * * * @dev Zunami is main contract. * Contract does not store user funds. * All user funds goes to Convex&Curve pools. * */
NatSpecMultiLine
setManagementFee
function setManagementFee(uint256 newManagementFee) external onlyRole(DEFAULT_ADMIN_ROLE) { require(newManagementFee < FEE_DENOMINATOR, 'Zunami: wrong fee'); managementFee = newManagementFee; }
/** * @dev update managementFee, this is a Zunami commission from protocol profit * @param newManagementFee - minAmount 0, maxAmount FEE_DENOMINATOR - 1 */
NatSpecMultiLine
v0.8.12+commit.f00d7308
{ "func_code_index": [ 3914, 4131 ] }
2,613
Zunami
contracts/Zunami.sol
0x9b43e47bec96a9345cd26fdde7efa5f8c06e126c
Solidity
Zunami
contract Zunami is ERC20, Pausable, AccessControl { using SafeERC20 for IERC20Metadata; bytes32 public constant OPERATOR_ROLE = keccak256('OPERATOR_ROLE'); struct PendingWithdrawal { uint256 lpShares; uint256[3] minAmounts; } struct PoolInfo { IStrategy strategy; uint256 startTime; uint256 lpShares; } uint8 public constant POOL_ASSETS = 3; uint256 public constant FEE_DENOMINATOR = 1000; uint256 public constant MIN_LOCK_TIME = 1 days; uint256 public constant FUNDS_DENOMINATOR = 10_000; uint8 public constant ALL_WITHDRAWAL_TYPES_MASK = uint8(7); // Binary 111 = 2^0 + 2^1 + 2^2; PoolInfo[] internal _poolInfo; uint256 public defaultDepositPid; uint256 public defaultWithdrawPid; uint8 public availableWithdrawalTypes; address[POOL_ASSETS] public tokens; uint256[POOL_ASSETS] public decimalsMultipliers; mapping(address => uint256[POOL_ASSETS]) public pendingDeposits; mapping(address => PendingWithdrawal) public pendingWithdrawals; uint256 public totalDeposited = 0; uint256 public managementFee = 100; // 10% bool public launched = false; event CreatedPendingDeposit(address indexed depositor, uint256[POOL_ASSETS] amounts); event CreatedPendingWithdrawal( address indexed withdrawer, uint256[POOL_ASSETS] amounts, uint256 lpShares ); event Deposited(address indexed depositor, uint256[POOL_ASSETS] amounts, uint256 lpShares); event Withdrawn(address indexed withdrawer, IStrategy.WithdrawalType withdrawalType, uint256[POOL_ASSETS] tokenAmounts, uint256 lpShares, uint128 tokenIndex); event AddedPool(uint256 pid, address strategyAddr, uint256 startTime); event FailedDeposit(address indexed depositor, uint256[POOL_ASSETS] amounts, uint256 lpShares); event FailedWithdrawal(address indexed withdrawer, uint256[POOL_ASSETS] amounts, uint256 lpShares); event SetDefaultDepositPid(uint256 pid); event SetDefaultWithdrawPid(uint256 pid); event ClaimedAllManagementFee(uint256 feeValue); event AutoCompoundAll(); modifier startedPool() { require(_poolInfo.length != 0, 'Zunami: pool not existed!'); require( block.timestamp >= _poolInfo[defaultDepositPid].startTime, 'Zunami: default deposit pool not started yet!' ); require( block.timestamp >= _poolInfo[defaultWithdrawPid].startTime, 'Zunami: default withdraw pool not started yet!' ); _; } constructor(address[POOL_ASSETS] memory _tokens) ERC20('ZunamiLP', 'ZLP') { tokens = _tokens; _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(OPERATOR_ROLE, msg.sender); for (uint256 i; i < POOL_ASSETS; i++) { uint256 decimals = IERC20Metadata(tokens[i]).decimals(); if (decimals < 18) { decimalsMultipliers[i] = 10**(18 - decimals); } else { decimalsMultipliers[i] = 1; } } availableWithdrawalTypes = ALL_WITHDRAWAL_TYPES_MASK; } function poolInfo(uint256 pid) external view returns (PoolInfo memory) { return _poolInfo[pid]; } function pause() external onlyRole(DEFAULT_ADMIN_ROLE) { _pause(); } function unpause() external onlyRole(DEFAULT_ADMIN_ROLE) { _unpause(); } function setAvailableWithdrawalTypes(uint8 newAvailableWithdrawalTypes) external onlyRole(DEFAULT_ADMIN_ROLE) { require(newAvailableWithdrawalTypes <= ALL_WITHDRAWAL_TYPES_MASK, 'Zunami: wrong available withdrawal types'); availableWithdrawalTypes = newAvailableWithdrawalTypes; } /** * @dev update managementFee, this is a Zunami commission from protocol profit * @param newManagementFee - minAmount 0, maxAmount FEE_DENOMINATOR - 1 */ function setManagementFee(uint256 newManagementFee) external onlyRole(DEFAULT_ADMIN_ROLE) { require(newManagementFee < FEE_DENOMINATOR, 'Zunami: wrong fee'); managementFee = newManagementFee; } /** * @dev Returns managementFee for strategy's when contract sell rewards * @return Returns commission on the amount of profit in the transaction * @param amount - amount of profit for calculate managementFee */ function calcManagementFee(uint256 amount) external view returns (uint256) { return (amount * managementFee) / FEE_DENOMINATOR; } /** * @dev Claims managementFee from all active strategies */ function claimAllManagementFee() external { uint256 feeTotalValue; for (uint256 i = 0; i < _poolInfo.length; i++) { feeTotalValue += _poolInfo[i].strategy.claimManagementFees(); } emit ClaimedAllManagementFee(feeTotalValue); } function autoCompoundAll() external { for (uint256 i = 0; i < _poolInfo.length; i++) { _poolInfo[i].strategy.autoCompound(); } emit AutoCompoundAll(); } /** * @dev Returns total holdings for all pools (strategy's) * @return Returns sum holdings (USD) for all pools */ function totalHoldings() public view returns (uint256) { uint256 length = _poolInfo.length; uint256 totalHold = 0; for (uint256 pid = 0; pid < length; pid++) { totalHold += _poolInfo[pid].strategy.totalHoldings(); } return totalHold; } /** * @dev Returns price depends on the income of users * @return Returns currently price of ZLP (1e18 = 1$) */ function lpPrice() external view returns (uint256) { return (totalHoldings() * 1e18) / totalSupply(); } /** * @dev Returns number of pools * @return number of pools */ function poolCount() external view returns (uint256) { return _poolInfo.length; } /** * @dev in this func user sends funds to the contract and then waits for the completion * of the transaction for all users * @param amounts - array of deposit amounts by user */ function delegateDeposit(uint256[3] memory amounts) external whenNotPaused { for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] > 0) { IERC20Metadata(tokens[i]).safeTransferFrom(_msgSender(), address(this), amounts[i]); pendingDeposits[_msgSender()][i] += amounts[i]; } } emit CreatedPendingDeposit(_msgSender(), amounts); } /** * @dev in this func user sends pending withdraw to the contract and then waits * for the completion of the transaction for all users * @param lpAmount - amount of ZLP for withdraw * @param minAmounts - array of amounts stablecoins that user want minimum receive */ function delegateWithdrawal(uint256 lpAmount, uint256[3] memory minAmounts) external whenNotPaused { PendingWithdrawal memory withdrawal; address userAddr = _msgSender(); require(lpAmount > 0, 'Zunami: lpAmount must be higher 0'); withdrawal.lpShares = lpAmount; withdrawal.minAmounts = minAmounts; pendingWithdrawals[userAddr] = withdrawal; emit CreatedPendingWithdrawal(userAddr, minAmounts, lpAmount); } /** * @dev Zunami protocol owner complete all active pending deposits of users * @param userList - dev send array of users from pending to complete */ function completeDeposits(address[] memory userList) external onlyRole(OPERATOR_ROLE) startedPool { IStrategy strategy = _poolInfo[defaultDepositPid].strategy; uint256 currentTotalHoldings = totalHoldings(); uint256 newHoldings = 0; uint256[3] memory totalAmounts; uint256[] memory userCompleteHoldings = new uint256[](userList.length); for (uint256 i = 0; i < userList.length; i++) { newHoldings = 0; for (uint256 x = 0; x < totalAmounts.length; x++) { uint256 userTokenDeposit = pendingDeposits[userList[i]][x]; totalAmounts[x] += userTokenDeposit; newHoldings += userTokenDeposit * decimalsMultipliers[x]; } userCompleteHoldings[i] = newHoldings; } newHoldings = 0; for (uint256 y = 0; y < POOL_ASSETS; y++) { uint256 totalTokenAmount = totalAmounts[y]; if (totalTokenAmount > 0) { newHoldings += totalTokenAmount * decimalsMultipliers[y]; IERC20Metadata(tokens[y]).safeTransfer(address(strategy), totalTokenAmount); } } uint256 totalDepositedNow = strategy.deposit(totalAmounts); require(totalDepositedNow > 0, 'Zunami: too low deposit!'); uint256 lpShares = 0; uint256 addedHoldings = 0; uint256 userDeposited = 0; for (uint256 z = 0; z < userList.length; z++) { userDeposited = (totalDepositedNow * userCompleteHoldings[z]) / newHoldings; address userAddr = userList[z]; if (totalSupply() == 0) { lpShares = userDeposited; } else { lpShares = (totalSupply() * userDeposited) / (currentTotalHoldings + addedHoldings); } addedHoldings += userDeposited; _mint(userAddr, lpShares); _poolInfo[defaultDepositPid].lpShares += lpShares; emit Deposited(userAddr, pendingDeposits[userAddr], lpShares); // remove deposit from list delete pendingDeposits[userAddr]; } totalDeposited += addedHoldings; } /** * @dev Zunami protocol owner complete all active pending withdrawals of users * @param userList - array of users from pending withdraw to complete */ function completeWithdrawals(address[] memory userList) external onlyRole(OPERATOR_ROLE) startedPool { require(userList.length > 0, 'Zunami: there are no pending withdrawals requests'); IStrategy strategy = _poolInfo[defaultWithdrawPid].strategy; address user; PendingWithdrawal memory withdrawal; for (uint256 i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; if (balanceOf(user) >= withdrawal.lpShares) { if ( !( strategy.withdraw( user, withdrawal.lpShares * 1e18 / _poolInfo[defaultWithdrawPid].lpShares, withdrawal.minAmounts, IStrategy.WithdrawalType.Base, 0 ) ) ) { emit FailedWithdrawal(user, withdrawal.minAmounts, withdrawal.lpShares); delete pendingWithdrawals[user]; continue; } uint256 userDeposit = (totalDeposited * withdrawal.lpShares) / totalSupply(); _burn(user, withdrawal.lpShares); _poolInfo[defaultWithdrawPid].lpShares -= withdrawal.lpShares; totalDeposited -= userDeposit; emit Withdrawn(user, IStrategy.WithdrawalType.Base, withdrawal.minAmounts, withdrawal.lpShares, 0); } delete pendingWithdrawals[user]; } } function completeWithdrawalsOptimized(address[] memory userList) external onlyRole(OPERATOR_ROLE) startedPool { require(userList.length > 0, 'Zunami: there are no pending withdrawals requests'); IStrategy strategy = _poolInfo[defaultWithdrawPid].strategy; uint256 lpSharesTotal; uint256[POOL_ASSETS] memory minAmountsTotal; uint256 i; address user; PendingWithdrawal memory withdrawal; for (i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; if (balanceOf(user) < withdrawal.lpShares) { emit FailedWithdrawal(user, withdrawal.minAmounts, withdrawal.lpShares); delete pendingWithdrawals[user]; continue; } lpSharesTotal += withdrawal.lpShares; minAmountsTotal[0] += withdrawal.minAmounts[0]; minAmountsTotal[1] += withdrawal.minAmounts[1]; minAmountsTotal[2] += withdrawal.minAmounts[2]; emit Withdrawn(user, IStrategy.WithdrawalType.Base, withdrawal.minAmounts, withdrawal.lpShares, 0); } require( lpSharesTotal <= _poolInfo[defaultWithdrawPid].lpShares, "Zunami: Insufficient pool LP shares"); uint256[POOL_ASSETS] memory prevBalances; for (i = 0; i < 3; i++) { prevBalances[i] = IERC20Metadata(tokens[i]).balanceOf(address(this)); } if( !strategy.withdraw(address(this), lpSharesTotal * 1e18 / _poolInfo[defaultWithdrawPid].lpShares, minAmountsTotal, IStrategy.WithdrawalType.Base, 0) ) { //TODO: do we really need to remove delegated requests for (i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; emit FailedWithdrawal(user, withdrawal.minAmounts, withdrawal.lpShares); delete pendingWithdrawals[user]; } return; } uint256[POOL_ASSETS] memory diffBalances; for (i = 0; i < 3; i++) { diffBalances[i] = IERC20Metadata(tokens[i]).balanceOf(address(this)) - prevBalances[i]; } for (i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; uint256 userDeposit = (totalDeposited * withdrawal.lpShares) / totalSupply(); _burn(user, withdrawal.lpShares); _poolInfo[defaultWithdrawPid].lpShares -= withdrawal.lpShares; totalDeposited -= userDeposit; for (uint256 j = 0; j < 3; j++) { IERC20Metadata(tokens[j]).safeTransfer( user, (diffBalances[j] * withdrawal.lpShares) / lpSharesTotal ); } delete pendingWithdrawals[user]; } } /** * @dev deposit in one tx, without waiting complete by dev * @return Returns amount of lpShares minted for user * @param amounts - user send amounts of stablecoins to deposit */ function deposit(uint256[POOL_ASSETS] memory amounts) external whenNotPaused startedPool returns (uint256) { IStrategy strategy = _poolInfo[defaultDepositPid].strategy; uint256 holdings = totalHoldings(); for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] > 0) { IERC20Metadata(tokens[i]).safeTransferFrom( _msgSender(), address(strategy), amounts[i] ); } } uint256 newDeposited = strategy.deposit(amounts); require(newDeposited > 0, 'Zunami: too low deposit!'); uint256 lpShares = 0; if (totalSupply() == 0) { lpShares = newDeposited; } else { lpShares = (totalSupply() * newDeposited) / holdings; } _mint(_msgSender(), lpShares); _poolInfo[defaultDepositPid].lpShares += lpShares; totalDeposited += newDeposited; emit Deposited(_msgSender(), amounts, lpShares); return lpShares; } /** * @dev withdraw in one tx, without waiting complete by dev * @param lpShares - amount of ZLP for withdraw * @param tokenAmounts - array of amounts stablecoins that user want minimum receive */ function withdraw( uint256 lpShares, uint256[POOL_ASSETS] memory tokenAmounts, IStrategy.WithdrawalType withdrawalType, uint128 tokenIndex ) external whenNotPaused startedPool { require( checkBit(availableWithdrawalTypes, uint8(withdrawalType)), 'Zunami: withdrawal type not available' ); IStrategy strategy = _poolInfo[defaultWithdrawPid].strategy; address userAddr = _msgSender(); require(balanceOf(userAddr) >= lpShares, 'Zunami: not enough LP balance'); require( strategy.withdraw(userAddr, lpShares * 1e18 / _poolInfo[defaultWithdrawPid].lpShares, tokenAmounts, withdrawalType, tokenIndex), 'Zunami: user lps share should be at least required' ); uint256 userDeposit = (totalDeposited * lpShares) / totalSupply(); _burn(userAddr, lpShares); _poolInfo[defaultWithdrawPid].lpShares -= lpShares; totalDeposited -= userDeposit; emit Withdrawn(userAddr, withdrawalType, tokenAmounts, lpShares, tokenIndex); } /** * @dev add a new pool, deposits in the new pool are blocked for one day for safety * @param _strategyAddr - the new pool strategy address */ function addPool(address _strategyAddr) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_strategyAddr != address(0), 'Zunami: zero strategy addr'); uint256 startTime = block.timestamp + (launched ? MIN_LOCK_TIME : 0); _poolInfo.push( PoolInfo({ strategy: IStrategy(_strategyAddr), startTime: startTime, lpShares: 0 }) ); emit AddedPool(_poolInfo.length - 1, _strategyAddr, startTime); } /** * @dev set a default pool for deposit funds * @param _newPoolId - new pool id */ function setDefaultDepositPid(uint256 _newPoolId) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_newPoolId < _poolInfo.length, 'Zunami: incorrect default deposit pool id'); defaultDepositPid = _newPoolId; emit SetDefaultDepositPid(_newPoolId); } /** * @dev set a default pool for withdraw funds * @param _newPoolId - new pool id */ function setDefaultWithdrawPid(uint256 _newPoolId) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_newPoolId < _poolInfo.length, 'Zunami: incorrect default withdraw pool id'); defaultWithdrawPid = _newPoolId; emit SetDefaultWithdrawPid(_newPoolId); } function launch() external onlyRole(DEFAULT_ADMIN_ROLE) { launched = true; } /** * @dev dev can transfer funds from few strategy's to one strategy for better APY * @param _strategies - array of strategy's, from which funds are withdrawn * @param withdrawalsPercents - A percentage of the funds that should be transfered * @param _receiverStrategyId - number strategy, to which funds are deposited */ function moveFundsBatch( uint256[] memory _strategies, uint256[] memory withdrawalsPercents, uint256 _receiverStrategyId ) external onlyRole(DEFAULT_ADMIN_ROLE) { require( _strategies.length == withdrawalsPercents.length, 'Zunami: incorrect arguments for the moveFundsBatch' ); require(_receiverStrategyId < _poolInfo.length, 'Zunami: incorrect a reciver strategy ID'); uint256[POOL_ASSETS] memory tokenBalance; for (uint256 y = 0; y < POOL_ASSETS; y++) { tokenBalance[y] = IERC20Metadata(tokens[y]).balanceOf(address(this)); } uint256 pid; uint256 zunamiLp; for (uint256 i = 0; i < _strategies.length; i++) { pid = _strategies[i]; zunamiLp += _moveFunds(pid, withdrawalsPercents[i]); } uint256[POOL_ASSETS] memory tokensRemainder; for (uint256 y = 0; y < POOL_ASSETS; y++) { tokensRemainder[y] = IERC20Metadata(tokens[y]).balanceOf(address(this)) - tokenBalance[y]; if (tokensRemainder[y] > 0) { IERC20Metadata(tokens[y]).safeTransfer( address(_poolInfo[_receiverStrategyId].strategy), tokensRemainder[y] ); } } _poolInfo[_receiverStrategyId].lpShares += zunamiLp; require( _poolInfo[_receiverStrategyId].strategy.deposit(tokensRemainder) > 0, 'Zunami: Too low amount!' ); } function _moveFunds(uint256 pid, uint256 withdrawAmount) private returns (uint256) { uint256 currentLpAmount; if (withdrawAmount == FUNDS_DENOMINATOR) { _poolInfo[pid].strategy.withdrawAll(); currentLpAmount = _poolInfo[pid].lpShares; _poolInfo[pid].lpShares = 0; } else { currentLpAmount = (_poolInfo[pid].lpShares * withdrawAmount) / FUNDS_DENOMINATOR; uint256[POOL_ASSETS] memory minAmounts; _poolInfo[pid].strategy.withdraw( address(this), currentLpAmount * 1e18 / _poolInfo[pid].lpShares, minAmounts, IStrategy.WithdrawalType.Base, 0 ); _poolInfo[pid].lpShares = _poolInfo[pid].lpShares - currentLpAmount; } return currentLpAmount; } /** * @dev user remove his active pending deposit */ function pendingDepositRemove() external { for (uint256 i = 0; i < POOL_ASSETS; i++) { if (pendingDeposits[_msgSender()][i] > 0) { IERC20Metadata(tokens[i]).safeTransfer( _msgSender(), pendingDeposits[_msgSender()][i] ); } } delete pendingDeposits[_msgSender()]; } /** * @dev governance can withdraw all stuck funds in emergency case * @param _token - IERC20Metadata token that should be fully withdraw from Zunami */ function withdrawStuckToken(IERC20Metadata _token) external onlyRole(DEFAULT_ADMIN_ROLE) { uint256 tokenBalance = _token.balanceOf(address(this)); _token.safeTransfer(_msgSender(), tokenBalance); } /** * @dev governance can add new operator for complete pending deposits and withdrawals * @param _newOperator - address that governance add in list of operators */ function updateOperator(address _newOperator) external onlyRole(DEFAULT_ADMIN_ROLE) { _grantRole(OPERATOR_ROLE, _newOperator); } // Get bit value at position function checkBit(uint8 mask, uint8 bit) internal pure returns (bool) { return mask & (0x01 << bit) != 0; } }
/** * * @title Zunami Protocol * * @notice Contract for Convex&Curve protocols optimize. * Users can use this contract for optimize yield and gas. * * * @dev Zunami is main contract. * Contract does not store user funds. * All user funds goes to Convex&Curve pools. * */
NatSpecMultiLine
calcManagementFee
function calcManagementFee(uint256 amount) external view returns (uint256) { return (amount * managementFee) / FEE_DENOMINATOR; }
/** * @dev Returns managementFee for strategy's when contract sell rewards * @return Returns commission on the amount of profit in the transaction * @param amount - amount of profit for calculate managementFee */
NatSpecMultiLine
v0.8.12+commit.f00d7308
{ "func_code_index": [ 4370, 4515 ] }
2,614
Zunami
contracts/Zunami.sol
0x9b43e47bec96a9345cd26fdde7efa5f8c06e126c
Solidity
Zunami
contract Zunami is ERC20, Pausable, AccessControl { using SafeERC20 for IERC20Metadata; bytes32 public constant OPERATOR_ROLE = keccak256('OPERATOR_ROLE'); struct PendingWithdrawal { uint256 lpShares; uint256[3] minAmounts; } struct PoolInfo { IStrategy strategy; uint256 startTime; uint256 lpShares; } uint8 public constant POOL_ASSETS = 3; uint256 public constant FEE_DENOMINATOR = 1000; uint256 public constant MIN_LOCK_TIME = 1 days; uint256 public constant FUNDS_DENOMINATOR = 10_000; uint8 public constant ALL_WITHDRAWAL_TYPES_MASK = uint8(7); // Binary 111 = 2^0 + 2^1 + 2^2; PoolInfo[] internal _poolInfo; uint256 public defaultDepositPid; uint256 public defaultWithdrawPid; uint8 public availableWithdrawalTypes; address[POOL_ASSETS] public tokens; uint256[POOL_ASSETS] public decimalsMultipliers; mapping(address => uint256[POOL_ASSETS]) public pendingDeposits; mapping(address => PendingWithdrawal) public pendingWithdrawals; uint256 public totalDeposited = 0; uint256 public managementFee = 100; // 10% bool public launched = false; event CreatedPendingDeposit(address indexed depositor, uint256[POOL_ASSETS] amounts); event CreatedPendingWithdrawal( address indexed withdrawer, uint256[POOL_ASSETS] amounts, uint256 lpShares ); event Deposited(address indexed depositor, uint256[POOL_ASSETS] amounts, uint256 lpShares); event Withdrawn(address indexed withdrawer, IStrategy.WithdrawalType withdrawalType, uint256[POOL_ASSETS] tokenAmounts, uint256 lpShares, uint128 tokenIndex); event AddedPool(uint256 pid, address strategyAddr, uint256 startTime); event FailedDeposit(address indexed depositor, uint256[POOL_ASSETS] amounts, uint256 lpShares); event FailedWithdrawal(address indexed withdrawer, uint256[POOL_ASSETS] amounts, uint256 lpShares); event SetDefaultDepositPid(uint256 pid); event SetDefaultWithdrawPid(uint256 pid); event ClaimedAllManagementFee(uint256 feeValue); event AutoCompoundAll(); modifier startedPool() { require(_poolInfo.length != 0, 'Zunami: pool not existed!'); require( block.timestamp >= _poolInfo[defaultDepositPid].startTime, 'Zunami: default deposit pool not started yet!' ); require( block.timestamp >= _poolInfo[defaultWithdrawPid].startTime, 'Zunami: default withdraw pool not started yet!' ); _; } constructor(address[POOL_ASSETS] memory _tokens) ERC20('ZunamiLP', 'ZLP') { tokens = _tokens; _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(OPERATOR_ROLE, msg.sender); for (uint256 i; i < POOL_ASSETS; i++) { uint256 decimals = IERC20Metadata(tokens[i]).decimals(); if (decimals < 18) { decimalsMultipliers[i] = 10**(18 - decimals); } else { decimalsMultipliers[i] = 1; } } availableWithdrawalTypes = ALL_WITHDRAWAL_TYPES_MASK; } function poolInfo(uint256 pid) external view returns (PoolInfo memory) { return _poolInfo[pid]; } function pause() external onlyRole(DEFAULT_ADMIN_ROLE) { _pause(); } function unpause() external onlyRole(DEFAULT_ADMIN_ROLE) { _unpause(); } function setAvailableWithdrawalTypes(uint8 newAvailableWithdrawalTypes) external onlyRole(DEFAULT_ADMIN_ROLE) { require(newAvailableWithdrawalTypes <= ALL_WITHDRAWAL_TYPES_MASK, 'Zunami: wrong available withdrawal types'); availableWithdrawalTypes = newAvailableWithdrawalTypes; } /** * @dev update managementFee, this is a Zunami commission from protocol profit * @param newManagementFee - minAmount 0, maxAmount FEE_DENOMINATOR - 1 */ function setManagementFee(uint256 newManagementFee) external onlyRole(DEFAULT_ADMIN_ROLE) { require(newManagementFee < FEE_DENOMINATOR, 'Zunami: wrong fee'); managementFee = newManagementFee; } /** * @dev Returns managementFee for strategy's when contract sell rewards * @return Returns commission on the amount of profit in the transaction * @param amount - amount of profit for calculate managementFee */ function calcManagementFee(uint256 amount) external view returns (uint256) { return (amount * managementFee) / FEE_DENOMINATOR; } /** * @dev Claims managementFee from all active strategies */ function claimAllManagementFee() external { uint256 feeTotalValue; for (uint256 i = 0; i < _poolInfo.length; i++) { feeTotalValue += _poolInfo[i].strategy.claimManagementFees(); } emit ClaimedAllManagementFee(feeTotalValue); } function autoCompoundAll() external { for (uint256 i = 0; i < _poolInfo.length; i++) { _poolInfo[i].strategy.autoCompound(); } emit AutoCompoundAll(); } /** * @dev Returns total holdings for all pools (strategy's) * @return Returns sum holdings (USD) for all pools */ function totalHoldings() public view returns (uint256) { uint256 length = _poolInfo.length; uint256 totalHold = 0; for (uint256 pid = 0; pid < length; pid++) { totalHold += _poolInfo[pid].strategy.totalHoldings(); } return totalHold; } /** * @dev Returns price depends on the income of users * @return Returns currently price of ZLP (1e18 = 1$) */ function lpPrice() external view returns (uint256) { return (totalHoldings() * 1e18) / totalSupply(); } /** * @dev Returns number of pools * @return number of pools */ function poolCount() external view returns (uint256) { return _poolInfo.length; } /** * @dev in this func user sends funds to the contract and then waits for the completion * of the transaction for all users * @param amounts - array of deposit amounts by user */ function delegateDeposit(uint256[3] memory amounts) external whenNotPaused { for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] > 0) { IERC20Metadata(tokens[i]).safeTransferFrom(_msgSender(), address(this), amounts[i]); pendingDeposits[_msgSender()][i] += amounts[i]; } } emit CreatedPendingDeposit(_msgSender(), amounts); } /** * @dev in this func user sends pending withdraw to the contract and then waits * for the completion of the transaction for all users * @param lpAmount - amount of ZLP for withdraw * @param minAmounts - array of amounts stablecoins that user want minimum receive */ function delegateWithdrawal(uint256 lpAmount, uint256[3] memory minAmounts) external whenNotPaused { PendingWithdrawal memory withdrawal; address userAddr = _msgSender(); require(lpAmount > 0, 'Zunami: lpAmount must be higher 0'); withdrawal.lpShares = lpAmount; withdrawal.minAmounts = minAmounts; pendingWithdrawals[userAddr] = withdrawal; emit CreatedPendingWithdrawal(userAddr, minAmounts, lpAmount); } /** * @dev Zunami protocol owner complete all active pending deposits of users * @param userList - dev send array of users from pending to complete */ function completeDeposits(address[] memory userList) external onlyRole(OPERATOR_ROLE) startedPool { IStrategy strategy = _poolInfo[defaultDepositPid].strategy; uint256 currentTotalHoldings = totalHoldings(); uint256 newHoldings = 0; uint256[3] memory totalAmounts; uint256[] memory userCompleteHoldings = new uint256[](userList.length); for (uint256 i = 0; i < userList.length; i++) { newHoldings = 0; for (uint256 x = 0; x < totalAmounts.length; x++) { uint256 userTokenDeposit = pendingDeposits[userList[i]][x]; totalAmounts[x] += userTokenDeposit; newHoldings += userTokenDeposit * decimalsMultipliers[x]; } userCompleteHoldings[i] = newHoldings; } newHoldings = 0; for (uint256 y = 0; y < POOL_ASSETS; y++) { uint256 totalTokenAmount = totalAmounts[y]; if (totalTokenAmount > 0) { newHoldings += totalTokenAmount * decimalsMultipliers[y]; IERC20Metadata(tokens[y]).safeTransfer(address(strategy), totalTokenAmount); } } uint256 totalDepositedNow = strategy.deposit(totalAmounts); require(totalDepositedNow > 0, 'Zunami: too low deposit!'); uint256 lpShares = 0; uint256 addedHoldings = 0; uint256 userDeposited = 0; for (uint256 z = 0; z < userList.length; z++) { userDeposited = (totalDepositedNow * userCompleteHoldings[z]) / newHoldings; address userAddr = userList[z]; if (totalSupply() == 0) { lpShares = userDeposited; } else { lpShares = (totalSupply() * userDeposited) / (currentTotalHoldings + addedHoldings); } addedHoldings += userDeposited; _mint(userAddr, lpShares); _poolInfo[defaultDepositPid].lpShares += lpShares; emit Deposited(userAddr, pendingDeposits[userAddr], lpShares); // remove deposit from list delete pendingDeposits[userAddr]; } totalDeposited += addedHoldings; } /** * @dev Zunami protocol owner complete all active pending withdrawals of users * @param userList - array of users from pending withdraw to complete */ function completeWithdrawals(address[] memory userList) external onlyRole(OPERATOR_ROLE) startedPool { require(userList.length > 0, 'Zunami: there are no pending withdrawals requests'); IStrategy strategy = _poolInfo[defaultWithdrawPid].strategy; address user; PendingWithdrawal memory withdrawal; for (uint256 i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; if (balanceOf(user) >= withdrawal.lpShares) { if ( !( strategy.withdraw( user, withdrawal.lpShares * 1e18 / _poolInfo[defaultWithdrawPid].lpShares, withdrawal.minAmounts, IStrategy.WithdrawalType.Base, 0 ) ) ) { emit FailedWithdrawal(user, withdrawal.minAmounts, withdrawal.lpShares); delete pendingWithdrawals[user]; continue; } uint256 userDeposit = (totalDeposited * withdrawal.lpShares) / totalSupply(); _burn(user, withdrawal.lpShares); _poolInfo[defaultWithdrawPid].lpShares -= withdrawal.lpShares; totalDeposited -= userDeposit; emit Withdrawn(user, IStrategy.WithdrawalType.Base, withdrawal.minAmounts, withdrawal.lpShares, 0); } delete pendingWithdrawals[user]; } } function completeWithdrawalsOptimized(address[] memory userList) external onlyRole(OPERATOR_ROLE) startedPool { require(userList.length > 0, 'Zunami: there are no pending withdrawals requests'); IStrategy strategy = _poolInfo[defaultWithdrawPid].strategy; uint256 lpSharesTotal; uint256[POOL_ASSETS] memory minAmountsTotal; uint256 i; address user; PendingWithdrawal memory withdrawal; for (i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; if (balanceOf(user) < withdrawal.lpShares) { emit FailedWithdrawal(user, withdrawal.minAmounts, withdrawal.lpShares); delete pendingWithdrawals[user]; continue; } lpSharesTotal += withdrawal.lpShares; minAmountsTotal[0] += withdrawal.minAmounts[0]; minAmountsTotal[1] += withdrawal.minAmounts[1]; minAmountsTotal[2] += withdrawal.minAmounts[2]; emit Withdrawn(user, IStrategy.WithdrawalType.Base, withdrawal.minAmounts, withdrawal.lpShares, 0); } require( lpSharesTotal <= _poolInfo[defaultWithdrawPid].lpShares, "Zunami: Insufficient pool LP shares"); uint256[POOL_ASSETS] memory prevBalances; for (i = 0; i < 3; i++) { prevBalances[i] = IERC20Metadata(tokens[i]).balanceOf(address(this)); } if( !strategy.withdraw(address(this), lpSharesTotal * 1e18 / _poolInfo[defaultWithdrawPid].lpShares, minAmountsTotal, IStrategy.WithdrawalType.Base, 0) ) { //TODO: do we really need to remove delegated requests for (i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; emit FailedWithdrawal(user, withdrawal.minAmounts, withdrawal.lpShares); delete pendingWithdrawals[user]; } return; } uint256[POOL_ASSETS] memory diffBalances; for (i = 0; i < 3; i++) { diffBalances[i] = IERC20Metadata(tokens[i]).balanceOf(address(this)) - prevBalances[i]; } for (i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; uint256 userDeposit = (totalDeposited * withdrawal.lpShares) / totalSupply(); _burn(user, withdrawal.lpShares); _poolInfo[defaultWithdrawPid].lpShares -= withdrawal.lpShares; totalDeposited -= userDeposit; for (uint256 j = 0; j < 3; j++) { IERC20Metadata(tokens[j]).safeTransfer( user, (diffBalances[j] * withdrawal.lpShares) / lpSharesTotal ); } delete pendingWithdrawals[user]; } } /** * @dev deposit in one tx, without waiting complete by dev * @return Returns amount of lpShares minted for user * @param amounts - user send amounts of stablecoins to deposit */ function deposit(uint256[POOL_ASSETS] memory amounts) external whenNotPaused startedPool returns (uint256) { IStrategy strategy = _poolInfo[defaultDepositPid].strategy; uint256 holdings = totalHoldings(); for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] > 0) { IERC20Metadata(tokens[i]).safeTransferFrom( _msgSender(), address(strategy), amounts[i] ); } } uint256 newDeposited = strategy.deposit(amounts); require(newDeposited > 0, 'Zunami: too low deposit!'); uint256 lpShares = 0; if (totalSupply() == 0) { lpShares = newDeposited; } else { lpShares = (totalSupply() * newDeposited) / holdings; } _mint(_msgSender(), lpShares); _poolInfo[defaultDepositPid].lpShares += lpShares; totalDeposited += newDeposited; emit Deposited(_msgSender(), amounts, lpShares); return lpShares; } /** * @dev withdraw in one tx, without waiting complete by dev * @param lpShares - amount of ZLP for withdraw * @param tokenAmounts - array of amounts stablecoins that user want minimum receive */ function withdraw( uint256 lpShares, uint256[POOL_ASSETS] memory tokenAmounts, IStrategy.WithdrawalType withdrawalType, uint128 tokenIndex ) external whenNotPaused startedPool { require( checkBit(availableWithdrawalTypes, uint8(withdrawalType)), 'Zunami: withdrawal type not available' ); IStrategy strategy = _poolInfo[defaultWithdrawPid].strategy; address userAddr = _msgSender(); require(balanceOf(userAddr) >= lpShares, 'Zunami: not enough LP balance'); require( strategy.withdraw(userAddr, lpShares * 1e18 / _poolInfo[defaultWithdrawPid].lpShares, tokenAmounts, withdrawalType, tokenIndex), 'Zunami: user lps share should be at least required' ); uint256 userDeposit = (totalDeposited * lpShares) / totalSupply(); _burn(userAddr, lpShares); _poolInfo[defaultWithdrawPid].lpShares -= lpShares; totalDeposited -= userDeposit; emit Withdrawn(userAddr, withdrawalType, tokenAmounts, lpShares, tokenIndex); } /** * @dev add a new pool, deposits in the new pool are blocked for one day for safety * @param _strategyAddr - the new pool strategy address */ function addPool(address _strategyAddr) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_strategyAddr != address(0), 'Zunami: zero strategy addr'); uint256 startTime = block.timestamp + (launched ? MIN_LOCK_TIME : 0); _poolInfo.push( PoolInfo({ strategy: IStrategy(_strategyAddr), startTime: startTime, lpShares: 0 }) ); emit AddedPool(_poolInfo.length - 1, _strategyAddr, startTime); } /** * @dev set a default pool for deposit funds * @param _newPoolId - new pool id */ function setDefaultDepositPid(uint256 _newPoolId) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_newPoolId < _poolInfo.length, 'Zunami: incorrect default deposit pool id'); defaultDepositPid = _newPoolId; emit SetDefaultDepositPid(_newPoolId); } /** * @dev set a default pool for withdraw funds * @param _newPoolId - new pool id */ function setDefaultWithdrawPid(uint256 _newPoolId) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_newPoolId < _poolInfo.length, 'Zunami: incorrect default withdraw pool id'); defaultWithdrawPid = _newPoolId; emit SetDefaultWithdrawPid(_newPoolId); } function launch() external onlyRole(DEFAULT_ADMIN_ROLE) { launched = true; } /** * @dev dev can transfer funds from few strategy's to one strategy for better APY * @param _strategies - array of strategy's, from which funds are withdrawn * @param withdrawalsPercents - A percentage of the funds that should be transfered * @param _receiverStrategyId - number strategy, to which funds are deposited */ function moveFundsBatch( uint256[] memory _strategies, uint256[] memory withdrawalsPercents, uint256 _receiverStrategyId ) external onlyRole(DEFAULT_ADMIN_ROLE) { require( _strategies.length == withdrawalsPercents.length, 'Zunami: incorrect arguments for the moveFundsBatch' ); require(_receiverStrategyId < _poolInfo.length, 'Zunami: incorrect a reciver strategy ID'); uint256[POOL_ASSETS] memory tokenBalance; for (uint256 y = 0; y < POOL_ASSETS; y++) { tokenBalance[y] = IERC20Metadata(tokens[y]).balanceOf(address(this)); } uint256 pid; uint256 zunamiLp; for (uint256 i = 0; i < _strategies.length; i++) { pid = _strategies[i]; zunamiLp += _moveFunds(pid, withdrawalsPercents[i]); } uint256[POOL_ASSETS] memory tokensRemainder; for (uint256 y = 0; y < POOL_ASSETS; y++) { tokensRemainder[y] = IERC20Metadata(tokens[y]).balanceOf(address(this)) - tokenBalance[y]; if (tokensRemainder[y] > 0) { IERC20Metadata(tokens[y]).safeTransfer( address(_poolInfo[_receiverStrategyId].strategy), tokensRemainder[y] ); } } _poolInfo[_receiverStrategyId].lpShares += zunamiLp; require( _poolInfo[_receiverStrategyId].strategy.deposit(tokensRemainder) > 0, 'Zunami: Too low amount!' ); } function _moveFunds(uint256 pid, uint256 withdrawAmount) private returns (uint256) { uint256 currentLpAmount; if (withdrawAmount == FUNDS_DENOMINATOR) { _poolInfo[pid].strategy.withdrawAll(); currentLpAmount = _poolInfo[pid].lpShares; _poolInfo[pid].lpShares = 0; } else { currentLpAmount = (_poolInfo[pid].lpShares * withdrawAmount) / FUNDS_DENOMINATOR; uint256[POOL_ASSETS] memory minAmounts; _poolInfo[pid].strategy.withdraw( address(this), currentLpAmount * 1e18 / _poolInfo[pid].lpShares, minAmounts, IStrategy.WithdrawalType.Base, 0 ); _poolInfo[pid].lpShares = _poolInfo[pid].lpShares - currentLpAmount; } return currentLpAmount; } /** * @dev user remove his active pending deposit */ function pendingDepositRemove() external { for (uint256 i = 0; i < POOL_ASSETS; i++) { if (pendingDeposits[_msgSender()][i] > 0) { IERC20Metadata(tokens[i]).safeTransfer( _msgSender(), pendingDeposits[_msgSender()][i] ); } } delete pendingDeposits[_msgSender()]; } /** * @dev governance can withdraw all stuck funds in emergency case * @param _token - IERC20Metadata token that should be fully withdraw from Zunami */ function withdrawStuckToken(IERC20Metadata _token) external onlyRole(DEFAULT_ADMIN_ROLE) { uint256 tokenBalance = _token.balanceOf(address(this)); _token.safeTransfer(_msgSender(), tokenBalance); } /** * @dev governance can add new operator for complete pending deposits and withdrawals * @param _newOperator - address that governance add in list of operators */ function updateOperator(address _newOperator) external onlyRole(DEFAULT_ADMIN_ROLE) { _grantRole(OPERATOR_ROLE, _newOperator); } // Get bit value at position function checkBit(uint8 mask, uint8 bit) internal pure returns (bool) { return mask & (0x01 << bit) != 0; } }
/** * * @title Zunami Protocol * * @notice Contract for Convex&Curve protocols optimize. * Users can use this contract for optimize yield and gas. * * * @dev Zunami is main contract. * Contract does not store user funds. * All user funds goes to Convex&Curve pools. * */
NatSpecMultiLine
claimAllManagementFee
function claimAllManagementFee() external { uint256 feeTotalValue; for (uint256 i = 0; i < _poolInfo.length; i++) { feeTotalValue += _poolInfo[i].strategy.claimManagementFees(); } emit ClaimedAllManagementFee(feeTotalValue); }
/** * @dev Claims managementFee from all active strategies */
NatSpecMultiLine
v0.8.12+commit.f00d7308
{ "func_code_index": [ 4593, 4872 ] }
2,615
Zunami
contracts/Zunami.sol
0x9b43e47bec96a9345cd26fdde7efa5f8c06e126c
Solidity
Zunami
contract Zunami is ERC20, Pausable, AccessControl { using SafeERC20 for IERC20Metadata; bytes32 public constant OPERATOR_ROLE = keccak256('OPERATOR_ROLE'); struct PendingWithdrawal { uint256 lpShares; uint256[3] minAmounts; } struct PoolInfo { IStrategy strategy; uint256 startTime; uint256 lpShares; } uint8 public constant POOL_ASSETS = 3; uint256 public constant FEE_DENOMINATOR = 1000; uint256 public constant MIN_LOCK_TIME = 1 days; uint256 public constant FUNDS_DENOMINATOR = 10_000; uint8 public constant ALL_WITHDRAWAL_TYPES_MASK = uint8(7); // Binary 111 = 2^0 + 2^1 + 2^2; PoolInfo[] internal _poolInfo; uint256 public defaultDepositPid; uint256 public defaultWithdrawPid; uint8 public availableWithdrawalTypes; address[POOL_ASSETS] public tokens; uint256[POOL_ASSETS] public decimalsMultipliers; mapping(address => uint256[POOL_ASSETS]) public pendingDeposits; mapping(address => PendingWithdrawal) public pendingWithdrawals; uint256 public totalDeposited = 0; uint256 public managementFee = 100; // 10% bool public launched = false; event CreatedPendingDeposit(address indexed depositor, uint256[POOL_ASSETS] amounts); event CreatedPendingWithdrawal( address indexed withdrawer, uint256[POOL_ASSETS] amounts, uint256 lpShares ); event Deposited(address indexed depositor, uint256[POOL_ASSETS] amounts, uint256 lpShares); event Withdrawn(address indexed withdrawer, IStrategy.WithdrawalType withdrawalType, uint256[POOL_ASSETS] tokenAmounts, uint256 lpShares, uint128 tokenIndex); event AddedPool(uint256 pid, address strategyAddr, uint256 startTime); event FailedDeposit(address indexed depositor, uint256[POOL_ASSETS] amounts, uint256 lpShares); event FailedWithdrawal(address indexed withdrawer, uint256[POOL_ASSETS] amounts, uint256 lpShares); event SetDefaultDepositPid(uint256 pid); event SetDefaultWithdrawPid(uint256 pid); event ClaimedAllManagementFee(uint256 feeValue); event AutoCompoundAll(); modifier startedPool() { require(_poolInfo.length != 0, 'Zunami: pool not existed!'); require( block.timestamp >= _poolInfo[defaultDepositPid].startTime, 'Zunami: default deposit pool not started yet!' ); require( block.timestamp >= _poolInfo[defaultWithdrawPid].startTime, 'Zunami: default withdraw pool not started yet!' ); _; } constructor(address[POOL_ASSETS] memory _tokens) ERC20('ZunamiLP', 'ZLP') { tokens = _tokens; _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(OPERATOR_ROLE, msg.sender); for (uint256 i; i < POOL_ASSETS; i++) { uint256 decimals = IERC20Metadata(tokens[i]).decimals(); if (decimals < 18) { decimalsMultipliers[i] = 10**(18 - decimals); } else { decimalsMultipliers[i] = 1; } } availableWithdrawalTypes = ALL_WITHDRAWAL_TYPES_MASK; } function poolInfo(uint256 pid) external view returns (PoolInfo memory) { return _poolInfo[pid]; } function pause() external onlyRole(DEFAULT_ADMIN_ROLE) { _pause(); } function unpause() external onlyRole(DEFAULT_ADMIN_ROLE) { _unpause(); } function setAvailableWithdrawalTypes(uint8 newAvailableWithdrawalTypes) external onlyRole(DEFAULT_ADMIN_ROLE) { require(newAvailableWithdrawalTypes <= ALL_WITHDRAWAL_TYPES_MASK, 'Zunami: wrong available withdrawal types'); availableWithdrawalTypes = newAvailableWithdrawalTypes; } /** * @dev update managementFee, this is a Zunami commission from protocol profit * @param newManagementFee - minAmount 0, maxAmount FEE_DENOMINATOR - 1 */ function setManagementFee(uint256 newManagementFee) external onlyRole(DEFAULT_ADMIN_ROLE) { require(newManagementFee < FEE_DENOMINATOR, 'Zunami: wrong fee'); managementFee = newManagementFee; } /** * @dev Returns managementFee for strategy's when contract sell rewards * @return Returns commission on the amount of profit in the transaction * @param amount - amount of profit for calculate managementFee */ function calcManagementFee(uint256 amount) external view returns (uint256) { return (amount * managementFee) / FEE_DENOMINATOR; } /** * @dev Claims managementFee from all active strategies */ function claimAllManagementFee() external { uint256 feeTotalValue; for (uint256 i = 0; i < _poolInfo.length; i++) { feeTotalValue += _poolInfo[i].strategy.claimManagementFees(); } emit ClaimedAllManagementFee(feeTotalValue); } function autoCompoundAll() external { for (uint256 i = 0; i < _poolInfo.length; i++) { _poolInfo[i].strategy.autoCompound(); } emit AutoCompoundAll(); } /** * @dev Returns total holdings for all pools (strategy's) * @return Returns sum holdings (USD) for all pools */ function totalHoldings() public view returns (uint256) { uint256 length = _poolInfo.length; uint256 totalHold = 0; for (uint256 pid = 0; pid < length; pid++) { totalHold += _poolInfo[pid].strategy.totalHoldings(); } return totalHold; } /** * @dev Returns price depends on the income of users * @return Returns currently price of ZLP (1e18 = 1$) */ function lpPrice() external view returns (uint256) { return (totalHoldings() * 1e18) / totalSupply(); } /** * @dev Returns number of pools * @return number of pools */ function poolCount() external view returns (uint256) { return _poolInfo.length; } /** * @dev in this func user sends funds to the contract and then waits for the completion * of the transaction for all users * @param amounts - array of deposit amounts by user */ function delegateDeposit(uint256[3] memory amounts) external whenNotPaused { for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] > 0) { IERC20Metadata(tokens[i]).safeTransferFrom(_msgSender(), address(this), amounts[i]); pendingDeposits[_msgSender()][i] += amounts[i]; } } emit CreatedPendingDeposit(_msgSender(), amounts); } /** * @dev in this func user sends pending withdraw to the contract and then waits * for the completion of the transaction for all users * @param lpAmount - amount of ZLP for withdraw * @param minAmounts - array of amounts stablecoins that user want minimum receive */ function delegateWithdrawal(uint256 lpAmount, uint256[3] memory minAmounts) external whenNotPaused { PendingWithdrawal memory withdrawal; address userAddr = _msgSender(); require(lpAmount > 0, 'Zunami: lpAmount must be higher 0'); withdrawal.lpShares = lpAmount; withdrawal.minAmounts = minAmounts; pendingWithdrawals[userAddr] = withdrawal; emit CreatedPendingWithdrawal(userAddr, minAmounts, lpAmount); } /** * @dev Zunami protocol owner complete all active pending deposits of users * @param userList - dev send array of users from pending to complete */ function completeDeposits(address[] memory userList) external onlyRole(OPERATOR_ROLE) startedPool { IStrategy strategy = _poolInfo[defaultDepositPid].strategy; uint256 currentTotalHoldings = totalHoldings(); uint256 newHoldings = 0; uint256[3] memory totalAmounts; uint256[] memory userCompleteHoldings = new uint256[](userList.length); for (uint256 i = 0; i < userList.length; i++) { newHoldings = 0; for (uint256 x = 0; x < totalAmounts.length; x++) { uint256 userTokenDeposit = pendingDeposits[userList[i]][x]; totalAmounts[x] += userTokenDeposit; newHoldings += userTokenDeposit * decimalsMultipliers[x]; } userCompleteHoldings[i] = newHoldings; } newHoldings = 0; for (uint256 y = 0; y < POOL_ASSETS; y++) { uint256 totalTokenAmount = totalAmounts[y]; if (totalTokenAmount > 0) { newHoldings += totalTokenAmount * decimalsMultipliers[y]; IERC20Metadata(tokens[y]).safeTransfer(address(strategy), totalTokenAmount); } } uint256 totalDepositedNow = strategy.deposit(totalAmounts); require(totalDepositedNow > 0, 'Zunami: too low deposit!'); uint256 lpShares = 0; uint256 addedHoldings = 0; uint256 userDeposited = 0; for (uint256 z = 0; z < userList.length; z++) { userDeposited = (totalDepositedNow * userCompleteHoldings[z]) / newHoldings; address userAddr = userList[z]; if (totalSupply() == 0) { lpShares = userDeposited; } else { lpShares = (totalSupply() * userDeposited) / (currentTotalHoldings + addedHoldings); } addedHoldings += userDeposited; _mint(userAddr, lpShares); _poolInfo[defaultDepositPid].lpShares += lpShares; emit Deposited(userAddr, pendingDeposits[userAddr], lpShares); // remove deposit from list delete pendingDeposits[userAddr]; } totalDeposited += addedHoldings; } /** * @dev Zunami protocol owner complete all active pending withdrawals of users * @param userList - array of users from pending withdraw to complete */ function completeWithdrawals(address[] memory userList) external onlyRole(OPERATOR_ROLE) startedPool { require(userList.length > 0, 'Zunami: there are no pending withdrawals requests'); IStrategy strategy = _poolInfo[defaultWithdrawPid].strategy; address user; PendingWithdrawal memory withdrawal; for (uint256 i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; if (balanceOf(user) >= withdrawal.lpShares) { if ( !( strategy.withdraw( user, withdrawal.lpShares * 1e18 / _poolInfo[defaultWithdrawPid].lpShares, withdrawal.minAmounts, IStrategy.WithdrawalType.Base, 0 ) ) ) { emit FailedWithdrawal(user, withdrawal.minAmounts, withdrawal.lpShares); delete pendingWithdrawals[user]; continue; } uint256 userDeposit = (totalDeposited * withdrawal.lpShares) / totalSupply(); _burn(user, withdrawal.lpShares); _poolInfo[defaultWithdrawPid].lpShares -= withdrawal.lpShares; totalDeposited -= userDeposit; emit Withdrawn(user, IStrategy.WithdrawalType.Base, withdrawal.minAmounts, withdrawal.lpShares, 0); } delete pendingWithdrawals[user]; } } function completeWithdrawalsOptimized(address[] memory userList) external onlyRole(OPERATOR_ROLE) startedPool { require(userList.length > 0, 'Zunami: there are no pending withdrawals requests'); IStrategy strategy = _poolInfo[defaultWithdrawPid].strategy; uint256 lpSharesTotal; uint256[POOL_ASSETS] memory minAmountsTotal; uint256 i; address user; PendingWithdrawal memory withdrawal; for (i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; if (balanceOf(user) < withdrawal.lpShares) { emit FailedWithdrawal(user, withdrawal.minAmounts, withdrawal.lpShares); delete pendingWithdrawals[user]; continue; } lpSharesTotal += withdrawal.lpShares; minAmountsTotal[0] += withdrawal.minAmounts[0]; minAmountsTotal[1] += withdrawal.minAmounts[1]; minAmountsTotal[2] += withdrawal.minAmounts[2]; emit Withdrawn(user, IStrategy.WithdrawalType.Base, withdrawal.minAmounts, withdrawal.lpShares, 0); } require( lpSharesTotal <= _poolInfo[defaultWithdrawPid].lpShares, "Zunami: Insufficient pool LP shares"); uint256[POOL_ASSETS] memory prevBalances; for (i = 0; i < 3; i++) { prevBalances[i] = IERC20Metadata(tokens[i]).balanceOf(address(this)); } if( !strategy.withdraw(address(this), lpSharesTotal * 1e18 / _poolInfo[defaultWithdrawPid].lpShares, minAmountsTotal, IStrategy.WithdrawalType.Base, 0) ) { //TODO: do we really need to remove delegated requests for (i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; emit FailedWithdrawal(user, withdrawal.minAmounts, withdrawal.lpShares); delete pendingWithdrawals[user]; } return; } uint256[POOL_ASSETS] memory diffBalances; for (i = 0; i < 3; i++) { diffBalances[i] = IERC20Metadata(tokens[i]).balanceOf(address(this)) - prevBalances[i]; } for (i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; uint256 userDeposit = (totalDeposited * withdrawal.lpShares) / totalSupply(); _burn(user, withdrawal.lpShares); _poolInfo[defaultWithdrawPid].lpShares -= withdrawal.lpShares; totalDeposited -= userDeposit; for (uint256 j = 0; j < 3; j++) { IERC20Metadata(tokens[j]).safeTransfer( user, (diffBalances[j] * withdrawal.lpShares) / lpSharesTotal ); } delete pendingWithdrawals[user]; } } /** * @dev deposit in one tx, without waiting complete by dev * @return Returns amount of lpShares minted for user * @param amounts - user send amounts of stablecoins to deposit */ function deposit(uint256[POOL_ASSETS] memory amounts) external whenNotPaused startedPool returns (uint256) { IStrategy strategy = _poolInfo[defaultDepositPid].strategy; uint256 holdings = totalHoldings(); for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] > 0) { IERC20Metadata(tokens[i]).safeTransferFrom( _msgSender(), address(strategy), amounts[i] ); } } uint256 newDeposited = strategy.deposit(amounts); require(newDeposited > 0, 'Zunami: too low deposit!'); uint256 lpShares = 0; if (totalSupply() == 0) { lpShares = newDeposited; } else { lpShares = (totalSupply() * newDeposited) / holdings; } _mint(_msgSender(), lpShares); _poolInfo[defaultDepositPid].lpShares += lpShares; totalDeposited += newDeposited; emit Deposited(_msgSender(), amounts, lpShares); return lpShares; } /** * @dev withdraw in one tx, without waiting complete by dev * @param lpShares - amount of ZLP for withdraw * @param tokenAmounts - array of amounts stablecoins that user want minimum receive */ function withdraw( uint256 lpShares, uint256[POOL_ASSETS] memory tokenAmounts, IStrategy.WithdrawalType withdrawalType, uint128 tokenIndex ) external whenNotPaused startedPool { require( checkBit(availableWithdrawalTypes, uint8(withdrawalType)), 'Zunami: withdrawal type not available' ); IStrategy strategy = _poolInfo[defaultWithdrawPid].strategy; address userAddr = _msgSender(); require(balanceOf(userAddr) >= lpShares, 'Zunami: not enough LP balance'); require( strategy.withdraw(userAddr, lpShares * 1e18 / _poolInfo[defaultWithdrawPid].lpShares, tokenAmounts, withdrawalType, tokenIndex), 'Zunami: user lps share should be at least required' ); uint256 userDeposit = (totalDeposited * lpShares) / totalSupply(); _burn(userAddr, lpShares); _poolInfo[defaultWithdrawPid].lpShares -= lpShares; totalDeposited -= userDeposit; emit Withdrawn(userAddr, withdrawalType, tokenAmounts, lpShares, tokenIndex); } /** * @dev add a new pool, deposits in the new pool are blocked for one day for safety * @param _strategyAddr - the new pool strategy address */ function addPool(address _strategyAddr) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_strategyAddr != address(0), 'Zunami: zero strategy addr'); uint256 startTime = block.timestamp + (launched ? MIN_LOCK_TIME : 0); _poolInfo.push( PoolInfo({ strategy: IStrategy(_strategyAddr), startTime: startTime, lpShares: 0 }) ); emit AddedPool(_poolInfo.length - 1, _strategyAddr, startTime); } /** * @dev set a default pool for deposit funds * @param _newPoolId - new pool id */ function setDefaultDepositPid(uint256 _newPoolId) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_newPoolId < _poolInfo.length, 'Zunami: incorrect default deposit pool id'); defaultDepositPid = _newPoolId; emit SetDefaultDepositPid(_newPoolId); } /** * @dev set a default pool for withdraw funds * @param _newPoolId - new pool id */ function setDefaultWithdrawPid(uint256 _newPoolId) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_newPoolId < _poolInfo.length, 'Zunami: incorrect default withdraw pool id'); defaultWithdrawPid = _newPoolId; emit SetDefaultWithdrawPid(_newPoolId); } function launch() external onlyRole(DEFAULT_ADMIN_ROLE) { launched = true; } /** * @dev dev can transfer funds from few strategy's to one strategy for better APY * @param _strategies - array of strategy's, from which funds are withdrawn * @param withdrawalsPercents - A percentage of the funds that should be transfered * @param _receiverStrategyId - number strategy, to which funds are deposited */ function moveFundsBatch( uint256[] memory _strategies, uint256[] memory withdrawalsPercents, uint256 _receiverStrategyId ) external onlyRole(DEFAULT_ADMIN_ROLE) { require( _strategies.length == withdrawalsPercents.length, 'Zunami: incorrect arguments for the moveFundsBatch' ); require(_receiverStrategyId < _poolInfo.length, 'Zunami: incorrect a reciver strategy ID'); uint256[POOL_ASSETS] memory tokenBalance; for (uint256 y = 0; y < POOL_ASSETS; y++) { tokenBalance[y] = IERC20Metadata(tokens[y]).balanceOf(address(this)); } uint256 pid; uint256 zunamiLp; for (uint256 i = 0; i < _strategies.length; i++) { pid = _strategies[i]; zunamiLp += _moveFunds(pid, withdrawalsPercents[i]); } uint256[POOL_ASSETS] memory tokensRemainder; for (uint256 y = 0; y < POOL_ASSETS; y++) { tokensRemainder[y] = IERC20Metadata(tokens[y]).balanceOf(address(this)) - tokenBalance[y]; if (tokensRemainder[y] > 0) { IERC20Metadata(tokens[y]).safeTransfer( address(_poolInfo[_receiverStrategyId].strategy), tokensRemainder[y] ); } } _poolInfo[_receiverStrategyId].lpShares += zunamiLp; require( _poolInfo[_receiverStrategyId].strategy.deposit(tokensRemainder) > 0, 'Zunami: Too low amount!' ); } function _moveFunds(uint256 pid, uint256 withdrawAmount) private returns (uint256) { uint256 currentLpAmount; if (withdrawAmount == FUNDS_DENOMINATOR) { _poolInfo[pid].strategy.withdrawAll(); currentLpAmount = _poolInfo[pid].lpShares; _poolInfo[pid].lpShares = 0; } else { currentLpAmount = (_poolInfo[pid].lpShares * withdrawAmount) / FUNDS_DENOMINATOR; uint256[POOL_ASSETS] memory minAmounts; _poolInfo[pid].strategy.withdraw( address(this), currentLpAmount * 1e18 / _poolInfo[pid].lpShares, minAmounts, IStrategy.WithdrawalType.Base, 0 ); _poolInfo[pid].lpShares = _poolInfo[pid].lpShares - currentLpAmount; } return currentLpAmount; } /** * @dev user remove his active pending deposit */ function pendingDepositRemove() external { for (uint256 i = 0; i < POOL_ASSETS; i++) { if (pendingDeposits[_msgSender()][i] > 0) { IERC20Metadata(tokens[i]).safeTransfer( _msgSender(), pendingDeposits[_msgSender()][i] ); } } delete pendingDeposits[_msgSender()]; } /** * @dev governance can withdraw all stuck funds in emergency case * @param _token - IERC20Metadata token that should be fully withdraw from Zunami */ function withdrawStuckToken(IERC20Metadata _token) external onlyRole(DEFAULT_ADMIN_ROLE) { uint256 tokenBalance = _token.balanceOf(address(this)); _token.safeTransfer(_msgSender(), tokenBalance); } /** * @dev governance can add new operator for complete pending deposits and withdrawals * @param _newOperator - address that governance add in list of operators */ function updateOperator(address _newOperator) external onlyRole(DEFAULT_ADMIN_ROLE) { _grantRole(OPERATOR_ROLE, _newOperator); } // Get bit value at position function checkBit(uint8 mask, uint8 bit) internal pure returns (bool) { return mask & (0x01 << bit) != 0; } }
/** * * @title Zunami Protocol * * @notice Contract for Convex&Curve protocols optimize. * Users can use this contract for optimize yield and gas. * * * @dev Zunami is main contract. * Contract does not store user funds. * All user funds goes to Convex&Curve pools. * */
NatSpecMultiLine
totalHoldings
function totalHoldings() public view returns (uint256) { uint256 length = _poolInfo.length; uint256 totalHold = 0; for (uint256 pid = 0; pid < length; pid++) { totalHold += _poolInfo[pid].strategy.totalHoldings(); } return totalHold; }
/** * @dev Returns total holdings for all pools (strategy's) * @return Returns sum holdings (USD) for all pools */
NatSpecMultiLine
v0.8.12+commit.f00d7308
{ "func_code_index": [ 5206, 5501 ] }
2,616
Zunami
contracts/Zunami.sol
0x9b43e47bec96a9345cd26fdde7efa5f8c06e126c
Solidity
Zunami
contract Zunami is ERC20, Pausable, AccessControl { using SafeERC20 for IERC20Metadata; bytes32 public constant OPERATOR_ROLE = keccak256('OPERATOR_ROLE'); struct PendingWithdrawal { uint256 lpShares; uint256[3] minAmounts; } struct PoolInfo { IStrategy strategy; uint256 startTime; uint256 lpShares; } uint8 public constant POOL_ASSETS = 3; uint256 public constant FEE_DENOMINATOR = 1000; uint256 public constant MIN_LOCK_TIME = 1 days; uint256 public constant FUNDS_DENOMINATOR = 10_000; uint8 public constant ALL_WITHDRAWAL_TYPES_MASK = uint8(7); // Binary 111 = 2^0 + 2^1 + 2^2; PoolInfo[] internal _poolInfo; uint256 public defaultDepositPid; uint256 public defaultWithdrawPid; uint8 public availableWithdrawalTypes; address[POOL_ASSETS] public tokens; uint256[POOL_ASSETS] public decimalsMultipliers; mapping(address => uint256[POOL_ASSETS]) public pendingDeposits; mapping(address => PendingWithdrawal) public pendingWithdrawals; uint256 public totalDeposited = 0; uint256 public managementFee = 100; // 10% bool public launched = false; event CreatedPendingDeposit(address indexed depositor, uint256[POOL_ASSETS] amounts); event CreatedPendingWithdrawal( address indexed withdrawer, uint256[POOL_ASSETS] amounts, uint256 lpShares ); event Deposited(address indexed depositor, uint256[POOL_ASSETS] amounts, uint256 lpShares); event Withdrawn(address indexed withdrawer, IStrategy.WithdrawalType withdrawalType, uint256[POOL_ASSETS] tokenAmounts, uint256 lpShares, uint128 tokenIndex); event AddedPool(uint256 pid, address strategyAddr, uint256 startTime); event FailedDeposit(address indexed depositor, uint256[POOL_ASSETS] amounts, uint256 lpShares); event FailedWithdrawal(address indexed withdrawer, uint256[POOL_ASSETS] amounts, uint256 lpShares); event SetDefaultDepositPid(uint256 pid); event SetDefaultWithdrawPid(uint256 pid); event ClaimedAllManagementFee(uint256 feeValue); event AutoCompoundAll(); modifier startedPool() { require(_poolInfo.length != 0, 'Zunami: pool not existed!'); require( block.timestamp >= _poolInfo[defaultDepositPid].startTime, 'Zunami: default deposit pool not started yet!' ); require( block.timestamp >= _poolInfo[defaultWithdrawPid].startTime, 'Zunami: default withdraw pool not started yet!' ); _; } constructor(address[POOL_ASSETS] memory _tokens) ERC20('ZunamiLP', 'ZLP') { tokens = _tokens; _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(OPERATOR_ROLE, msg.sender); for (uint256 i; i < POOL_ASSETS; i++) { uint256 decimals = IERC20Metadata(tokens[i]).decimals(); if (decimals < 18) { decimalsMultipliers[i] = 10**(18 - decimals); } else { decimalsMultipliers[i] = 1; } } availableWithdrawalTypes = ALL_WITHDRAWAL_TYPES_MASK; } function poolInfo(uint256 pid) external view returns (PoolInfo memory) { return _poolInfo[pid]; } function pause() external onlyRole(DEFAULT_ADMIN_ROLE) { _pause(); } function unpause() external onlyRole(DEFAULT_ADMIN_ROLE) { _unpause(); } function setAvailableWithdrawalTypes(uint8 newAvailableWithdrawalTypes) external onlyRole(DEFAULT_ADMIN_ROLE) { require(newAvailableWithdrawalTypes <= ALL_WITHDRAWAL_TYPES_MASK, 'Zunami: wrong available withdrawal types'); availableWithdrawalTypes = newAvailableWithdrawalTypes; } /** * @dev update managementFee, this is a Zunami commission from protocol profit * @param newManagementFee - minAmount 0, maxAmount FEE_DENOMINATOR - 1 */ function setManagementFee(uint256 newManagementFee) external onlyRole(DEFAULT_ADMIN_ROLE) { require(newManagementFee < FEE_DENOMINATOR, 'Zunami: wrong fee'); managementFee = newManagementFee; } /** * @dev Returns managementFee for strategy's when contract sell rewards * @return Returns commission on the amount of profit in the transaction * @param amount - amount of profit for calculate managementFee */ function calcManagementFee(uint256 amount) external view returns (uint256) { return (amount * managementFee) / FEE_DENOMINATOR; } /** * @dev Claims managementFee from all active strategies */ function claimAllManagementFee() external { uint256 feeTotalValue; for (uint256 i = 0; i < _poolInfo.length; i++) { feeTotalValue += _poolInfo[i].strategy.claimManagementFees(); } emit ClaimedAllManagementFee(feeTotalValue); } function autoCompoundAll() external { for (uint256 i = 0; i < _poolInfo.length; i++) { _poolInfo[i].strategy.autoCompound(); } emit AutoCompoundAll(); } /** * @dev Returns total holdings for all pools (strategy's) * @return Returns sum holdings (USD) for all pools */ function totalHoldings() public view returns (uint256) { uint256 length = _poolInfo.length; uint256 totalHold = 0; for (uint256 pid = 0; pid < length; pid++) { totalHold += _poolInfo[pid].strategy.totalHoldings(); } return totalHold; } /** * @dev Returns price depends on the income of users * @return Returns currently price of ZLP (1e18 = 1$) */ function lpPrice() external view returns (uint256) { return (totalHoldings() * 1e18) / totalSupply(); } /** * @dev Returns number of pools * @return number of pools */ function poolCount() external view returns (uint256) { return _poolInfo.length; } /** * @dev in this func user sends funds to the contract and then waits for the completion * of the transaction for all users * @param amounts - array of deposit amounts by user */ function delegateDeposit(uint256[3] memory amounts) external whenNotPaused { for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] > 0) { IERC20Metadata(tokens[i]).safeTransferFrom(_msgSender(), address(this), amounts[i]); pendingDeposits[_msgSender()][i] += amounts[i]; } } emit CreatedPendingDeposit(_msgSender(), amounts); } /** * @dev in this func user sends pending withdraw to the contract and then waits * for the completion of the transaction for all users * @param lpAmount - amount of ZLP for withdraw * @param minAmounts - array of amounts stablecoins that user want minimum receive */ function delegateWithdrawal(uint256 lpAmount, uint256[3] memory minAmounts) external whenNotPaused { PendingWithdrawal memory withdrawal; address userAddr = _msgSender(); require(lpAmount > 0, 'Zunami: lpAmount must be higher 0'); withdrawal.lpShares = lpAmount; withdrawal.minAmounts = minAmounts; pendingWithdrawals[userAddr] = withdrawal; emit CreatedPendingWithdrawal(userAddr, minAmounts, lpAmount); } /** * @dev Zunami protocol owner complete all active pending deposits of users * @param userList - dev send array of users from pending to complete */ function completeDeposits(address[] memory userList) external onlyRole(OPERATOR_ROLE) startedPool { IStrategy strategy = _poolInfo[defaultDepositPid].strategy; uint256 currentTotalHoldings = totalHoldings(); uint256 newHoldings = 0; uint256[3] memory totalAmounts; uint256[] memory userCompleteHoldings = new uint256[](userList.length); for (uint256 i = 0; i < userList.length; i++) { newHoldings = 0; for (uint256 x = 0; x < totalAmounts.length; x++) { uint256 userTokenDeposit = pendingDeposits[userList[i]][x]; totalAmounts[x] += userTokenDeposit; newHoldings += userTokenDeposit * decimalsMultipliers[x]; } userCompleteHoldings[i] = newHoldings; } newHoldings = 0; for (uint256 y = 0; y < POOL_ASSETS; y++) { uint256 totalTokenAmount = totalAmounts[y]; if (totalTokenAmount > 0) { newHoldings += totalTokenAmount * decimalsMultipliers[y]; IERC20Metadata(tokens[y]).safeTransfer(address(strategy), totalTokenAmount); } } uint256 totalDepositedNow = strategy.deposit(totalAmounts); require(totalDepositedNow > 0, 'Zunami: too low deposit!'); uint256 lpShares = 0; uint256 addedHoldings = 0; uint256 userDeposited = 0; for (uint256 z = 0; z < userList.length; z++) { userDeposited = (totalDepositedNow * userCompleteHoldings[z]) / newHoldings; address userAddr = userList[z]; if (totalSupply() == 0) { lpShares = userDeposited; } else { lpShares = (totalSupply() * userDeposited) / (currentTotalHoldings + addedHoldings); } addedHoldings += userDeposited; _mint(userAddr, lpShares); _poolInfo[defaultDepositPid].lpShares += lpShares; emit Deposited(userAddr, pendingDeposits[userAddr], lpShares); // remove deposit from list delete pendingDeposits[userAddr]; } totalDeposited += addedHoldings; } /** * @dev Zunami protocol owner complete all active pending withdrawals of users * @param userList - array of users from pending withdraw to complete */ function completeWithdrawals(address[] memory userList) external onlyRole(OPERATOR_ROLE) startedPool { require(userList.length > 0, 'Zunami: there are no pending withdrawals requests'); IStrategy strategy = _poolInfo[defaultWithdrawPid].strategy; address user; PendingWithdrawal memory withdrawal; for (uint256 i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; if (balanceOf(user) >= withdrawal.lpShares) { if ( !( strategy.withdraw( user, withdrawal.lpShares * 1e18 / _poolInfo[defaultWithdrawPid].lpShares, withdrawal.minAmounts, IStrategy.WithdrawalType.Base, 0 ) ) ) { emit FailedWithdrawal(user, withdrawal.minAmounts, withdrawal.lpShares); delete pendingWithdrawals[user]; continue; } uint256 userDeposit = (totalDeposited * withdrawal.lpShares) / totalSupply(); _burn(user, withdrawal.lpShares); _poolInfo[defaultWithdrawPid].lpShares -= withdrawal.lpShares; totalDeposited -= userDeposit; emit Withdrawn(user, IStrategy.WithdrawalType.Base, withdrawal.minAmounts, withdrawal.lpShares, 0); } delete pendingWithdrawals[user]; } } function completeWithdrawalsOptimized(address[] memory userList) external onlyRole(OPERATOR_ROLE) startedPool { require(userList.length > 0, 'Zunami: there are no pending withdrawals requests'); IStrategy strategy = _poolInfo[defaultWithdrawPid].strategy; uint256 lpSharesTotal; uint256[POOL_ASSETS] memory minAmountsTotal; uint256 i; address user; PendingWithdrawal memory withdrawal; for (i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; if (balanceOf(user) < withdrawal.lpShares) { emit FailedWithdrawal(user, withdrawal.minAmounts, withdrawal.lpShares); delete pendingWithdrawals[user]; continue; } lpSharesTotal += withdrawal.lpShares; minAmountsTotal[0] += withdrawal.minAmounts[0]; minAmountsTotal[1] += withdrawal.minAmounts[1]; minAmountsTotal[2] += withdrawal.minAmounts[2]; emit Withdrawn(user, IStrategy.WithdrawalType.Base, withdrawal.minAmounts, withdrawal.lpShares, 0); } require( lpSharesTotal <= _poolInfo[defaultWithdrawPid].lpShares, "Zunami: Insufficient pool LP shares"); uint256[POOL_ASSETS] memory prevBalances; for (i = 0; i < 3; i++) { prevBalances[i] = IERC20Metadata(tokens[i]).balanceOf(address(this)); } if( !strategy.withdraw(address(this), lpSharesTotal * 1e18 / _poolInfo[defaultWithdrawPid].lpShares, minAmountsTotal, IStrategy.WithdrawalType.Base, 0) ) { //TODO: do we really need to remove delegated requests for (i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; emit FailedWithdrawal(user, withdrawal.minAmounts, withdrawal.lpShares); delete pendingWithdrawals[user]; } return; } uint256[POOL_ASSETS] memory diffBalances; for (i = 0; i < 3; i++) { diffBalances[i] = IERC20Metadata(tokens[i]).balanceOf(address(this)) - prevBalances[i]; } for (i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; uint256 userDeposit = (totalDeposited * withdrawal.lpShares) / totalSupply(); _burn(user, withdrawal.lpShares); _poolInfo[defaultWithdrawPid].lpShares -= withdrawal.lpShares; totalDeposited -= userDeposit; for (uint256 j = 0; j < 3; j++) { IERC20Metadata(tokens[j]).safeTransfer( user, (diffBalances[j] * withdrawal.lpShares) / lpSharesTotal ); } delete pendingWithdrawals[user]; } } /** * @dev deposit in one tx, without waiting complete by dev * @return Returns amount of lpShares minted for user * @param amounts - user send amounts of stablecoins to deposit */ function deposit(uint256[POOL_ASSETS] memory amounts) external whenNotPaused startedPool returns (uint256) { IStrategy strategy = _poolInfo[defaultDepositPid].strategy; uint256 holdings = totalHoldings(); for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] > 0) { IERC20Metadata(tokens[i]).safeTransferFrom( _msgSender(), address(strategy), amounts[i] ); } } uint256 newDeposited = strategy.deposit(amounts); require(newDeposited > 0, 'Zunami: too low deposit!'); uint256 lpShares = 0; if (totalSupply() == 0) { lpShares = newDeposited; } else { lpShares = (totalSupply() * newDeposited) / holdings; } _mint(_msgSender(), lpShares); _poolInfo[defaultDepositPid].lpShares += lpShares; totalDeposited += newDeposited; emit Deposited(_msgSender(), amounts, lpShares); return lpShares; } /** * @dev withdraw in one tx, without waiting complete by dev * @param lpShares - amount of ZLP for withdraw * @param tokenAmounts - array of amounts stablecoins that user want minimum receive */ function withdraw( uint256 lpShares, uint256[POOL_ASSETS] memory tokenAmounts, IStrategy.WithdrawalType withdrawalType, uint128 tokenIndex ) external whenNotPaused startedPool { require( checkBit(availableWithdrawalTypes, uint8(withdrawalType)), 'Zunami: withdrawal type not available' ); IStrategy strategy = _poolInfo[defaultWithdrawPid].strategy; address userAddr = _msgSender(); require(balanceOf(userAddr) >= lpShares, 'Zunami: not enough LP balance'); require( strategy.withdraw(userAddr, lpShares * 1e18 / _poolInfo[defaultWithdrawPid].lpShares, tokenAmounts, withdrawalType, tokenIndex), 'Zunami: user lps share should be at least required' ); uint256 userDeposit = (totalDeposited * lpShares) / totalSupply(); _burn(userAddr, lpShares); _poolInfo[defaultWithdrawPid].lpShares -= lpShares; totalDeposited -= userDeposit; emit Withdrawn(userAddr, withdrawalType, tokenAmounts, lpShares, tokenIndex); } /** * @dev add a new pool, deposits in the new pool are blocked for one day for safety * @param _strategyAddr - the new pool strategy address */ function addPool(address _strategyAddr) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_strategyAddr != address(0), 'Zunami: zero strategy addr'); uint256 startTime = block.timestamp + (launched ? MIN_LOCK_TIME : 0); _poolInfo.push( PoolInfo({ strategy: IStrategy(_strategyAddr), startTime: startTime, lpShares: 0 }) ); emit AddedPool(_poolInfo.length - 1, _strategyAddr, startTime); } /** * @dev set a default pool for deposit funds * @param _newPoolId - new pool id */ function setDefaultDepositPid(uint256 _newPoolId) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_newPoolId < _poolInfo.length, 'Zunami: incorrect default deposit pool id'); defaultDepositPid = _newPoolId; emit SetDefaultDepositPid(_newPoolId); } /** * @dev set a default pool for withdraw funds * @param _newPoolId - new pool id */ function setDefaultWithdrawPid(uint256 _newPoolId) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_newPoolId < _poolInfo.length, 'Zunami: incorrect default withdraw pool id'); defaultWithdrawPid = _newPoolId; emit SetDefaultWithdrawPid(_newPoolId); } function launch() external onlyRole(DEFAULT_ADMIN_ROLE) { launched = true; } /** * @dev dev can transfer funds from few strategy's to one strategy for better APY * @param _strategies - array of strategy's, from which funds are withdrawn * @param withdrawalsPercents - A percentage of the funds that should be transfered * @param _receiverStrategyId - number strategy, to which funds are deposited */ function moveFundsBatch( uint256[] memory _strategies, uint256[] memory withdrawalsPercents, uint256 _receiverStrategyId ) external onlyRole(DEFAULT_ADMIN_ROLE) { require( _strategies.length == withdrawalsPercents.length, 'Zunami: incorrect arguments for the moveFundsBatch' ); require(_receiverStrategyId < _poolInfo.length, 'Zunami: incorrect a reciver strategy ID'); uint256[POOL_ASSETS] memory tokenBalance; for (uint256 y = 0; y < POOL_ASSETS; y++) { tokenBalance[y] = IERC20Metadata(tokens[y]).balanceOf(address(this)); } uint256 pid; uint256 zunamiLp; for (uint256 i = 0; i < _strategies.length; i++) { pid = _strategies[i]; zunamiLp += _moveFunds(pid, withdrawalsPercents[i]); } uint256[POOL_ASSETS] memory tokensRemainder; for (uint256 y = 0; y < POOL_ASSETS; y++) { tokensRemainder[y] = IERC20Metadata(tokens[y]).balanceOf(address(this)) - tokenBalance[y]; if (tokensRemainder[y] > 0) { IERC20Metadata(tokens[y]).safeTransfer( address(_poolInfo[_receiverStrategyId].strategy), tokensRemainder[y] ); } } _poolInfo[_receiverStrategyId].lpShares += zunamiLp; require( _poolInfo[_receiverStrategyId].strategy.deposit(tokensRemainder) > 0, 'Zunami: Too low amount!' ); } function _moveFunds(uint256 pid, uint256 withdrawAmount) private returns (uint256) { uint256 currentLpAmount; if (withdrawAmount == FUNDS_DENOMINATOR) { _poolInfo[pid].strategy.withdrawAll(); currentLpAmount = _poolInfo[pid].lpShares; _poolInfo[pid].lpShares = 0; } else { currentLpAmount = (_poolInfo[pid].lpShares * withdrawAmount) / FUNDS_DENOMINATOR; uint256[POOL_ASSETS] memory minAmounts; _poolInfo[pid].strategy.withdraw( address(this), currentLpAmount * 1e18 / _poolInfo[pid].lpShares, minAmounts, IStrategy.WithdrawalType.Base, 0 ); _poolInfo[pid].lpShares = _poolInfo[pid].lpShares - currentLpAmount; } return currentLpAmount; } /** * @dev user remove his active pending deposit */ function pendingDepositRemove() external { for (uint256 i = 0; i < POOL_ASSETS; i++) { if (pendingDeposits[_msgSender()][i] > 0) { IERC20Metadata(tokens[i]).safeTransfer( _msgSender(), pendingDeposits[_msgSender()][i] ); } } delete pendingDeposits[_msgSender()]; } /** * @dev governance can withdraw all stuck funds in emergency case * @param _token - IERC20Metadata token that should be fully withdraw from Zunami */ function withdrawStuckToken(IERC20Metadata _token) external onlyRole(DEFAULT_ADMIN_ROLE) { uint256 tokenBalance = _token.balanceOf(address(this)); _token.safeTransfer(_msgSender(), tokenBalance); } /** * @dev governance can add new operator for complete pending deposits and withdrawals * @param _newOperator - address that governance add in list of operators */ function updateOperator(address _newOperator) external onlyRole(DEFAULT_ADMIN_ROLE) { _grantRole(OPERATOR_ROLE, _newOperator); } // Get bit value at position function checkBit(uint8 mask, uint8 bit) internal pure returns (bool) { return mask & (0x01 << bit) != 0; } }
/** * * @title Zunami Protocol * * @notice Contract for Convex&Curve protocols optimize. * Users can use this contract for optimize yield and gas. * * * @dev Zunami is main contract. * Contract does not store user funds. * All user funds goes to Convex&Curve pools. * */
NatSpecMultiLine
lpPrice
function lpPrice() external view returns (uint256) { return (totalHoldings() * 1e18) / totalSupply(); }
/** * @dev Returns price depends on the income of users * @return Returns currently price of ZLP (1e18 = 1$) */
NatSpecMultiLine
v0.8.12+commit.f00d7308
{ "func_code_index": [ 5634, 5753 ] }
2,617
Zunami
contracts/Zunami.sol
0x9b43e47bec96a9345cd26fdde7efa5f8c06e126c
Solidity
Zunami
contract Zunami is ERC20, Pausable, AccessControl { using SafeERC20 for IERC20Metadata; bytes32 public constant OPERATOR_ROLE = keccak256('OPERATOR_ROLE'); struct PendingWithdrawal { uint256 lpShares; uint256[3] minAmounts; } struct PoolInfo { IStrategy strategy; uint256 startTime; uint256 lpShares; } uint8 public constant POOL_ASSETS = 3; uint256 public constant FEE_DENOMINATOR = 1000; uint256 public constant MIN_LOCK_TIME = 1 days; uint256 public constant FUNDS_DENOMINATOR = 10_000; uint8 public constant ALL_WITHDRAWAL_TYPES_MASK = uint8(7); // Binary 111 = 2^0 + 2^1 + 2^2; PoolInfo[] internal _poolInfo; uint256 public defaultDepositPid; uint256 public defaultWithdrawPid; uint8 public availableWithdrawalTypes; address[POOL_ASSETS] public tokens; uint256[POOL_ASSETS] public decimalsMultipliers; mapping(address => uint256[POOL_ASSETS]) public pendingDeposits; mapping(address => PendingWithdrawal) public pendingWithdrawals; uint256 public totalDeposited = 0; uint256 public managementFee = 100; // 10% bool public launched = false; event CreatedPendingDeposit(address indexed depositor, uint256[POOL_ASSETS] amounts); event CreatedPendingWithdrawal( address indexed withdrawer, uint256[POOL_ASSETS] amounts, uint256 lpShares ); event Deposited(address indexed depositor, uint256[POOL_ASSETS] amounts, uint256 lpShares); event Withdrawn(address indexed withdrawer, IStrategy.WithdrawalType withdrawalType, uint256[POOL_ASSETS] tokenAmounts, uint256 lpShares, uint128 tokenIndex); event AddedPool(uint256 pid, address strategyAddr, uint256 startTime); event FailedDeposit(address indexed depositor, uint256[POOL_ASSETS] amounts, uint256 lpShares); event FailedWithdrawal(address indexed withdrawer, uint256[POOL_ASSETS] amounts, uint256 lpShares); event SetDefaultDepositPid(uint256 pid); event SetDefaultWithdrawPid(uint256 pid); event ClaimedAllManagementFee(uint256 feeValue); event AutoCompoundAll(); modifier startedPool() { require(_poolInfo.length != 0, 'Zunami: pool not existed!'); require( block.timestamp >= _poolInfo[defaultDepositPid].startTime, 'Zunami: default deposit pool not started yet!' ); require( block.timestamp >= _poolInfo[defaultWithdrawPid].startTime, 'Zunami: default withdraw pool not started yet!' ); _; } constructor(address[POOL_ASSETS] memory _tokens) ERC20('ZunamiLP', 'ZLP') { tokens = _tokens; _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(OPERATOR_ROLE, msg.sender); for (uint256 i; i < POOL_ASSETS; i++) { uint256 decimals = IERC20Metadata(tokens[i]).decimals(); if (decimals < 18) { decimalsMultipliers[i] = 10**(18 - decimals); } else { decimalsMultipliers[i] = 1; } } availableWithdrawalTypes = ALL_WITHDRAWAL_TYPES_MASK; } function poolInfo(uint256 pid) external view returns (PoolInfo memory) { return _poolInfo[pid]; } function pause() external onlyRole(DEFAULT_ADMIN_ROLE) { _pause(); } function unpause() external onlyRole(DEFAULT_ADMIN_ROLE) { _unpause(); } function setAvailableWithdrawalTypes(uint8 newAvailableWithdrawalTypes) external onlyRole(DEFAULT_ADMIN_ROLE) { require(newAvailableWithdrawalTypes <= ALL_WITHDRAWAL_TYPES_MASK, 'Zunami: wrong available withdrawal types'); availableWithdrawalTypes = newAvailableWithdrawalTypes; } /** * @dev update managementFee, this is a Zunami commission from protocol profit * @param newManagementFee - minAmount 0, maxAmount FEE_DENOMINATOR - 1 */ function setManagementFee(uint256 newManagementFee) external onlyRole(DEFAULT_ADMIN_ROLE) { require(newManagementFee < FEE_DENOMINATOR, 'Zunami: wrong fee'); managementFee = newManagementFee; } /** * @dev Returns managementFee for strategy's when contract sell rewards * @return Returns commission on the amount of profit in the transaction * @param amount - amount of profit for calculate managementFee */ function calcManagementFee(uint256 amount) external view returns (uint256) { return (amount * managementFee) / FEE_DENOMINATOR; } /** * @dev Claims managementFee from all active strategies */ function claimAllManagementFee() external { uint256 feeTotalValue; for (uint256 i = 0; i < _poolInfo.length; i++) { feeTotalValue += _poolInfo[i].strategy.claimManagementFees(); } emit ClaimedAllManagementFee(feeTotalValue); } function autoCompoundAll() external { for (uint256 i = 0; i < _poolInfo.length; i++) { _poolInfo[i].strategy.autoCompound(); } emit AutoCompoundAll(); } /** * @dev Returns total holdings for all pools (strategy's) * @return Returns sum holdings (USD) for all pools */ function totalHoldings() public view returns (uint256) { uint256 length = _poolInfo.length; uint256 totalHold = 0; for (uint256 pid = 0; pid < length; pid++) { totalHold += _poolInfo[pid].strategy.totalHoldings(); } return totalHold; } /** * @dev Returns price depends on the income of users * @return Returns currently price of ZLP (1e18 = 1$) */ function lpPrice() external view returns (uint256) { return (totalHoldings() * 1e18) / totalSupply(); } /** * @dev Returns number of pools * @return number of pools */ function poolCount() external view returns (uint256) { return _poolInfo.length; } /** * @dev in this func user sends funds to the contract and then waits for the completion * of the transaction for all users * @param amounts - array of deposit amounts by user */ function delegateDeposit(uint256[3] memory amounts) external whenNotPaused { for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] > 0) { IERC20Metadata(tokens[i]).safeTransferFrom(_msgSender(), address(this), amounts[i]); pendingDeposits[_msgSender()][i] += amounts[i]; } } emit CreatedPendingDeposit(_msgSender(), amounts); } /** * @dev in this func user sends pending withdraw to the contract and then waits * for the completion of the transaction for all users * @param lpAmount - amount of ZLP for withdraw * @param minAmounts - array of amounts stablecoins that user want minimum receive */ function delegateWithdrawal(uint256 lpAmount, uint256[3] memory minAmounts) external whenNotPaused { PendingWithdrawal memory withdrawal; address userAddr = _msgSender(); require(lpAmount > 0, 'Zunami: lpAmount must be higher 0'); withdrawal.lpShares = lpAmount; withdrawal.minAmounts = minAmounts; pendingWithdrawals[userAddr] = withdrawal; emit CreatedPendingWithdrawal(userAddr, minAmounts, lpAmount); } /** * @dev Zunami protocol owner complete all active pending deposits of users * @param userList - dev send array of users from pending to complete */ function completeDeposits(address[] memory userList) external onlyRole(OPERATOR_ROLE) startedPool { IStrategy strategy = _poolInfo[defaultDepositPid].strategy; uint256 currentTotalHoldings = totalHoldings(); uint256 newHoldings = 0; uint256[3] memory totalAmounts; uint256[] memory userCompleteHoldings = new uint256[](userList.length); for (uint256 i = 0; i < userList.length; i++) { newHoldings = 0; for (uint256 x = 0; x < totalAmounts.length; x++) { uint256 userTokenDeposit = pendingDeposits[userList[i]][x]; totalAmounts[x] += userTokenDeposit; newHoldings += userTokenDeposit * decimalsMultipliers[x]; } userCompleteHoldings[i] = newHoldings; } newHoldings = 0; for (uint256 y = 0; y < POOL_ASSETS; y++) { uint256 totalTokenAmount = totalAmounts[y]; if (totalTokenAmount > 0) { newHoldings += totalTokenAmount * decimalsMultipliers[y]; IERC20Metadata(tokens[y]).safeTransfer(address(strategy), totalTokenAmount); } } uint256 totalDepositedNow = strategy.deposit(totalAmounts); require(totalDepositedNow > 0, 'Zunami: too low deposit!'); uint256 lpShares = 0; uint256 addedHoldings = 0; uint256 userDeposited = 0; for (uint256 z = 0; z < userList.length; z++) { userDeposited = (totalDepositedNow * userCompleteHoldings[z]) / newHoldings; address userAddr = userList[z]; if (totalSupply() == 0) { lpShares = userDeposited; } else { lpShares = (totalSupply() * userDeposited) / (currentTotalHoldings + addedHoldings); } addedHoldings += userDeposited; _mint(userAddr, lpShares); _poolInfo[defaultDepositPid].lpShares += lpShares; emit Deposited(userAddr, pendingDeposits[userAddr], lpShares); // remove deposit from list delete pendingDeposits[userAddr]; } totalDeposited += addedHoldings; } /** * @dev Zunami protocol owner complete all active pending withdrawals of users * @param userList - array of users from pending withdraw to complete */ function completeWithdrawals(address[] memory userList) external onlyRole(OPERATOR_ROLE) startedPool { require(userList.length > 0, 'Zunami: there are no pending withdrawals requests'); IStrategy strategy = _poolInfo[defaultWithdrawPid].strategy; address user; PendingWithdrawal memory withdrawal; for (uint256 i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; if (balanceOf(user) >= withdrawal.lpShares) { if ( !( strategy.withdraw( user, withdrawal.lpShares * 1e18 / _poolInfo[defaultWithdrawPid].lpShares, withdrawal.minAmounts, IStrategy.WithdrawalType.Base, 0 ) ) ) { emit FailedWithdrawal(user, withdrawal.minAmounts, withdrawal.lpShares); delete pendingWithdrawals[user]; continue; } uint256 userDeposit = (totalDeposited * withdrawal.lpShares) / totalSupply(); _burn(user, withdrawal.lpShares); _poolInfo[defaultWithdrawPid].lpShares -= withdrawal.lpShares; totalDeposited -= userDeposit; emit Withdrawn(user, IStrategy.WithdrawalType.Base, withdrawal.minAmounts, withdrawal.lpShares, 0); } delete pendingWithdrawals[user]; } } function completeWithdrawalsOptimized(address[] memory userList) external onlyRole(OPERATOR_ROLE) startedPool { require(userList.length > 0, 'Zunami: there are no pending withdrawals requests'); IStrategy strategy = _poolInfo[defaultWithdrawPid].strategy; uint256 lpSharesTotal; uint256[POOL_ASSETS] memory minAmountsTotal; uint256 i; address user; PendingWithdrawal memory withdrawal; for (i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; if (balanceOf(user) < withdrawal.lpShares) { emit FailedWithdrawal(user, withdrawal.minAmounts, withdrawal.lpShares); delete pendingWithdrawals[user]; continue; } lpSharesTotal += withdrawal.lpShares; minAmountsTotal[0] += withdrawal.minAmounts[0]; minAmountsTotal[1] += withdrawal.minAmounts[1]; minAmountsTotal[2] += withdrawal.minAmounts[2]; emit Withdrawn(user, IStrategy.WithdrawalType.Base, withdrawal.minAmounts, withdrawal.lpShares, 0); } require( lpSharesTotal <= _poolInfo[defaultWithdrawPid].lpShares, "Zunami: Insufficient pool LP shares"); uint256[POOL_ASSETS] memory prevBalances; for (i = 0; i < 3; i++) { prevBalances[i] = IERC20Metadata(tokens[i]).balanceOf(address(this)); } if( !strategy.withdraw(address(this), lpSharesTotal * 1e18 / _poolInfo[defaultWithdrawPid].lpShares, minAmountsTotal, IStrategy.WithdrawalType.Base, 0) ) { //TODO: do we really need to remove delegated requests for (i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; emit FailedWithdrawal(user, withdrawal.minAmounts, withdrawal.lpShares); delete pendingWithdrawals[user]; } return; } uint256[POOL_ASSETS] memory diffBalances; for (i = 0; i < 3; i++) { diffBalances[i] = IERC20Metadata(tokens[i]).balanceOf(address(this)) - prevBalances[i]; } for (i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; uint256 userDeposit = (totalDeposited * withdrawal.lpShares) / totalSupply(); _burn(user, withdrawal.lpShares); _poolInfo[defaultWithdrawPid].lpShares -= withdrawal.lpShares; totalDeposited -= userDeposit; for (uint256 j = 0; j < 3; j++) { IERC20Metadata(tokens[j]).safeTransfer( user, (diffBalances[j] * withdrawal.lpShares) / lpSharesTotal ); } delete pendingWithdrawals[user]; } } /** * @dev deposit in one tx, without waiting complete by dev * @return Returns amount of lpShares minted for user * @param amounts - user send amounts of stablecoins to deposit */ function deposit(uint256[POOL_ASSETS] memory amounts) external whenNotPaused startedPool returns (uint256) { IStrategy strategy = _poolInfo[defaultDepositPid].strategy; uint256 holdings = totalHoldings(); for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] > 0) { IERC20Metadata(tokens[i]).safeTransferFrom( _msgSender(), address(strategy), amounts[i] ); } } uint256 newDeposited = strategy.deposit(amounts); require(newDeposited > 0, 'Zunami: too low deposit!'); uint256 lpShares = 0; if (totalSupply() == 0) { lpShares = newDeposited; } else { lpShares = (totalSupply() * newDeposited) / holdings; } _mint(_msgSender(), lpShares); _poolInfo[defaultDepositPid].lpShares += lpShares; totalDeposited += newDeposited; emit Deposited(_msgSender(), amounts, lpShares); return lpShares; } /** * @dev withdraw in one tx, without waiting complete by dev * @param lpShares - amount of ZLP for withdraw * @param tokenAmounts - array of amounts stablecoins that user want minimum receive */ function withdraw( uint256 lpShares, uint256[POOL_ASSETS] memory tokenAmounts, IStrategy.WithdrawalType withdrawalType, uint128 tokenIndex ) external whenNotPaused startedPool { require( checkBit(availableWithdrawalTypes, uint8(withdrawalType)), 'Zunami: withdrawal type not available' ); IStrategy strategy = _poolInfo[defaultWithdrawPid].strategy; address userAddr = _msgSender(); require(balanceOf(userAddr) >= lpShares, 'Zunami: not enough LP balance'); require( strategy.withdraw(userAddr, lpShares * 1e18 / _poolInfo[defaultWithdrawPid].lpShares, tokenAmounts, withdrawalType, tokenIndex), 'Zunami: user lps share should be at least required' ); uint256 userDeposit = (totalDeposited * lpShares) / totalSupply(); _burn(userAddr, lpShares); _poolInfo[defaultWithdrawPid].lpShares -= lpShares; totalDeposited -= userDeposit; emit Withdrawn(userAddr, withdrawalType, tokenAmounts, lpShares, tokenIndex); } /** * @dev add a new pool, deposits in the new pool are blocked for one day for safety * @param _strategyAddr - the new pool strategy address */ function addPool(address _strategyAddr) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_strategyAddr != address(0), 'Zunami: zero strategy addr'); uint256 startTime = block.timestamp + (launched ? MIN_LOCK_TIME : 0); _poolInfo.push( PoolInfo({ strategy: IStrategy(_strategyAddr), startTime: startTime, lpShares: 0 }) ); emit AddedPool(_poolInfo.length - 1, _strategyAddr, startTime); } /** * @dev set a default pool for deposit funds * @param _newPoolId - new pool id */ function setDefaultDepositPid(uint256 _newPoolId) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_newPoolId < _poolInfo.length, 'Zunami: incorrect default deposit pool id'); defaultDepositPid = _newPoolId; emit SetDefaultDepositPid(_newPoolId); } /** * @dev set a default pool for withdraw funds * @param _newPoolId - new pool id */ function setDefaultWithdrawPid(uint256 _newPoolId) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_newPoolId < _poolInfo.length, 'Zunami: incorrect default withdraw pool id'); defaultWithdrawPid = _newPoolId; emit SetDefaultWithdrawPid(_newPoolId); } function launch() external onlyRole(DEFAULT_ADMIN_ROLE) { launched = true; } /** * @dev dev can transfer funds from few strategy's to one strategy for better APY * @param _strategies - array of strategy's, from which funds are withdrawn * @param withdrawalsPercents - A percentage of the funds that should be transfered * @param _receiverStrategyId - number strategy, to which funds are deposited */ function moveFundsBatch( uint256[] memory _strategies, uint256[] memory withdrawalsPercents, uint256 _receiverStrategyId ) external onlyRole(DEFAULT_ADMIN_ROLE) { require( _strategies.length == withdrawalsPercents.length, 'Zunami: incorrect arguments for the moveFundsBatch' ); require(_receiverStrategyId < _poolInfo.length, 'Zunami: incorrect a reciver strategy ID'); uint256[POOL_ASSETS] memory tokenBalance; for (uint256 y = 0; y < POOL_ASSETS; y++) { tokenBalance[y] = IERC20Metadata(tokens[y]).balanceOf(address(this)); } uint256 pid; uint256 zunamiLp; for (uint256 i = 0; i < _strategies.length; i++) { pid = _strategies[i]; zunamiLp += _moveFunds(pid, withdrawalsPercents[i]); } uint256[POOL_ASSETS] memory tokensRemainder; for (uint256 y = 0; y < POOL_ASSETS; y++) { tokensRemainder[y] = IERC20Metadata(tokens[y]).balanceOf(address(this)) - tokenBalance[y]; if (tokensRemainder[y] > 0) { IERC20Metadata(tokens[y]).safeTransfer( address(_poolInfo[_receiverStrategyId].strategy), tokensRemainder[y] ); } } _poolInfo[_receiverStrategyId].lpShares += zunamiLp; require( _poolInfo[_receiverStrategyId].strategy.deposit(tokensRemainder) > 0, 'Zunami: Too low amount!' ); } function _moveFunds(uint256 pid, uint256 withdrawAmount) private returns (uint256) { uint256 currentLpAmount; if (withdrawAmount == FUNDS_DENOMINATOR) { _poolInfo[pid].strategy.withdrawAll(); currentLpAmount = _poolInfo[pid].lpShares; _poolInfo[pid].lpShares = 0; } else { currentLpAmount = (_poolInfo[pid].lpShares * withdrawAmount) / FUNDS_DENOMINATOR; uint256[POOL_ASSETS] memory minAmounts; _poolInfo[pid].strategy.withdraw( address(this), currentLpAmount * 1e18 / _poolInfo[pid].lpShares, minAmounts, IStrategy.WithdrawalType.Base, 0 ); _poolInfo[pid].lpShares = _poolInfo[pid].lpShares - currentLpAmount; } return currentLpAmount; } /** * @dev user remove his active pending deposit */ function pendingDepositRemove() external { for (uint256 i = 0; i < POOL_ASSETS; i++) { if (pendingDeposits[_msgSender()][i] > 0) { IERC20Metadata(tokens[i]).safeTransfer( _msgSender(), pendingDeposits[_msgSender()][i] ); } } delete pendingDeposits[_msgSender()]; } /** * @dev governance can withdraw all stuck funds in emergency case * @param _token - IERC20Metadata token that should be fully withdraw from Zunami */ function withdrawStuckToken(IERC20Metadata _token) external onlyRole(DEFAULT_ADMIN_ROLE) { uint256 tokenBalance = _token.balanceOf(address(this)); _token.safeTransfer(_msgSender(), tokenBalance); } /** * @dev governance can add new operator for complete pending deposits and withdrawals * @param _newOperator - address that governance add in list of operators */ function updateOperator(address _newOperator) external onlyRole(DEFAULT_ADMIN_ROLE) { _grantRole(OPERATOR_ROLE, _newOperator); } // Get bit value at position function checkBit(uint8 mask, uint8 bit) internal pure returns (bool) { return mask & (0x01 << bit) != 0; } }
/** * * @title Zunami Protocol * * @notice Contract for Convex&Curve protocols optimize. * Users can use this contract for optimize yield and gas. * * * @dev Zunami is main contract. * Contract does not store user funds. * All user funds goes to Convex&Curve pools. * */
NatSpecMultiLine
poolCount
function poolCount() external view returns (uint256) { return _poolInfo.length; }
/** * @dev Returns number of pools * @return number of pools */
NatSpecMultiLine
v0.8.12+commit.f00d7308
{ "func_code_index": [ 5838, 5935 ] }
2,618
Zunami
contracts/Zunami.sol
0x9b43e47bec96a9345cd26fdde7efa5f8c06e126c
Solidity
Zunami
contract Zunami is ERC20, Pausable, AccessControl { using SafeERC20 for IERC20Metadata; bytes32 public constant OPERATOR_ROLE = keccak256('OPERATOR_ROLE'); struct PendingWithdrawal { uint256 lpShares; uint256[3] minAmounts; } struct PoolInfo { IStrategy strategy; uint256 startTime; uint256 lpShares; } uint8 public constant POOL_ASSETS = 3; uint256 public constant FEE_DENOMINATOR = 1000; uint256 public constant MIN_LOCK_TIME = 1 days; uint256 public constant FUNDS_DENOMINATOR = 10_000; uint8 public constant ALL_WITHDRAWAL_TYPES_MASK = uint8(7); // Binary 111 = 2^0 + 2^1 + 2^2; PoolInfo[] internal _poolInfo; uint256 public defaultDepositPid; uint256 public defaultWithdrawPid; uint8 public availableWithdrawalTypes; address[POOL_ASSETS] public tokens; uint256[POOL_ASSETS] public decimalsMultipliers; mapping(address => uint256[POOL_ASSETS]) public pendingDeposits; mapping(address => PendingWithdrawal) public pendingWithdrawals; uint256 public totalDeposited = 0; uint256 public managementFee = 100; // 10% bool public launched = false; event CreatedPendingDeposit(address indexed depositor, uint256[POOL_ASSETS] amounts); event CreatedPendingWithdrawal( address indexed withdrawer, uint256[POOL_ASSETS] amounts, uint256 lpShares ); event Deposited(address indexed depositor, uint256[POOL_ASSETS] amounts, uint256 lpShares); event Withdrawn(address indexed withdrawer, IStrategy.WithdrawalType withdrawalType, uint256[POOL_ASSETS] tokenAmounts, uint256 lpShares, uint128 tokenIndex); event AddedPool(uint256 pid, address strategyAddr, uint256 startTime); event FailedDeposit(address indexed depositor, uint256[POOL_ASSETS] amounts, uint256 lpShares); event FailedWithdrawal(address indexed withdrawer, uint256[POOL_ASSETS] amounts, uint256 lpShares); event SetDefaultDepositPid(uint256 pid); event SetDefaultWithdrawPid(uint256 pid); event ClaimedAllManagementFee(uint256 feeValue); event AutoCompoundAll(); modifier startedPool() { require(_poolInfo.length != 0, 'Zunami: pool not existed!'); require( block.timestamp >= _poolInfo[defaultDepositPid].startTime, 'Zunami: default deposit pool not started yet!' ); require( block.timestamp >= _poolInfo[defaultWithdrawPid].startTime, 'Zunami: default withdraw pool not started yet!' ); _; } constructor(address[POOL_ASSETS] memory _tokens) ERC20('ZunamiLP', 'ZLP') { tokens = _tokens; _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(OPERATOR_ROLE, msg.sender); for (uint256 i; i < POOL_ASSETS; i++) { uint256 decimals = IERC20Metadata(tokens[i]).decimals(); if (decimals < 18) { decimalsMultipliers[i] = 10**(18 - decimals); } else { decimalsMultipliers[i] = 1; } } availableWithdrawalTypes = ALL_WITHDRAWAL_TYPES_MASK; } function poolInfo(uint256 pid) external view returns (PoolInfo memory) { return _poolInfo[pid]; } function pause() external onlyRole(DEFAULT_ADMIN_ROLE) { _pause(); } function unpause() external onlyRole(DEFAULT_ADMIN_ROLE) { _unpause(); } function setAvailableWithdrawalTypes(uint8 newAvailableWithdrawalTypes) external onlyRole(DEFAULT_ADMIN_ROLE) { require(newAvailableWithdrawalTypes <= ALL_WITHDRAWAL_TYPES_MASK, 'Zunami: wrong available withdrawal types'); availableWithdrawalTypes = newAvailableWithdrawalTypes; } /** * @dev update managementFee, this is a Zunami commission from protocol profit * @param newManagementFee - minAmount 0, maxAmount FEE_DENOMINATOR - 1 */ function setManagementFee(uint256 newManagementFee) external onlyRole(DEFAULT_ADMIN_ROLE) { require(newManagementFee < FEE_DENOMINATOR, 'Zunami: wrong fee'); managementFee = newManagementFee; } /** * @dev Returns managementFee for strategy's when contract sell rewards * @return Returns commission on the amount of profit in the transaction * @param amount - amount of profit for calculate managementFee */ function calcManagementFee(uint256 amount) external view returns (uint256) { return (amount * managementFee) / FEE_DENOMINATOR; } /** * @dev Claims managementFee from all active strategies */ function claimAllManagementFee() external { uint256 feeTotalValue; for (uint256 i = 0; i < _poolInfo.length; i++) { feeTotalValue += _poolInfo[i].strategy.claimManagementFees(); } emit ClaimedAllManagementFee(feeTotalValue); } function autoCompoundAll() external { for (uint256 i = 0; i < _poolInfo.length; i++) { _poolInfo[i].strategy.autoCompound(); } emit AutoCompoundAll(); } /** * @dev Returns total holdings for all pools (strategy's) * @return Returns sum holdings (USD) for all pools */ function totalHoldings() public view returns (uint256) { uint256 length = _poolInfo.length; uint256 totalHold = 0; for (uint256 pid = 0; pid < length; pid++) { totalHold += _poolInfo[pid].strategy.totalHoldings(); } return totalHold; } /** * @dev Returns price depends on the income of users * @return Returns currently price of ZLP (1e18 = 1$) */ function lpPrice() external view returns (uint256) { return (totalHoldings() * 1e18) / totalSupply(); } /** * @dev Returns number of pools * @return number of pools */ function poolCount() external view returns (uint256) { return _poolInfo.length; } /** * @dev in this func user sends funds to the contract and then waits for the completion * of the transaction for all users * @param amounts - array of deposit amounts by user */ function delegateDeposit(uint256[3] memory amounts) external whenNotPaused { for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] > 0) { IERC20Metadata(tokens[i]).safeTransferFrom(_msgSender(), address(this), amounts[i]); pendingDeposits[_msgSender()][i] += amounts[i]; } } emit CreatedPendingDeposit(_msgSender(), amounts); } /** * @dev in this func user sends pending withdraw to the contract and then waits * for the completion of the transaction for all users * @param lpAmount - amount of ZLP for withdraw * @param minAmounts - array of amounts stablecoins that user want minimum receive */ function delegateWithdrawal(uint256 lpAmount, uint256[3] memory minAmounts) external whenNotPaused { PendingWithdrawal memory withdrawal; address userAddr = _msgSender(); require(lpAmount > 0, 'Zunami: lpAmount must be higher 0'); withdrawal.lpShares = lpAmount; withdrawal.minAmounts = minAmounts; pendingWithdrawals[userAddr] = withdrawal; emit CreatedPendingWithdrawal(userAddr, minAmounts, lpAmount); } /** * @dev Zunami protocol owner complete all active pending deposits of users * @param userList - dev send array of users from pending to complete */ function completeDeposits(address[] memory userList) external onlyRole(OPERATOR_ROLE) startedPool { IStrategy strategy = _poolInfo[defaultDepositPid].strategy; uint256 currentTotalHoldings = totalHoldings(); uint256 newHoldings = 0; uint256[3] memory totalAmounts; uint256[] memory userCompleteHoldings = new uint256[](userList.length); for (uint256 i = 0; i < userList.length; i++) { newHoldings = 0; for (uint256 x = 0; x < totalAmounts.length; x++) { uint256 userTokenDeposit = pendingDeposits[userList[i]][x]; totalAmounts[x] += userTokenDeposit; newHoldings += userTokenDeposit * decimalsMultipliers[x]; } userCompleteHoldings[i] = newHoldings; } newHoldings = 0; for (uint256 y = 0; y < POOL_ASSETS; y++) { uint256 totalTokenAmount = totalAmounts[y]; if (totalTokenAmount > 0) { newHoldings += totalTokenAmount * decimalsMultipliers[y]; IERC20Metadata(tokens[y]).safeTransfer(address(strategy), totalTokenAmount); } } uint256 totalDepositedNow = strategy.deposit(totalAmounts); require(totalDepositedNow > 0, 'Zunami: too low deposit!'); uint256 lpShares = 0; uint256 addedHoldings = 0; uint256 userDeposited = 0; for (uint256 z = 0; z < userList.length; z++) { userDeposited = (totalDepositedNow * userCompleteHoldings[z]) / newHoldings; address userAddr = userList[z]; if (totalSupply() == 0) { lpShares = userDeposited; } else { lpShares = (totalSupply() * userDeposited) / (currentTotalHoldings + addedHoldings); } addedHoldings += userDeposited; _mint(userAddr, lpShares); _poolInfo[defaultDepositPid].lpShares += lpShares; emit Deposited(userAddr, pendingDeposits[userAddr], lpShares); // remove deposit from list delete pendingDeposits[userAddr]; } totalDeposited += addedHoldings; } /** * @dev Zunami protocol owner complete all active pending withdrawals of users * @param userList - array of users from pending withdraw to complete */ function completeWithdrawals(address[] memory userList) external onlyRole(OPERATOR_ROLE) startedPool { require(userList.length > 0, 'Zunami: there are no pending withdrawals requests'); IStrategy strategy = _poolInfo[defaultWithdrawPid].strategy; address user; PendingWithdrawal memory withdrawal; for (uint256 i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; if (balanceOf(user) >= withdrawal.lpShares) { if ( !( strategy.withdraw( user, withdrawal.lpShares * 1e18 / _poolInfo[defaultWithdrawPid].lpShares, withdrawal.minAmounts, IStrategy.WithdrawalType.Base, 0 ) ) ) { emit FailedWithdrawal(user, withdrawal.minAmounts, withdrawal.lpShares); delete pendingWithdrawals[user]; continue; } uint256 userDeposit = (totalDeposited * withdrawal.lpShares) / totalSupply(); _burn(user, withdrawal.lpShares); _poolInfo[defaultWithdrawPid].lpShares -= withdrawal.lpShares; totalDeposited -= userDeposit; emit Withdrawn(user, IStrategy.WithdrawalType.Base, withdrawal.minAmounts, withdrawal.lpShares, 0); } delete pendingWithdrawals[user]; } } function completeWithdrawalsOptimized(address[] memory userList) external onlyRole(OPERATOR_ROLE) startedPool { require(userList.length > 0, 'Zunami: there are no pending withdrawals requests'); IStrategy strategy = _poolInfo[defaultWithdrawPid].strategy; uint256 lpSharesTotal; uint256[POOL_ASSETS] memory minAmountsTotal; uint256 i; address user; PendingWithdrawal memory withdrawal; for (i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; if (balanceOf(user) < withdrawal.lpShares) { emit FailedWithdrawal(user, withdrawal.minAmounts, withdrawal.lpShares); delete pendingWithdrawals[user]; continue; } lpSharesTotal += withdrawal.lpShares; minAmountsTotal[0] += withdrawal.minAmounts[0]; minAmountsTotal[1] += withdrawal.minAmounts[1]; minAmountsTotal[2] += withdrawal.minAmounts[2]; emit Withdrawn(user, IStrategy.WithdrawalType.Base, withdrawal.minAmounts, withdrawal.lpShares, 0); } require( lpSharesTotal <= _poolInfo[defaultWithdrawPid].lpShares, "Zunami: Insufficient pool LP shares"); uint256[POOL_ASSETS] memory prevBalances; for (i = 0; i < 3; i++) { prevBalances[i] = IERC20Metadata(tokens[i]).balanceOf(address(this)); } if( !strategy.withdraw(address(this), lpSharesTotal * 1e18 / _poolInfo[defaultWithdrawPid].lpShares, minAmountsTotal, IStrategy.WithdrawalType.Base, 0) ) { //TODO: do we really need to remove delegated requests for (i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; emit FailedWithdrawal(user, withdrawal.minAmounts, withdrawal.lpShares); delete pendingWithdrawals[user]; } return; } uint256[POOL_ASSETS] memory diffBalances; for (i = 0; i < 3; i++) { diffBalances[i] = IERC20Metadata(tokens[i]).balanceOf(address(this)) - prevBalances[i]; } for (i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; uint256 userDeposit = (totalDeposited * withdrawal.lpShares) / totalSupply(); _burn(user, withdrawal.lpShares); _poolInfo[defaultWithdrawPid].lpShares -= withdrawal.lpShares; totalDeposited -= userDeposit; for (uint256 j = 0; j < 3; j++) { IERC20Metadata(tokens[j]).safeTransfer( user, (diffBalances[j] * withdrawal.lpShares) / lpSharesTotal ); } delete pendingWithdrawals[user]; } } /** * @dev deposit in one tx, without waiting complete by dev * @return Returns amount of lpShares minted for user * @param amounts - user send amounts of stablecoins to deposit */ function deposit(uint256[POOL_ASSETS] memory amounts) external whenNotPaused startedPool returns (uint256) { IStrategy strategy = _poolInfo[defaultDepositPid].strategy; uint256 holdings = totalHoldings(); for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] > 0) { IERC20Metadata(tokens[i]).safeTransferFrom( _msgSender(), address(strategy), amounts[i] ); } } uint256 newDeposited = strategy.deposit(amounts); require(newDeposited > 0, 'Zunami: too low deposit!'); uint256 lpShares = 0; if (totalSupply() == 0) { lpShares = newDeposited; } else { lpShares = (totalSupply() * newDeposited) / holdings; } _mint(_msgSender(), lpShares); _poolInfo[defaultDepositPid].lpShares += lpShares; totalDeposited += newDeposited; emit Deposited(_msgSender(), amounts, lpShares); return lpShares; } /** * @dev withdraw in one tx, without waiting complete by dev * @param lpShares - amount of ZLP for withdraw * @param tokenAmounts - array of amounts stablecoins that user want minimum receive */ function withdraw( uint256 lpShares, uint256[POOL_ASSETS] memory tokenAmounts, IStrategy.WithdrawalType withdrawalType, uint128 tokenIndex ) external whenNotPaused startedPool { require( checkBit(availableWithdrawalTypes, uint8(withdrawalType)), 'Zunami: withdrawal type not available' ); IStrategy strategy = _poolInfo[defaultWithdrawPid].strategy; address userAddr = _msgSender(); require(balanceOf(userAddr) >= lpShares, 'Zunami: not enough LP balance'); require( strategy.withdraw(userAddr, lpShares * 1e18 / _poolInfo[defaultWithdrawPid].lpShares, tokenAmounts, withdrawalType, tokenIndex), 'Zunami: user lps share should be at least required' ); uint256 userDeposit = (totalDeposited * lpShares) / totalSupply(); _burn(userAddr, lpShares); _poolInfo[defaultWithdrawPid].lpShares -= lpShares; totalDeposited -= userDeposit; emit Withdrawn(userAddr, withdrawalType, tokenAmounts, lpShares, tokenIndex); } /** * @dev add a new pool, deposits in the new pool are blocked for one day for safety * @param _strategyAddr - the new pool strategy address */ function addPool(address _strategyAddr) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_strategyAddr != address(0), 'Zunami: zero strategy addr'); uint256 startTime = block.timestamp + (launched ? MIN_LOCK_TIME : 0); _poolInfo.push( PoolInfo({ strategy: IStrategy(_strategyAddr), startTime: startTime, lpShares: 0 }) ); emit AddedPool(_poolInfo.length - 1, _strategyAddr, startTime); } /** * @dev set a default pool for deposit funds * @param _newPoolId - new pool id */ function setDefaultDepositPid(uint256 _newPoolId) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_newPoolId < _poolInfo.length, 'Zunami: incorrect default deposit pool id'); defaultDepositPid = _newPoolId; emit SetDefaultDepositPid(_newPoolId); } /** * @dev set a default pool for withdraw funds * @param _newPoolId - new pool id */ function setDefaultWithdrawPid(uint256 _newPoolId) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_newPoolId < _poolInfo.length, 'Zunami: incorrect default withdraw pool id'); defaultWithdrawPid = _newPoolId; emit SetDefaultWithdrawPid(_newPoolId); } function launch() external onlyRole(DEFAULT_ADMIN_ROLE) { launched = true; } /** * @dev dev can transfer funds from few strategy's to one strategy for better APY * @param _strategies - array of strategy's, from which funds are withdrawn * @param withdrawalsPercents - A percentage of the funds that should be transfered * @param _receiverStrategyId - number strategy, to which funds are deposited */ function moveFundsBatch( uint256[] memory _strategies, uint256[] memory withdrawalsPercents, uint256 _receiverStrategyId ) external onlyRole(DEFAULT_ADMIN_ROLE) { require( _strategies.length == withdrawalsPercents.length, 'Zunami: incorrect arguments for the moveFundsBatch' ); require(_receiverStrategyId < _poolInfo.length, 'Zunami: incorrect a reciver strategy ID'); uint256[POOL_ASSETS] memory tokenBalance; for (uint256 y = 0; y < POOL_ASSETS; y++) { tokenBalance[y] = IERC20Metadata(tokens[y]).balanceOf(address(this)); } uint256 pid; uint256 zunamiLp; for (uint256 i = 0; i < _strategies.length; i++) { pid = _strategies[i]; zunamiLp += _moveFunds(pid, withdrawalsPercents[i]); } uint256[POOL_ASSETS] memory tokensRemainder; for (uint256 y = 0; y < POOL_ASSETS; y++) { tokensRemainder[y] = IERC20Metadata(tokens[y]).balanceOf(address(this)) - tokenBalance[y]; if (tokensRemainder[y] > 0) { IERC20Metadata(tokens[y]).safeTransfer( address(_poolInfo[_receiverStrategyId].strategy), tokensRemainder[y] ); } } _poolInfo[_receiverStrategyId].lpShares += zunamiLp; require( _poolInfo[_receiverStrategyId].strategy.deposit(tokensRemainder) > 0, 'Zunami: Too low amount!' ); } function _moveFunds(uint256 pid, uint256 withdrawAmount) private returns (uint256) { uint256 currentLpAmount; if (withdrawAmount == FUNDS_DENOMINATOR) { _poolInfo[pid].strategy.withdrawAll(); currentLpAmount = _poolInfo[pid].lpShares; _poolInfo[pid].lpShares = 0; } else { currentLpAmount = (_poolInfo[pid].lpShares * withdrawAmount) / FUNDS_DENOMINATOR; uint256[POOL_ASSETS] memory minAmounts; _poolInfo[pid].strategy.withdraw( address(this), currentLpAmount * 1e18 / _poolInfo[pid].lpShares, minAmounts, IStrategy.WithdrawalType.Base, 0 ); _poolInfo[pid].lpShares = _poolInfo[pid].lpShares - currentLpAmount; } return currentLpAmount; } /** * @dev user remove his active pending deposit */ function pendingDepositRemove() external { for (uint256 i = 0; i < POOL_ASSETS; i++) { if (pendingDeposits[_msgSender()][i] > 0) { IERC20Metadata(tokens[i]).safeTransfer( _msgSender(), pendingDeposits[_msgSender()][i] ); } } delete pendingDeposits[_msgSender()]; } /** * @dev governance can withdraw all stuck funds in emergency case * @param _token - IERC20Metadata token that should be fully withdraw from Zunami */ function withdrawStuckToken(IERC20Metadata _token) external onlyRole(DEFAULT_ADMIN_ROLE) { uint256 tokenBalance = _token.balanceOf(address(this)); _token.safeTransfer(_msgSender(), tokenBalance); } /** * @dev governance can add new operator for complete pending deposits and withdrawals * @param _newOperator - address that governance add in list of operators */ function updateOperator(address _newOperator) external onlyRole(DEFAULT_ADMIN_ROLE) { _grantRole(OPERATOR_ROLE, _newOperator); } // Get bit value at position function checkBit(uint8 mask, uint8 bit) internal pure returns (bool) { return mask & (0x01 << bit) != 0; } }
/** * * @title Zunami Protocol * * @notice Contract for Convex&Curve protocols optimize. * Users can use this contract for optimize yield and gas. * * * @dev Zunami is main contract. * Contract does not store user funds. * All user funds goes to Convex&Curve pools. * */
NatSpecMultiLine
delegateDeposit
function delegateDeposit(uint256[3] memory amounts) external whenNotPaused { for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] > 0) { IERC20Metadata(tokens[i]).safeTransferFrom(_msgSender(), address(this), amounts[i]); pendingDeposits[_msgSender()][i] += amounts[i]; } } emit CreatedPendingDeposit(_msgSender(), amounts); }
/** * @dev in this func user sends funds to the contract and then waits for the completion * of the transaction for all users * @param amounts - array of deposit amounts by user */
NatSpecMultiLine
v0.8.12+commit.f00d7308
{ "func_code_index": [ 6142, 6566 ] }
2,619
Zunami
contracts/Zunami.sol
0x9b43e47bec96a9345cd26fdde7efa5f8c06e126c
Solidity
Zunami
contract Zunami is ERC20, Pausable, AccessControl { using SafeERC20 for IERC20Metadata; bytes32 public constant OPERATOR_ROLE = keccak256('OPERATOR_ROLE'); struct PendingWithdrawal { uint256 lpShares; uint256[3] minAmounts; } struct PoolInfo { IStrategy strategy; uint256 startTime; uint256 lpShares; } uint8 public constant POOL_ASSETS = 3; uint256 public constant FEE_DENOMINATOR = 1000; uint256 public constant MIN_LOCK_TIME = 1 days; uint256 public constant FUNDS_DENOMINATOR = 10_000; uint8 public constant ALL_WITHDRAWAL_TYPES_MASK = uint8(7); // Binary 111 = 2^0 + 2^1 + 2^2; PoolInfo[] internal _poolInfo; uint256 public defaultDepositPid; uint256 public defaultWithdrawPid; uint8 public availableWithdrawalTypes; address[POOL_ASSETS] public tokens; uint256[POOL_ASSETS] public decimalsMultipliers; mapping(address => uint256[POOL_ASSETS]) public pendingDeposits; mapping(address => PendingWithdrawal) public pendingWithdrawals; uint256 public totalDeposited = 0; uint256 public managementFee = 100; // 10% bool public launched = false; event CreatedPendingDeposit(address indexed depositor, uint256[POOL_ASSETS] amounts); event CreatedPendingWithdrawal( address indexed withdrawer, uint256[POOL_ASSETS] amounts, uint256 lpShares ); event Deposited(address indexed depositor, uint256[POOL_ASSETS] amounts, uint256 lpShares); event Withdrawn(address indexed withdrawer, IStrategy.WithdrawalType withdrawalType, uint256[POOL_ASSETS] tokenAmounts, uint256 lpShares, uint128 tokenIndex); event AddedPool(uint256 pid, address strategyAddr, uint256 startTime); event FailedDeposit(address indexed depositor, uint256[POOL_ASSETS] amounts, uint256 lpShares); event FailedWithdrawal(address indexed withdrawer, uint256[POOL_ASSETS] amounts, uint256 lpShares); event SetDefaultDepositPid(uint256 pid); event SetDefaultWithdrawPid(uint256 pid); event ClaimedAllManagementFee(uint256 feeValue); event AutoCompoundAll(); modifier startedPool() { require(_poolInfo.length != 0, 'Zunami: pool not existed!'); require( block.timestamp >= _poolInfo[defaultDepositPid].startTime, 'Zunami: default deposit pool not started yet!' ); require( block.timestamp >= _poolInfo[defaultWithdrawPid].startTime, 'Zunami: default withdraw pool not started yet!' ); _; } constructor(address[POOL_ASSETS] memory _tokens) ERC20('ZunamiLP', 'ZLP') { tokens = _tokens; _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(OPERATOR_ROLE, msg.sender); for (uint256 i; i < POOL_ASSETS; i++) { uint256 decimals = IERC20Metadata(tokens[i]).decimals(); if (decimals < 18) { decimalsMultipliers[i] = 10**(18 - decimals); } else { decimalsMultipliers[i] = 1; } } availableWithdrawalTypes = ALL_WITHDRAWAL_TYPES_MASK; } function poolInfo(uint256 pid) external view returns (PoolInfo memory) { return _poolInfo[pid]; } function pause() external onlyRole(DEFAULT_ADMIN_ROLE) { _pause(); } function unpause() external onlyRole(DEFAULT_ADMIN_ROLE) { _unpause(); } function setAvailableWithdrawalTypes(uint8 newAvailableWithdrawalTypes) external onlyRole(DEFAULT_ADMIN_ROLE) { require(newAvailableWithdrawalTypes <= ALL_WITHDRAWAL_TYPES_MASK, 'Zunami: wrong available withdrawal types'); availableWithdrawalTypes = newAvailableWithdrawalTypes; } /** * @dev update managementFee, this is a Zunami commission from protocol profit * @param newManagementFee - minAmount 0, maxAmount FEE_DENOMINATOR - 1 */ function setManagementFee(uint256 newManagementFee) external onlyRole(DEFAULT_ADMIN_ROLE) { require(newManagementFee < FEE_DENOMINATOR, 'Zunami: wrong fee'); managementFee = newManagementFee; } /** * @dev Returns managementFee for strategy's when contract sell rewards * @return Returns commission on the amount of profit in the transaction * @param amount - amount of profit for calculate managementFee */ function calcManagementFee(uint256 amount) external view returns (uint256) { return (amount * managementFee) / FEE_DENOMINATOR; } /** * @dev Claims managementFee from all active strategies */ function claimAllManagementFee() external { uint256 feeTotalValue; for (uint256 i = 0; i < _poolInfo.length; i++) { feeTotalValue += _poolInfo[i].strategy.claimManagementFees(); } emit ClaimedAllManagementFee(feeTotalValue); } function autoCompoundAll() external { for (uint256 i = 0; i < _poolInfo.length; i++) { _poolInfo[i].strategy.autoCompound(); } emit AutoCompoundAll(); } /** * @dev Returns total holdings for all pools (strategy's) * @return Returns sum holdings (USD) for all pools */ function totalHoldings() public view returns (uint256) { uint256 length = _poolInfo.length; uint256 totalHold = 0; for (uint256 pid = 0; pid < length; pid++) { totalHold += _poolInfo[pid].strategy.totalHoldings(); } return totalHold; } /** * @dev Returns price depends on the income of users * @return Returns currently price of ZLP (1e18 = 1$) */ function lpPrice() external view returns (uint256) { return (totalHoldings() * 1e18) / totalSupply(); } /** * @dev Returns number of pools * @return number of pools */ function poolCount() external view returns (uint256) { return _poolInfo.length; } /** * @dev in this func user sends funds to the contract and then waits for the completion * of the transaction for all users * @param amounts - array of deposit amounts by user */ function delegateDeposit(uint256[3] memory amounts) external whenNotPaused { for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] > 0) { IERC20Metadata(tokens[i]).safeTransferFrom(_msgSender(), address(this), amounts[i]); pendingDeposits[_msgSender()][i] += amounts[i]; } } emit CreatedPendingDeposit(_msgSender(), amounts); } /** * @dev in this func user sends pending withdraw to the contract and then waits * for the completion of the transaction for all users * @param lpAmount - amount of ZLP for withdraw * @param minAmounts - array of amounts stablecoins that user want minimum receive */ function delegateWithdrawal(uint256 lpAmount, uint256[3] memory minAmounts) external whenNotPaused { PendingWithdrawal memory withdrawal; address userAddr = _msgSender(); require(lpAmount > 0, 'Zunami: lpAmount must be higher 0'); withdrawal.lpShares = lpAmount; withdrawal.minAmounts = minAmounts; pendingWithdrawals[userAddr] = withdrawal; emit CreatedPendingWithdrawal(userAddr, minAmounts, lpAmount); } /** * @dev Zunami protocol owner complete all active pending deposits of users * @param userList - dev send array of users from pending to complete */ function completeDeposits(address[] memory userList) external onlyRole(OPERATOR_ROLE) startedPool { IStrategy strategy = _poolInfo[defaultDepositPid].strategy; uint256 currentTotalHoldings = totalHoldings(); uint256 newHoldings = 0; uint256[3] memory totalAmounts; uint256[] memory userCompleteHoldings = new uint256[](userList.length); for (uint256 i = 0; i < userList.length; i++) { newHoldings = 0; for (uint256 x = 0; x < totalAmounts.length; x++) { uint256 userTokenDeposit = pendingDeposits[userList[i]][x]; totalAmounts[x] += userTokenDeposit; newHoldings += userTokenDeposit * decimalsMultipliers[x]; } userCompleteHoldings[i] = newHoldings; } newHoldings = 0; for (uint256 y = 0; y < POOL_ASSETS; y++) { uint256 totalTokenAmount = totalAmounts[y]; if (totalTokenAmount > 0) { newHoldings += totalTokenAmount * decimalsMultipliers[y]; IERC20Metadata(tokens[y]).safeTransfer(address(strategy), totalTokenAmount); } } uint256 totalDepositedNow = strategy.deposit(totalAmounts); require(totalDepositedNow > 0, 'Zunami: too low deposit!'); uint256 lpShares = 0; uint256 addedHoldings = 0; uint256 userDeposited = 0; for (uint256 z = 0; z < userList.length; z++) { userDeposited = (totalDepositedNow * userCompleteHoldings[z]) / newHoldings; address userAddr = userList[z]; if (totalSupply() == 0) { lpShares = userDeposited; } else { lpShares = (totalSupply() * userDeposited) / (currentTotalHoldings + addedHoldings); } addedHoldings += userDeposited; _mint(userAddr, lpShares); _poolInfo[defaultDepositPid].lpShares += lpShares; emit Deposited(userAddr, pendingDeposits[userAddr], lpShares); // remove deposit from list delete pendingDeposits[userAddr]; } totalDeposited += addedHoldings; } /** * @dev Zunami protocol owner complete all active pending withdrawals of users * @param userList - array of users from pending withdraw to complete */ function completeWithdrawals(address[] memory userList) external onlyRole(OPERATOR_ROLE) startedPool { require(userList.length > 0, 'Zunami: there are no pending withdrawals requests'); IStrategy strategy = _poolInfo[defaultWithdrawPid].strategy; address user; PendingWithdrawal memory withdrawal; for (uint256 i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; if (balanceOf(user) >= withdrawal.lpShares) { if ( !( strategy.withdraw( user, withdrawal.lpShares * 1e18 / _poolInfo[defaultWithdrawPid].lpShares, withdrawal.minAmounts, IStrategy.WithdrawalType.Base, 0 ) ) ) { emit FailedWithdrawal(user, withdrawal.minAmounts, withdrawal.lpShares); delete pendingWithdrawals[user]; continue; } uint256 userDeposit = (totalDeposited * withdrawal.lpShares) / totalSupply(); _burn(user, withdrawal.lpShares); _poolInfo[defaultWithdrawPid].lpShares -= withdrawal.lpShares; totalDeposited -= userDeposit; emit Withdrawn(user, IStrategy.WithdrawalType.Base, withdrawal.minAmounts, withdrawal.lpShares, 0); } delete pendingWithdrawals[user]; } } function completeWithdrawalsOptimized(address[] memory userList) external onlyRole(OPERATOR_ROLE) startedPool { require(userList.length > 0, 'Zunami: there are no pending withdrawals requests'); IStrategy strategy = _poolInfo[defaultWithdrawPid].strategy; uint256 lpSharesTotal; uint256[POOL_ASSETS] memory minAmountsTotal; uint256 i; address user; PendingWithdrawal memory withdrawal; for (i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; if (balanceOf(user) < withdrawal.lpShares) { emit FailedWithdrawal(user, withdrawal.minAmounts, withdrawal.lpShares); delete pendingWithdrawals[user]; continue; } lpSharesTotal += withdrawal.lpShares; minAmountsTotal[0] += withdrawal.minAmounts[0]; minAmountsTotal[1] += withdrawal.minAmounts[1]; minAmountsTotal[2] += withdrawal.minAmounts[2]; emit Withdrawn(user, IStrategy.WithdrawalType.Base, withdrawal.minAmounts, withdrawal.lpShares, 0); } require( lpSharesTotal <= _poolInfo[defaultWithdrawPid].lpShares, "Zunami: Insufficient pool LP shares"); uint256[POOL_ASSETS] memory prevBalances; for (i = 0; i < 3; i++) { prevBalances[i] = IERC20Metadata(tokens[i]).balanceOf(address(this)); } if( !strategy.withdraw(address(this), lpSharesTotal * 1e18 / _poolInfo[defaultWithdrawPid].lpShares, minAmountsTotal, IStrategy.WithdrawalType.Base, 0) ) { //TODO: do we really need to remove delegated requests for (i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; emit FailedWithdrawal(user, withdrawal.minAmounts, withdrawal.lpShares); delete pendingWithdrawals[user]; } return; } uint256[POOL_ASSETS] memory diffBalances; for (i = 0; i < 3; i++) { diffBalances[i] = IERC20Metadata(tokens[i]).balanceOf(address(this)) - prevBalances[i]; } for (i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; uint256 userDeposit = (totalDeposited * withdrawal.lpShares) / totalSupply(); _burn(user, withdrawal.lpShares); _poolInfo[defaultWithdrawPid].lpShares -= withdrawal.lpShares; totalDeposited -= userDeposit; for (uint256 j = 0; j < 3; j++) { IERC20Metadata(tokens[j]).safeTransfer( user, (diffBalances[j] * withdrawal.lpShares) / lpSharesTotal ); } delete pendingWithdrawals[user]; } } /** * @dev deposit in one tx, without waiting complete by dev * @return Returns amount of lpShares minted for user * @param amounts - user send amounts of stablecoins to deposit */ function deposit(uint256[POOL_ASSETS] memory amounts) external whenNotPaused startedPool returns (uint256) { IStrategy strategy = _poolInfo[defaultDepositPid].strategy; uint256 holdings = totalHoldings(); for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] > 0) { IERC20Metadata(tokens[i]).safeTransferFrom( _msgSender(), address(strategy), amounts[i] ); } } uint256 newDeposited = strategy.deposit(amounts); require(newDeposited > 0, 'Zunami: too low deposit!'); uint256 lpShares = 0; if (totalSupply() == 0) { lpShares = newDeposited; } else { lpShares = (totalSupply() * newDeposited) / holdings; } _mint(_msgSender(), lpShares); _poolInfo[defaultDepositPid].lpShares += lpShares; totalDeposited += newDeposited; emit Deposited(_msgSender(), amounts, lpShares); return lpShares; } /** * @dev withdraw in one tx, without waiting complete by dev * @param lpShares - amount of ZLP for withdraw * @param tokenAmounts - array of amounts stablecoins that user want minimum receive */ function withdraw( uint256 lpShares, uint256[POOL_ASSETS] memory tokenAmounts, IStrategy.WithdrawalType withdrawalType, uint128 tokenIndex ) external whenNotPaused startedPool { require( checkBit(availableWithdrawalTypes, uint8(withdrawalType)), 'Zunami: withdrawal type not available' ); IStrategy strategy = _poolInfo[defaultWithdrawPid].strategy; address userAddr = _msgSender(); require(balanceOf(userAddr) >= lpShares, 'Zunami: not enough LP balance'); require( strategy.withdraw(userAddr, lpShares * 1e18 / _poolInfo[defaultWithdrawPid].lpShares, tokenAmounts, withdrawalType, tokenIndex), 'Zunami: user lps share should be at least required' ); uint256 userDeposit = (totalDeposited * lpShares) / totalSupply(); _burn(userAddr, lpShares); _poolInfo[defaultWithdrawPid].lpShares -= lpShares; totalDeposited -= userDeposit; emit Withdrawn(userAddr, withdrawalType, tokenAmounts, lpShares, tokenIndex); } /** * @dev add a new pool, deposits in the new pool are blocked for one day for safety * @param _strategyAddr - the new pool strategy address */ function addPool(address _strategyAddr) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_strategyAddr != address(0), 'Zunami: zero strategy addr'); uint256 startTime = block.timestamp + (launched ? MIN_LOCK_TIME : 0); _poolInfo.push( PoolInfo({ strategy: IStrategy(_strategyAddr), startTime: startTime, lpShares: 0 }) ); emit AddedPool(_poolInfo.length - 1, _strategyAddr, startTime); } /** * @dev set a default pool for deposit funds * @param _newPoolId - new pool id */ function setDefaultDepositPid(uint256 _newPoolId) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_newPoolId < _poolInfo.length, 'Zunami: incorrect default deposit pool id'); defaultDepositPid = _newPoolId; emit SetDefaultDepositPid(_newPoolId); } /** * @dev set a default pool for withdraw funds * @param _newPoolId - new pool id */ function setDefaultWithdrawPid(uint256 _newPoolId) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_newPoolId < _poolInfo.length, 'Zunami: incorrect default withdraw pool id'); defaultWithdrawPid = _newPoolId; emit SetDefaultWithdrawPid(_newPoolId); } function launch() external onlyRole(DEFAULT_ADMIN_ROLE) { launched = true; } /** * @dev dev can transfer funds from few strategy's to one strategy for better APY * @param _strategies - array of strategy's, from which funds are withdrawn * @param withdrawalsPercents - A percentage of the funds that should be transfered * @param _receiverStrategyId - number strategy, to which funds are deposited */ function moveFundsBatch( uint256[] memory _strategies, uint256[] memory withdrawalsPercents, uint256 _receiverStrategyId ) external onlyRole(DEFAULT_ADMIN_ROLE) { require( _strategies.length == withdrawalsPercents.length, 'Zunami: incorrect arguments for the moveFundsBatch' ); require(_receiverStrategyId < _poolInfo.length, 'Zunami: incorrect a reciver strategy ID'); uint256[POOL_ASSETS] memory tokenBalance; for (uint256 y = 0; y < POOL_ASSETS; y++) { tokenBalance[y] = IERC20Metadata(tokens[y]).balanceOf(address(this)); } uint256 pid; uint256 zunamiLp; for (uint256 i = 0; i < _strategies.length; i++) { pid = _strategies[i]; zunamiLp += _moveFunds(pid, withdrawalsPercents[i]); } uint256[POOL_ASSETS] memory tokensRemainder; for (uint256 y = 0; y < POOL_ASSETS; y++) { tokensRemainder[y] = IERC20Metadata(tokens[y]).balanceOf(address(this)) - tokenBalance[y]; if (tokensRemainder[y] > 0) { IERC20Metadata(tokens[y]).safeTransfer( address(_poolInfo[_receiverStrategyId].strategy), tokensRemainder[y] ); } } _poolInfo[_receiverStrategyId].lpShares += zunamiLp; require( _poolInfo[_receiverStrategyId].strategy.deposit(tokensRemainder) > 0, 'Zunami: Too low amount!' ); } function _moveFunds(uint256 pid, uint256 withdrawAmount) private returns (uint256) { uint256 currentLpAmount; if (withdrawAmount == FUNDS_DENOMINATOR) { _poolInfo[pid].strategy.withdrawAll(); currentLpAmount = _poolInfo[pid].lpShares; _poolInfo[pid].lpShares = 0; } else { currentLpAmount = (_poolInfo[pid].lpShares * withdrawAmount) / FUNDS_DENOMINATOR; uint256[POOL_ASSETS] memory minAmounts; _poolInfo[pid].strategy.withdraw( address(this), currentLpAmount * 1e18 / _poolInfo[pid].lpShares, minAmounts, IStrategy.WithdrawalType.Base, 0 ); _poolInfo[pid].lpShares = _poolInfo[pid].lpShares - currentLpAmount; } return currentLpAmount; } /** * @dev user remove his active pending deposit */ function pendingDepositRemove() external { for (uint256 i = 0; i < POOL_ASSETS; i++) { if (pendingDeposits[_msgSender()][i] > 0) { IERC20Metadata(tokens[i]).safeTransfer( _msgSender(), pendingDeposits[_msgSender()][i] ); } } delete pendingDeposits[_msgSender()]; } /** * @dev governance can withdraw all stuck funds in emergency case * @param _token - IERC20Metadata token that should be fully withdraw from Zunami */ function withdrawStuckToken(IERC20Metadata _token) external onlyRole(DEFAULT_ADMIN_ROLE) { uint256 tokenBalance = _token.balanceOf(address(this)); _token.safeTransfer(_msgSender(), tokenBalance); } /** * @dev governance can add new operator for complete pending deposits and withdrawals * @param _newOperator - address that governance add in list of operators */ function updateOperator(address _newOperator) external onlyRole(DEFAULT_ADMIN_ROLE) { _grantRole(OPERATOR_ROLE, _newOperator); } // Get bit value at position function checkBit(uint8 mask, uint8 bit) internal pure returns (bool) { return mask & (0x01 << bit) != 0; } }
/** * * @title Zunami Protocol * * @notice Contract for Convex&Curve protocols optimize. * Users can use this contract for optimize yield and gas. * * * @dev Zunami is main contract. * Contract does not store user funds. * All user funds goes to Convex&Curve pools. * */
NatSpecMultiLine
delegateWithdrawal
function delegateWithdrawal(uint256 lpAmount, uint256[3] memory minAmounts) external whenNotPaused { PendingWithdrawal memory withdrawal; address userAddr = _msgSender(); require(lpAmount > 0, 'Zunami: lpAmount must be higher 0'); withdrawal.lpShares = lpAmount; withdrawal.minAmounts = minAmounts; pendingWithdrawals[userAddr] = withdrawal; emit CreatedPendingWithdrawal(userAddr, minAmounts, lpAmount); }
/** * @dev in this func user sends pending withdraw to the contract and then waits * for the completion of the transaction for all users * @param lpAmount - amount of ZLP for withdraw * @param minAmounts - array of amounts stablecoins that user want minimum receive */
NatSpecMultiLine
v0.8.12+commit.f00d7308
{ "func_code_index": [ 6867, 7360 ] }
2,620
Zunami
contracts/Zunami.sol
0x9b43e47bec96a9345cd26fdde7efa5f8c06e126c
Solidity
Zunami
contract Zunami is ERC20, Pausable, AccessControl { using SafeERC20 for IERC20Metadata; bytes32 public constant OPERATOR_ROLE = keccak256('OPERATOR_ROLE'); struct PendingWithdrawal { uint256 lpShares; uint256[3] minAmounts; } struct PoolInfo { IStrategy strategy; uint256 startTime; uint256 lpShares; } uint8 public constant POOL_ASSETS = 3; uint256 public constant FEE_DENOMINATOR = 1000; uint256 public constant MIN_LOCK_TIME = 1 days; uint256 public constant FUNDS_DENOMINATOR = 10_000; uint8 public constant ALL_WITHDRAWAL_TYPES_MASK = uint8(7); // Binary 111 = 2^0 + 2^1 + 2^2; PoolInfo[] internal _poolInfo; uint256 public defaultDepositPid; uint256 public defaultWithdrawPid; uint8 public availableWithdrawalTypes; address[POOL_ASSETS] public tokens; uint256[POOL_ASSETS] public decimalsMultipliers; mapping(address => uint256[POOL_ASSETS]) public pendingDeposits; mapping(address => PendingWithdrawal) public pendingWithdrawals; uint256 public totalDeposited = 0; uint256 public managementFee = 100; // 10% bool public launched = false; event CreatedPendingDeposit(address indexed depositor, uint256[POOL_ASSETS] amounts); event CreatedPendingWithdrawal( address indexed withdrawer, uint256[POOL_ASSETS] amounts, uint256 lpShares ); event Deposited(address indexed depositor, uint256[POOL_ASSETS] amounts, uint256 lpShares); event Withdrawn(address indexed withdrawer, IStrategy.WithdrawalType withdrawalType, uint256[POOL_ASSETS] tokenAmounts, uint256 lpShares, uint128 tokenIndex); event AddedPool(uint256 pid, address strategyAddr, uint256 startTime); event FailedDeposit(address indexed depositor, uint256[POOL_ASSETS] amounts, uint256 lpShares); event FailedWithdrawal(address indexed withdrawer, uint256[POOL_ASSETS] amounts, uint256 lpShares); event SetDefaultDepositPid(uint256 pid); event SetDefaultWithdrawPid(uint256 pid); event ClaimedAllManagementFee(uint256 feeValue); event AutoCompoundAll(); modifier startedPool() { require(_poolInfo.length != 0, 'Zunami: pool not existed!'); require( block.timestamp >= _poolInfo[defaultDepositPid].startTime, 'Zunami: default deposit pool not started yet!' ); require( block.timestamp >= _poolInfo[defaultWithdrawPid].startTime, 'Zunami: default withdraw pool not started yet!' ); _; } constructor(address[POOL_ASSETS] memory _tokens) ERC20('ZunamiLP', 'ZLP') { tokens = _tokens; _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(OPERATOR_ROLE, msg.sender); for (uint256 i; i < POOL_ASSETS; i++) { uint256 decimals = IERC20Metadata(tokens[i]).decimals(); if (decimals < 18) { decimalsMultipliers[i] = 10**(18 - decimals); } else { decimalsMultipliers[i] = 1; } } availableWithdrawalTypes = ALL_WITHDRAWAL_TYPES_MASK; } function poolInfo(uint256 pid) external view returns (PoolInfo memory) { return _poolInfo[pid]; } function pause() external onlyRole(DEFAULT_ADMIN_ROLE) { _pause(); } function unpause() external onlyRole(DEFAULT_ADMIN_ROLE) { _unpause(); } function setAvailableWithdrawalTypes(uint8 newAvailableWithdrawalTypes) external onlyRole(DEFAULT_ADMIN_ROLE) { require(newAvailableWithdrawalTypes <= ALL_WITHDRAWAL_TYPES_MASK, 'Zunami: wrong available withdrawal types'); availableWithdrawalTypes = newAvailableWithdrawalTypes; } /** * @dev update managementFee, this is a Zunami commission from protocol profit * @param newManagementFee - minAmount 0, maxAmount FEE_DENOMINATOR - 1 */ function setManagementFee(uint256 newManagementFee) external onlyRole(DEFAULT_ADMIN_ROLE) { require(newManagementFee < FEE_DENOMINATOR, 'Zunami: wrong fee'); managementFee = newManagementFee; } /** * @dev Returns managementFee for strategy's when contract sell rewards * @return Returns commission on the amount of profit in the transaction * @param amount - amount of profit for calculate managementFee */ function calcManagementFee(uint256 amount) external view returns (uint256) { return (amount * managementFee) / FEE_DENOMINATOR; } /** * @dev Claims managementFee from all active strategies */ function claimAllManagementFee() external { uint256 feeTotalValue; for (uint256 i = 0; i < _poolInfo.length; i++) { feeTotalValue += _poolInfo[i].strategy.claimManagementFees(); } emit ClaimedAllManagementFee(feeTotalValue); } function autoCompoundAll() external { for (uint256 i = 0; i < _poolInfo.length; i++) { _poolInfo[i].strategy.autoCompound(); } emit AutoCompoundAll(); } /** * @dev Returns total holdings for all pools (strategy's) * @return Returns sum holdings (USD) for all pools */ function totalHoldings() public view returns (uint256) { uint256 length = _poolInfo.length; uint256 totalHold = 0; for (uint256 pid = 0; pid < length; pid++) { totalHold += _poolInfo[pid].strategy.totalHoldings(); } return totalHold; } /** * @dev Returns price depends on the income of users * @return Returns currently price of ZLP (1e18 = 1$) */ function lpPrice() external view returns (uint256) { return (totalHoldings() * 1e18) / totalSupply(); } /** * @dev Returns number of pools * @return number of pools */ function poolCount() external view returns (uint256) { return _poolInfo.length; } /** * @dev in this func user sends funds to the contract and then waits for the completion * of the transaction for all users * @param amounts - array of deposit amounts by user */ function delegateDeposit(uint256[3] memory amounts) external whenNotPaused { for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] > 0) { IERC20Metadata(tokens[i]).safeTransferFrom(_msgSender(), address(this), amounts[i]); pendingDeposits[_msgSender()][i] += amounts[i]; } } emit CreatedPendingDeposit(_msgSender(), amounts); } /** * @dev in this func user sends pending withdraw to the contract and then waits * for the completion of the transaction for all users * @param lpAmount - amount of ZLP for withdraw * @param minAmounts - array of amounts stablecoins that user want minimum receive */ function delegateWithdrawal(uint256 lpAmount, uint256[3] memory minAmounts) external whenNotPaused { PendingWithdrawal memory withdrawal; address userAddr = _msgSender(); require(lpAmount > 0, 'Zunami: lpAmount must be higher 0'); withdrawal.lpShares = lpAmount; withdrawal.minAmounts = minAmounts; pendingWithdrawals[userAddr] = withdrawal; emit CreatedPendingWithdrawal(userAddr, minAmounts, lpAmount); } /** * @dev Zunami protocol owner complete all active pending deposits of users * @param userList - dev send array of users from pending to complete */ function completeDeposits(address[] memory userList) external onlyRole(OPERATOR_ROLE) startedPool { IStrategy strategy = _poolInfo[defaultDepositPid].strategy; uint256 currentTotalHoldings = totalHoldings(); uint256 newHoldings = 0; uint256[3] memory totalAmounts; uint256[] memory userCompleteHoldings = new uint256[](userList.length); for (uint256 i = 0; i < userList.length; i++) { newHoldings = 0; for (uint256 x = 0; x < totalAmounts.length; x++) { uint256 userTokenDeposit = pendingDeposits[userList[i]][x]; totalAmounts[x] += userTokenDeposit; newHoldings += userTokenDeposit * decimalsMultipliers[x]; } userCompleteHoldings[i] = newHoldings; } newHoldings = 0; for (uint256 y = 0; y < POOL_ASSETS; y++) { uint256 totalTokenAmount = totalAmounts[y]; if (totalTokenAmount > 0) { newHoldings += totalTokenAmount * decimalsMultipliers[y]; IERC20Metadata(tokens[y]).safeTransfer(address(strategy), totalTokenAmount); } } uint256 totalDepositedNow = strategy.deposit(totalAmounts); require(totalDepositedNow > 0, 'Zunami: too low deposit!'); uint256 lpShares = 0; uint256 addedHoldings = 0; uint256 userDeposited = 0; for (uint256 z = 0; z < userList.length; z++) { userDeposited = (totalDepositedNow * userCompleteHoldings[z]) / newHoldings; address userAddr = userList[z]; if (totalSupply() == 0) { lpShares = userDeposited; } else { lpShares = (totalSupply() * userDeposited) / (currentTotalHoldings + addedHoldings); } addedHoldings += userDeposited; _mint(userAddr, lpShares); _poolInfo[defaultDepositPid].lpShares += lpShares; emit Deposited(userAddr, pendingDeposits[userAddr], lpShares); // remove deposit from list delete pendingDeposits[userAddr]; } totalDeposited += addedHoldings; } /** * @dev Zunami protocol owner complete all active pending withdrawals of users * @param userList - array of users from pending withdraw to complete */ function completeWithdrawals(address[] memory userList) external onlyRole(OPERATOR_ROLE) startedPool { require(userList.length > 0, 'Zunami: there are no pending withdrawals requests'); IStrategy strategy = _poolInfo[defaultWithdrawPid].strategy; address user; PendingWithdrawal memory withdrawal; for (uint256 i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; if (balanceOf(user) >= withdrawal.lpShares) { if ( !( strategy.withdraw( user, withdrawal.lpShares * 1e18 / _poolInfo[defaultWithdrawPid].lpShares, withdrawal.minAmounts, IStrategy.WithdrawalType.Base, 0 ) ) ) { emit FailedWithdrawal(user, withdrawal.minAmounts, withdrawal.lpShares); delete pendingWithdrawals[user]; continue; } uint256 userDeposit = (totalDeposited * withdrawal.lpShares) / totalSupply(); _burn(user, withdrawal.lpShares); _poolInfo[defaultWithdrawPid].lpShares -= withdrawal.lpShares; totalDeposited -= userDeposit; emit Withdrawn(user, IStrategy.WithdrawalType.Base, withdrawal.minAmounts, withdrawal.lpShares, 0); } delete pendingWithdrawals[user]; } } function completeWithdrawalsOptimized(address[] memory userList) external onlyRole(OPERATOR_ROLE) startedPool { require(userList.length > 0, 'Zunami: there are no pending withdrawals requests'); IStrategy strategy = _poolInfo[defaultWithdrawPid].strategy; uint256 lpSharesTotal; uint256[POOL_ASSETS] memory minAmountsTotal; uint256 i; address user; PendingWithdrawal memory withdrawal; for (i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; if (balanceOf(user) < withdrawal.lpShares) { emit FailedWithdrawal(user, withdrawal.minAmounts, withdrawal.lpShares); delete pendingWithdrawals[user]; continue; } lpSharesTotal += withdrawal.lpShares; minAmountsTotal[0] += withdrawal.minAmounts[0]; minAmountsTotal[1] += withdrawal.minAmounts[1]; minAmountsTotal[2] += withdrawal.minAmounts[2]; emit Withdrawn(user, IStrategy.WithdrawalType.Base, withdrawal.minAmounts, withdrawal.lpShares, 0); } require( lpSharesTotal <= _poolInfo[defaultWithdrawPid].lpShares, "Zunami: Insufficient pool LP shares"); uint256[POOL_ASSETS] memory prevBalances; for (i = 0; i < 3; i++) { prevBalances[i] = IERC20Metadata(tokens[i]).balanceOf(address(this)); } if( !strategy.withdraw(address(this), lpSharesTotal * 1e18 / _poolInfo[defaultWithdrawPid].lpShares, minAmountsTotal, IStrategy.WithdrawalType.Base, 0) ) { //TODO: do we really need to remove delegated requests for (i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; emit FailedWithdrawal(user, withdrawal.minAmounts, withdrawal.lpShares); delete pendingWithdrawals[user]; } return; } uint256[POOL_ASSETS] memory diffBalances; for (i = 0; i < 3; i++) { diffBalances[i] = IERC20Metadata(tokens[i]).balanceOf(address(this)) - prevBalances[i]; } for (i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; uint256 userDeposit = (totalDeposited * withdrawal.lpShares) / totalSupply(); _burn(user, withdrawal.lpShares); _poolInfo[defaultWithdrawPid].lpShares -= withdrawal.lpShares; totalDeposited -= userDeposit; for (uint256 j = 0; j < 3; j++) { IERC20Metadata(tokens[j]).safeTransfer( user, (diffBalances[j] * withdrawal.lpShares) / lpSharesTotal ); } delete pendingWithdrawals[user]; } } /** * @dev deposit in one tx, without waiting complete by dev * @return Returns amount of lpShares minted for user * @param amounts - user send amounts of stablecoins to deposit */ function deposit(uint256[POOL_ASSETS] memory amounts) external whenNotPaused startedPool returns (uint256) { IStrategy strategy = _poolInfo[defaultDepositPid].strategy; uint256 holdings = totalHoldings(); for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] > 0) { IERC20Metadata(tokens[i]).safeTransferFrom( _msgSender(), address(strategy), amounts[i] ); } } uint256 newDeposited = strategy.deposit(amounts); require(newDeposited > 0, 'Zunami: too low deposit!'); uint256 lpShares = 0; if (totalSupply() == 0) { lpShares = newDeposited; } else { lpShares = (totalSupply() * newDeposited) / holdings; } _mint(_msgSender(), lpShares); _poolInfo[defaultDepositPid].lpShares += lpShares; totalDeposited += newDeposited; emit Deposited(_msgSender(), amounts, lpShares); return lpShares; } /** * @dev withdraw in one tx, without waiting complete by dev * @param lpShares - amount of ZLP for withdraw * @param tokenAmounts - array of amounts stablecoins that user want minimum receive */ function withdraw( uint256 lpShares, uint256[POOL_ASSETS] memory tokenAmounts, IStrategy.WithdrawalType withdrawalType, uint128 tokenIndex ) external whenNotPaused startedPool { require( checkBit(availableWithdrawalTypes, uint8(withdrawalType)), 'Zunami: withdrawal type not available' ); IStrategy strategy = _poolInfo[defaultWithdrawPid].strategy; address userAddr = _msgSender(); require(balanceOf(userAddr) >= lpShares, 'Zunami: not enough LP balance'); require( strategy.withdraw(userAddr, lpShares * 1e18 / _poolInfo[defaultWithdrawPid].lpShares, tokenAmounts, withdrawalType, tokenIndex), 'Zunami: user lps share should be at least required' ); uint256 userDeposit = (totalDeposited * lpShares) / totalSupply(); _burn(userAddr, lpShares); _poolInfo[defaultWithdrawPid].lpShares -= lpShares; totalDeposited -= userDeposit; emit Withdrawn(userAddr, withdrawalType, tokenAmounts, lpShares, tokenIndex); } /** * @dev add a new pool, deposits in the new pool are blocked for one day for safety * @param _strategyAddr - the new pool strategy address */ function addPool(address _strategyAddr) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_strategyAddr != address(0), 'Zunami: zero strategy addr'); uint256 startTime = block.timestamp + (launched ? MIN_LOCK_TIME : 0); _poolInfo.push( PoolInfo({ strategy: IStrategy(_strategyAddr), startTime: startTime, lpShares: 0 }) ); emit AddedPool(_poolInfo.length - 1, _strategyAddr, startTime); } /** * @dev set a default pool for deposit funds * @param _newPoolId - new pool id */ function setDefaultDepositPid(uint256 _newPoolId) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_newPoolId < _poolInfo.length, 'Zunami: incorrect default deposit pool id'); defaultDepositPid = _newPoolId; emit SetDefaultDepositPid(_newPoolId); } /** * @dev set a default pool for withdraw funds * @param _newPoolId - new pool id */ function setDefaultWithdrawPid(uint256 _newPoolId) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_newPoolId < _poolInfo.length, 'Zunami: incorrect default withdraw pool id'); defaultWithdrawPid = _newPoolId; emit SetDefaultWithdrawPid(_newPoolId); } function launch() external onlyRole(DEFAULT_ADMIN_ROLE) { launched = true; } /** * @dev dev can transfer funds from few strategy's to one strategy for better APY * @param _strategies - array of strategy's, from which funds are withdrawn * @param withdrawalsPercents - A percentage of the funds that should be transfered * @param _receiverStrategyId - number strategy, to which funds are deposited */ function moveFundsBatch( uint256[] memory _strategies, uint256[] memory withdrawalsPercents, uint256 _receiverStrategyId ) external onlyRole(DEFAULT_ADMIN_ROLE) { require( _strategies.length == withdrawalsPercents.length, 'Zunami: incorrect arguments for the moveFundsBatch' ); require(_receiverStrategyId < _poolInfo.length, 'Zunami: incorrect a reciver strategy ID'); uint256[POOL_ASSETS] memory tokenBalance; for (uint256 y = 0; y < POOL_ASSETS; y++) { tokenBalance[y] = IERC20Metadata(tokens[y]).balanceOf(address(this)); } uint256 pid; uint256 zunamiLp; for (uint256 i = 0; i < _strategies.length; i++) { pid = _strategies[i]; zunamiLp += _moveFunds(pid, withdrawalsPercents[i]); } uint256[POOL_ASSETS] memory tokensRemainder; for (uint256 y = 0; y < POOL_ASSETS; y++) { tokensRemainder[y] = IERC20Metadata(tokens[y]).balanceOf(address(this)) - tokenBalance[y]; if (tokensRemainder[y] > 0) { IERC20Metadata(tokens[y]).safeTransfer( address(_poolInfo[_receiverStrategyId].strategy), tokensRemainder[y] ); } } _poolInfo[_receiverStrategyId].lpShares += zunamiLp; require( _poolInfo[_receiverStrategyId].strategy.deposit(tokensRemainder) > 0, 'Zunami: Too low amount!' ); } function _moveFunds(uint256 pid, uint256 withdrawAmount) private returns (uint256) { uint256 currentLpAmount; if (withdrawAmount == FUNDS_DENOMINATOR) { _poolInfo[pid].strategy.withdrawAll(); currentLpAmount = _poolInfo[pid].lpShares; _poolInfo[pid].lpShares = 0; } else { currentLpAmount = (_poolInfo[pid].lpShares * withdrawAmount) / FUNDS_DENOMINATOR; uint256[POOL_ASSETS] memory minAmounts; _poolInfo[pid].strategy.withdraw( address(this), currentLpAmount * 1e18 / _poolInfo[pid].lpShares, minAmounts, IStrategy.WithdrawalType.Base, 0 ); _poolInfo[pid].lpShares = _poolInfo[pid].lpShares - currentLpAmount; } return currentLpAmount; } /** * @dev user remove his active pending deposit */ function pendingDepositRemove() external { for (uint256 i = 0; i < POOL_ASSETS; i++) { if (pendingDeposits[_msgSender()][i] > 0) { IERC20Metadata(tokens[i]).safeTransfer( _msgSender(), pendingDeposits[_msgSender()][i] ); } } delete pendingDeposits[_msgSender()]; } /** * @dev governance can withdraw all stuck funds in emergency case * @param _token - IERC20Metadata token that should be fully withdraw from Zunami */ function withdrawStuckToken(IERC20Metadata _token) external onlyRole(DEFAULT_ADMIN_ROLE) { uint256 tokenBalance = _token.balanceOf(address(this)); _token.safeTransfer(_msgSender(), tokenBalance); } /** * @dev governance can add new operator for complete pending deposits and withdrawals * @param _newOperator - address that governance add in list of operators */ function updateOperator(address _newOperator) external onlyRole(DEFAULT_ADMIN_ROLE) { _grantRole(OPERATOR_ROLE, _newOperator); } // Get bit value at position function checkBit(uint8 mask, uint8 bit) internal pure returns (bool) { return mask & (0x01 << bit) != 0; } }
/** * * @title Zunami Protocol * * @notice Contract for Convex&Curve protocols optimize. * Users can use this contract for optimize yield and gas. * * * @dev Zunami is main contract. * Contract does not store user funds. * All user funds goes to Convex&Curve pools. * */
NatSpecMultiLine
completeDeposits
function completeDeposits(address[] memory userList) external onlyRole(OPERATOR_ROLE) startedPool { IStrategy strategy = _poolInfo[defaultDepositPid].strategy; uint256 currentTotalHoldings = totalHoldings(); uint256 newHoldings = 0; uint256[3] memory totalAmounts; uint256[] memory userCompleteHoldings = new uint256[](userList.length); for (uint256 i = 0; i < userList.length; i++) { newHoldings = 0; for (uint256 x = 0; x < totalAmounts.length; x++) { uint256 userTokenDeposit = pendingDeposits[userList[i]][x]; totalAmounts[x] += userTokenDeposit; newHoldings += userTokenDeposit * decimalsMultipliers[x]; } userCompleteHoldings[i] = newHoldings; } newHoldings = 0; for (uint256 y = 0; y < POOL_ASSETS; y++) { uint256 totalTokenAmount = totalAmounts[y]; if (totalTokenAmount > 0) { newHoldings += totalTokenAmount * decimalsMultipliers[y]; IERC20Metadata(tokens[y]).safeTransfer(address(strategy), totalTokenAmount); } } uint256 totalDepositedNow = strategy.deposit(totalAmounts); require(totalDepositedNow > 0, 'Zunami: too low deposit!'); uint256 lpShares = 0; uint256 addedHoldings = 0; uint256 userDeposited = 0; for (uint256 z = 0; z < userList.length; z++) { userDeposited = (totalDepositedNow * userCompleteHoldings[z]) / newHoldings; address userAddr = userList[z]; if (totalSupply() == 0) { lpShares = userDeposited; } else { lpShares = (totalSupply() * userDeposited) / (currentTotalHoldings + addedHoldings); } addedHoldings += userDeposited; _mint(userAddr, lpShares); _poolInfo[defaultDepositPid].lpShares += lpShares; emit Deposited(userAddr, pendingDeposits[userAddr], lpShares); // remove deposit from list delete pendingDeposits[userAddr]; } totalDeposited += addedHoldings; }
/** * @dev Zunami protocol owner complete all active pending deposits of users * @param userList - dev send array of users from pending to complete */
NatSpecMultiLine
v0.8.12+commit.f00d7308
{ "func_code_index": [ 7532, 9741 ] }
2,621
Zunami
contracts/Zunami.sol
0x9b43e47bec96a9345cd26fdde7efa5f8c06e126c
Solidity
Zunami
contract Zunami is ERC20, Pausable, AccessControl { using SafeERC20 for IERC20Metadata; bytes32 public constant OPERATOR_ROLE = keccak256('OPERATOR_ROLE'); struct PendingWithdrawal { uint256 lpShares; uint256[3] minAmounts; } struct PoolInfo { IStrategy strategy; uint256 startTime; uint256 lpShares; } uint8 public constant POOL_ASSETS = 3; uint256 public constant FEE_DENOMINATOR = 1000; uint256 public constant MIN_LOCK_TIME = 1 days; uint256 public constant FUNDS_DENOMINATOR = 10_000; uint8 public constant ALL_WITHDRAWAL_TYPES_MASK = uint8(7); // Binary 111 = 2^0 + 2^1 + 2^2; PoolInfo[] internal _poolInfo; uint256 public defaultDepositPid; uint256 public defaultWithdrawPid; uint8 public availableWithdrawalTypes; address[POOL_ASSETS] public tokens; uint256[POOL_ASSETS] public decimalsMultipliers; mapping(address => uint256[POOL_ASSETS]) public pendingDeposits; mapping(address => PendingWithdrawal) public pendingWithdrawals; uint256 public totalDeposited = 0; uint256 public managementFee = 100; // 10% bool public launched = false; event CreatedPendingDeposit(address indexed depositor, uint256[POOL_ASSETS] amounts); event CreatedPendingWithdrawal( address indexed withdrawer, uint256[POOL_ASSETS] amounts, uint256 lpShares ); event Deposited(address indexed depositor, uint256[POOL_ASSETS] amounts, uint256 lpShares); event Withdrawn(address indexed withdrawer, IStrategy.WithdrawalType withdrawalType, uint256[POOL_ASSETS] tokenAmounts, uint256 lpShares, uint128 tokenIndex); event AddedPool(uint256 pid, address strategyAddr, uint256 startTime); event FailedDeposit(address indexed depositor, uint256[POOL_ASSETS] amounts, uint256 lpShares); event FailedWithdrawal(address indexed withdrawer, uint256[POOL_ASSETS] amounts, uint256 lpShares); event SetDefaultDepositPid(uint256 pid); event SetDefaultWithdrawPid(uint256 pid); event ClaimedAllManagementFee(uint256 feeValue); event AutoCompoundAll(); modifier startedPool() { require(_poolInfo.length != 0, 'Zunami: pool not existed!'); require( block.timestamp >= _poolInfo[defaultDepositPid].startTime, 'Zunami: default deposit pool not started yet!' ); require( block.timestamp >= _poolInfo[defaultWithdrawPid].startTime, 'Zunami: default withdraw pool not started yet!' ); _; } constructor(address[POOL_ASSETS] memory _tokens) ERC20('ZunamiLP', 'ZLP') { tokens = _tokens; _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(OPERATOR_ROLE, msg.sender); for (uint256 i; i < POOL_ASSETS; i++) { uint256 decimals = IERC20Metadata(tokens[i]).decimals(); if (decimals < 18) { decimalsMultipliers[i] = 10**(18 - decimals); } else { decimalsMultipliers[i] = 1; } } availableWithdrawalTypes = ALL_WITHDRAWAL_TYPES_MASK; } function poolInfo(uint256 pid) external view returns (PoolInfo memory) { return _poolInfo[pid]; } function pause() external onlyRole(DEFAULT_ADMIN_ROLE) { _pause(); } function unpause() external onlyRole(DEFAULT_ADMIN_ROLE) { _unpause(); } function setAvailableWithdrawalTypes(uint8 newAvailableWithdrawalTypes) external onlyRole(DEFAULT_ADMIN_ROLE) { require(newAvailableWithdrawalTypes <= ALL_WITHDRAWAL_TYPES_MASK, 'Zunami: wrong available withdrawal types'); availableWithdrawalTypes = newAvailableWithdrawalTypes; } /** * @dev update managementFee, this is a Zunami commission from protocol profit * @param newManagementFee - minAmount 0, maxAmount FEE_DENOMINATOR - 1 */ function setManagementFee(uint256 newManagementFee) external onlyRole(DEFAULT_ADMIN_ROLE) { require(newManagementFee < FEE_DENOMINATOR, 'Zunami: wrong fee'); managementFee = newManagementFee; } /** * @dev Returns managementFee for strategy's when contract sell rewards * @return Returns commission on the amount of profit in the transaction * @param amount - amount of profit for calculate managementFee */ function calcManagementFee(uint256 amount) external view returns (uint256) { return (amount * managementFee) / FEE_DENOMINATOR; } /** * @dev Claims managementFee from all active strategies */ function claimAllManagementFee() external { uint256 feeTotalValue; for (uint256 i = 0; i < _poolInfo.length; i++) { feeTotalValue += _poolInfo[i].strategy.claimManagementFees(); } emit ClaimedAllManagementFee(feeTotalValue); } function autoCompoundAll() external { for (uint256 i = 0; i < _poolInfo.length; i++) { _poolInfo[i].strategy.autoCompound(); } emit AutoCompoundAll(); } /** * @dev Returns total holdings for all pools (strategy's) * @return Returns sum holdings (USD) for all pools */ function totalHoldings() public view returns (uint256) { uint256 length = _poolInfo.length; uint256 totalHold = 0; for (uint256 pid = 0; pid < length; pid++) { totalHold += _poolInfo[pid].strategy.totalHoldings(); } return totalHold; } /** * @dev Returns price depends on the income of users * @return Returns currently price of ZLP (1e18 = 1$) */ function lpPrice() external view returns (uint256) { return (totalHoldings() * 1e18) / totalSupply(); } /** * @dev Returns number of pools * @return number of pools */ function poolCount() external view returns (uint256) { return _poolInfo.length; } /** * @dev in this func user sends funds to the contract and then waits for the completion * of the transaction for all users * @param amounts - array of deposit amounts by user */ function delegateDeposit(uint256[3] memory amounts) external whenNotPaused { for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] > 0) { IERC20Metadata(tokens[i]).safeTransferFrom(_msgSender(), address(this), amounts[i]); pendingDeposits[_msgSender()][i] += amounts[i]; } } emit CreatedPendingDeposit(_msgSender(), amounts); } /** * @dev in this func user sends pending withdraw to the contract and then waits * for the completion of the transaction for all users * @param lpAmount - amount of ZLP for withdraw * @param minAmounts - array of amounts stablecoins that user want minimum receive */ function delegateWithdrawal(uint256 lpAmount, uint256[3] memory minAmounts) external whenNotPaused { PendingWithdrawal memory withdrawal; address userAddr = _msgSender(); require(lpAmount > 0, 'Zunami: lpAmount must be higher 0'); withdrawal.lpShares = lpAmount; withdrawal.minAmounts = minAmounts; pendingWithdrawals[userAddr] = withdrawal; emit CreatedPendingWithdrawal(userAddr, minAmounts, lpAmount); } /** * @dev Zunami protocol owner complete all active pending deposits of users * @param userList - dev send array of users from pending to complete */ function completeDeposits(address[] memory userList) external onlyRole(OPERATOR_ROLE) startedPool { IStrategy strategy = _poolInfo[defaultDepositPid].strategy; uint256 currentTotalHoldings = totalHoldings(); uint256 newHoldings = 0; uint256[3] memory totalAmounts; uint256[] memory userCompleteHoldings = new uint256[](userList.length); for (uint256 i = 0; i < userList.length; i++) { newHoldings = 0; for (uint256 x = 0; x < totalAmounts.length; x++) { uint256 userTokenDeposit = pendingDeposits[userList[i]][x]; totalAmounts[x] += userTokenDeposit; newHoldings += userTokenDeposit * decimalsMultipliers[x]; } userCompleteHoldings[i] = newHoldings; } newHoldings = 0; for (uint256 y = 0; y < POOL_ASSETS; y++) { uint256 totalTokenAmount = totalAmounts[y]; if (totalTokenAmount > 0) { newHoldings += totalTokenAmount * decimalsMultipliers[y]; IERC20Metadata(tokens[y]).safeTransfer(address(strategy), totalTokenAmount); } } uint256 totalDepositedNow = strategy.deposit(totalAmounts); require(totalDepositedNow > 0, 'Zunami: too low deposit!'); uint256 lpShares = 0; uint256 addedHoldings = 0; uint256 userDeposited = 0; for (uint256 z = 0; z < userList.length; z++) { userDeposited = (totalDepositedNow * userCompleteHoldings[z]) / newHoldings; address userAddr = userList[z]; if (totalSupply() == 0) { lpShares = userDeposited; } else { lpShares = (totalSupply() * userDeposited) / (currentTotalHoldings + addedHoldings); } addedHoldings += userDeposited; _mint(userAddr, lpShares); _poolInfo[defaultDepositPid].lpShares += lpShares; emit Deposited(userAddr, pendingDeposits[userAddr], lpShares); // remove deposit from list delete pendingDeposits[userAddr]; } totalDeposited += addedHoldings; } /** * @dev Zunami protocol owner complete all active pending withdrawals of users * @param userList - array of users from pending withdraw to complete */ function completeWithdrawals(address[] memory userList) external onlyRole(OPERATOR_ROLE) startedPool { require(userList.length > 0, 'Zunami: there are no pending withdrawals requests'); IStrategy strategy = _poolInfo[defaultWithdrawPid].strategy; address user; PendingWithdrawal memory withdrawal; for (uint256 i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; if (balanceOf(user) >= withdrawal.lpShares) { if ( !( strategy.withdraw( user, withdrawal.lpShares * 1e18 / _poolInfo[defaultWithdrawPid].lpShares, withdrawal.minAmounts, IStrategy.WithdrawalType.Base, 0 ) ) ) { emit FailedWithdrawal(user, withdrawal.minAmounts, withdrawal.lpShares); delete pendingWithdrawals[user]; continue; } uint256 userDeposit = (totalDeposited * withdrawal.lpShares) / totalSupply(); _burn(user, withdrawal.lpShares); _poolInfo[defaultWithdrawPid].lpShares -= withdrawal.lpShares; totalDeposited -= userDeposit; emit Withdrawn(user, IStrategy.WithdrawalType.Base, withdrawal.minAmounts, withdrawal.lpShares, 0); } delete pendingWithdrawals[user]; } } function completeWithdrawalsOptimized(address[] memory userList) external onlyRole(OPERATOR_ROLE) startedPool { require(userList.length > 0, 'Zunami: there are no pending withdrawals requests'); IStrategy strategy = _poolInfo[defaultWithdrawPid].strategy; uint256 lpSharesTotal; uint256[POOL_ASSETS] memory minAmountsTotal; uint256 i; address user; PendingWithdrawal memory withdrawal; for (i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; if (balanceOf(user) < withdrawal.lpShares) { emit FailedWithdrawal(user, withdrawal.minAmounts, withdrawal.lpShares); delete pendingWithdrawals[user]; continue; } lpSharesTotal += withdrawal.lpShares; minAmountsTotal[0] += withdrawal.minAmounts[0]; minAmountsTotal[1] += withdrawal.minAmounts[1]; minAmountsTotal[2] += withdrawal.minAmounts[2]; emit Withdrawn(user, IStrategy.WithdrawalType.Base, withdrawal.minAmounts, withdrawal.lpShares, 0); } require( lpSharesTotal <= _poolInfo[defaultWithdrawPid].lpShares, "Zunami: Insufficient pool LP shares"); uint256[POOL_ASSETS] memory prevBalances; for (i = 0; i < 3; i++) { prevBalances[i] = IERC20Metadata(tokens[i]).balanceOf(address(this)); } if( !strategy.withdraw(address(this), lpSharesTotal * 1e18 / _poolInfo[defaultWithdrawPid].lpShares, minAmountsTotal, IStrategy.WithdrawalType.Base, 0) ) { //TODO: do we really need to remove delegated requests for (i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; emit FailedWithdrawal(user, withdrawal.minAmounts, withdrawal.lpShares); delete pendingWithdrawals[user]; } return; } uint256[POOL_ASSETS] memory diffBalances; for (i = 0; i < 3; i++) { diffBalances[i] = IERC20Metadata(tokens[i]).balanceOf(address(this)) - prevBalances[i]; } for (i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; uint256 userDeposit = (totalDeposited * withdrawal.lpShares) / totalSupply(); _burn(user, withdrawal.lpShares); _poolInfo[defaultWithdrawPid].lpShares -= withdrawal.lpShares; totalDeposited -= userDeposit; for (uint256 j = 0; j < 3; j++) { IERC20Metadata(tokens[j]).safeTransfer( user, (diffBalances[j] * withdrawal.lpShares) / lpSharesTotal ); } delete pendingWithdrawals[user]; } } /** * @dev deposit in one tx, without waiting complete by dev * @return Returns amount of lpShares minted for user * @param amounts - user send amounts of stablecoins to deposit */ function deposit(uint256[POOL_ASSETS] memory amounts) external whenNotPaused startedPool returns (uint256) { IStrategy strategy = _poolInfo[defaultDepositPid].strategy; uint256 holdings = totalHoldings(); for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] > 0) { IERC20Metadata(tokens[i]).safeTransferFrom( _msgSender(), address(strategy), amounts[i] ); } } uint256 newDeposited = strategy.deposit(amounts); require(newDeposited > 0, 'Zunami: too low deposit!'); uint256 lpShares = 0; if (totalSupply() == 0) { lpShares = newDeposited; } else { lpShares = (totalSupply() * newDeposited) / holdings; } _mint(_msgSender(), lpShares); _poolInfo[defaultDepositPid].lpShares += lpShares; totalDeposited += newDeposited; emit Deposited(_msgSender(), amounts, lpShares); return lpShares; } /** * @dev withdraw in one tx, without waiting complete by dev * @param lpShares - amount of ZLP for withdraw * @param tokenAmounts - array of amounts stablecoins that user want minimum receive */ function withdraw( uint256 lpShares, uint256[POOL_ASSETS] memory tokenAmounts, IStrategy.WithdrawalType withdrawalType, uint128 tokenIndex ) external whenNotPaused startedPool { require( checkBit(availableWithdrawalTypes, uint8(withdrawalType)), 'Zunami: withdrawal type not available' ); IStrategy strategy = _poolInfo[defaultWithdrawPid].strategy; address userAddr = _msgSender(); require(balanceOf(userAddr) >= lpShares, 'Zunami: not enough LP balance'); require( strategy.withdraw(userAddr, lpShares * 1e18 / _poolInfo[defaultWithdrawPid].lpShares, tokenAmounts, withdrawalType, tokenIndex), 'Zunami: user lps share should be at least required' ); uint256 userDeposit = (totalDeposited * lpShares) / totalSupply(); _burn(userAddr, lpShares); _poolInfo[defaultWithdrawPid].lpShares -= lpShares; totalDeposited -= userDeposit; emit Withdrawn(userAddr, withdrawalType, tokenAmounts, lpShares, tokenIndex); } /** * @dev add a new pool, deposits in the new pool are blocked for one day for safety * @param _strategyAddr - the new pool strategy address */ function addPool(address _strategyAddr) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_strategyAddr != address(0), 'Zunami: zero strategy addr'); uint256 startTime = block.timestamp + (launched ? MIN_LOCK_TIME : 0); _poolInfo.push( PoolInfo({ strategy: IStrategy(_strategyAddr), startTime: startTime, lpShares: 0 }) ); emit AddedPool(_poolInfo.length - 1, _strategyAddr, startTime); } /** * @dev set a default pool for deposit funds * @param _newPoolId - new pool id */ function setDefaultDepositPid(uint256 _newPoolId) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_newPoolId < _poolInfo.length, 'Zunami: incorrect default deposit pool id'); defaultDepositPid = _newPoolId; emit SetDefaultDepositPid(_newPoolId); } /** * @dev set a default pool for withdraw funds * @param _newPoolId - new pool id */ function setDefaultWithdrawPid(uint256 _newPoolId) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_newPoolId < _poolInfo.length, 'Zunami: incorrect default withdraw pool id'); defaultWithdrawPid = _newPoolId; emit SetDefaultWithdrawPid(_newPoolId); } function launch() external onlyRole(DEFAULT_ADMIN_ROLE) { launched = true; } /** * @dev dev can transfer funds from few strategy's to one strategy for better APY * @param _strategies - array of strategy's, from which funds are withdrawn * @param withdrawalsPercents - A percentage of the funds that should be transfered * @param _receiverStrategyId - number strategy, to which funds are deposited */ function moveFundsBatch( uint256[] memory _strategies, uint256[] memory withdrawalsPercents, uint256 _receiverStrategyId ) external onlyRole(DEFAULT_ADMIN_ROLE) { require( _strategies.length == withdrawalsPercents.length, 'Zunami: incorrect arguments for the moveFundsBatch' ); require(_receiverStrategyId < _poolInfo.length, 'Zunami: incorrect a reciver strategy ID'); uint256[POOL_ASSETS] memory tokenBalance; for (uint256 y = 0; y < POOL_ASSETS; y++) { tokenBalance[y] = IERC20Metadata(tokens[y]).balanceOf(address(this)); } uint256 pid; uint256 zunamiLp; for (uint256 i = 0; i < _strategies.length; i++) { pid = _strategies[i]; zunamiLp += _moveFunds(pid, withdrawalsPercents[i]); } uint256[POOL_ASSETS] memory tokensRemainder; for (uint256 y = 0; y < POOL_ASSETS; y++) { tokensRemainder[y] = IERC20Metadata(tokens[y]).balanceOf(address(this)) - tokenBalance[y]; if (tokensRemainder[y] > 0) { IERC20Metadata(tokens[y]).safeTransfer( address(_poolInfo[_receiverStrategyId].strategy), tokensRemainder[y] ); } } _poolInfo[_receiverStrategyId].lpShares += zunamiLp; require( _poolInfo[_receiverStrategyId].strategy.deposit(tokensRemainder) > 0, 'Zunami: Too low amount!' ); } function _moveFunds(uint256 pid, uint256 withdrawAmount) private returns (uint256) { uint256 currentLpAmount; if (withdrawAmount == FUNDS_DENOMINATOR) { _poolInfo[pid].strategy.withdrawAll(); currentLpAmount = _poolInfo[pid].lpShares; _poolInfo[pid].lpShares = 0; } else { currentLpAmount = (_poolInfo[pid].lpShares * withdrawAmount) / FUNDS_DENOMINATOR; uint256[POOL_ASSETS] memory minAmounts; _poolInfo[pid].strategy.withdraw( address(this), currentLpAmount * 1e18 / _poolInfo[pid].lpShares, minAmounts, IStrategy.WithdrawalType.Base, 0 ); _poolInfo[pid].lpShares = _poolInfo[pid].lpShares - currentLpAmount; } return currentLpAmount; } /** * @dev user remove his active pending deposit */ function pendingDepositRemove() external { for (uint256 i = 0; i < POOL_ASSETS; i++) { if (pendingDeposits[_msgSender()][i] > 0) { IERC20Metadata(tokens[i]).safeTransfer( _msgSender(), pendingDeposits[_msgSender()][i] ); } } delete pendingDeposits[_msgSender()]; } /** * @dev governance can withdraw all stuck funds in emergency case * @param _token - IERC20Metadata token that should be fully withdraw from Zunami */ function withdrawStuckToken(IERC20Metadata _token) external onlyRole(DEFAULT_ADMIN_ROLE) { uint256 tokenBalance = _token.balanceOf(address(this)); _token.safeTransfer(_msgSender(), tokenBalance); } /** * @dev governance can add new operator for complete pending deposits and withdrawals * @param _newOperator - address that governance add in list of operators */ function updateOperator(address _newOperator) external onlyRole(DEFAULT_ADMIN_ROLE) { _grantRole(OPERATOR_ROLE, _newOperator); } // Get bit value at position function checkBit(uint8 mask, uint8 bit) internal pure returns (bool) { return mask & (0x01 << bit) != 0; } }
/** * * @title Zunami Protocol * * @notice Contract for Convex&Curve protocols optimize. * Users can use this contract for optimize yield and gas. * * * @dev Zunami is main contract. * Contract does not store user funds. * All user funds goes to Convex&Curve pools. * */
NatSpecMultiLine
completeWithdrawals
function completeWithdrawals(address[] memory userList) external onlyRole(OPERATOR_ROLE) startedPool { require(userList.length > 0, 'Zunami: there are no pending withdrawals requests'); IStrategy strategy = _poolInfo[defaultWithdrawPid].strategy; address user; PendingWithdrawal memory withdrawal; for (uint256 i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; if (balanceOf(user) >= withdrawal.lpShares) { if ( !( strategy.withdraw( user, withdrawal.lpShares * 1e18 / _poolInfo[defaultWithdrawPid].lpShares, withdrawal.minAmounts, IStrategy.WithdrawalType.Base, 0 ) ) ) { emit FailedWithdrawal(user, withdrawal.minAmounts, withdrawal.lpShares); delete pendingWithdrawals[user]; continue; } uint256 userDeposit = (totalDeposited * withdrawal.lpShares) / totalSupply(); _burn(user, withdrawal.lpShares); _poolInfo[defaultWithdrawPid].lpShares -= withdrawal.lpShares; totalDeposited -= userDeposit; emit Withdrawn(user, IStrategy.WithdrawalType.Base, withdrawal.minAmounts, withdrawal.lpShares, 0); } delete pendingWithdrawals[user]; } }
/** * @dev Zunami protocol owner complete all active pending withdrawals of users * @param userList - array of users from pending withdraw to complete */
NatSpecMultiLine
v0.8.12+commit.f00d7308
{ "func_code_index": [ 9916, 11561 ] }
2,622
Zunami
contracts/Zunami.sol
0x9b43e47bec96a9345cd26fdde7efa5f8c06e126c
Solidity
Zunami
contract Zunami is ERC20, Pausable, AccessControl { using SafeERC20 for IERC20Metadata; bytes32 public constant OPERATOR_ROLE = keccak256('OPERATOR_ROLE'); struct PendingWithdrawal { uint256 lpShares; uint256[3] minAmounts; } struct PoolInfo { IStrategy strategy; uint256 startTime; uint256 lpShares; } uint8 public constant POOL_ASSETS = 3; uint256 public constant FEE_DENOMINATOR = 1000; uint256 public constant MIN_LOCK_TIME = 1 days; uint256 public constant FUNDS_DENOMINATOR = 10_000; uint8 public constant ALL_WITHDRAWAL_TYPES_MASK = uint8(7); // Binary 111 = 2^0 + 2^1 + 2^2; PoolInfo[] internal _poolInfo; uint256 public defaultDepositPid; uint256 public defaultWithdrawPid; uint8 public availableWithdrawalTypes; address[POOL_ASSETS] public tokens; uint256[POOL_ASSETS] public decimalsMultipliers; mapping(address => uint256[POOL_ASSETS]) public pendingDeposits; mapping(address => PendingWithdrawal) public pendingWithdrawals; uint256 public totalDeposited = 0; uint256 public managementFee = 100; // 10% bool public launched = false; event CreatedPendingDeposit(address indexed depositor, uint256[POOL_ASSETS] amounts); event CreatedPendingWithdrawal( address indexed withdrawer, uint256[POOL_ASSETS] amounts, uint256 lpShares ); event Deposited(address indexed depositor, uint256[POOL_ASSETS] amounts, uint256 lpShares); event Withdrawn(address indexed withdrawer, IStrategy.WithdrawalType withdrawalType, uint256[POOL_ASSETS] tokenAmounts, uint256 lpShares, uint128 tokenIndex); event AddedPool(uint256 pid, address strategyAddr, uint256 startTime); event FailedDeposit(address indexed depositor, uint256[POOL_ASSETS] amounts, uint256 lpShares); event FailedWithdrawal(address indexed withdrawer, uint256[POOL_ASSETS] amounts, uint256 lpShares); event SetDefaultDepositPid(uint256 pid); event SetDefaultWithdrawPid(uint256 pid); event ClaimedAllManagementFee(uint256 feeValue); event AutoCompoundAll(); modifier startedPool() { require(_poolInfo.length != 0, 'Zunami: pool not existed!'); require( block.timestamp >= _poolInfo[defaultDepositPid].startTime, 'Zunami: default deposit pool not started yet!' ); require( block.timestamp >= _poolInfo[defaultWithdrawPid].startTime, 'Zunami: default withdraw pool not started yet!' ); _; } constructor(address[POOL_ASSETS] memory _tokens) ERC20('ZunamiLP', 'ZLP') { tokens = _tokens; _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(OPERATOR_ROLE, msg.sender); for (uint256 i; i < POOL_ASSETS; i++) { uint256 decimals = IERC20Metadata(tokens[i]).decimals(); if (decimals < 18) { decimalsMultipliers[i] = 10**(18 - decimals); } else { decimalsMultipliers[i] = 1; } } availableWithdrawalTypes = ALL_WITHDRAWAL_TYPES_MASK; } function poolInfo(uint256 pid) external view returns (PoolInfo memory) { return _poolInfo[pid]; } function pause() external onlyRole(DEFAULT_ADMIN_ROLE) { _pause(); } function unpause() external onlyRole(DEFAULT_ADMIN_ROLE) { _unpause(); } function setAvailableWithdrawalTypes(uint8 newAvailableWithdrawalTypes) external onlyRole(DEFAULT_ADMIN_ROLE) { require(newAvailableWithdrawalTypes <= ALL_WITHDRAWAL_TYPES_MASK, 'Zunami: wrong available withdrawal types'); availableWithdrawalTypes = newAvailableWithdrawalTypes; } /** * @dev update managementFee, this is a Zunami commission from protocol profit * @param newManagementFee - minAmount 0, maxAmount FEE_DENOMINATOR - 1 */ function setManagementFee(uint256 newManagementFee) external onlyRole(DEFAULT_ADMIN_ROLE) { require(newManagementFee < FEE_DENOMINATOR, 'Zunami: wrong fee'); managementFee = newManagementFee; } /** * @dev Returns managementFee for strategy's when contract sell rewards * @return Returns commission on the amount of profit in the transaction * @param amount - amount of profit for calculate managementFee */ function calcManagementFee(uint256 amount) external view returns (uint256) { return (amount * managementFee) / FEE_DENOMINATOR; } /** * @dev Claims managementFee from all active strategies */ function claimAllManagementFee() external { uint256 feeTotalValue; for (uint256 i = 0; i < _poolInfo.length; i++) { feeTotalValue += _poolInfo[i].strategy.claimManagementFees(); } emit ClaimedAllManagementFee(feeTotalValue); } function autoCompoundAll() external { for (uint256 i = 0; i < _poolInfo.length; i++) { _poolInfo[i].strategy.autoCompound(); } emit AutoCompoundAll(); } /** * @dev Returns total holdings for all pools (strategy's) * @return Returns sum holdings (USD) for all pools */ function totalHoldings() public view returns (uint256) { uint256 length = _poolInfo.length; uint256 totalHold = 0; for (uint256 pid = 0; pid < length; pid++) { totalHold += _poolInfo[pid].strategy.totalHoldings(); } return totalHold; } /** * @dev Returns price depends on the income of users * @return Returns currently price of ZLP (1e18 = 1$) */ function lpPrice() external view returns (uint256) { return (totalHoldings() * 1e18) / totalSupply(); } /** * @dev Returns number of pools * @return number of pools */ function poolCount() external view returns (uint256) { return _poolInfo.length; } /** * @dev in this func user sends funds to the contract and then waits for the completion * of the transaction for all users * @param amounts - array of deposit amounts by user */ function delegateDeposit(uint256[3] memory amounts) external whenNotPaused { for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] > 0) { IERC20Metadata(tokens[i]).safeTransferFrom(_msgSender(), address(this), amounts[i]); pendingDeposits[_msgSender()][i] += amounts[i]; } } emit CreatedPendingDeposit(_msgSender(), amounts); } /** * @dev in this func user sends pending withdraw to the contract and then waits * for the completion of the transaction for all users * @param lpAmount - amount of ZLP for withdraw * @param minAmounts - array of amounts stablecoins that user want minimum receive */ function delegateWithdrawal(uint256 lpAmount, uint256[3] memory minAmounts) external whenNotPaused { PendingWithdrawal memory withdrawal; address userAddr = _msgSender(); require(lpAmount > 0, 'Zunami: lpAmount must be higher 0'); withdrawal.lpShares = lpAmount; withdrawal.minAmounts = minAmounts; pendingWithdrawals[userAddr] = withdrawal; emit CreatedPendingWithdrawal(userAddr, minAmounts, lpAmount); } /** * @dev Zunami protocol owner complete all active pending deposits of users * @param userList - dev send array of users from pending to complete */ function completeDeposits(address[] memory userList) external onlyRole(OPERATOR_ROLE) startedPool { IStrategy strategy = _poolInfo[defaultDepositPid].strategy; uint256 currentTotalHoldings = totalHoldings(); uint256 newHoldings = 0; uint256[3] memory totalAmounts; uint256[] memory userCompleteHoldings = new uint256[](userList.length); for (uint256 i = 0; i < userList.length; i++) { newHoldings = 0; for (uint256 x = 0; x < totalAmounts.length; x++) { uint256 userTokenDeposit = pendingDeposits[userList[i]][x]; totalAmounts[x] += userTokenDeposit; newHoldings += userTokenDeposit * decimalsMultipliers[x]; } userCompleteHoldings[i] = newHoldings; } newHoldings = 0; for (uint256 y = 0; y < POOL_ASSETS; y++) { uint256 totalTokenAmount = totalAmounts[y]; if (totalTokenAmount > 0) { newHoldings += totalTokenAmount * decimalsMultipliers[y]; IERC20Metadata(tokens[y]).safeTransfer(address(strategy), totalTokenAmount); } } uint256 totalDepositedNow = strategy.deposit(totalAmounts); require(totalDepositedNow > 0, 'Zunami: too low deposit!'); uint256 lpShares = 0; uint256 addedHoldings = 0; uint256 userDeposited = 0; for (uint256 z = 0; z < userList.length; z++) { userDeposited = (totalDepositedNow * userCompleteHoldings[z]) / newHoldings; address userAddr = userList[z]; if (totalSupply() == 0) { lpShares = userDeposited; } else { lpShares = (totalSupply() * userDeposited) / (currentTotalHoldings + addedHoldings); } addedHoldings += userDeposited; _mint(userAddr, lpShares); _poolInfo[defaultDepositPid].lpShares += lpShares; emit Deposited(userAddr, pendingDeposits[userAddr], lpShares); // remove deposit from list delete pendingDeposits[userAddr]; } totalDeposited += addedHoldings; } /** * @dev Zunami protocol owner complete all active pending withdrawals of users * @param userList - array of users from pending withdraw to complete */ function completeWithdrawals(address[] memory userList) external onlyRole(OPERATOR_ROLE) startedPool { require(userList.length > 0, 'Zunami: there are no pending withdrawals requests'); IStrategy strategy = _poolInfo[defaultWithdrawPid].strategy; address user; PendingWithdrawal memory withdrawal; for (uint256 i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; if (balanceOf(user) >= withdrawal.lpShares) { if ( !( strategy.withdraw( user, withdrawal.lpShares * 1e18 / _poolInfo[defaultWithdrawPid].lpShares, withdrawal.minAmounts, IStrategy.WithdrawalType.Base, 0 ) ) ) { emit FailedWithdrawal(user, withdrawal.minAmounts, withdrawal.lpShares); delete pendingWithdrawals[user]; continue; } uint256 userDeposit = (totalDeposited * withdrawal.lpShares) / totalSupply(); _burn(user, withdrawal.lpShares); _poolInfo[defaultWithdrawPid].lpShares -= withdrawal.lpShares; totalDeposited -= userDeposit; emit Withdrawn(user, IStrategy.WithdrawalType.Base, withdrawal.minAmounts, withdrawal.lpShares, 0); } delete pendingWithdrawals[user]; } } function completeWithdrawalsOptimized(address[] memory userList) external onlyRole(OPERATOR_ROLE) startedPool { require(userList.length > 0, 'Zunami: there are no pending withdrawals requests'); IStrategy strategy = _poolInfo[defaultWithdrawPid].strategy; uint256 lpSharesTotal; uint256[POOL_ASSETS] memory minAmountsTotal; uint256 i; address user; PendingWithdrawal memory withdrawal; for (i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; if (balanceOf(user) < withdrawal.lpShares) { emit FailedWithdrawal(user, withdrawal.minAmounts, withdrawal.lpShares); delete pendingWithdrawals[user]; continue; } lpSharesTotal += withdrawal.lpShares; minAmountsTotal[0] += withdrawal.minAmounts[0]; minAmountsTotal[1] += withdrawal.minAmounts[1]; minAmountsTotal[2] += withdrawal.minAmounts[2]; emit Withdrawn(user, IStrategy.WithdrawalType.Base, withdrawal.minAmounts, withdrawal.lpShares, 0); } require( lpSharesTotal <= _poolInfo[defaultWithdrawPid].lpShares, "Zunami: Insufficient pool LP shares"); uint256[POOL_ASSETS] memory prevBalances; for (i = 0; i < 3; i++) { prevBalances[i] = IERC20Metadata(tokens[i]).balanceOf(address(this)); } if( !strategy.withdraw(address(this), lpSharesTotal * 1e18 / _poolInfo[defaultWithdrawPid].lpShares, minAmountsTotal, IStrategy.WithdrawalType.Base, 0) ) { //TODO: do we really need to remove delegated requests for (i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; emit FailedWithdrawal(user, withdrawal.minAmounts, withdrawal.lpShares); delete pendingWithdrawals[user]; } return; } uint256[POOL_ASSETS] memory diffBalances; for (i = 0; i < 3; i++) { diffBalances[i] = IERC20Metadata(tokens[i]).balanceOf(address(this)) - prevBalances[i]; } for (i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; uint256 userDeposit = (totalDeposited * withdrawal.lpShares) / totalSupply(); _burn(user, withdrawal.lpShares); _poolInfo[defaultWithdrawPid].lpShares -= withdrawal.lpShares; totalDeposited -= userDeposit; for (uint256 j = 0; j < 3; j++) { IERC20Metadata(tokens[j]).safeTransfer( user, (diffBalances[j] * withdrawal.lpShares) / lpSharesTotal ); } delete pendingWithdrawals[user]; } } /** * @dev deposit in one tx, without waiting complete by dev * @return Returns amount of lpShares minted for user * @param amounts - user send amounts of stablecoins to deposit */ function deposit(uint256[POOL_ASSETS] memory amounts) external whenNotPaused startedPool returns (uint256) { IStrategy strategy = _poolInfo[defaultDepositPid].strategy; uint256 holdings = totalHoldings(); for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] > 0) { IERC20Metadata(tokens[i]).safeTransferFrom( _msgSender(), address(strategy), amounts[i] ); } } uint256 newDeposited = strategy.deposit(amounts); require(newDeposited > 0, 'Zunami: too low deposit!'); uint256 lpShares = 0; if (totalSupply() == 0) { lpShares = newDeposited; } else { lpShares = (totalSupply() * newDeposited) / holdings; } _mint(_msgSender(), lpShares); _poolInfo[defaultDepositPid].lpShares += lpShares; totalDeposited += newDeposited; emit Deposited(_msgSender(), amounts, lpShares); return lpShares; } /** * @dev withdraw in one tx, without waiting complete by dev * @param lpShares - amount of ZLP for withdraw * @param tokenAmounts - array of amounts stablecoins that user want minimum receive */ function withdraw( uint256 lpShares, uint256[POOL_ASSETS] memory tokenAmounts, IStrategy.WithdrawalType withdrawalType, uint128 tokenIndex ) external whenNotPaused startedPool { require( checkBit(availableWithdrawalTypes, uint8(withdrawalType)), 'Zunami: withdrawal type not available' ); IStrategy strategy = _poolInfo[defaultWithdrawPid].strategy; address userAddr = _msgSender(); require(balanceOf(userAddr) >= lpShares, 'Zunami: not enough LP balance'); require( strategy.withdraw(userAddr, lpShares * 1e18 / _poolInfo[defaultWithdrawPid].lpShares, tokenAmounts, withdrawalType, tokenIndex), 'Zunami: user lps share should be at least required' ); uint256 userDeposit = (totalDeposited * lpShares) / totalSupply(); _burn(userAddr, lpShares); _poolInfo[defaultWithdrawPid].lpShares -= lpShares; totalDeposited -= userDeposit; emit Withdrawn(userAddr, withdrawalType, tokenAmounts, lpShares, tokenIndex); } /** * @dev add a new pool, deposits in the new pool are blocked for one day for safety * @param _strategyAddr - the new pool strategy address */ function addPool(address _strategyAddr) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_strategyAddr != address(0), 'Zunami: zero strategy addr'); uint256 startTime = block.timestamp + (launched ? MIN_LOCK_TIME : 0); _poolInfo.push( PoolInfo({ strategy: IStrategy(_strategyAddr), startTime: startTime, lpShares: 0 }) ); emit AddedPool(_poolInfo.length - 1, _strategyAddr, startTime); } /** * @dev set a default pool for deposit funds * @param _newPoolId - new pool id */ function setDefaultDepositPid(uint256 _newPoolId) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_newPoolId < _poolInfo.length, 'Zunami: incorrect default deposit pool id'); defaultDepositPid = _newPoolId; emit SetDefaultDepositPid(_newPoolId); } /** * @dev set a default pool for withdraw funds * @param _newPoolId - new pool id */ function setDefaultWithdrawPid(uint256 _newPoolId) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_newPoolId < _poolInfo.length, 'Zunami: incorrect default withdraw pool id'); defaultWithdrawPid = _newPoolId; emit SetDefaultWithdrawPid(_newPoolId); } function launch() external onlyRole(DEFAULT_ADMIN_ROLE) { launched = true; } /** * @dev dev can transfer funds from few strategy's to one strategy for better APY * @param _strategies - array of strategy's, from which funds are withdrawn * @param withdrawalsPercents - A percentage of the funds that should be transfered * @param _receiverStrategyId - number strategy, to which funds are deposited */ function moveFundsBatch( uint256[] memory _strategies, uint256[] memory withdrawalsPercents, uint256 _receiverStrategyId ) external onlyRole(DEFAULT_ADMIN_ROLE) { require( _strategies.length == withdrawalsPercents.length, 'Zunami: incorrect arguments for the moveFundsBatch' ); require(_receiverStrategyId < _poolInfo.length, 'Zunami: incorrect a reciver strategy ID'); uint256[POOL_ASSETS] memory tokenBalance; for (uint256 y = 0; y < POOL_ASSETS; y++) { tokenBalance[y] = IERC20Metadata(tokens[y]).balanceOf(address(this)); } uint256 pid; uint256 zunamiLp; for (uint256 i = 0; i < _strategies.length; i++) { pid = _strategies[i]; zunamiLp += _moveFunds(pid, withdrawalsPercents[i]); } uint256[POOL_ASSETS] memory tokensRemainder; for (uint256 y = 0; y < POOL_ASSETS; y++) { tokensRemainder[y] = IERC20Metadata(tokens[y]).balanceOf(address(this)) - tokenBalance[y]; if (tokensRemainder[y] > 0) { IERC20Metadata(tokens[y]).safeTransfer( address(_poolInfo[_receiverStrategyId].strategy), tokensRemainder[y] ); } } _poolInfo[_receiverStrategyId].lpShares += zunamiLp; require( _poolInfo[_receiverStrategyId].strategy.deposit(tokensRemainder) > 0, 'Zunami: Too low amount!' ); } function _moveFunds(uint256 pid, uint256 withdrawAmount) private returns (uint256) { uint256 currentLpAmount; if (withdrawAmount == FUNDS_DENOMINATOR) { _poolInfo[pid].strategy.withdrawAll(); currentLpAmount = _poolInfo[pid].lpShares; _poolInfo[pid].lpShares = 0; } else { currentLpAmount = (_poolInfo[pid].lpShares * withdrawAmount) / FUNDS_DENOMINATOR; uint256[POOL_ASSETS] memory minAmounts; _poolInfo[pid].strategy.withdraw( address(this), currentLpAmount * 1e18 / _poolInfo[pid].lpShares, minAmounts, IStrategy.WithdrawalType.Base, 0 ); _poolInfo[pid].lpShares = _poolInfo[pid].lpShares - currentLpAmount; } return currentLpAmount; } /** * @dev user remove his active pending deposit */ function pendingDepositRemove() external { for (uint256 i = 0; i < POOL_ASSETS; i++) { if (pendingDeposits[_msgSender()][i] > 0) { IERC20Metadata(tokens[i]).safeTransfer( _msgSender(), pendingDeposits[_msgSender()][i] ); } } delete pendingDeposits[_msgSender()]; } /** * @dev governance can withdraw all stuck funds in emergency case * @param _token - IERC20Metadata token that should be fully withdraw from Zunami */ function withdrawStuckToken(IERC20Metadata _token) external onlyRole(DEFAULT_ADMIN_ROLE) { uint256 tokenBalance = _token.balanceOf(address(this)); _token.safeTransfer(_msgSender(), tokenBalance); } /** * @dev governance can add new operator for complete pending deposits and withdrawals * @param _newOperator - address that governance add in list of operators */ function updateOperator(address _newOperator) external onlyRole(DEFAULT_ADMIN_ROLE) { _grantRole(OPERATOR_ROLE, _newOperator); } // Get bit value at position function checkBit(uint8 mask, uint8 bit) internal pure returns (bool) { return mask & (0x01 << bit) != 0; } }
/** * * @title Zunami Protocol * * @notice Contract for Convex&Curve protocols optimize. * Users can use this contract for optimize yield and gas. * * * @dev Zunami is main contract. * Contract does not store user funds. * All user funds goes to Convex&Curve pools. * */
NatSpecMultiLine
deposit
function deposit(uint256[POOL_ASSETS] memory amounts) external whenNotPaused startedPool returns (uint256) { IStrategy strategy = _poolInfo[defaultDepositPid].strategy; uint256 holdings = totalHoldings(); for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] > 0) { IERC20Metadata(tokens[i]).safeTransferFrom( _msgSender(), address(strategy), amounts[i] ); } } uint256 newDeposited = strategy.deposit(amounts); require(newDeposited > 0, 'Zunami: too low deposit!'); uint256 lpShares = 0; if (totalSupply() == 0) { lpShares = newDeposited; } else { lpShares = (totalSupply() * newDeposited) / holdings; } _mint(_msgSender(), lpShares); _poolInfo[defaultDepositPid].lpShares += lpShares; totalDeposited += newDeposited; emit Deposited(_msgSender(), amounts, lpShares); return lpShares; }
/** * @dev deposit in one tx, without waiting complete by dev * @return Returns amount of lpShares minted for user * @param amounts - user send amounts of stablecoins to deposit */
NatSpecMultiLine
v0.8.12+commit.f00d7308
{ "func_code_index": [ 14700, 15800 ] }
2,623
Zunami
contracts/Zunami.sol
0x9b43e47bec96a9345cd26fdde7efa5f8c06e126c
Solidity
Zunami
contract Zunami is ERC20, Pausable, AccessControl { using SafeERC20 for IERC20Metadata; bytes32 public constant OPERATOR_ROLE = keccak256('OPERATOR_ROLE'); struct PendingWithdrawal { uint256 lpShares; uint256[3] minAmounts; } struct PoolInfo { IStrategy strategy; uint256 startTime; uint256 lpShares; } uint8 public constant POOL_ASSETS = 3; uint256 public constant FEE_DENOMINATOR = 1000; uint256 public constant MIN_LOCK_TIME = 1 days; uint256 public constant FUNDS_DENOMINATOR = 10_000; uint8 public constant ALL_WITHDRAWAL_TYPES_MASK = uint8(7); // Binary 111 = 2^0 + 2^1 + 2^2; PoolInfo[] internal _poolInfo; uint256 public defaultDepositPid; uint256 public defaultWithdrawPid; uint8 public availableWithdrawalTypes; address[POOL_ASSETS] public tokens; uint256[POOL_ASSETS] public decimalsMultipliers; mapping(address => uint256[POOL_ASSETS]) public pendingDeposits; mapping(address => PendingWithdrawal) public pendingWithdrawals; uint256 public totalDeposited = 0; uint256 public managementFee = 100; // 10% bool public launched = false; event CreatedPendingDeposit(address indexed depositor, uint256[POOL_ASSETS] amounts); event CreatedPendingWithdrawal( address indexed withdrawer, uint256[POOL_ASSETS] amounts, uint256 lpShares ); event Deposited(address indexed depositor, uint256[POOL_ASSETS] amounts, uint256 lpShares); event Withdrawn(address indexed withdrawer, IStrategy.WithdrawalType withdrawalType, uint256[POOL_ASSETS] tokenAmounts, uint256 lpShares, uint128 tokenIndex); event AddedPool(uint256 pid, address strategyAddr, uint256 startTime); event FailedDeposit(address indexed depositor, uint256[POOL_ASSETS] amounts, uint256 lpShares); event FailedWithdrawal(address indexed withdrawer, uint256[POOL_ASSETS] amounts, uint256 lpShares); event SetDefaultDepositPid(uint256 pid); event SetDefaultWithdrawPid(uint256 pid); event ClaimedAllManagementFee(uint256 feeValue); event AutoCompoundAll(); modifier startedPool() { require(_poolInfo.length != 0, 'Zunami: pool not existed!'); require( block.timestamp >= _poolInfo[defaultDepositPid].startTime, 'Zunami: default deposit pool not started yet!' ); require( block.timestamp >= _poolInfo[defaultWithdrawPid].startTime, 'Zunami: default withdraw pool not started yet!' ); _; } constructor(address[POOL_ASSETS] memory _tokens) ERC20('ZunamiLP', 'ZLP') { tokens = _tokens; _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(OPERATOR_ROLE, msg.sender); for (uint256 i; i < POOL_ASSETS; i++) { uint256 decimals = IERC20Metadata(tokens[i]).decimals(); if (decimals < 18) { decimalsMultipliers[i] = 10**(18 - decimals); } else { decimalsMultipliers[i] = 1; } } availableWithdrawalTypes = ALL_WITHDRAWAL_TYPES_MASK; } function poolInfo(uint256 pid) external view returns (PoolInfo memory) { return _poolInfo[pid]; } function pause() external onlyRole(DEFAULT_ADMIN_ROLE) { _pause(); } function unpause() external onlyRole(DEFAULT_ADMIN_ROLE) { _unpause(); } function setAvailableWithdrawalTypes(uint8 newAvailableWithdrawalTypes) external onlyRole(DEFAULT_ADMIN_ROLE) { require(newAvailableWithdrawalTypes <= ALL_WITHDRAWAL_TYPES_MASK, 'Zunami: wrong available withdrawal types'); availableWithdrawalTypes = newAvailableWithdrawalTypes; } /** * @dev update managementFee, this is a Zunami commission from protocol profit * @param newManagementFee - minAmount 0, maxAmount FEE_DENOMINATOR - 1 */ function setManagementFee(uint256 newManagementFee) external onlyRole(DEFAULT_ADMIN_ROLE) { require(newManagementFee < FEE_DENOMINATOR, 'Zunami: wrong fee'); managementFee = newManagementFee; } /** * @dev Returns managementFee for strategy's when contract sell rewards * @return Returns commission on the amount of profit in the transaction * @param amount - amount of profit for calculate managementFee */ function calcManagementFee(uint256 amount) external view returns (uint256) { return (amount * managementFee) / FEE_DENOMINATOR; } /** * @dev Claims managementFee from all active strategies */ function claimAllManagementFee() external { uint256 feeTotalValue; for (uint256 i = 0; i < _poolInfo.length; i++) { feeTotalValue += _poolInfo[i].strategy.claimManagementFees(); } emit ClaimedAllManagementFee(feeTotalValue); } function autoCompoundAll() external { for (uint256 i = 0; i < _poolInfo.length; i++) { _poolInfo[i].strategy.autoCompound(); } emit AutoCompoundAll(); } /** * @dev Returns total holdings for all pools (strategy's) * @return Returns sum holdings (USD) for all pools */ function totalHoldings() public view returns (uint256) { uint256 length = _poolInfo.length; uint256 totalHold = 0; for (uint256 pid = 0; pid < length; pid++) { totalHold += _poolInfo[pid].strategy.totalHoldings(); } return totalHold; } /** * @dev Returns price depends on the income of users * @return Returns currently price of ZLP (1e18 = 1$) */ function lpPrice() external view returns (uint256) { return (totalHoldings() * 1e18) / totalSupply(); } /** * @dev Returns number of pools * @return number of pools */ function poolCount() external view returns (uint256) { return _poolInfo.length; } /** * @dev in this func user sends funds to the contract and then waits for the completion * of the transaction for all users * @param amounts - array of deposit amounts by user */ function delegateDeposit(uint256[3] memory amounts) external whenNotPaused { for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] > 0) { IERC20Metadata(tokens[i]).safeTransferFrom(_msgSender(), address(this), amounts[i]); pendingDeposits[_msgSender()][i] += amounts[i]; } } emit CreatedPendingDeposit(_msgSender(), amounts); } /** * @dev in this func user sends pending withdraw to the contract and then waits * for the completion of the transaction for all users * @param lpAmount - amount of ZLP for withdraw * @param minAmounts - array of amounts stablecoins that user want minimum receive */ function delegateWithdrawal(uint256 lpAmount, uint256[3] memory minAmounts) external whenNotPaused { PendingWithdrawal memory withdrawal; address userAddr = _msgSender(); require(lpAmount > 0, 'Zunami: lpAmount must be higher 0'); withdrawal.lpShares = lpAmount; withdrawal.minAmounts = minAmounts; pendingWithdrawals[userAddr] = withdrawal; emit CreatedPendingWithdrawal(userAddr, minAmounts, lpAmount); } /** * @dev Zunami protocol owner complete all active pending deposits of users * @param userList - dev send array of users from pending to complete */ function completeDeposits(address[] memory userList) external onlyRole(OPERATOR_ROLE) startedPool { IStrategy strategy = _poolInfo[defaultDepositPid].strategy; uint256 currentTotalHoldings = totalHoldings(); uint256 newHoldings = 0; uint256[3] memory totalAmounts; uint256[] memory userCompleteHoldings = new uint256[](userList.length); for (uint256 i = 0; i < userList.length; i++) { newHoldings = 0; for (uint256 x = 0; x < totalAmounts.length; x++) { uint256 userTokenDeposit = pendingDeposits[userList[i]][x]; totalAmounts[x] += userTokenDeposit; newHoldings += userTokenDeposit * decimalsMultipliers[x]; } userCompleteHoldings[i] = newHoldings; } newHoldings = 0; for (uint256 y = 0; y < POOL_ASSETS; y++) { uint256 totalTokenAmount = totalAmounts[y]; if (totalTokenAmount > 0) { newHoldings += totalTokenAmount * decimalsMultipliers[y]; IERC20Metadata(tokens[y]).safeTransfer(address(strategy), totalTokenAmount); } } uint256 totalDepositedNow = strategy.deposit(totalAmounts); require(totalDepositedNow > 0, 'Zunami: too low deposit!'); uint256 lpShares = 0; uint256 addedHoldings = 0; uint256 userDeposited = 0; for (uint256 z = 0; z < userList.length; z++) { userDeposited = (totalDepositedNow * userCompleteHoldings[z]) / newHoldings; address userAddr = userList[z]; if (totalSupply() == 0) { lpShares = userDeposited; } else { lpShares = (totalSupply() * userDeposited) / (currentTotalHoldings + addedHoldings); } addedHoldings += userDeposited; _mint(userAddr, lpShares); _poolInfo[defaultDepositPid].lpShares += lpShares; emit Deposited(userAddr, pendingDeposits[userAddr], lpShares); // remove deposit from list delete pendingDeposits[userAddr]; } totalDeposited += addedHoldings; } /** * @dev Zunami protocol owner complete all active pending withdrawals of users * @param userList - array of users from pending withdraw to complete */ function completeWithdrawals(address[] memory userList) external onlyRole(OPERATOR_ROLE) startedPool { require(userList.length > 0, 'Zunami: there are no pending withdrawals requests'); IStrategy strategy = _poolInfo[defaultWithdrawPid].strategy; address user; PendingWithdrawal memory withdrawal; for (uint256 i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; if (balanceOf(user) >= withdrawal.lpShares) { if ( !( strategy.withdraw( user, withdrawal.lpShares * 1e18 / _poolInfo[defaultWithdrawPid].lpShares, withdrawal.minAmounts, IStrategy.WithdrawalType.Base, 0 ) ) ) { emit FailedWithdrawal(user, withdrawal.minAmounts, withdrawal.lpShares); delete pendingWithdrawals[user]; continue; } uint256 userDeposit = (totalDeposited * withdrawal.lpShares) / totalSupply(); _burn(user, withdrawal.lpShares); _poolInfo[defaultWithdrawPid].lpShares -= withdrawal.lpShares; totalDeposited -= userDeposit; emit Withdrawn(user, IStrategy.WithdrawalType.Base, withdrawal.minAmounts, withdrawal.lpShares, 0); } delete pendingWithdrawals[user]; } } function completeWithdrawalsOptimized(address[] memory userList) external onlyRole(OPERATOR_ROLE) startedPool { require(userList.length > 0, 'Zunami: there are no pending withdrawals requests'); IStrategy strategy = _poolInfo[defaultWithdrawPid].strategy; uint256 lpSharesTotal; uint256[POOL_ASSETS] memory minAmountsTotal; uint256 i; address user; PendingWithdrawal memory withdrawal; for (i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; if (balanceOf(user) < withdrawal.lpShares) { emit FailedWithdrawal(user, withdrawal.minAmounts, withdrawal.lpShares); delete pendingWithdrawals[user]; continue; } lpSharesTotal += withdrawal.lpShares; minAmountsTotal[0] += withdrawal.minAmounts[0]; minAmountsTotal[1] += withdrawal.minAmounts[1]; minAmountsTotal[2] += withdrawal.minAmounts[2]; emit Withdrawn(user, IStrategy.WithdrawalType.Base, withdrawal.minAmounts, withdrawal.lpShares, 0); } require( lpSharesTotal <= _poolInfo[defaultWithdrawPid].lpShares, "Zunami: Insufficient pool LP shares"); uint256[POOL_ASSETS] memory prevBalances; for (i = 0; i < 3; i++) { prevBalances[i] = IERC20Metadata(tokens[i]).balanceOf(address(this)); } if( !strategy.withdraw(address(this), lpSharesTotal * 1e18 / _poolInfo[defaultWithdrawPid].lpShares, minAmountsTotal, IStrategy.WithdrawalType.Base, 0) ) { //TODO: do we really need to remove delegated requests for (i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; emit FailedWithdrawal(user, withdrawal.minAmounts, withdrawal.lpShares); delete pendingWithdrawals[user]; } return; } uint256[POOL_ASSETS] memory diffBalances; for (i = 0; i < 3; i++) { diffBalances[i] = IERC20Metadata(tokens[i]).balanceOf(address(this)) - prevBalances[i]; } for (i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; uint256 userDeposit = (totalDeposited * withdrawal.lpShares) / totalSupply(); _burn(user, withdrawal.lpShares); _poolInfo[defaultWithdrawPid].lpShares -= withdrawal.lpShares; totalDeposited -= userDeposit; for (uint256 j = 0; j < 3; j++) { IERC20Metadata(tokens[j]).safeTransfer( user, (diffBalances[j] * withdrawal.lpShares) / lpSharesTotal ); } delete pendingWithdrawals[user]; } } /** * @dev deposit in one tx, without waiting complete by dev * @return Returns amount of lpShares minted for user * @param amounts - user send amounts of stablecoins to deposit */ function deposit(uint256[POOL_ASSETS] memory amounts) external whenNotPaused startedPool returns (uint256) { IStrategy strategy = _poolInfo[defaultDepositPid].strategy; uint256 holdings = totalHoldings(); for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] > 0) { IERC20Metadata(tokens[i]).safeTransferFrom( _msgSender(), address(strategy), amounts[i] ); } } uint256 newDeposited = strategy.deposit(amounts); require(newDeposited > 0, 'Zunami: too low deposit!'); uint256 lpShares = 0; if (totalSupply() == 0) { lpShares = newDeposited; } else { lpShares = (totalSupply() * newDeposited) / holdings; } _mint(_msgSender(), lpShares); _poolInfo[defaultDepositPid].lpShares += lpShares; totalDeposited += newDeposited; emit Deposited(_msgSender(), amounts, lpShares); return lpShares; } /** * @dev withdraw in one tx, without waiting complete by dev * @param lpShares - amount of ZLP for withdraw * @param tokenAmounts - array of amounts stablecoins that user want minimum receive */ function withdraw( uint256 lpShares, uint256[POOL_ASSETS] memory tokenAmounts, IStrategy.WithdrawalType withdrawalType, uint128 tokenIndex ) external whenNotPaused startedPool { require( checkBit(availableWithdrawalTypes, uint8(withdrawalType)), 'Zunami: withdrawal type not available' ); IStrategy strategy = _poolInfo[defaultWithdrawPid].strategy; address userAddr = _msgSender(); require(balanceOf(userAddr) >= lpShares, 'Zunami: not enough LP balance'); require( strategy.withdraw(userAddr, lpShares * 1e18 / _poolInfo[defaultWithdrawPid].lpShares, tokenAmounts, withdrawalType, tokenIndex), 'Zunami: user lps share should be at least required' ); uint256 userDeposit = (totalDeposited * lpShares) / totalSupply(); _burn(userAddr, lpShares); _poolInfo[defaultWithdrawPid].lpShares -= lpShares; totalDeposited -= userDeposit; emit Withdrawn(userAddr, withdrawalType, tokenAmounts, lpShares, tokenIndex); } /** * @dev add a new pool, deposits in the new pool are blocked for one day for safety * @param _strategyAddr - the new pool strategy address */ function addPool(address _strategyAddr) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_strategyAddr != address(0), 'Zunami: zero strategy addr'); uint256 startTime = block.timestamp + (launched ? MIN_LOCK_TIME : 0); _poolInfo.push( PoolInfo({ strategy: IStrategy(_strategyAddr), startTime: startTime, lpShares: 0 }) ); emit AddedPool(_poolInfo.length - 1, _strategyAddr, startTime); } /** * @dev set a default pool for deposit funds * @param _newPoolId - new pool id */ function setDefaultDepositPid(uint256 _newPoolId) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_newPoolId < _poolInfo.length, 'Zunami: incorrect default deposit pool id'); defaultDepositPid = _newPoolId; emit SetDefaultDepositPid(_newPoolId); } /** * @dev set a default pool for withdraw funds * @param _newPoolId - new pool id */ function setDefaultWithdrawPid(uint256 _newPoolId) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_newPoolId < _poolInfo.length, 'Zunami: incorrect default withdraw pool id'); defaultWithdrawPid = _newPoolId; emit SetDefaultWithdrawPid(_newPoolId); } function launch() external onlyRole(DEFAULT_ADMIN_ROLE) { launched = true; } /** * @dev dev can transfer funds from few strategy's to one strategy for better APY * @param _strategies - array of strategy's, from which funds are withdrawn * @param withdrawalsPercents - A percentage of the funds that should be transfered * @param _receiverStrategyId - number strategy, to which funds are deposited */ function moveFundsBatch( uint256[] memory _strategies, uint256[] memory withdrawalsPercents, uint256 _receiverStrategyId ) external onlyRole(DEFAULT_ADMIN_ROLE) { require( _strategies.length == withdrawalsPercents.length, 'Zunami: incorrect arguments for the moveFundsBatch' ); require(_receiverStrategyId < _poolInfo.length, 'Zunami: incorrect a reciver strategy ID'); uint256[POOL_ASSETS] memory tokenBalance; for (uint256 y = 0; y < POOL_ASSETS; y++) { tokenBalance[y] = IERC20Metadata(tokens[y]).balanceOf(address(this)); } uint256 pid; uint256 zunamiLp; for (uint256 i = 0; i < _strategies.length; i++) { pid = _strategies[i]; zunamiLp += _moveFunds(pid, withdrawalsPercents[i]); } uint256[POOL_ASSETS] memory tokensRemainder; for (uint256 y = 0; y < POOL_ASSETS; y++) { tokensRemainder[y] = IERC20Metadata(tokens[y]).balanceOf(address(this)) - tokenBalance[y]; if (tokensRemainder[y] > 0) { IERC20Metadata(tokens[y]).safeTransfer( address(_poolInfo[_receiverStrategyId].strategy), tokensRemainder[y] ); } } _poolInfo[_receiverStrategyId].lpShares += zunamiLp; require( _poolInfo[_receiverStrategyId].strategy.deposit(tokensRemainder) > 0, 'Zunami: Too low amount!' ); } function _moveFunds(uint256 pid, uint256 withdrawAmount) private returns (uint256) { uint256 currentLpAmount; if (withdrawAmount == FUNDS_DENOMINATOR) { _poolInfo[pid].strategy.withdrawAll(); currentLpAmount = _poolInfo[pid].lpShares; _poolInfo[pid].lpShares = 0; } else { currentLpAmount = (_poolInfo[pid].lpShares * withdrawAmount) / FUNDS_DENOMINATOR; uint256[POOL_ASSETS] memory minAmounts; _poolInfo[pid].strategy.withdraw( address(this), currentLpAmount * 1e18 / _poolInfo[pid].lpShares, minAmounts, IStrategy.WithdrawalType.Base, 0 ); _poolInfo[pid].lpShares = _poolInfo[pid].lpShares - currentLpAmount; } return currentLpAmount; } /** * @dev user remove his active pending deposit */ function pendingDepositRemove() external { for (uint256 i = 0; i < POOL_ASSETS; i++) { if (pendingDeposits[_msgSender()][i] > 0) { IERC20Metadata(tokens[i]).safeTransfer( _msgSender(), pendingDeposits[_msgSender()][i] ); } } delete pendingDeposits[_msgSender()]; } /** * @dev governance can withdraw all stuck funds in emergency case * @param _token - IERC20Metadata token that should be fully withdraw from Zunami */ function withdrawStuckToken(IERC20Metadata _token) external onlyRole(DEFAULT_ADMIN_ROLE) { uint256 tokenBalance = _token.balanceOf(address(this)); _token.safeTransfer(_msgSender(), tokenBalance); } /** * @dev governance can add new operator for complete pending deposits and withdrawals * @param _newOperator - address that governance add in list of operators */ function updateOperator(address _newOperator) external onlyRole(DEFAULT_ADMIN_ROLE) { _grantRole(OPERATOR_ROLE, _newOperator); } // Get bit value at position function checkBit(uint8 mask, uint8 bit) internal pure returns (bool) { return mask & (0x01 << bit) != 0; } }
/** * * @title Zunami Protocol * * @notice Contract for Convex&Curve protocols optimize. * Users can use this contract for optimize yield and gas. * * * @dev Zunami is main contract. * Contract does not store user funds. * All user funds goes to Convex&Curve pools. * */
NatSpecMultiLine
withdraw
function withdraw( uint256 lpShares, uint256[POOL_ASSETS] memory tokenAmounts, IStrategy.WithdrawalType withdrawalType, uint128 tokenIndex ) external whenNotPaused startedPool { require( checkBit(availableWithdrawalTypes, uint8(withdrawalType)), 'Zunami: withdrawal type not available' ); IStrategy strategy = _poolInfo[defaultWithdrawPid].strategy; address userAddr = _msgSender(); require(balanceOf(userAddr) >= lpShares, 'Zunami: not enough LP balance'); require( strategy.withdraw(userAddr, lpShares * 1e18 / _poolInfo[defaultWithdrawPid].lpShares, tokenAmounts, withdrawalType, tokenIndex), 'Zunami: user lps share should be at least required' ); uint256 userDeposit = (totalDeposited * lpShares) / totalSupply(); _burn(userAddr, lpShares); _poolInfo[defaultWithdrawPid].lpShares -= lpShares; totalDeposited -= userDeposit; emit Withdrawn(userAddr, withdrawalType, tokenAmounts, lpShares, tokenIndex); }
/** * @dev withdraw in one tx, without waiting complete by dev * @param lpShares - amount of ZLP for withdraw * @param tokenAmounts - array of amounts stablecoins that user want minimum receive */
NatSpecMultiLine
v0.8.12+commit.f00d7308
{ "func_code_index": [ 16024, 17092 ] }
2,624
Zunami
contracts/Zunami.sol
0x9b43e47bec96a9345cd26fdde7efa5f8c06e126c
Solidity
Zunami
contract Zunami is ERC20, Pausable, AccessControl { using SafeERC20 for IERC20Metadata; bytes32 public constant OPERATOR_ROLE = keccak256('OPERATOR_ROLE'); struct PendingWithdrawal { uint256 lpShares; uint256[3] minAmounts; } struct PoolInfo { IStrategy strategy; uint256 startTime; uint256 lpShares; } uint8 public constant POOL_ASSETS = 3; uint256 public constant FEE_DENOMINATOR = 1000; uint256 public constant MIN_LOCK_TIME = 1 days; uint256 public constant FUNDS_DENOMINATOR = 10_000; uint8 public constant ALL_WITHDRAWAL_TYPES_MASK = uint8(7); // Binary 111 = 2^0 + 2^1 + 2^2; PoolInfo[] internal _poolInfo; uint256 public defaultDepositPid; uint256 public defaultWithdrawPid; uint8 public availableWithdrawalTypes; address[POOL_ASSETS] public tokens; uint256[POOL_ASSETS] public decimalsMultipliers; mapping(address => uint256[POOL_ASSETS]) public pendingDeposits; mapping(address => PendingWithdrawal) public pendingWithdrawals; uint256 public totalDeposited = 0; uint256 public managementFee = 100; // 10% bool public launched = false; event CreatedPendingDeposit(address indexed depositor, uint256[POOL_ASSETS] amounts); event CreatedPendingWithdrawal( address indexed withdrawer, uint256[POOL_ASSETS] amounts, uint256 lpShares ); event Deposited(address indexed depositor, uint256[POOL_ASSETS] amounts, uint256 lpShares); event Withdrawn(address indexed withdrawer, IStrategy.WithdrawalType withdrawalType, uint256[POOL_ASSETS] tokenAmounts, uint256 lpShares, uint128 tokenIndex); event AddedPool(uint256 pid, address strategyAddr, uint256 startTime); event FailedDeposit(address indexed depositor, uint256[POOL_ASSETS] amounts, uint256 lpShares); event FailedWithdrawal(address indexed withdrawer, uint256[POOL_ASSETS] amounts, uint256 lpShares); event SetDefaultDepositPid(uint256 pid); event SetDefaultWithdrawPid(uint256 pid); event ClaimedAllManagementFee(uint256 feeValue); event AutoCompoundAll(); modifier startedPool() { require(_poolInfo.length != 0, 'Zunami: pool not existed!'); require( block.timestamp >= _poolInfo[defaultDepositPid].startTime, 'Zunami: default deposit pool not started yet!' ); require( block.timestamp >= _poolInfo[defaultWithdrawPid].startTime, 'Zunami: default withdraw pool not started yet!' ); _; } constructor(address[POOL_ASSETS] memory _tokens) ERC20('ZunamiLP', 'ZLP') { tokens = _tokens; _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(OPERATOR_ROLE, msg.sender); for (uint256 i; i < POOL_ASSETS; i++) { uint256 decimals = IERC20Metadata(tokens[i]).decimals(); if (decimals < 18) { decimalsMultipliers[i] = 10**(18 - decimals); } else { decimalsMultipliers[i] = 1; } } availableWithdrawalTypes = ALL_WITHDRAWAL_TYPES_MASK; } function poolInfo(uint256 pid) external view returns (PoolInfo memory) { return _poolInfo[pid]; } function pause() external onlyRole(DEFAULT_ADMIN_ROLE) { _pause(); } function unpause() external onlyRole(DEFAULT_ADMIN_ROLE) { _unpause(); } function setAvailableWithdrawalTypes(uint8 newAvailableWithdrawalTypes) external onlyRole(DEFAULT_ADMIN_ROLE) { require(newAvailableWithdrawalTypes <= ALL_WITHDRAWAL_TYPES_MASK, 'Zunami: wrong available withdrawal types'); availableWithdrawalTypes = newAvailableWithdrawalTypes; } /** * @dev update managementFee, this is a Zunami commission from protocol profit * @param newManagementFee - minAmount 0, maxAmount FEE_DENOMINATOR - 1 */ function setManagementFee(uint256 newManagementFee) external onlyRole(DEFAULT_ADMIN_ROLE) { require(newManagementFee < FEE_DENOMINATOR, 'Zunami: wrong fee'); managementFee = newManagementFee; } /** * @dev Returns managementFee for strategy's when contract sell rewards * @return Returns commission on the amount of profit in the transaction * @param amount - amount of profit for calculate managementFee */ function calcManagementFee(uint256 amount) external view returns (uint256) { return (amount * managementFee) / FEE_DENOMINATOR; } /** * @dev Claims managementFee from all active strategies */ function claimAllManagementFee() external { uint256 feeTotalValue; for (uint256 i = 0; i < _poolInfo.length; i++) { feeTotalValue += _poolInfo[i].strategy.claimManagementFees(); } emit ClaimedAllManagementFee(feeTotalValue); } function autoCompoundAll() external { for (uint256 i = 0; i < _poolInfo.length; i++) { _poolInfo[i].strategy.autoCompound(); } emit AutoCompoundAll(); } /** * @dev Returns total holdings for all pools (strategy's) * @return Returns sum holdings (USD) for all pools */ function totalHoldings() public view returns (uint256) { uint256 length = _poolInfo.length; uint256 totalHold = 0; for (uint256 pid = 0; pid < length; pid++) { totalHold += _poolInfo[pid].strategy.totalHoldings(); } return totalHold; } /** * @dev Returns price depends on the income of users * @return Returns currently price of ZLP (1e18 = 1$) */ function lpPrice() external view returns (uint256) { return (totalHoldings() * 1e18) / totalSupply(); } /** * @dev Returns number of pools * @return number of pools */ function poolCount() external view returns (uint256) { return _poolInfo.length; } /** * @dev in this func user sends funds to the contract and then waits for the completion * of the transaction for all users * @param amounts - array of deposit amounts by user */ function delegateDeposit(uint256[3] memory amounts) external whenNotPaused { for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] > 0) { IERC20Metadata(tokens[i]).safeTransferFrom(_msgSender(), address(this), amounts[i]); pendingDeposits[_msgSender()][i] += amounts[i]; } } emit CreatedPendingDeposit(_msgSender(), amounts); } /** * @dev in this func user sends pending withdraw to the contract and then waits * for the completion of the transaction for all users * @param lpAmount - amount of ZLP for withdraw * @param minAmounts - array of amounts stablecoins that user want minimum receive */ function delegateWithdrawal(uint256 lpAmount, uint256[3] memory minAmounts) external whenNotPaused { PendingWithdrawal memory withdrawal; address userAddr = _msgSender(); require(lpAmount > 0, 'Zunami: lpAmount must be higher 0'); withdrawal.lpShares = lpAmount; withdrawal.minAmounts = minAmounts; pendingWithdrawals[userAddr] = withdrawal; emit CreatedPendingWithdrawal(userAddr, minAmounts, lpAmount); } /** * @dev Zunami protocol owner complete all active pending deposits of users * @param userList - dev send array of users from pending to complete */ function completeDeposits(address[] memory userList) external onlyRole(OPERATOR_ROLE) startedPool { IStrategy strategy = _poolInfo[defaultDepositPid].strategy; uint256 currentTotalHoldings = totalHoldings(); uint256 newHoldings = 0; uint256[3] memory totalAmounts; uint256[] memory userCompleteHoldings = new uint256[](userList.length); for (uint256 i = 0; i < userList.length; i++) { newHoldings = 0; for (uint256 x = 0; x < totalAmounts.length; x++) { uint256 userTokenDeposit = pendingDeposits[userList[i]][x]; totalAmounts[x] += userTokenDeposit; newHoldings += userTokenDeposit * decimalsMultipliers[x]; } userCompleteHoldings[i] = newHoldings; } newHoldings = 0; for (uint256 y = 0; y < POOL_ASSETS; y++) { uint256 totalTokenAmount = totalAmounts[y]; if (totalTokenAmount > 0) { newHoldings += totalTokenAmount * decimalsMultipliers[y]; IERC20Metadata(tokens[y]).safeTransfer(address(strategy), totalTokenAmount); } } uint256 totalDepositedNow = strategy.deposit(totalAmounts); require(totalDepositedNow > 0, 'Zunami: too low deposit!'); uint256 lpShares = 0; uint256 addedHoldings = 0; uint256 userDeposited = 0; for (uint256 z = 0; z < userList.length; z++) { userDeposited = (totalDepositedNow * userCompleteHoldings[z]) / newHoldings; address userAddr = userList[z]; if (totalSupply() == 0) { lpShares = userDeposited; } else { lpShares = (totalSupply() * userDeposited) / (currentTotalHoldings + addedHoldings); } addedHoldings += userDeposited; _mint(userAddr, lpShares); _poolInfo[defaultDepositPid].lpShares += lpShares; emit Deposited(userAddr, pendingDeposits[userAddr], lpShares); // remove deposit from list delete pendingDeposits[userAddr]; } totalDeposited += addedHoldings; } /** * @dev Zunami protocol owner complete all active pending withdrawals of users * @param userList - array of users from pending withdraw to complete */ function completeWithdrawals(address[] memory userList) external onlyRole(OPERATOR_ROLE) startedPool { require(userList.length > 0, 'Zunami: there are no pending withdrawals requests'); IStrategy strategy = _poolInfo[defaultWithdrawPid].strategy; address user; PendingWithdrawal memory withdrawal; for (uint256 i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; if (balanceOf(user) >= withdrawal.lpShares) { if ( !( strategy.withdraw( user, withdrawal.lpShares * 1e18 / _poolInfo[defaultWithdrawPid].lpShares, withdrawal.minAmounts, IStrategy.WithdrawalType.Base, 0 ) ) ) { emit FailedWithdrawal(user, withdrawal.minAmounts, withdrawal.lpShares); delete pendingWithdrawals[user]; continue; } uint256 userDeposit = (totalDeposited * withdrawal.lpShares) / totalSupply(); _burn(user, withdrawal.lpShares); _poolInfo[defaultWithdrawPid].lpShares -= withdrawal.lpShares; totalDeposited -= userDeposit; emit Withdrawn(user, IStrategy.WithdrawalType.Base, withdrawal.minAmounts, withdrawal.lpShares, 0); } delete pendingWithdrawals[user]; } } function completeWithdrawalsOptimized(address[] memory userList) external onlyRole(OPERATOR_ROLE) startedPool { require(userList.length > 0, 'Zunami: there are no pending withdrawals requests'); IStrategy strategy = _poolInfo[defaultWithdrawPid].strategy; uint256 lpSharesTotal; uint256[POOL_ASSETS] memory minAmountsTotal; uint256 i; address user; PendingWithdrawal memory withdrawal; for (i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; if (balanceOf(user) < withdrawal.lpShares) { emit FailedWithdrawal(user, withdrawal.minAmounts, withdrawal.lpShares); delete pendingWithdrawals[user]; continue; } lpSharesTotal += withdrawal.lpShares; minAmountsTotal[0] += withdrawal.minAmounts[0]; minAmountsTotal[1] += withdrawal.minAmounts[1]; minAmountsTotal[2] += withdrawal.minAmounts[2]; emit Withdrawn(user, IStrategy.WithdrawalType.Base, withdrawal.minAmounts, withdrawal.lpShares, 0); } require( lpSharesTotal <= _poolInfo[defaultWithdrawPid].lpShares, "Zunami: Insufficient pool LP shares"); uint256[POOL_ASSETS] memory prevBalances; for (i = 0; i < 3; i++) { prevBalances[i] = IERC20Metadata(tokens[i]).balanceOf(address(this)); } if( !strategy.withdraw(address(this), lpSharesTotal * 1e18 / _poolInfo[defaultWithdrawPid].lpShares, minAmountsTotal, IStrategy.WithdrawalType.Base, 0) ) { //TODO: do we really need to remove delegated requests for (i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; emit FailedWithdrawal(user, withdrawal.minAmounts, withdrawal.lpShares); delete pendingWithdrawals[user]; } return; } uint256[POOL_ASSETS] memory diffBalances; for (i = 0; i < 3; i++) { diffBalances[i] = IERC20Metadata(tokens[i]).balanceOf(address(this)) - prevBalances[i]; } for (i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; uint256 userDeposit = (totalDeposited * withdrawal.lpShares) / totalSupply(); _burn(user, withdrawal.lpShares); _poolInfo[defaultWithdrawPid].lpShares -= withdrawal.lpShares; totalDeposited -= userDeposit; for (uint256 j = 0; j < 3; j++) { IERC20Metadata(tokens[j]).safeTransfer( user, (diffBalances[j] * withdrawal.lpShares) / lpSharesTotal ); } delete pendingWithdrawals[user]; } } /** * @dev deposit in one tx, without waiting complete by dev * @return Returns amount of lpShares minted for user * @param amounts - user send amounts of stablecoins to deposit */ function deposit(uint256[POOL_ASSETS] memory amounts) external whenNotPaused startedPool returns (uint256) { IStrategy strategy = _poolInfo[defaultDepositPid].strategy; uint256 holdings = totalHoldings(); for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] > 0) { IERC20Metadata(tokens[i]).safeTransferFrom( _msgSender(), address(strategy), amounts[i] ); } } uint256 newDeposited = strategy.deposit(amounts); require(newDeposited > 0, 'Zunami: too low deposit!'); uint256 lpShares = 0; if (totalSupply() == 0) { lpShares = newDeposited; } else { lpShares = (totalSupply() * newDeposited) / holdings; } _mint(_msgSender(), lpShares); _poolInfo[defaultDepositPid].lpShares += lpShares; totalDeposited += newDeposited; emit Deposited(_msgSender(), amounts, lpShares); return lpShares; } /** * @dev withdraw in one tx, without waiting complete by dev * @param lpShares - amount of ZLP for withdraw * @param tokenAmounts - array of amounts stablecoins that user want minimum receive */ function withdraw( uint256 lpShares, uint256[POOL_ASSETS] memory tokenAmounts, IStrategy.WithdrawalType withdrawalType, uint128 tokenIndex ) external whenNotPaused startedPool { require( checkBit(availableWithdrawalTypes, uint8(withdrawalType)), 'Zunami: withdrawal type not available' ); IStrategy strategy = _poolInfo[defaultWithdrawPid].strategy; address userAddr = _msgSender(); require(balanceOf(userAddr) >= lpShares, 'Zunami: not enough LP balance'); require( strategy.withdraw(userAddr, lpShares * 1e18 / _poolInfo[defaultWithdrawPid].lpShares, tokenAmounts, withdrawalType, tokenIndex), 'Zunami: user lps share should be at least required' ); uint256 userDeposit = (totalDeposited * lpShares) / totalSupply(); _burn(userAddr, lpShares); _poolInfo[defaultWithdrawPid].lpShares -= lpShares; totalDeposited -= userDeposit; emit Withdrawn(userAddr, withdrawalType, tokenAmounts, lpShares, tokenIndex); } /** * @dev add a new pool, deposits in the new pool are blocked for one day for safety * @param _strategyAddr - the new pool strategy address */ function addPool(address _strategyAddr) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_strategyAddr != address(0), 'Zunami: zero strategy addr'); uint256 startTime = block.timestamp + (launched ? MIN_LOCK_TIME : 0); _poolInfo.push( PoolInfo({ strategy: IStrategy(_strategyAddr), startTime: startTime, lpShares: 0 }) ); emit AddedPool(_poolInfo.length - 1, _strategyAddr, startTime); } /** * @dev set a default pool for deposit funds * @param _newPoolId - new pool id */ function setDefaultDepositPid(uint256 _newPoolId) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_newPoolId < _poolInfo.length, 'Zunami: incorrect default deposit pool id'); defaultDepositPid = _newPoolId; emit SetDefaultDepositPid(_newPoolId); } /** * @dev set a default pool for withdraw funds * @param _newPoolId - new pool id */ function setDefaultWithdrawPid(uint256 _newPoolId) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_newPoolId < _poolInfo.length, 'Zunami: incorrect default withdraw pool id'); defaultWithdrawPid = _newPoolId; emit SetDefaultWithdrawPid(_newPoolId); } function launch() external onlyRole(DEFAULT_ADMIN_ROLE) { launched = true; } /** * @dev dev can transfer funds from few strategy's to one strategy for better APY * @param _strategies - array of strategy's, from which funds are withdrawn * @param withdrawalsPercents - A percentage of the funds that should be transfered * @param _receiverStrategyId - number strategy, to which funds are deposited */ function moveFundsBatch( uint256[] memory _strategies, uint256[] memory withdrawalsPercents, uint256 _receiverStrategyId ) external onlyRole(DEFAULT_ADMIN_ROLE) { require( _strategies.length == withdrawalsPercents.length, 'Zunami: incorrect arguments for the moveFundsBatch' ); require(_receiverStrategyId < _poolInfo.length, 'Zunami: incorrect a reciver strategy ID'); uint256[POOL_ASSETS] memory tokenBalance; for (uint256 y = 0; y < POOL_ASSETS; y++) { tokenBalance[y] = IERC20Metadata(tokens[y]).balanceOf(address(this)); } uint256 pid; uint256 zunamiLp; for (uint256 i = 0; i < _strategies.length; i++) { pid = _strategies[i]; zunamiLp += _moveFunds(pid, withdrawalsPercents[i]); } uint256[POOL_ASSETS] memory tokensRemainder; for (uint256 y = 0; y < POOL_ASSETS; y++) { tokensRemainder[y] = IERC20Metadata(tokens[y]).balanceOf(address(this)) - tokenBalance[y]; if (tokensRemainder[y] > 0) { IERC20Metadata(tokens[y]).safeTransfer( address(_poolInfo[_receiverStrategyId].strategy), tokensRemainder[y] ); } } _poolInfo[_receiverStrategyId].lpShares += zunamiLp; require( _poolInfo[_receiverStrategyId].strategy.deposit(tokensRemainder) > 0, 'Zunami: Too low amount!' ); } function _moveFunds(uint256 pid, uint256 withdrawAmount) private returns (uint256) { uint256 currentLpAmount; if (withdrawAmount == FUNDS_DENOMINATOR) { _poolInfo[pid].strategy.withdrawAll(); currentLpAmount = _poolInfo[pid].lpShares; _poolInfo[pid].lpShares = 0; } else { currentLpAmount = (_poolInfo[pid].lpShares * withdrawAmount) / FUNDS_DENOMINATOR; uint256[POOL_ASSETS] memory minAmounts; _poolInfo[pid].strategy.withdraw( address(this), currentLpAmount * 1e18 / _poolInfo[pid].lpShares, minAmounts, IStrategy.WithdrawalType.Base, 0 ); _poolInfo[pid].lpShares = _poolInfo[pid].lpShares - currentLpAmount; } return currentLpAmount; } /** * @dev user remove his active pending deposit */ function pendingDepositRemove() external { for (uint256 i = 0; i < POOL_ASSETS; i++) { if (pendingDeposits[_msgSender()][i] > 0) { IERC20Metadata(tokens[i]).safeTransfer( _msgSender(), pendingDeposits[_msgSender()][i] ); } } delete pendingDeposits[_msgSender()]; } /** * @dev governance can withdraw all stuck funds in emergency case * @param _token - IERC20Metadata token that should be fully withdraw from Zunami */ function withdrawStuckToken(IERC20Metadata _token) external onlyRole(DEFAULT_ADMIN_ROLE) { uint256 tokenBalance = _token.balanceOf(address(this)); _token.safeTransfer(_msgSender(), tokenBalance); } /** * @dev governance can add new operator for complete pending deposits and withdrawals * @param _newOperator - address that governance add in list of operators */ function updateOperator(address _newOperator) external onlyRole(DEFAULT_ADMIN_ROLE) { _grantRole(OPERATOR_ROLE, _newOperator); } // Get bit value at position function checkBit(uint8 mask, uint8 bit) internal pure returns (bool) { return mask & (0x01 << bit) != 0; } }
/** * * @title Zunami Protocol * * @notice Contract for Convex&Curve protocols optimize. * Users can use this contract for optimize yield and gas. * * * @dev Zunami is main contract. * Contract does not store user funds. * All user funds goes to Convex&Curve pools. * */
NatSpecMultiLine
addPool
function addPool(address _strategyAddr) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_strategyAddr != address(0), 'Zunami: zero strategy addr'); uint256 startTime = block.timestamp + (launched ? MIN_LOCK_TIME : 0); _poolInfo.push( PoolInfo({ strategy: IStrategy(_strategyAddr), startTime: startTime, lpShares: 0 }) ); emit AddedPool(_poolInfo.length - 1, _strategyAddr, startTime); }
/** * @dev add a new pool, deposits in the new pool are blocked for one day for safety * @param _strategyAddr - the new pool strategy address */
NatSpecMultiLine
v0.8.12+commit.f00d7308
{ "func_code_index": [ 17259, 17705 ] }
2,625
Zunami
contracts/Zunami.sol
0x9b43e47bec96a9345cd26fdde7efa5f8c06e126c
Solidity
Zunami
contract Zunami is ERC20, Pausable, AccessControl { using SafeERC20 for IERC20Metadata; bytes32 public constant OPERATOR_ROLE = keccak256('OPERATOR_ROLE'); struct PendingWithdrawal { uint256 lpShares; uint256[3] minAmounts; } struct PoolInfo { IStrategy strategy; uint256 startTime; uint256 lpShares; } uint8 public constant POOL_ASSETS = 3; uint256 public constant FEE_DENOMINATOR = 1000; uint256 public constant MIN_LOCK_TIME = 1 days; uint256 public constant FUNDS_DENOMINATOR = 10_000; uint8 public constant ALL_WITHDRAWAL_TYPES_MASK = uint8(7); // Binary 111 = 2^0 + 2^1 + 2^2; PoolInfo[] internal _poolInfo; uint256 public defaultDepositPid; uint256 public defaultWithdrawPid; uint8 public availableWithdrawalTypes; address[POOL_ASSETS] public tokens; uint256[POOL_ASSETS] public decimalsMultipliers; mapping(address => uint256[POOL_ASSETS]) public pendingDeposits; mapping(address => PendingWithdrawal) public pendingWithdrawals; uint256 public totalDeposited = 0; uint256 public managementFee = 100; // 10% bool public launched = false; event CreatedPendingDeposit(address indexed depositor, uint256[POOL_ASSETS] amounts); event CreatedPendingWithdrawal( address indexed withdrawer, uint256[POOL_ASSETS] amounts, uint256 lpShares ); event Deposited(address indexed depositor, uint256[POOL_ASSETS] amounts, uint256 lpShares); event Withdrawn(address indexed withdrawer, IStrategy.WithdrawalType withdrawalType, uint256[POOL_ASSETS] tokenAmounts, uint256 lpShares, uint128 tokenIndex); event AddedPool(uint256 pid, address strategyAddr, uint256 startTime); event FailedDeposit(address indexed depositor, uint256[POOL_ASSETS] amounts, uint256 lpShares); event FailedWithdrawal(address indexed withdrawer, uint256[POOL_ASSETS] amounts, uint256 lpShares); event SetDefaultDepositPid(uint256 pid); event SetDefaultWithdrawPid(uint256 pid); event ClaimedAllManagementFee(uint256 feeValue); event AutoCompoundAll(); modifier startedPool() { require(_poolInfo.length != 0, 'Zunami: pool not existed!'); require( block.timestamp >= _poolInfo[defaultDepositPid].startTime, 'Zunami: default deposit pool not started yet!' ); require( block.timestamp >= _poolInfo[defaultWithdrawPid].startTime, 'Zunami: default withdraw pool not started yet!' ); _; } constructor(address[POOL_ASSETS] memory _tokens) ERC20('ZunamiLP', 'ZLP') { tokens = _tokens; _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(OPERATOR_ROLE, msg.sender); for (uint256 i; i < POOL_ASSETS; i++) { uint256 decimals = IERC20Metadata(tokens[i]).decimals(); if (decimals < 18) { decimalsMultipliers[i] = 10**(18 - decimals); } else { decimalsMultipliers[i] = 1; } } availableWithdrawalTypes = ALL_WITHDRAWAL_TYPES_MASK; } function poolInfo(uint256 pid) external view returns (PoolInfo memory) { return _poolInfo[pid]; } function pause() external onlyRole(DEFAULT_ADMIN_ROLE) { _pause(); } function unpause() external onlyRole(DEFAULT_ADMIN_ROLE) { _unpause(); } function setAvailableWithdrawalTypes(uint8 newAvailableWithdrawalTypes) external onlyRole(DEFAULT_ADMIN_ROLE) { require(newAvailableWithdrawalTypes <= ALL_WITHDRAWAL_TYPES_MASK, 'Zunami: wrong available withdrawal types'); availableWithdrawalTypes = newAvailableWithdrawalTypes; } /** * @dev update managementFee, this is a Zunami commission from protocol profit * @param newManagementFee - minAmount 0, maxAmount FEE_DENOMINATOR - 1 */ function setManagementFee(uint256 newManagementFee) external onlyRole(DEFAULT_ADMIN_ROLE) { require(newManagementFee < FEE_DENOMINATOR, 'Zunami: wrong fee'); managementFee = newManagementFee; } /** * @dev Returns managementFee for strategy's when contract sell rewards * @return Returns commission on the amount of profit in the transaction * @param amount - amount of profit for calculate managementFee */ function calcManagementFee(uint256 amount) external view returns (uint256) { return (amount * managementFee) / FEE_DENOMINATOR; } /** * @dev Claims managementFee from all active strategies */ function claimAllManagementFee() external { uint256 feeTotalValue; for (uint256 i = 0; i < _poolInfo.length; i++) { feeTotalValue += _poolInfo[i].strategy.claimManagementFees(); } emit ClaimedAllManagementFee(feeTotalValue); } function autoCompoundAll() external { for (uint256 i = 0; i < _poolInfo.length; i++) { _poolInfo[i].strategy.autoCompound(); } emit AutoCompoundAll(); } /** * @dev Returns total holdings for all pools (strategy's) * @return Returns sum holdings (USD) for all pools */ function totalHoldings() public view returns (uint256) { uint256 length = _poolInfo.length; uint256 totalHold = 0; for (uint256 pid = 0; pid < length; pid++) { totalHold += _poolInfo[pid].strategy.totalHoldings(); } return totalHold; } /** * @dev Returns price depends on the income of users * @return Returns currently price of ZLP (1e18 = 1$) */ function lpPrice() external view returns (uint256) { return (totalHoldings() * 1e18) / totalSupply(); } /** * @dev Returns number of pools * @return number of pools */ function poolCount() external view returns (uint256) { return _poolInfo.length; } /** * @dev in this func user sends funds to the contract and then waits for the completion * of the transaction for all users * @param amounts - array of deposit amounts by user */ function delegateDeposit(uint256[3] memory amounts) external whenNotPaused { for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] > 0) { IERC20Metadata(tokens[i]).safeTransferFrom(_msgSender(), address(this), amounts[i]); pendingDeposits[_msgSender()][i] += amounts[i]; } } emit CreatedPendingDeposit(_msgSender(), amounts); } /** * @dev in this func user sends pending withdraw to the contract and then waits * for the completion of the transaction for all users * @param lpAmount - amount of ZLP for withdraw * @param minAmounts - array of amounts stablecoins that user want minimum receive */ function delegateWithdrawal(uint256 lpAmount, uint256[3] memory minAmounts) external whenNotPaused { PendingWithdrawal memory withdrawal; address userAddr = _msgSender(); require(lpAmount > 0, 'Zunami: lpAmount must be higher 0'); withdrawal.lpShares = lpAmount; withdrawal.minAmounts = minAmounts; pendingWithdrawals[userAddr] = withdrawal; emit CreatedPendingWithdrawal(userAddr, minAmounts, lpAmount); } /** * @dev Zunami protocol owner complete all active pending deposits of users * @param userList - dev send array of users from pending to complete */ function completeDeposits(address[] memory userList) external onlyRole(OPERATOR_ROLE) startedPool { IStrategy strategy = _poolInfo[defaultDepositPid].strategy; uint256 currentTotalHoldings = totalHoldings(); uint256 newHoldings = 0; uint256[3] memory totalAmounts; uint256[] memory userCompleteHoldings = new uint256[](userList.length); for (uint256 i = 0; i < userList.length; i++) { newHoldings = 0; for (uint256 x = 0; x < totalAmounts.length; x++) { uint256 userTokenDeposit = pendingDeposits[userList[i]][x]; totalAmounts[x] += userTokenDeposit; newHoldings += userTokenDeposit * decimalsMultipliers[x]; } userCompleteHoldings[i] = newHoldings; } newHoldings = 0; for (uint256 y = 0; y < POOL_ASSETS; y++) { uint256 totalTokenAmount = totalAmounts[y]; if (totalTokenAmount > 0) { newHoldings += totalTokenAmount * decimalsMultipliers[y]; IERC20Metadata(tokens[y]).safeTransfer(address(strategy), totalTokenAmount); } } uint256 totalDepositedNow = strategy.deposit(totalAmounts); require(totalDepositedNow > 0, 'Zunami: too low deposit!'); uint256 lpShares = 0; uint256 addedHoldings = 0; uint256 userDeposited = 0; for (uint256 z = 0; z < userList.length; z++) { userDeposited = (totalDepositedNow * userCompleteHoldings[z]) / newHoldings; address userAddr = userList[z]; if (totalSupply() == 0) { lpShares = userDeposited; } else { lpShares = (totalSupply() * userDeposited) / (currentTotalHoldings + addedHoldings); } addedHoldings += userDeposited; _mint(userAddr, lpShares); _poolInfo[defaultDepositPid].lpShares += lpShares; emit Deposited(userAddr, pendingDeposits[userAddr], lpShares); // remove deposit from list delete pendingDeposits[userAddr]; } totalDeposited += addedHoldings; } /** * @dev Zunami protocol owner complete all active pending withdrawals of users * @param userList - array of users from pending withdraw to complete */ function completeWithdrawals(address[] memory userList) external onlyRole(OPERATOR_ROLE) startedPool { require(userList.length > 0, 'Zunami: there are no pending withdrawals requests'); IStrategy strategy = _poolInfo[defaultWithdrawPid].strategy; address user; PendingWithdrawal memory withdrawal; for (uint256 i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; if (balanceOf(user) >= withdrawal.lpShares) { if ( !( strategy.withdraw( user, withdrawal.lpShares * 1e18 / _poolInfo[defaultWithdrawPid].lpShares, withdrawal.minAmounts, IStrategy.WithdrawalType.Base, 0 ) ) ) { emit FailedWithdrawal(user, withdrawal.minAmounts, withdrawal.lpShares); delete pendingWithdrawals[user]; continue; } uint256 userDeposit = (totalDeposited * withdrawal.lpShares) / totalSupply(); _burn(user, withdrawal.lpShares); _poolInfo[defaultWithdrawPid].lpShares -= withdrawal.lpShares; totalDeposited -= userDeposit; emit Withdrawn(user, IStrategy.WithdrawalType.Base, withdrawal.minAmounts, withdrawal.lpShares, 0); } delete pendingWithdrawals[user]; } } function completeWithdrawalsOptimized(address[] memory userList) external onlyRole(OPERATOR_ROLE) startedPool { require(userList.length > 0, 'Zunami: there are no pending withdrawals requests'); IStrategy strategy = _poolInfo[defaultWithdrawPid].strategy; uint256 lpSharesTotal; uint256[POOL_ASSETS] memory minAmountsTotal; uint256 i; address user; PendingWithdrawal memory withdrawal; for (i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; if (balanceOf(user) < withdrawal.lpShares) { emit FailedWithdrawal(user, withdrawal.minAmounts, withdrawal.lpShares); delete pendingWithdrawals[user]; continue; } lpSharesTotal += withdrawal.lpShares; minAmountsTotal[0] += withdrawal.minAmounts[0]; minAmountsTotal[1] += withdrawal.minAmounts[1]; minAmountsTotal[2] += withdrawal.minAmounts[2]; emit Withdrawn(user, IStrategy.WithdrawalType.Base, withdrawal.minAmounts, withdrawal.lpShares, 0); } require( lpSharesTotal <= _poolInfo[defaultWithdrawPid].lpShares, "Zunami: Insufficient pool LP shares"); uint256[POOL_ASSETS] memory prevBalances; for (i = 0; i < 3; i++) { prevBalances[i] = IERC20Metadata(tokens[i]).balanceOf(address(this)); } if( !strategy.withdraw(address(this), lpSharesTotal * 1e18 / _poolInfo[defaultWithdrawPid].lpShares, minAmountsTotal, IStrategy.WithdrawalType.Base, 0) ) { //TODO: do we really need to remove delegated requests for (i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; emit FailedWithdrawal(user, withdrawal.minAmounts, withdrawal.lpShares); delete pendingWithdrawals[user]; } return; } uint256[POOL_ASSETS] memory diffBalances; for (i = 0; i < 3; i++) { diffBalances[i] = IERC20Metadata(tokens[i]).balanceOf(address(this)) - prevBalances[i]; } for (i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; uint256 userDeposit = (totalDeposited * withdrawal.lpShares) / totalSupply(); _burn(user, withdrawal.lpShares); _poolInfo[defaultWithdrawPid].lpShares -= withdrawal.lpShares; totalDeposited -= userDeposit; for (uint256 j = 0; j < 3; j++) { IERC20Metadata(tokens[j]).safeTransfer( user, (diffBalances[j] * withdrawal.lpShares) / lpSharesTotal ); } delete pendingWithdrawals[user]; } } /** * @dev deposit in one tx, without waiting complete by dev * @return Returns amount of lpShares minted for user * @param amounts - user send amounts of stablecoins to deposit */ function deposit(uint256[POOL_ASSETS] memory amounts) external whenNotPaused startedPool returns (uint256) { IStrategy strategy = _poolInfo[defaultDepositPid].strategy; uint256 holdings = totalHoldings(); for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] > 0) { IERC20Metadata(tokens[i]).safeTransferFrom( _msgSender(), address(strategy), amounts[i] ); } } uint256 newDeposited = strategy.deposit(amounts); require(newDeposited > 0, 'Zunami: too low deposit!'); uint256 lpShares = 0; if (totalSupply() == 0) { lpShares = newDeposited; } else { lpShares = (totalSupply() * newDeposited) / holdings; } _mint(_msgSender(), lpShares); _poolInfo[defaultDepositPid].lpShares += lpShares; totalDeposited += newDeposited; emit Deposited(_msgSender(), amounts, lpShares); return lpShares; } /** * @dev withdraw in one tx, without waiting complete by dev * @param lpShares - amount of ZLP for withdraw * @param tokenAmounts - array of amounts stablecoins that user want minimum receive */ function withdraw( uint256 lpShares, uint256[POOL_ASSETS] memory tokenAmounts, IStrategy.WithdrawalType withdrawalType, uint128 tokenIndex ) external whenNotPaused startedPool { require( checkBit(availableWithdrawalTypes, uint8(withdrawalType)), 'Zunami: withdrawal type not available' ); IStrategy strategy = _poolInfo[defaultWithdrawPid].strategy; address userAddr = _msgSender(); require(balanceOf(userAddr) >= lpShares, 'Zunami: not enough LP balance'); require( strategy.withdraw(userAddr, lpShares * 1e18 / _poolInfo[defaultWithdrawPid].lpShares, tokenAmounts, withdrawalType, tokenIndex), 'Zunami: user lps share should be at least required' ); uint256 userDeposit = (totalDeposited * lpShares) / totalSupply(); _burn(userAddr, lpShares); _poolInfo[defaultWithdrawPid].lpShares -= lpShares; totalDeposited -= userDeposit; emit Withdrawn(userAddr, withdrawalType, tokenAmounts, lpShares, tokenIndex); } /** * @dev add a new pool, deposits in the new pool are blocked for one day for safety * @param _strategyAddr - the new pool strategy address */ function addPool(address _strategyAddr) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_strategyAddr != address(0), 'Zunami: zero strategy addr'); uint256 startTime = block.timestamp + (launched ? MIN_LOCK_TIME : 0); _poolInfo.push( PoolInfo({ strategy: IStrategy(_strategyAddr), startTime: startTime, lpShares: 0 }) ); emit AddedPool(_poolInfo.length - 1, _strategyAddr, startTime); } /** * @dev set a default pool for deposit funds * @param _newPoolId - new pool id */ function setDefaultDepositPid(uint256 _newPoolId) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_newPoolId < _poolInfo.length, 'Zunami: incorrect default deposit pool id'); defaultDepositPid = _newPoolId; emit SetDefaultDepositPid(_newPoolId); } /** * @dev set a default pool for withdraw funds * @param _newPoolId - new pool id */ function setDefaultWithdrawPid(uint256 _newPoolId) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_newPoolId < _poolInfo.length, 'Zunami: incorrect default withdraw pool id'); defaultWithdrawPid = _newPoolId; emit SetDefaultWithdrawPid(_newPoolId); } function launch() external onlyRole(DEFAULT_ADMIN_ROLE) { launched = true; } /** * @dev dev can transfer funds from few strategy's to one strategy for better APY * @param _strategies - array of strategy's, from which funds are withdrawn * @param withdrawalsPercents - A percentage of the funds that should be transfered * @param _receiverStrategyId - number strategy, to which funds are deposited */ function moveFundsBatch( uint256[] memory _strategies, uint256[] memory withdrawalsPercents, uint256 _receiverStrategyId ) external onlyRole(DEFAULT_ADMIN_ROLE) { require( _strategies.length == withdrawalsPercents.length, 'Zunami: incorrect arguments for the moveFundsBatch' ); require(_receiverStrategyId < _poolInfo.length, 'Zunami: incorrect a reciver strategy ID'); uint256[POOL_ASSETS] memory tokenBalance; for (uint256 y = 0; y < POOL_ASSETS; y++) { tokenBalance[y] = IERC20Metadata(tokens[y]).balanceOf(address(this)); } uint256 pid; uint256 zunamiLp; for (uint256 i = 0; i < _strategies.length; i++) { pid = _strategies[i]; zunamiLp += _moveFunds(pid, withdrawalsPercents[i]); } uint256[POOL_ASSETS] memory tokensRemainder; for (uint256 y = 0; y < POOL_ASSETS; y++) { tokensRemainder[y] = IERC20Metadata(tokens[y]).balanceOf(address(this)) - tokenBalance[y]; if (tokensRemainder[y] > 0) { IERC20Metadata(tokens[y]).safeTransfer( address(_poolInfo[_receiverStrategyId].strategy), tokensRemainder[y] ); } } _poolInfo[_receiverStrategyId].lpShares += zunamiLp; require( _poolInfo[_receiverStrategyId].strategy.deposit(tokensRemainder) > 0, 'Zunami: Too low amount!' ); } function _moveFunds(uint256 pid, uint256 withdrawAmount) private returns (uint256) { uint256 currentLpAmount; if (withdrawAmount == FUNDS_DENOMINATOR) { _poolInfo[pid].strategy.withdrawAll(); currentLpAmount = _poolInfo[pid].lpShares; _poolInfo[pid].lpShares = 0; } else { currentLpAmount = (_poolInfo[pid].lpShares * withdrawAmount) / FUNDS_DENOMINATOR; uint256[POOL_ASSETS] memory minAmounts; _poolInfo[pid].strategy.withdraw( address(this), currentLpAmount * 1e18 / _poolInfo[pid].lpShares, minAmounts, IStrategy.WithdrawalType.Base, 0 ); _poolInfo[pid].lpShares = _poolInfo[pid].lpShares - currentLpAmount; } return currentLpAmount; } /** * @dev user remove his active pending deposit */ function pendingDepositRemove() external { for (uint256 i = 0; i < POOL_ASSETS; i++) { if (pendingDeposits[_msgSender()][i] > 0) { IERC20Metadata(tokens[i]).safeTransfer( _msgSender(), pendingDeposits[_msgSender()][i] ); } } delete pendingDeposits[_msgSender()]; } /** * @dev governance can withdraw all stuck funds in emergency case * @param _token - IERC20Metadata token that should be fully withdraw from Zunami */ function withdrawStuckToken(IERC20Metadata _token) external onlyRole(DEFAULT_ADMIN_ROLE) { uint256 tokenBalance = _token.balanceOf(address(this)); _token.safeTransfer(_msgSender(), tokenBalance); } /** * @dev governance can add new operator for complete pending deposits and withdrawals * @param _newOperator - address that governance add in list of operators */ function updateOperator(address _newOperator) external onlyRole(DEFAULT_ADMIN_ROLE) { _grantRole(OPERATOR_ROLE, _newOperator); } // Get bit value at position function checkBit(uint8 mask, uint8 bit) internal pure returns (bool) { return mask & (0x01 << bit) != 0; } }
/** * * @title Zunami Protocol * * @notice Contract for Convex&Curve protocols optimize. * Users can use this contract for optimize yield and gas. * * * @dev Zunami is main contract. * Contract does not store user funds. * All user funds goes to Convex&Curve pools. * */
NatSpecMultiLine
setDefaultDepositPid
function setDefaultDepositPid(uint256 _newPoolId) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_newPoolId < _poolInfo.length, 'Zunami: incorrect default deposit pool id'); defaultDepositPid = _newPoolId; emit SetDefaultDepositPid(_newPoolId); }
/** * @dev set a default pool for deposit funds * @param _newPoolId - new pool id */
NatSpecMultiLine
v0.8.12+commit.f00d7308
{ "func_code_index": [ 17811, 18091 ] }
2,626
Zunami
contracts/Zunami.sol
0x9b43e47bec96a9345cd26fdde7efa5f8c06e126c
Solidity
Zunami
contract Zunami is ERC20, Pausable, AccessControl { using SafeERC20 for IERC20Metadata; bytes32 public constant OPERATOR_ROLE = keccak256('OPERATOR_ROLE'); struct PendingWithdrawal { uint256 lpShares; uint256[3] minAmounts; } struct PoolInfo { IStrategy strategy; uint256 startTime; uint256 lpShares; } uint8 public constant POOL_ASSETS = 3; uint256 public constant FEE_DENOMINATOR = 1000; uint256 public constant MIN_LOCK_TIME = 1 days; uint256 public constant FUNDS_DENOMINATOR = 10_000; uint8 public constant ALL_WITHDRAWAL_TYPES_MASK = uint8(7); // Binary 111 = 2^0 + 2^1 + 2^2; PoolInfo[] internal _poolInfo; uint256 public defaultDepositPid; uint256 public defaultWithdrawPid; uint8 public availableWithdrawalTypes; address[POOL_ASSETS] public tokens; uint256[POOL_ASSETS] public decimalsMultipliers; mapping(address => uint256[POOL_ASSETS]) public pendingDeposits; mapping(address => PendingWithdrawal) public pendingWithdrawals; uint256 public totalDeposited = 0; uint256 public managementFee = 100; // 10% bool public launched = false; event CreatedPendingDeposit(address indexed depositor, uint256[POOL_ASSETS] amounts); event CreatedPendingWithdrawal( address indexed withdrawer, uint256[POOL_ASSETS] amounts, uint256 lpShares ); event Deposited(address indexed depositor, uint256[POOL_ASSETS] amounts, uint256 lpShares); event Withdrawn(address indexed withdrawer, IStrategy.WithdrawalType withdrawalType, uint256[POOL_ASSETS] tokenAmounts, uint256 lpShares, uint128 tokenIndex); event AddedPool(uint256 pid, address strategyAddr, uint256 startTime); event FailedDeposit(address indexed depositor, uint256[POOL_ASSETS] amounts, uint256 lpShares); event FailedWithdrawal(address indexed withdrawer, uint256[POOL_ASSETS] amounts, uint256 lpShares); event SetDefaultDepositPid(uint256 pid); event SetDefaultWithdrawPid(uint256 pid); event ClaimedAllManagementFee(uint256 feeValue); event AutoCompoundAll(); modifier startedPool() { require(_poolInfo.length != 0, 'Zunami: pool not existed!'); require( block.timestamp >= _poolInfo[defaultDepositPid].startTime, 'Zunami: default deposit pool not started yet!' ); require( block.timestamp >= _poolInfo[defaultWithdrawPid].startTime, 'Zunami: default withdraw pool not started yet!' ); _; } constructor(address[POOL_ASSETS] memory _tokens) ERC20('ZunamiLP', 'ZLP') { tokens = _tokens; _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(OPERATOR_ROLE, msg.sender); for (uint256 i; i < POOL_ASSETS; i++) { uint256 decimals = IERC20Metadata(tokens[i]).decimals(); if (decimals < 18) { decimalsMultipliers[i] = 10**(18 - decimals); } else { decimalsMultipliers[i] = 1; } } availableWithdrawalTypes = ALL_WITHDRAWAL_TYPES_MASK; } function poolInfo(uint256 pid) external view returns (PoolInfo memory) { return _poolInfo[pid]; } function pause() external onlyRole(DEFAULT_ADMIN_ROLE) { _pause(); } function unpause() external onlyRole(DEFAULT_ADMIN_ROLE) { _unpause(); } function setAvailableWithdrawalTypes(uint8 newAvailableWithdrawalTypes) external onlyRole(DEFAULT_ADMIN_ROLE) { require(newAvailableWithdrawalTypes <= ALL_WITHDRAWAL_TYPES_MASK, 'Zunami: wrong available withdrawal types'); availableWithdrawalTypes = newAvailableWithdrawalTypes; } /** * @dev update managementFee, this is a Zunami commission from protocol profit * @param newManagementFee - minAmount 0, maxAmount FEE_DENOMINATOR - 1 */ function setManagementFee(uint256 newManagementFee) external onlyRole(DEFAULT_ADMIN_ROLE) { require(newManagementFee < FEE_DENOMINATOR, 'Zunami: wrong fee'); managementFee = newManagementFee; } /** * @dev Returns managementFee for strategy's when contract sell rewards * @return Returns commission on the amount of profit in the transaction * @param amount - amount of profit for calculate managementFee */ function calcManagementFee(uint256 amount) external view returns (uint256) { return (amount * managementFee) / FEE_DENOMINATOR; } /** * @dev Claims managementFee from all active strategies */ function claimAllManagementFee() external { uint256 feeTotalValue; for (uint256 i = 0; i < _poolInfo.length; i++) { feeTotalValue += _poolInfo[i].strategy.claimManagementFees(); } emit ClaimedAllManagementFee(feeTotalValue); } function autoCompoundAll() external { for (uint256 i = 0; i < _poolInfo.length; i++) { _poolInfo[i].strategy.autoCompound(); } emit AutoCompoundAll(); } /** * @dev Returns total holdings for all pools (strategy's) * @return Returns sum holdings (USD) for all pools */ function totalHoldings() public view returns (uint256) { uint256 length = _poolInfo.length; uint256 totalHold = 0; for (uint256 pid = 0; pid < length; pid++) { totalHold += _poolInfo[pid].strategy.totalHoldings(); } return totalHold; } /** * @dev Returns price depends on the income of users * @return Returns currently price of ZLP (1e18 = 1$) */ function lpPrice() external view returns (uint256) { return (totalHoldings() * 1e18) / totalSupply(); } /** * @dev Returns number of pools * @return number of pools */ function poolCount() external view returns (uint256) { return _poolInfo.length; } /** * @dev in this func user sends funds to the contract and then waits for the completion * of the transaction for all users * @param amounts - array of deposit amounts by user */ function delegateDeposit(uint256[3] memory amounts) external whenNotPaused { for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] > 0) { IERC20Metadata(tokens[i]).safeTransferFrom(_msgSender(), address(this), amounts[i]); pendingDeposits[_msgSender()][i] += amounts[i]; } } emit CreatedPendingDeposit(_msgSender(), amounts); } /** * @dev in this func user sends pending withdraw to the contract and then waits * for the completion of the transaction for all users * @param lpAmount - amount of ZLP for withdraw * @param minAmounts - array of amounts stablecoins that user want minimum receive */ function delegateWithdrawal(uint256 lpAmount, uint256[3] memory minAmounts) external whenNotPaused { PendingWithdrawal memory withdrawal; address userAddr = _msgSender(); require(lpAmount > 0, 'Zunami: lpAmount must be higher 0'); withdrawal.lpShares = lpAmount; withdrawal.minAmounts = minAmounts; pendingWithdrawals[userAddr] = withdrawal; emit CreatedPendingWithdrawal(userAddr, minAmounts, lpAmount); } /** * @dev Zunami protocol owner complete all active pending deposits of users * @param userList - dev send array of users from pending to complete */ function completeDeposits(address[] memory userList) external onlyRole(OPERATOR_ROLE) startedPool { IStrategy strategy = _poolInfo[defaultDepositPid].strategy; uint256 currentTotalHoldings = totalHoldings(); uint256 newHoldings = 0; uint256[3] memory totalAmounts; uint256[] memory userCompleteHoldings = new uint256[](userList.length); for (uint256 i = 0; i < userList.length; i++) { newHoldings = 0; for (uint256 x = 0; x < totalAmounts.length; x++) { uint256 userTokenDeposit = pendingDeposits[userList[i]][x]; totalAmounts[x] += userTokenDeposit; newHoldings += userTokenDeposit * decimalsMultipliers[x]; } userCompleteHoldings[i] = newHoldings; } newHoldings = 0; for (uint256 y = 0; y < POOL_ASSETS; y++) { uint256 totalTokenAmount = totalAmounts[y]; if (totalTokenAmount > 0) { newHoldings += totalTokenAmount * decimalsMultipliers[y]; IERC20Metadata(tokens[y]).safeTransfer(address(strategy), totalTokenAmount); } } uint256 totalDepositedNow = strategy.deposit(totalAmounts); require(totalDepositedNow > 0, 'Zunami: too low deposit!'); uint256 lpShares = 0; uint256 addedHoldings = 0; uint256 userDeposited = 0; for (uint256 z = 0; z < userList.length; z++) { userDeposited = (totalDepositedNow * userCompleteHoldings[z]) / newHoldings; address userAddr = userList[z]; if (totalSupply() == 0) { lpShares = userDeposited; } else { lpShares = (totalSupply() * userDeposited) / (currentTotalHoldings + addedHoldings); } addedHoldings += userDeposited; _mint(userAddr, lpShares); _poolInfo[defaultDepositPid].lpShares += lpShares; emit Deposited(userAddr, pendingDeposits[userAddr], lpShares); // remove deposit from list delete pendingDeposits[userAddr]; } totalDeposited += addedHoldings; } /** * @dev Zunami protocol owner complete all active pending withdrawals of users * @param userList - array of users from pending withdraw to complete */ function completeWithdrawals(address[] memory userList) external onlyRole(OPERATOR_ROLE) startedPool { require(userList.length > 0, 'Zunami: there are no pending withdrawals requests'); IStrategy strategy = _poolInfo[defaultWithdrawPid].strategy; address user; PendingWithdrawal memory withdrawal; for (uint256 i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; if (balanceOf(user) >= withdrawal.lpShares) { if ( !( strategy.withdraw( user, withdrawal.lpShares * 1e18 / _poolInfo[defaultWithdrawPid].lpShares, withdrawal.minAmounts, IStrategy.WithdrawalType.Base, 0 ) ) ) { emit FailedWithdrawal(user, withdrawal.minAmounts, withdrawal.lpShares); delete pendingWithdrawals[user]; continue; } uint256 userDeposit = (totalDeposited * withdrawal.lpShares) / totalSupply(); _burn(user, withdrawal.lpShares); _poolInfo[defaultWithdrawPid].lpShares -= withdrawal.lpShares; totalDeposited -= userDeposit; emit Withdrawn(user, IStrategy.WithdrawalType.Base, withdrawal.minAmounts, withdrawal.lpShares, 0); } delete pendingWithdrawals[user]; } } function completeWithdrawalsOptimized(address[] memory userList) external onlyRole(OPERATOR_ROLE) startedPool { require(userList.length > 0, 'Zunami: there are no pending withdrawals requests'); IStrategy strategy = _poolInfo[defaultWithdrawPid].strategy; uint256 lpSharesTotal; uint256[POOL_ASSETS] memory minAmountsTotal; uint256 i; address user; PendingWithdrawal memory withdrawal; for (i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; if (balanceOf(user) < withdrawal.lpShares) { emit FailedWithdrawal(user, withdrawal.minAmounts, withdrawal.lpShares); delete pendingWithdrawals[user]; continue; } lpSharesTotal += withdrawal.lpShares; minAmountsTotal[0] += withdrawal.minAmounts[0]; minAmountsTotal[1] += withdrawal.minAmounts[1]; minAmountsTotal[2] += withdrawal.minAmounts[2]; emit Withdrawn(user, IStrategy.WithdrawalType.Base, withdrawal.minAmounts, withdrawal.lpShares, 0); } require( lpSharesTotal <= _poolInfo[defaultWithdrawPid].lpShares, "Zunami: Insufficient pool LP shares"); uint256[POOL_ASSETS] memory prevBalances; for (i = 0; i < 3; i++) { prevBalances[i] = IERC20Metadata(tokens[i]).balanceOf(address(this)); } if( !strategy.withdraw(address(this), lpSharesTotal * 1e18 / _poolInfo[defaultWithdrawPid].lpShares, minAmountsTotal, IStrategy.WithdrawalType.Base, 0) ) { //TODO: do we really need to remove delegated requests for (i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; emit FailedWithdrawal(user, withdrawal.minAmounts, withdrawal.lpShares); delete pendingWithdrawals[user]; } return; } uint256[POOL_ASSETS] memory diffBalances; for (i = 0; i < 3; i++) { diffBalances[i] = IERC20Metadata(tokens[i]).balanceOf(address(this)) - prevBalances[i]; } for (i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; uint256 userDeposit = (totalDeposited * withdrawal.lpShares) / totalSupply(); _burn(user, withdrawal.lpShares); _poolInfo[defaultWithdrawPid].lpShares -= withdrawal.lpShares; totalDeposited -= userDeposit; for (uint256 j = 0; j < 3; j++) { IERC20Metadata(tokens[j]).safeTransfer( user, (diffBalances[j] * withdrawal.lpShares) / lpSharesTotal ); } delete pendingWithdrawals[user]; } } /** * @dev deposit in one tx, without waiting complete by dev * @return Returns amount of lpShares minted for user * @param amounts - user send amounts of stablecoins to deposit */ function deposit(uint256[POOL_ASSETS] memory amounts) external whenNotPaused startedPool returns (uint256) { IStrategy strategy = _poolInfo[defaultDepositPid].strategy; uint256 holdings = totalHoldings(); for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] > 0) { IERC20Metadata(tokens[i]).safeTransferFrom( _msgSender(), address(strategy), amounts[i] ); } } uint256 newDeposited = strategy.deposit(amounts); require(newDeposited > 0, 'Zunami: too low deposit!'); uint256 lpShares = 0; if (totalSupply() == 0) { lpShares = newDeposited; } else { lpShares = (totalSupply() * newDeposited) / holdings; } _mint(_msgSender(), lpShares); _poolInfo[defaultDepositPid].lpShares += lpShares; totalDeposited += newDeposited; emit Deposited(_msgSender(), amounts, lpShares); return lpShares; } /** * @dev withdraw in one tx, without waiting complete by dev * @param lpShares - amount of ZLP for withdraw * @param tokenAmounts - array of amounts stablecoins that user want minimum receive */ function withdraw( uint256 lpShares, uint256[POOL_ASSETS] memory tokenAmounts, IStrategy.WithdrawalType withdrawalType, uint128 tokenIndex ) external whenNotPaused startedPool { require( checkBit(availableWithdrawalTypes, uint8(withdrawalType)), 'Zunami: withdrawal type not available' ); IStrategy strategy = _poolInfo[defaultWithdrawPid].strategy; address userAddr = _msgSender(); require(balanceOf(userAddr) >= lpShares, 'Zunami: not enough LP balance'); require( strategy.withdraw(userAddr, lpShares * 1e18 / _poolInfo[defaultWithdrawPid].lpShares, tokenAmounts, withdrawalType, tokenIndex), 'Zunami: user lps share should be at least required' ); uint256 userDeposit = (totalDeposited * lpShares) / totalSupply(); _burn(userAddr, lpShares); _poolInfo[defaultWithdrawPid].lpShares -= lpShares; totalDeposited -= userDeposit; emit Withdrawn(userAddr, withdrawalType, tokenAmounts, lpShares, tokenIndex); } /** * @dev add a new pool, deposits in the new pool are blocked for one day for safety * @param _strategyAddr - the new pool strategy address */ function addPool(address _strategyAddr) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_strategyAddr != address(0), 'Zunami: zero strategy addr'); uint256 startTime = block.timestamp + (launched ? MIN_LOCK_TIME : 0); _poolInfo.push( PoolInfo({ strategy: IStrategy(_strategyAddr), startTime: startTime, lpShares: 0 }) ); emit AddedPool(_poolInfo.length - 1, _strategyAddr, startTime); } /** * @dev set a default pool for deposit funds * @param _newPoolId - new pool id */ function setDefaultDepositPid(uint256 _newPoolId) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_newPoolId < _poolInfo.length, 'Zunami: incorrect default deposit pool id'); defaultDepositPid = _newPoolId; emit SetDefaultDepositPid(_newPoolId); } /** * @dev set a default pool for withdraw funds * @param _newPoolId - new pool id */ function setDefaultWithdrawPid(uint256 _newPoolId) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_newPoolId < _poolInfo.length, 'Zunami: incorrect default withdraw pool id'); defaultWithdrawPid = _newPoolId; emit SetDefaultWithdrawPid(_newPoolId); } function launch() external onlyRole(DEFAULT_ADMIN_ROLE) { launched = true; } /** * @dev dev can transfer funds from few strategy's to one strategy for better APY * @param _strategies - array of strategy's, from which funds are withdrawn * @param withdrawalsPercents - A percentage of the funds that should be transfered * @param _receiverStrategyId - number strategy, to which funds are deposited */ function moveFundsBatch( uint256[] memory _strategies, uint256[] memory withdrawalsPercents, uint256 _receiverStrategyId ) external onlyRole(DEFAULT_ADMIN_ROLE) { require( _strategies.length == withdrawalsPercents.length, 'Zunami: incorrect arguments for the moveFundsBatch' ); require(_receiverStrategyId < _poolInfo.length, 'Zunami: incorrect a reciver strategy ID'); uint256[POOL_ASSETS] memory tokenBalance; for (uint256 y = 0; y < POOL_ASSETS; y++) { tokenBalance[y] = IERC20Metadata(tokens[y]).balanceOf(address(this)); } uint256 pid; uint256 zunamiLp; for (uint256 i = 0; i < _strategies.length; i++) { pid = _strategies[i]; zunamiLp += _moveFunds(pid, withdrawalsPercents[i]); } uint256[POOL_ASSETS] memory tokensRemainder; for (uint256 y = 0; y < POOL_ASSETS; y++) { tokensRemainder[y] = IERC20Metadata(tokens[y]).balanceOf(address(this)) - tokenBalance[y]; if (tokensRemainder[y] > 0) { IERC20Metadata(tokens[y]).safeTransfer( address(_poolInfo[_receiverStrategyId].strategy), tokensRemainder[y] ); } } _poolInfo[_receiverStrategyId].lpShares += zunamiLp; require( _poolInfo[_receiverStrategyId].strategy.deposit(tokensRemainder) > 0, 'Zunami: Too low amount!' ); } function _moveFunds(uint256 pid, uint256 withdrawAmount) private returns (uint256) { uint256 currentLpAmount; if (withdrawAmount == FUNDS_DENOMINATOR) { _poolInfo[pid].strategy.withdrawAll(); currentLpAmount = _poolInfo[pid].lpShares; _poolInfo[pid].lpShares = 0; } else { currentLpAmount = (_poolInfo[pid].lpShares * withdrawAmount) / FUNDS_DENOMINATOR; uint256[POOL_ASSETS] memory minAmounts; _poolInfo[pid].strategy.withdraw( address(this), currentLpAmount * 1e18 / _poolInfo[pid].lpShares, minAmounts, IStrategy.WithdrawalType.Base, 0 ); _poolInfo[pid].lpShares = _poolInfo[pid].lpShares - currentLpAmount; } return currentLpAmount; } /** * @dev user remove his active pending deposit */ function pendingDepositRemove() external { for (uint256 i = 0; i < POOL_ASSETS; i++) { if (pendingDeposits[_msgSender()][i] > 0) { IERC20Metadata(tokens[i]).safeTransfer( _msgSender(), pendingDeposits[_msgSender()][i] ); } } delete pendingDeposits[_msgSender()]; } /** * @dev governance can withdraw all stuck funds in emergency case * @param _token - IERC20Metadata token that should be fully withdraw from Zunami */ function withdrawStuckToken(IERC20Metadata _token) external onlyRole(DEFAULT_ADMIN_ROLE) { uint256 tokenBalance = _token.balanceOf(address(this)); _token.safeTransfer(_msgSender(), tokenBalance); } /** * @dev governance can add new operator for complete pending deposits and withdrawals * @param _newOperator - address that governance add in list of operators */ function updateOperator(address _newOperator) external onlyRole(DEFAULT_ADMIN_ROLE) { _grantRole(OPERATOR_ROLE, _newOperator); } // Get bit value at position function checkBit(uint8 mask, uint8 bit) internal pure returns (bool) { return mask & (0x01 << bit) != 0; } }
/** * * @title Zunami Protocol * * @notice Contract for Convex&Curve protocols optimize. * Users can use this contract for optimize yield and gas. * * * @dev Zunami is main contract. * Contract does not store user funds. * All user funds goes to Convex&Curve pools. * */
NatSpecMultiLine
setDefaultWithdrawPid
function setDefaultWithdrawPid(uint256 _newPoolId) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_newPoolId < _poolInfo.length, 'Zunami: incorrect default withdraw pool id'); defaultWithdrawPid = _newPoolId; emit SetDefaultWithdrawPid(_newPoolId); }
/** * @dev set a default pool for withdraw funds * @param _newPoolId - new pool id */
NatSpecMultiLine
v0.8.12+commit.f00d7308
{ "func_code_index": [ 18198, 18482 ] }
2,627
Zunami
contracts/Zunami.sol
0x9b43e47bec96a9345cd26fdde7efa5f8c06e126c
Solidity
Zunami
contract Zunami is ERC20, Pausable, AccessControl { using SafeERC20 for IERC20Metadata; bytes32 public constant OPERATOR_ROLE = keccak256('OPERATOR_ROLE'); struct PendingWithdrawal { uint256 lpShares; uint256[3] minAmounts; } struct PoolInfo { IStrategy strategy; uint256 startTime; uint256 lpShares; } uint8 public constant POOL_ASSETS = 3; uint256 public constant FEE_DENOMINATOR = 1000; uint256 public constant MIN_LOCK_TIME = 1 days; uint256 public constant FUNDS_DENOMINATOR = 10_000; uint8 public constant ALL_WITHDRAWAL_TYPES_MASK = uint8(7); // Binary 111 = 2^0 + 2^1 + 2^2; PoolInfo[] internal _poolInfo; uint256 public defaultDepositPid; uint256 public defaultWithdrawPid; uint8 public availableWithdrawalTypes; address[POOL_ASSETS] public tokens; uint256[POOL_ASSETS] public decimalsMultipliers; mapping(address => uint256[POOL_ASSETS]) public pendingDeposits; mapping(address => PendingWithdrawal) public pendingWithdrawals; uint256 public totalDeposited = 0; uint256 public managementFee = 100; // 10% bool public launched = false; event CreatedPendingDeposit(address indexed depositor, uint256[POOL_ASSETS] amounts); event CreatedPendingWithdrawal( address indexed withdrawer, uint256[POOL_ASSETS] amounts, uint256 lpShares ); event Deposited(address indexed depositor, uint256[POOL_ASSETS] amounts, uint256 lpShares); event Withdrawn(address indexed withdrawer, IStrategy.WithdrawalType withdrawalType, uint256[POOL_ASSETS] tokenAmounts, uint256 lpShares, uint128 tokenIndex); event AddedPool(uint256 pid, address strategyAddr, uint256 startTime); event FailedDeposit(address indexed depositor, uint256[POOL_ASSETS] amounts, uint256 lpShares); event FailedWithdrawal(address indexed withdrawer, uint256[POOL_ASSETS] amounts, uint256 lpShares); event SetDefaultDepositPid(uint256 pid); event SetDefaultWithdrawPid(uint256 pid); event ClaimedAllManagementFee(uint256 feeValue); event AutoCompoundAll(); modifier startedPool() { require(_poolInfo.length != 0, 'Zunami: pool not existed!'); require( block.timestamp >= _poolInfo[defaultDepositPid].startTime, 'Zunami: default deposit pool not started yet!' ); require( block.timestamp >= _poolInfo[defaultWithdrawPid].startTime, 'Zunami: default withdraw pool not started yet!' ); _; } constructor(address[POOL_ASSETS] memory _tokens) ERC20('ZunamiLP', 'ZLP') { tokens = _tokens; _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(OPERATOR_ROLE, msg.sender); for (uint256 i; i < POOL_ASSETS; i++) { uint256 decimals = IERC20Metadata(tokens[i]).decimals(); if (decimals < 18) { decimalsMultipliers[i] = 10**(18 - decimals); } else { decimalsMultipliers[i] = 1; } } availableWithdrawalTypes = ALL_WITHDRAWAL_TYPES_MASK; } function poolInfo(uint256 pid) external view returns (PoolInfo memory) { return _poolInfo[pid]; } function pause() external onlyRole(DEFAULT_ADMIN_ROLE) { _pause(); } function unpause() external onlyRole(DEFAULT_ADMIN_ROLE) { _unpause(); } function setAvailableWithdrawalTypes(uint8 newAvailableWithdrawalTypes) external onlyRole(DEFAULT_ADMIN_ROLE) { require(newAvailableWithdrawalTypes <= ALL_WITHDRAWAL_TYPES_MASK, 'Zunami: wrong available withdrawal types'); availableWithdrawalTypes = newAvailableWithdrawalTypes; } /** * @dev update managementFee, this is a Zunami commission from protocol profit * @param newManagementFee - minAmount 0, maxAmount FEE_DENOMINATOR - 1 */ function setManagementFee(uint256 newManagementFee) external onlyRole(DEFAULT_ADMIN_ROLE) { require(newManagementFee < FEE_DENOMINATOR, 'Zunami: wrong fee'); managementFee = newManagementFee; } /** * @dev Returns managementFee for strategy's when contract sell rewards * @return Returns commission on the amount of profit in the transaction * @param amount - amount of profit for calculate managementFee */ function calcManagementFee(uint256 amount) external view returns (uint256) { return (amount * managementFee) / FEE_DENOMINATOR; } /** * @dev Claims managementFee from all active strategies */ function claimAllManagementFee() external { uint256 feeTotalValue; for (uint256 i = 0; i < _poolInfo.length; i++) { feeTotalValue += _poolInfo[i].strategy.claimManagementFees(); } emit ClaimedAllManagementFee(feeTotalValue); } function autoCompoundAll() external { for (uint256 i = 0; i < _poolInfo.length; i++) { _poolInfo[i].strategy.autoCompound(); } emit AutoCompoundAll(); } /** * @dev Returns total holdings for all pools (strategy's) * @return Returns sum holdings (USD) for all pools */ function totalHoldings() public view returns (uint256) { uint256 length = _poolInfo.length; uint256 totalHold = 0; for (uint256 pid = 0; pid < length; pid++) { totalHold += _poolInfo[pid].strategy.totalHoldings(); } return totalHold; } /** * @dev Returns price depends on the income of users * @return Returns currently price of ZLP (1e18 = 1$) */ function lpPrice() external view returns (uint256) { return (totalHoldings() * 1e18) / totalSupply(); } /** * @dev Returns number of pools * @return number of pools */ function poolCount() external view returns (uint256) { return _poolInfo.length; } /** * @dev in this func user sends funds to the contract and then waits for the completion * of the transaction for all users * @param amounts - array of deposit amounts by user */ function delegateDeposit(uint256[3] memory amounts) external whenNotPaused { for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] > 0) { IERC20Metadata(tokens[i]).safeTransferFrom(_msgSender(), address(this), amounts[i]); pendingDeposits[_msgSender()][i] += amounts[i]; } } emit CreatedPendingDeposit(_msgSender(), amounts); } /** * @dev in this func user sends pending withdraw to the contract and then waits * for the completion of the transaction for all users * @param lpAmount - amount of ZLP for withdraw * @param minAmounts - array of amounts stablecoins that user want minimum receive */ function delegateWithdrawal(uint256 lpAmount, uint256[3] memory minAmounts) external whenNotPaused { PendingWithdrawal memory withdrawal; address userAddr = _msgSender(); require(lpAmount > 0, 'Zunami: lpAmount must be higher 0'); withdrawal.lpShares = lpAmount; withdrawal.minAmounts = minAmounts; pendingWithdrawals[userAddr] = withdrawal; emit CreatedPendingWithdrawal(userAddr, minAmounts, lpAmount); } /** * @dev Zunami protocol owner complete all active pending deposits of users * @param userList - dev send array of users from pending to complete */ function completeDeposits(address[] memory userList) external onlyRole(OPERATOR_ROLE) startedPool { IStrategy strategy = _poolInfo[defaultDepositPid].strategy; uint256 currentTotalHoldings = totalHoldings(); uint256 newHoldings = 0; uint256[3] memory totalAmounts; uint256[] memory userCompleteHoldings = new uint256[](userList.length); for (uint256 i = 0; i < userList.length; i++) { newHoldings = 0; for (uint256 x = 0; x < totalAmounts.length; x++) { uint256 userTokenDeposit = pendingDeposits[userList[i]][x]; totalAmounts[x] += userTokenDeposit; newHoldings += userTokenDeposit * decimalsMultipliers[x]; } userCompleteHoldings[i] = newHoldings; } newHoldings = 0; for (uint256 y = 0; y < POOL_ASSETS; y++) { uint256 totalTokenAmount = totalAmounts[y]; if (totalTokenAmount > 0) { newHoldings += totalTokenAmount * decimalsMultipliers[y]; IERC20Metadata(tokens[y]).safeTransfer(address(strategy), totalTokenAmount); } } uint256 totalDepositedNow = strategy.deposit(totalAmounts); require(totalDepositedNow > 0, 'Zunami: too low deposit!'); uint256 lpShares = 0; uint256 addedHoldings = 0; uint256 userDeposited = 0; for (uint256 z = 0; z < userList.length; z++) { userDeposited = (totalDepositedNow * userCompleteHoldings[z]) / newHoldings; address userAddr = userList[z]; if (totalSupply() == 0) { lpShares = userDeposited; } else { lpShares = (totalSupply() * userDeposited) / (currentTotalHoldings + addedHoldings); } addedHoldings += userDeposited; _mint(userAddr, lpShares); _poolInfo[defaultDepositPid].lpShares += lpShares; emit Deposited(userAddr, pendingDeposits[userAddr], lpShares); // remove deposit from list delete pendingDeposits[userAddr]; } totalDeposited += addedHoldings; } /** * @dev Zunami protocol owner complete all active pending withdrawals of users * @param userList - array of users from pending withdraw to complete */ function completeWithdrawals(address[] memory userList) external onlyRole(OPERATOR_ROLE) startedPool { require(userList.length > 0, 'Zunami: there are no pending withdrawals requests'); IStrategy strategy = _poolInfo[defaultWithdrawPid].strategy; address user; PendingWithdrawal memory withdrawal; for (uint256 i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; if (balanceOf(user) >= withdrawal.lpShares) { if ( !( strategy.withdraw( user, withdrawal.lpShares * 1e18 / _poolInfo[defaultWithdrawPid].lpShares, withdrawal.minAmounts, IStrategy.WithdrawalType.Base, 0 ) ) ) { emit FailedWithdrawal(user, withdrawal.minAmounts, withdrawal.lpShares); delete pendingWithdrawals[user]; continue; } uint256 userDeposit = (totalDeposited * withdrawal.lpShares) / totalSupply(); _burn(user, withdrawal.lpShares); _poolInfo[defaultWithdrawPid].lpShares -= withdrawal.lpShares; totalDeposited -= userDeposit; emit Withdrawn(user, IStrategy.WithdrawalType.Base, withdrawal.minAmounts, withdrawal.lpShares, 0); } delete pendingWithdrawals[user]; } } function completeWithdrawalsOptimized(address[] memory userList) external onlyRole(OPERATOR_ROLE) startedPool { require(userList.length > 0, 'Zunami: there are no pending withdrawals requests'); IStrategy strategy = _poolInfo[defaultWithdrawPid].strategy; uint256 lpSharesTotal; uint256[POOL_ASSETS] memory minAmountsTotal; uint256 i; address user; PendingWithdrawal memory withdrawal; for (i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; if (balanceOf(user) < withdrawal.lpShares) { emit FailedWithdrawal(user, withdrawal.minAmounts, withdrawal.lpShares); delete pendingWithdrawals[user]; continue; } lpSharesTotal += withdrawal.lpShares; minAmountsTotal[0] += withdrawal.minAmounts[0]; minAmountsTotal[1] += withdrawal.minAmounts[1]; minAmountsTotal[2] += withdrawal.minAmounts[2]; emit Withdrawn(user, IStrategy.WithdrawalType.Base, withdrawal.minAmounts, withdrawal.lpShares, 0); } require( lpSharesTotal <= _poolInfo[defaultWithdrawPid].lpShares, "Zunami: Insufficient pool LP shares"); uint256[POOL_ASSETS] memory prevBalances; for (i = 0; i < 3; i++) { prevBalances[i] = IERC20Metadata(tokens[i]).balanceOf(address(this)); } if( !strategy.withdraw(address(this), lpSharesTotal * 1e18 / _poolInfo[defaultWithdrawPid].lpShares, minAmountsTotal, IStrategy.WithdrawalType.Base, 0) ) { //TODO: do we really need to remove delegated requests for (i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; emit FailedWithdrawal(user, withdrawal.minAmounts, withdrawal.lpShares); delete pendingWithdrawals[user]; } return; } uint256[POOL_ASSETS] memory diffBalances; for (i = 0; i < 3; i++) { diffBalances[i] = IERC20Metadata(tokens[i]).balanceOf(address(this)) - prevBalances[i]; } for (i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; uint256 userDeposit = (totalDeposited * withdrawal.lpShares) / totalSupply(); _burn(user, withdrawal.lpShares); _poolInfo[defaultWithdrawPid].lpShares -= withdrawal.lpShares; totalDeposited -= userDeposit; for (uint256 j = 0; j < 3; j++) { IERC20Metadata(tokens[j]).safeTransfer( user, (diffBalances[j] * withdrawal.lpShares) / lpSharesTotal ); } delete pendingWithdrawals[user]; } } /** * @dev deposit in one tx, without waiting complete by dev * @return Returns amount of lpShares minted for user * @param amounts - user send amounts of stablecoins to deposit */ function deposit(uint256[POOL_ASSETS] memory amounts) external whenNotPaused startedPool returns (uint256) { IStrategy strategy = _poolInfo[defaultDepositPid].strategy; uint256 holdings = totalHoldings(); for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] > 0) { IERC20Metadata(tokens[i]).safeTransferFrom( _msgSender(), address(strategy), amounts[i] ); } } uint256 newDeposited = strategy.deposit(amounts); require(newDeposited > 0, 'Zunami: too low deposit!'); uint256 lpShares = 0; if (totalSupply() == 0) { lpShares = newDeposited; } else { lpShares = (totalSupply() * newDeposited) / holdings; } _mint(_msgSender(), lpShares); _poolInfo[defaultDepositPid].lpShares += lpShares; totalDeposited += newDeposited; emit Deposited(_msgSender(), amounts, lpShares); return lpShares; } /** * @dev withdraw in one tx, without waiting complete by dev * @param lpShares - amount of ZLP for withdraw * @param tokenAmounts - array of amounts stablecoins that user want minimum receive */ function withdraw( uint256 lpShares, uint256[POOL_ASSETS] memory tokenAmounts, IStrategy.WithdrawalType withdrawalType, uint128 tokenIndex ) external whenNotPaused startedPool { require( checkBit(availableWithdrawalTypes, uint8(withdrawalType)), 'Zunami: withdrawal type not available' ); IStrategy strategy = _poolInfo[defaultWithdrawPid].strategy; address userAddr = _msgSender(); require(balanceOf(userAddr) >= lpShares, 'Zunami: not enough LP balance'); require( strategy.withdraw(userAddr, lpShares * 1e18 / _poolInfo[defaultWithdrawPid].lpShares, tokenAmounts, withdrawalType, tokenIndex), 'Zunami: user lps share should be at least required' ); uint256 userDeposit = (totalDeposited * lpShares) / totalSupply(); _burn(userAddr, lpShares); _poolInfo[defaultWithdrawPid].lpShares -= lpShares; totalDeposited -= userDeposit; emit Withdrawn(userAddr, withdrawalType, tokenAmounts, lpShares, tokenIndex); } /** * @dev add a new pool, deposits in the new pool are blocked for one day for safety * @param _strategyAddr - the new pool strategy address */ function addPool(address _strategyAddr) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_strategyAddr != address(0), 'Zunami: zero strategy addr'); uint256 startTime = block.timestamp + (launched ? MIN_LOCK_TIME : 0); _poolInfo.push( PoolInfo({ strategy: IStrategy(_strategyAddr), startTime: startTime, lpShares: 0 }) ); emit AddedPool(_poolInfo.length - 1, _strategyAddr, startTime); } /** * @dev set a default pool for deposit funds * @param _newPoolId - new pool id */ function setDefaultDepositPid(uint256 _newPoolId) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_newPoolId < _poolInfo.length, 'Zunami: incorrect default deposit pool id'); defaultDepositPid = _newPoolId; emit SetDefaultDepositPid(_newPoolId); } /** * @dev set a default pool for withdraw funds * @param _newPoolId - new pool id */ function setDefaultWithdrawPid(uint256 _newPoolId) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_newPoolId < _poolInfo.length, 'Zunami: incorrect default withdraw pool id'); defaultWithdrawPid = _newPoolId; emit SetDefaultWithdrawPid(_newPoolId); } function launch() external onlyRole(DEFAULT_ADMIN_ROLE) { launched = true; } /** * @dev dev can transfer funds from few strategy's to one strategy for better APY * @param _strategies - array of strategy's, from which funds are withdrawn * @param withdrawalsPercents - A percentage of the funds that should be transfered * @param _receiverStrategyId - number strategy, to which funds are deposited */ function moveFundsBatch( uint256[] memory _strategies, uint256[] memory withdrawalsPercents, uint256 _receiverStrategyId ) external onlyRole(DEFAULT_ADMIN_ROLE) { require( _strategies.length == withdrawalsPercents.length, 'Zunami: incorrect arguments for the moveFundsBatch' ); require(_receiverStrategyId < _poolInfo.length, 'Zunami: incorrect a reciver strategy ID'); uint256[POOL_ASSETS] memory tokenBalance; for (uint256 y = 0; y < POOL_ASSETS; y++) { tokenBalance[y] = IERC20Metadata(tokens[y]).balanceOf(address(this)); } uint256 pid; uint256 zunamiLp; for (uint256 i = 0; i < _strategies.length; i++) { pid = _strategies[i]; zunamiLp += _moveFunds(pid, withdrawalsPercents[i]); } uint256[POOL_ASSETS] memory tokensRemainder; for (uint256 y = 0; y < POOL_ASSETS; y++) { tokensRemainder[y] = IERC20Metadata(tokens[y]).balanceOf(address(this)) - tokenBalance[y]; if (tokensRemainder[y] > 0) { IERC20Metadata(tokens[y]).safeTransfer( address(_poolInfo[_receiverStrategyId].strategy), tokensRemainder[y] ); } } _poolInfo[_receiverStrategyId].lpShares += zunamiLp; require( _poolInfo[_receiverStrategyId].strategy.deposit(tokensRemainder) > 0, 'Zunami: Too low amount!' ); } function _moveFunds(uint256 pid, uint256 withdrawAmount) private returns (uint256) { uint256 currentLpAmount; if (withdrawAmount == FUNDS_DENOMINATOR) { _poolInfo[pid].strategy.withdrawAll(); currentLpAmount = _poolInfo[pid].lpShares; _poolInfo[pid].lpShares = 0; } else { currentLpAmount = (_poolInfo[pid].lpShares * withdrawAmount) / FUNDS_DENOMINATOR; uint256[POOL_ASSETS] memory minAmounts; _poolInfo[pid].strategy.withdraw( address(this), currentLpAmount * 1e18 / _poolInfo[pid].lpShares, minAmounts, IStrategy.WithdrawalType.Base, 0 ); _poolInfo[pid].lpShares = _poolInfo[pid].lpShares - currentLpAmount; } return currentLpAmount; } /** * @dev user remove his active pending deposit */ function pendingDepositRemove() external { for (uint256 i = 0; i < POOL_ASSETS; i++) { if (pendingDeposits[_msgSender()][i] > 0) { IERC20Metadata(tokens[i]).safeTransfer( _msgSender(), pendingDeposits[_msgSender()][i] ); } } delete pendingDeposits[_msgSender()]; } /** * @dev governance can withdraw all stuck funds in emergency case * @param _token - IERC20Metadata token that should be fully withdraw from Zunami */ function withdrawStuckToken(IERC20Metadata _token) external onlyRole(DEFAULT_ADMIN_ROLE) { uint256 tokenBalance = _token.balanceOf(address(this)); _token.safeTransfer(_msgSender(), tokenBalance); } /** * @dev governance can add new operator for complete pending deposits and withdrawals * @param _newOperator - address that governance add in list of operators */ function updateOperator(address _newOperator) external onlyRole(DEFAULT_ADMIN_ROLE) { _grantRole(OPERATOR_ROLE, _newOperator); } // Get bit value at position function checkBit(uint8 mask, uint8 bit) internal pure returns (bool) { return mask & (0x01 << bit) != 0; } }
/** * * @title Zunami Protocol * * @notice Contract for Convex&Curve protocols optimize. * Users can use this contract for optimize yield and gas. * * * @dev Zunami is main contract. * Contract does not store user funds. * All user funds goes to Convex&Curve pools. * */
NatSpecMultiLine
moveFundsBatch
function moveFundsBatch( uint256[] memory _strategies, uint256[] memory withdrawalsPercents, uint256 _receiverStrategyId ) external onlyRole(DEFAULT_ADMIN_ROLE) { require( _strategies.length == withdrawalsPercents.length, 'Zunami: incorrect arguments for the moveFundsBatch' ); require(_receiverStrategyId < _poolInfo.length, 'Zunami: incorrect a reciver strategy ID'); uint256[POOL_ASSETS] memory tokenBalance; for (uint256 y = 0; y < POOL_ASSETS; y++) { tokenBalance[y] = IERC20Metadata(tokens[y]).balanceOf(address(this)); } uint256 pid; uint256 zunamiLp; for (uint256 i = 0; i < _strategies.length; i++) { pid = _strategies[i]; zunamiLp += _moveFunds(pid, withdrawalsPercents[i]); } uint256[POOL_ASSETS] memory tokensRemainder; for (uint256 y = 0; y < POOL_ASSETS; y++) { tokensRemainder[y] = IERC20Metadata(tokens[y]).balanceOf(address(this)) - tokenBalance[y]; if (tokensRemainder[y] > 0) { IERC20Metadata(tokens[y]).safeTransfer( address(_poolInfo[_receiverStrategyId].strategy), tokensRemainder[y] ); } } _poolInfo[_receiverStrategyId].lpShares += zunamiLp; require( _poolInfo[_receiverStrategyId].strategy.deposit(tokensRemainder) > 0, 'Zunami: Too low amount!' ); }
/** * @dev dev can transfer funds from few strategy's to one strategy for better APY * @param _strategies - array of strategy's, from which funds are withdrawn * @param withdrawalsPercents - A percentage of the funds that should be transfered * @param _receiverStrategyId - number strategy, to which funds are deposited */
NatSpecMultiLine
v0.8.12+commit.f00d7308
{ "func_code_index": [ 18930, 20498 ] }
2,628
Zunami
contracts/Zunami.sol
0x9b43e47bec96a9345cd26fdde7efa5f8c06e126c
Solidity
Zunami
contract Zunami is ERC20, Pausable, AccessControl { using SafeERC20 for IERC20Metadata; bytes32 public constant OPERATOR_ROLE = keccak256('OPERATOR_ROLE'); struct PendingWithdrawal { uint256 lpShares; uint256[3] minAmounts; } struct PoolInfo { IStrategy strategy; uint256 startTime; uint256 lpShares; } uint8 public constant POOL_ASSETS = 3; uint256 public constant FEE_DENOMINATOR = 1000; uint256 public constant MIN_LOCK_TIME = 1 days; uint256 public constant FUNDS_DENOMINATOR = 10_000; uint8 public constant ALL_WITHDRAWAL_TYPES_MASK = uint8(7); // Binary 111 = 2^0 + 2^1 + 2^2; PoolInfo[] internal _poolInfo; uint256 public defaultDepositPid; uint256 public defaultWithdrawPid; uint8 public availableWithdrawalTypes; address[POOL_ASSETS] public tokens; uint256[POOL_ASSETS] public decimalsMultipliers; mapping(address => uint256[POOL_ASSETS]) public pendingDeposits; mapping(address => PendingWithdrawal) public pendingWithdrawals; uint256 public totalDeposited = 0; uint256 public managementFee = 100; // 10% bool public launched = false; event CreatedPendingDeposit(address indexed depositor, uint256[POOL_ASSETS] amounts); event CreatedPendingWithdrawal( address indexed withdrawer, uint256[POOL_ASSETS] amounts, uint256 lpShares ); event Deposited(address indexed depositor, uint256[POOL_ASSETS] amounts, uint256 lpShares); event Withdrawn(address indexed withdrawer, IStrategy.WithdrawalType withdrawalType, uint256[POOL_ASSETS] tokenAmounts, uint256 lpShares, uint128 tokenIndex); event AddedPool(uint256 pid, address strategyAddr, uint256 startTime); event FailedDeposit(address indexed depositor, uint256[POOL_ASSETS] amounts, uint256 lpShares); event FailedWithdrawal(address indexed withdrawer, uint256[POOL_ASSETS] amounts, uint256 lpShares); event SetDefaultDepositPid(uint256 pid); event SetDefaultWithdrawPid(uint256 pid); event ClaimedAllManagementFee(uint256 feeValue); event AutoCompoundAll(); modifier startedPool() { require(_poolInfo.length != 0, 'Zunami: pool not existed!'); require( block.timestamp >= _poolInfo[defaultDepositPid].startTime, 'Zunami: default deposit pool not started yet!' ); require( block.timestamp >= _poolInfo[defaultWithdrawPid].startTime, 'Zunami: default withdraw pool not started yet!' ); _; } constructor(address[POOL_ASSETS] memory _tokens) ERC20('ZunamiLP', 'ZLP') { tokens = _tokens; _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(OPERATOR_ROLE, msg.sender); for (uint256 i; i < POOL_ASSETS; i++) { uint256 decimals = IERC20Metadata(tokens[i]).decimals(); if (decimals < 18) { decimalsMultipliers[i] = 10**(18 - decimals); } else { decimalsMultipliers[i] = 1; } } availableWithdrawalTypes = ALL_WITHDRAWAL_TYPES_MASK; } function poolInfo(uint256 pid) external view returns (PoolInfo memory) { return _poolInfo[pid]; } function pause() external onlyRole(DEFAULT_ADMIN_ROLE) { _pause(); } function unpause() external onlyRole(DEFAULT_ADMIN_ROLE) { _unpause(); } function setAvailableWithdrawalTypes(uint8 newAvailableWithdrawalTypes) external onlyRole(DEFAULT_ADMIN_ROLE) { require(newAvailableWithdrawalTypes <= ALL_WITHDRAWAL_TYPES_MASK, 'Zunami: wrong available withdrawal types'); availableWithdrawalTypes = newAvailableWithdrawalTypes; } /** * @dev update managementFee, this is a Zunami commission from protocol profit * @param newManagementFee - minAmount 0, maxAmount FEE_DENOMINATOR - 1 */ function setManagementFee(uint256 newManagementFee) external onlyRole(DEFAULT_ADMIN_ROLE) { require(newManagementFee < FEE_DENOMINATOR, 'Zunami: wrong fee'); managementFee = newManagementFee; } /** * @dev Returns managementFee for strategy's when contract sell rewards * @return Returns commission on the amount of profit in the transaction * @param amount - amount of profit for calculate managementFee */ function calcManagementFee(uint256 amount) external view returns (uint256) { return (amount * managementFee) / FEE_DENOMINATOR; } /** * @dev Claims managementFee from all active strategies */ function claimAllManagementFee() external { uint256 feeTotalValue; for (uint256 i = 0; i < _poolInfo.length; i++) { feeTotalValue += _poolInfo[i].strategy.claimManagementFees(); } emit ClaimedAllManagementFee(feeTotalValue); } function autoCompoundAll() external { for (uint256 i = 0; i < _poolInfo.length; i++) { _poolInfo[i].strategy.autoCompound(); } emit AutoCompoundAll(); } /** * @dev Returns total holdings for all pools (strategy's) * @return Returns sum holdings (USD) for all pools */ function totalHoldings() public view returns (uint256) { uint256 length = _poolInfo.length; uint256 totalHold = 0; for (uint256 pid = 0; pid < length; pid++) { totalHold += _poolInfo[pid].strategy.totalHoldings(); } return totalHold; } /** * @dev Returns price depends on the income of users * @return Returns currently price of ZLP (1e18 = 1$) */ function lpPrice() external view returns (uint256) { return (totalHoldings() * 1e18) / totalSupply(); } /** * @dev Returns number of pools * @return number of pools */ function poolCount() external view returns (uint256) { return _poolInfo.length; } /** * @dev in this func user sends funds to the contract and then waits for the completion * of the transaction for all users * @param amounts - array of deposit amounts by user */ function delegateDeposit(uint256[3] memory amounts) external whenNotPaused { for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] > 0) { IERC20Metadata(tokens[i]).safeTransferFrom(_msgSender(), address(this), amounts[i]); pendingDeposits[_msgSender()][i] += amounts[i]; } } emit CreatedPendingDeposit(_msgSender(), amounts); } /** * @dev in this func user sends pending withdraw to the contract and then waits * for the completion of the transaction for all users * @param lpAmount - amount of ZLP for withdraw * @param minAmounts - array of amounts stablecoins that user want minimum receive */ function delegateWithdrawal(uint256 lpAmount, uint256[3] memory minAmounts) external whenNotPaused { PendingWithdrawal memory withdrawal; address userAddr = _msgSender(); require(lpAmount > 0, 'Zunami: lpAmount must be higher 0'); withdrawal.lpShares = lpAmount; withdrawal.minAmounts = minAmounts; pendingWithdrawals[userAddr] = withdrawal; emit CreatedPendingWithdrawal(userAddr, minAmounts, lpAmount); } /** * @dev Zunami protocol owner complete all active pending deposits of users * @param userList - dev send array of users from pending to complete */ function completeDeposits(address[] memory userList) external onlyRole(OPERATOR_ROLE) startedPool { IStrategy strategy = _poolInfo[defaultDepositPid].strategy; uint256 currentTotalHoldings = totalHoldings(); uint256 newHoldings = 0; uint256[3] memory totalAmounts; uint256[] memory userCompleteHoldings = new uint256[](userList.length); for (uint256 i = 0; i < userList.length; i++) { newHoldings = 0; for (uint256 x = 0; x < totalAmounts.length; x++) { uint256 userTokenDeposit = pendingDeposits[userList[i]][x]; totalAmounts[x] += userTokenDeposit; newHoldings += userTokenDeposit * decimalsMultipliers[x]; } userCompleteHoldings[i] = newHoldings; } newHoldings = 0; for (uint256 y = 0; y < POOL_ASSETS; y++) { uint256 totalTokenAmount = totalAmounts[y]; if (totalTokenAmount > 0) { newHoldings += totalTokenAmount * decimalsMultipliers[y]; IERC20Metadata(tokens[y]).safeTransfer(address(strategy), totalTokenAmount); } } uint256 totalDepositedNow = strategy.deposit(totalAmounts); require(totalDepositedNow > 0, 'Zunami: too low deposit!'); uint256 lpShares = 0; uint256 addedHoldings = 0; uint256 userDeposited = 0; for (uint256 z = 0; z < userList.length; z++) { userDeposited = (totalDepositedNow * userCompleteHoldings[z]) / newHoldings; address userAddr = userList[z]; if (totalSupply() == 0) { lpShares = userDeposited; } else { lpShares = (totalSupply() * userDeposited) / (currentTotalHoldings + addedHoldings); } addedHoldings += userDeposited; _mint(userAddr, lpShares); _poolInfo[defaultDepositPid].lpShares += lpShares; emit Deposited(userAddr, pendingDeposits[userAddr], lpShares); // remove deposit from list delete pendingDeposits[userAddr]; } totalDeposited += addedHoldings; } /** * @dev Zunami protocol owner complete all active pending withdrawals of users * @param userList - array of users from pending withdraw to complete */ function completeWithdrawals(address[] memory userList) external onlyRole(OPERATOR_ROLE) startedPool { require(userList.length > 0, 'Zunami: there are no pending withdrawals requests'); IStrategy strategy = _poolInfo[defaultWithdrawPid].strategy; address user; PendingWithdrawal memory withdrawal; for (uint256 i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; if (balanceOf(user) >= withdrawal.lpShares) { if ( !( strategy.withdraw( user, withdrawal.lpShares * 1e18 / _poolInfo[defaultWithdrawPid].lpShares, withdrawal.minAmounts, IStrategy.WithdrawalType.Base, 0 ) ) ) { emit FailedWithdrawal(user, withdrawal.minAmounts, withdrawal.lpShares); delete pendingWithdrawals[user]; continue; } uint256 userDeposit = (totalDeposited * withdrawal.lpShares) / totalSupply(); _burn(user, withdrawal.lpShares); _poolInfo[defaultWithdrawPid].lpShares -= withdrawal.lpShares; totalDeposited -= userDeposit; emit Withdrawn(user, IStrategy.WithdrawalType.Base, withdrawal.minAmounts, withdrawal.lpShares, 0); } delete pendingWithdrawals[user]; } } function completeWithdrawalsOptimized(address[] memory userList) external onlyRole(OPERATOR_ROLE) startedPool { require(userList.length > 0, 'Zunami: there are no pending withdrawals requests'); IStrategy strategy = _poolInfo[defaultWithdrawPid].strategy; uint256 lpSharesTotal; uint256[POOL_ASSETS] memory minAmountsTotal; uint256 i; address user; PendingWithdrawal memory withdrawal; for (i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; if (balanceOf(user) < withdrawal.lpShares) { emit FailedWithdrawal(user, withdrawal.minAmounts, withdrawal.lpShares); delete pendingWithdrawals[user]; continue; } lpSharesTotal += withdrawal.lpShares; minAmountsTotal[0] += withdrawal.minAmounts[0]; minAmountsTotal[1] += withdrawal.minAmounts[1]; minAmountsTotal[2] += withdrawal.minAmounts[2]; emit Withdrawn(user, IStrategy.WithdrawalType.Base, withdrawal.minAmounts, withdrawal.lpShares, 0); } require( lpSharesTotal <= _poolInfo[defaultWithdrawPid].lpShares, "Zunami: Insufficient pool LP shares"); uint256[POOL_ASSETS] memory prevBalances; for (i = 0; i < 3; i++) { prevBalances[i] = IERC20Metadata(tokens[i]).balanceOf(address(this)); } if( !strategy.withdraw(address(this), lpSharesTotal * 1e18 / _poolInfo[defaultWithdrawPid].lpShares, minAmountsTotal, IStrategy.WithdrawalType.Base, 0) ) { //TODO: do we really need to remove delegated requests for (i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; emit FailedWithdrawal(user, withdrawal.minAmounts, withdrawal.lpShares); delete pendingWithdrawals[user]; } return; } uint256[POOL_ASSETS] memory diffBalances; for (i = 0; i < 3; i++) { diffBalances[i] = IERC20Metadata(tokens[i]).balanceOf(address(this)) - prevBalances[i]; } for (i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; uint256 userDeposit = (totalDeposited * withdrawal.lpShares) / totalSupply(); _burn(user, withdrawal.lpShares); _poolInfo[defaultWithdrawPid].lpShares -= withdrawal.lpShares; totalDeposited -= userDeposit; for (uint256 j = 0; j < 3; j++) { IERC20Metadata(tokens[j]).safeTransfer( user, (diffBalances[j] * withdrawal.lpShares) / lpSharesTotal ); } delete pendingWithdrawals[user]; } } /** * @dev deposit in one tx, without waiting complete by dev * @return Returns amount of lpShares minted for user * @param amounts - user send amounts of stablecoins to deposit */ function deposit(uint256[POOL_ASSETS] memory amounts) external whenNotPaused startedPool returns (uint256) { IStrategy strategy = _poolInfo[defaultDepositPid].strategy; uint256 holdings = totalHoldings(); for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] > 0) { IERC20Metadata(tokens[i]).safeTransferFrom( _msgSender(), address(strategy), amounts[i] ); } } uint256 newDeposited = strategy.deposit(amounts); require(newDeposited > 0, 'Zunami: too low deposit!'); uint256 lpShares = 0; if (totalSupply() == 0) { lpShares = newDeposited; } else { lpShares = (totalSupply() * newDeposited) / holdings; } _mint(_msgSender(), lpShares); _poolInfo[defaultDepositPid].lpShares += lpShares; totalDeposited += newDeposited; emit Deposited(_msgSender(), amounts, lpShares); return lpShares; } /** * @dev withdraw in one tx, without waiting complete by dev * @param lpShares - amount of ZLP for withdraw * @param tokenAmounts - array of amounts stablecoins that user want minimum receive */ function withdraw( uint256 lpShares, uint256[POOL_ASSETS] memory tokenAmounts, IStrategy.WithdrawalType withdrawalType, uint128 tokenIndex ) external whenNotPaused startedPool { require( checkBit(availableWithdrawalTypes, uint8(withdrawalType)), 'Zunami: withdrawal type not available' ); IStrategy strategy = _poolInfo[defaultWithdrawPid].strategy; address userAddr = _msgSender(); require(balanceOf(userAddr) >= lpShares, 'Zunami: not enough LP balance'); require( strategy.withdraw(userAddr, lpShares * 1e18 / _poolInfo[defaultWithdrawPid].lpShares, tokenAmounts, withdrawalType, tokenIndex), 'Zunami: user lps share should be at least required' ); uint256 userDeposit = (totalDeposited * lpShares) / totalSupply(); _burn(userAddr, lpShares); _poolInfo[defaultWithdrawPid].lpShares -= lpShares; totalDeposited -= userDeposit; emit Withdrawn(userAddr, withdrawalType, tokenAmounts, lpShares, tokenIndex); } /** * @dev add a new pool, deposits in the new pool are blocked for one day for safety * @param _strategyAddr - the new pool strategy address */ function addPool(address _strategyAddr) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_strategyAddr != address(0), 'Zunami: zero strategy addr'); uint256 startTime = block.timestamp + (launched ? MIN_LOCK_TIME : 0); _poolInfo.push( PoolInfo({ strategy: IStrategy(_strategyAddr), startTime: startTime, lpShares: 0 }) ); emit AddedPool(_poolInfo.length - 1, _strategyAddr, startTime); } /** * @dev set a default pool for deposit funds * @param _newPoolId - new pool id */ function setDefaultDepositPid(uint256 _newPoolId) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_newPoolId < _poolInfo.length, 'Zunami: incorrect default deposit pool id'); defaultDepositPid = _newPoolId; emit SetDefaultDepositPid(_newPoolId); } /** * @dev set a default pool for withdraw funds * @param _newPoolId - new pool id */ function setDefaultWithdrawPid(uint256 _newPoolId) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_newPoolId < _poolInfo.length, 'Zunami: incorrect default withdraw pool id'); defaultWithdrawPid = _newPoolId; emit SetDefaultWithdrawPid(_newPoolId); } function launch() external onlyRole(DEFAULT_ADMIN_ROLE) { launched = true; } /** * @dev dev can transfer funds from few strategy's to one strategy for better APY * @param _strategies - array of strategy's, from which funds are withdrawn * @param withdrawalsPercents - A percentage of the funds that should be transfered * @param _receiverStrategyId - number strategy, to which funds are deposited */ function moveFundsBatch( uint256[] memory _strategies, uint256[] memory withdrawalsPercents, uint256 _receiverStrategyId ) external onlyRole(DEFAULT_ADMIN_ROLE) { require( _strategies.length == withdrawalsPercents.length, 'Zunami: incorrect arguments for the moveFundsBatch' ); require(_receiverStrategyId < _poolInfo.length, 'Zunami: incorrect a reciver strategy ID'); uint256[POOL_ASSETS] memory tokenBalance; for (uint256 y = 0; y < POOL_ASSETS; y++) { tokenBalance[y] = IERC20Metadata(tokens[y]).balanceOf(address(this)); } uint256 pid; uint256 zunamiLp; for (uint256 i = 0; i < _strategies.length; i++) { pid = _strategies[i]; zunamiLp += _moveFunds(pid, withdrawalsPercents[i]); } uint256[POOL_ASSETS] memory tokensRemainder; for (uint256 y = 0; y < POOL_ASSETS; y++) { tokensRemainder[y] = IERC20Metadata(tokens[y]).balanceOf(address(this)) - tokenBalance[y]; if (tokensRemainder[y] > 0) { IERC20Metadata(tokens[y]).safeTransfer( address(_poolInfo[_receiverStrategyId].strategy), tokensRemainder[y] ); } } _poolInfo[_receiverStrategyId].lpShares += zunamiLp; require( _poolInfo[_receiverStrategyId].strategy.deposit(tokensRemainder) > 0, 'Zunami: Too low amount!' ); } function _moveFunds(uint256 pid, uint256 withdrawAmount) private returns (uint256) { uint256 currentLpAmount; if (withdrawAmount == FUNDS_DENOMINATOR) { _poolInfo[pid].strategy.withdrawAll(); currentLpAmount = _poolInfo[pid].lpShares; _poolInfo[pid].lpShares = 0; } else { currentLpAmount = (_poolInfo[pid].lpShares * withdrawAmount) / FUNDS_DENOMINATOR; uint256[POOL_ASSETS] memory minAmounts; _poolInfo[pid].strategy.withdraw( address(this), currentLpAmount * 1e18 / _poolInfo[pid].lpShares, minAmounts, IStrategy.WithdrawalType.Base, 0 ); _poolInfo[pid].lpShares = _poolInfo[pid].lpShares - currentLpAmount; } return currentLpAmount; } /** * @dev user remove his active pending deposit */ function pendingDepositRemove() external { for (uint256 i = 0; i < POOL_ASSETS; i++) { if (pendingDeposits[_msgSender()][i] > 0) { IERC20Metadata(tokens[i]).safeTransfer( _msgSender(), pendingDeposits[_msgSender()][i] ); } } delete pendingDeposits[_msgSender()]; } /** * @dev governance can withdraw all stuck funds in emergency case * @param _token - IERC20Metadata token that should be fully withdraw from Zunami */ function withdrawStuckToken(IERC20Metadata _token) external onlyRole(DEFAULT_ADMIN_ROLE) { uint256 tokenBalance = _token.balanceOf(address(this)); _token.safeTransfer(_msgSender(), tokenBalance); } /** * @dev governance can add new operator for complete pending deposits and withdrawals * @param _newOperator - address that governance add in list of operators */ function updateOperator(address _newOperator) external onlyRole(DEFAULT_ADMIN_ROLE) { _grantRole(OPERATOR_ROLE, _newOperator); } // Get bit value at position function checkBit(uint8 mask, uint8 bit) internal pure returns (bool) { return mask & (0x01 << bit) != 0; } }
/** * * @title Zunami Protocol * * @notice Contract for Convex&Curve protocols optimize. * Users can use this contract for optimize yield and gas. * * * @dev Zunami is main contract. * Contract does not store user funds. * All user funds goes to Convex&Curve pools. * */
NatSpecMultiLine
pendingDepositRemove
function pendingDepositRemove() external { for (uint256 i = 0; i < POOL_ASSETS; i++) { if (pendingDeposits[_msgSender()][i] > 0) { IERC20Metadata(tokens[i]).safeTransfer( _msgSender(), pendingDeposits[_msgSender()][i] ); } } delete pendingDeposits[_msgSender()]; }
/** * @dev user remove his active pending deposit */
NatSpecMultiLine
v0.8.12+commit.f00d7308
{ "func_code_index": [ 21435, 21827 ] }
2,629
Zunami
contracts/Zunami.sol
0x9b43e47bec96a9345cd26fdde7efa5f8c06e126c
Solidity
Zunami
contract Zunami is ERC20, Pausable, AccessControl { using SafeERC20 for IERC20Metadata; bytes32 public constant OPERATOR_ROLE = keccak256('OPERATOR_ROLE'); struct PendingWithdrawal { uint256 lpShares; uint256[3] minAmounts; } struct PoolInfo { IStrategy strategy; uint256 startTime; uint256 lpShares; } uint8 public constant POOL_ASSETS = 3; uint256 public constant FEE_DENOMINATOR = 1000; uint256 public constant MIN_LOCK_TIME = 1 days; uint256 public constant FUNDS_DENOMINATOR = 10_000; uint8 public constant ALL_WITHDRAWAL_TYPES_MASK = uint8(7); // Binary 111 = 2^0 + 2^1 + 2^2; PoolInfo[] internal _poolInfo; uint256 public defaultDepositPid; uint256 public defaultWithdrawPid; uint8 public availableWithdrawalTypes; address[POOL_ASSETS] public tokens; uint256[POOL_ASSETS] public decimalsMultipliers; mapping(address => uint256[POOL_ASSETS]) public pendingDeposits; mapping(address => PendingWithdrawal) public pendingWithdrawals; uint256 public totalDeposited = 0; uint256 public managementFee = 100; // 10% bool public launched = false; event CreatedPendingDeposit(address indexed depositor, uint256[POOL_ASSETS] amounts); event CreatedPendingWithdrawal( address indexed withdrawer, uint256[POOL_ASSETS] amounts, uint256 lpShares ); event Deposited(address indexed depositor, uint256[POOL_ASSETS] amounts, uint256 lpShares); event Withdrawn(address indexed withdrawer, IStrategy.WithdrawalType withdrawalType, uint256[POOL_ASSETS] tokenAmounts, uint256 lpShares, uint128 tokenIndex); event AddedPool(uint256 pid, address strategyAddr, uint256 startTime); event FailedDeposit(address indexed depositor, uint256[POOL_ASSETS] amounts, uint256 lpShares); event FailedWithdrawal(address indexed withdrawer, uint256[POOL_ASSETS] amounts, uint256 lpShares); event SetDefaultDepositPid(uint256 pid); event SetDefaultWithdrawPid(uint256 pid); event ClaimedAllManagementFee(uint256 feeValue); event AutoCompoundAll(); modifier startedPool() { require(_poolInfo.length != 0, 'Zunami: pool not existed!'); require( block.timestamp >= _poolInfo[defaultDepositPid].startTime, 'Zunami: default deposit pool not started yet!' ); require( block.timestamp >= _poolInfo[defaultWithdrawPid].startTime, 'Zunami: default withdraw pool not started yet!' ); _; } constructor(address[POOL_ASSETS] memory _tokens) ERC20('ZunamiLP', 'ZLP') { tokens = _tokens; _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(OPERATOR_ROLE, msg.sender); for (uint256 i; i < POOL_ASSETS; i++) { uint256 decimals = IERC20Metadata(tokens[i]).decimals(); if (decimals < 18) { decimalsMultipliers[i] = 10**(18 - decimals); } else { decimalsMultipliers[i] = 1; } } availableWithdrawalTypes = ALL_WITHDRAWAL_TYPES_MASK; } function poolInfo(uint256 pid) external view returns (PoolInfo memory) { return _poolInfo[pid]; } function pause() external onlyRole(DEFAULT_ADMIN_ROLE) { _pause(); } function unpause() external onlyRole(DEFAULT_ADMIN_ROLE) { _unpause(); } function setAvailableWithdrawalTypes(uint8 newAvailableWithdrawalTypes) external onlyRole(DEFAULT_ADMIN_ROLE) { require(newAvailableWithdrawalTypes <= ALL_WITHDRAWAL_TYPES_MASK, 'Zunami: wrong available withdrawal types'); availableWithdrawalTypes = newAvailableWithdrawalTypes; } /** * @dev update managementFee, this is a Zunami commission from protocol profit * @param newManagementFee - minAmount 0, maxAmount FEE_DENOMINATOR - 1 */ function setManagementFee(uint256 newManagementFee) external onlyRole(DEFAULT_ADMIN_ROLE) { require(newManagementFee < FEE_DENOMINATOR, 'Zunami: wrong fee'); managementFee = newManagementFee; } /** * @dev Returns managementFee for strategy's when contract sell rewards * @return Returns commission on the amount of profit in the transaction * @param amount - amount of profit for calculate managementFee */ function calcManagementFee(uint256 amount) external view returns (uint256) { return (amount * managementFee) / FEE_DENOMINATOR; } /** * @dev Claims managementFee from all active strategies */ function claimAllManagementFee() external { uint256 feeTotalValue; for (uint256 i = 0; i < _poolInfo.length; i++) { feeTotalValue += _poolInfo[i].strategy.claimManagementFees(); } emit ClaimedAllManagementFee(feeTotalValue); } function autoCompoundAll() external { for (uint256 i = 0; i < _poolInfo.length; i++) { _poolInfo[i].strategy.autoCompound(); } emit AutoCompoundAll(); } /** * @dev Returns total holdings for all pools (strategy's) * @return Returns sum holdings (USD) for all pools */ function totalHoldings() public view returns (uint256) { uint256 length = _poolInfo.length; uint256 totalHold = 0; for (uint256 pid = 0; pid < length; pid++) { totalHold += _poolInfo[pid].strategy.totalHoldings(); } return totalHold; } /** * @dev Returns price depends on the income of users * @return Returns currently price of ZLP (1e18 = 1$) */ function lpPrice() external view returns (uint256) { return (totalHoldings() * 1e18) / totalSupply(); } /** * @dev Returns number of pools * @return number of pools */ function poolCount() external view returns (uint256) { return _poolInfo.length; } /** * @dev in this func user sends funds to the contract and then waits for the completion * of the transaction for all users * @param amounts - array of deposit amounts by user */ function delegateDeposit(uint256[3] memory amounts) external whenNotPaused { for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] > 0) { IERC20Metadata(tokens[i]).safeTransferFrom(_msgSender(), address(this), amounts[i]); pendingDeposits[_msgSender()][i] += amounts[i]; } } emit CreatedPendingDeposit(_msgSender(), amounts); } /** * @dev in this func user sends pending withdraw to the contract and then waits * for the completion of the transaction for all users * @param lpAmount - amount of ZLP for withdraw * @param minAmounts - array of amounts stablecoins that user want minimum receive */ function delegateWithdrawal(uint256 lpAmount, uint256[3] memory minAmounts) external whenNotPaused { PendingWithdrawal memory withdrawal; address userAddr = _msgSender(); require(lpAmount > 0, 'Zunami: lpAmount must be higher 0'); withdrawal.lpShares = lpAmount; withdrawal.minAmounts = minAmounts; pendingWithdrawals[userAddr] = withdrawal; emit CreatedPendingWithdrawal(userAddr, minAmounts, lpAmount); } /** * @dev Zunami protocol owner complete all active pending deposits of users * @param userList - dev send array of users from pending to complete */ function completeDeposits(address[] memory userList) external onlyRole(OPERATOR_ROLE) startedPool { IStrategy strategy = _poolInfo[defaultDepositPid].strategy; uint256 currentTotalHoldings = totalHoldings(); uint256 newHoldings = 0; uint256[3] memory totalAmounts; uint256[] memory userCompleteHoldings = new uint256[](userList.length); for (uint256 i = 0; i < userList.length; i++) { newHoldings = 0; for (uint256 x = 0; x < totalAmounts.length; x++) { uint256 userTokenDeposit = pendingDeposits[userList[i]][x]; totalAmounts[x] += userTokenDeposit; newHoldings += userTokenDeposit * decimalsMultipliers[x]; } userCompleteHoldings[i] = newHoldings; } newHoldings = 0; for (uint256 y = 0; y < POOL_ASSETS; y++) { uint256 totalTokenAmount = totalAmounts[y]; if (totalTokenAmount > 0) { newHoldings += totalTokenAmount * decimalsMultipliers[y]; IERC20Metadata(tokens[y]).safeTransfer(address(strategy), totalTokenAmount); } } uint256 totalDepositedNow = strategy.deposit(totalAmounts); require(totalDepositedNow > 0, 'Zunami: too low deposit!'); uint256 lpShares = 0; uint256 addedHoldings = 0; uint256 userDeposited = 0; for (uint256 z = 0; z < userList.length; z++) { userDeposited = (totalDepositedNow * userCompleteHoldings[z]) / newHoldings; address userAddr = userList[z]; if (totalSupply() == 0) { lpShares = userDeposited; } else { lpShares = (totalSupply() * userDeposited) / (currentTotalHoldings + addedHoldings); } addedHoldings += userDeposited; _mint(userAddr, lpShares); _poolInfo[defaultDepositPid].lpShares += lpShares; emit Deposited(userAddr, pendingDeposits[userAddr], lpShares); // remove deposit from list delete pendingDeposits[userAddr]; } totalDeposited += addedHoldings; } /** * @dev Zunami protocol owner complete all active pending withdrawals of users * @param userList - array of users from pending withdraw to complete */ function completeWithdrawals(address[] memory userList) external onlyRole(OPERATOR_ROLE) startedPool { require(userList.length > 0, 'Zunami: there are no pending withdrawals requests'); IStrategy strategy = _poolInfo[defaultWithdrawPid].strategy; address user; PendingWithdrawal memory withdrawal; for (uint256 i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; if (balanceOf(user) >= withdrawal.lpShares) { if ( !( strategy.withdraw( user, withdrawal.lpShares * 1e18 / _poolInfo[defaultWithdrawPid].lpShares, withdrawal.minAmounts, IStrategy.WithdrawalType.Base, 0 ) ) ) { emit FailedWithdrawal(user, withdrawal.minAmounts, withdrawal.lpShares); delete pendingWithdrawals[user]; continue; } uint256 userDeposit = (totalDeposited * withdrawal.lpShares) / totalSupply(); _burn(user, withdrawal.lpShares); _poolInfo[defaultWithdrawPid].lpShares -= withdrawal.lpShares; totalDeposited -= userDeposit; emit Withdrawn(user, IStrategy.WithdrawalType.Base, withdrawal.minAmounts, withdrawal.lpShares, 0); } delete pendingWithdrawals[user]; } } function completeWithdrawalsOptimized(address[] memory userList) external onlyRole(OPERATOR_ROLE) startedPool { require(userList.length > 0, 'Zunami: there are no pending withdrawals requests'); IStrategy strategy = _poolInfo[defaultWithdrawPid].strategy; uint256 lpSharesTotal; uint256[POOL_ASSETS] memory minAmountsTotal; uint256 i; address user; PendingWithdrawal memory withdrawal; for (i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; if (balanceOf(user) < withdrawal.lpShares) { emit FailedWithdrawal(user, withdrawal.minAmounts, withdrawal.lpShares); delete pendingWithdrawals[user]; continue; } lpSharesTotal += withdrawal.lpShares; minAmountsTotal[0] += withdrawal.minAmounts[0]; minAmountsTotal[1] += withdrawal.minAmounts[1]; minAmountsTotal[2] += withdrawal.minAmounts[2]; emit Withdrawn(user, IStrategy.WithdrawalType.Base, withdrawal.minAmounts, withdrawal.lpShares, 0); } require( lpSharesTotal <= _poolInfo[defaultWithdrawPid].lpShares, "Zunami: Insufficient pool LP shares"); uint256[POOL_ASSETS] memory prevBalances; for (i = 0; i < 3; i++) { prevBalances[i] = IERC20Metadata(tokens[i]).balanceOf(address(this)); } if( !strategy.withdraw(address(this), lpSharesTotal * 1e18 / _poolInfo[defaultWithdrawPid].lpShares, minAmountsTotal, IStrategy.WithdrawalType.Base, 0) ) { //TODO: do we really need to remove delegated requests for (i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; emit FailedWithdrawal(user, withdrawal.minAmounts, withdrawal.lpShares); delete pendingWithdrawals[user]; } return; } uint256[POOL_ASSETS] memory diffBalances; for (i = 0; i < 3; i++) { diffBalances[i] = IERC20Metadata(tokens[i]).balanceOf(address(this)) - prevBalances[i]; } for (i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; uint256 userDeposit = (totalDeposited * withdrawal.lpShares) / totalSupply(); _burn(user, withdrawal.lpShares); _poolInfo[defaultWithdrawPid].lpShares -= withdrawal.lpShares; totalDeposited -= userDeposit; for (uint256 j = 0; j < 3; j++) { IERC20Metadata(tokens[j]).safeTransfer( user, (diffBalances[j] * withdrawal.lpShares) / lpSharesTotal ); } delete pendingWithdrawals[user]; } } /** * @dev deposit in one tx, without waiting complete by dev * @return Returns amount of lpShares minted for user * @param amounts - user send amounts of stablecoins to deposit */ function deposit(uint256[POOL_ASSETS] memory amounts) external whenNotPaused startedPool returns (uint256) { IStrategy strategy = _poolInfo[defaultDepositPid].strategy; uint256 holdings = totalHoldings(); for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] > 0) { IERC20Metadata(tokens[i]).safeTransferFrom( _msgSender(), address(strategy), amounts[i] ); } } uint256 newDeposited = strategy.deposit(amounts); require(newDeposited > 0, 'Zunami: too low deposit!'); uint256 lpShares = 0; if (totalSupply() == 0) { lpShares = newDeposited; } else { lpShares = (totalSupply() * newDeposited) / holdings; } _mint(_msgSender(), lpShares); _poolInfo[defaultDepositPid].lpShares += lpShares; totalDeposited += newDeposited; emit Deposited(_msgSender(), amounts, lpShares); return lpShares; } /** * @dev withdraw in one tx, without waiting complete by dev * @param lpShares - amount of ZLP for withdraw * @param tokenAmounts - array of amounts stablecoins that user want minimum receive */ function withdraw( uint256 lpShares, uint256[POOL_ASSETS] memory tokenAmounts, IStrategy.WithdrawalType withdrawalType, uint128 tokenIndex ) external whenNotPaused startedPool { require( checkBit(availableWithdrawalTypes, uint8(withdrawalType)), 'Zunami: withdrawal type not available' ); IStrategy strategy = _poolInfo[defaultWithdrawPid].strategy; address userAddr = _msgSender(); require(balanceOf(userAddr) >= lpShares, 'Zunami: not enough LP balance'); require( strategy.withdraw(userAddr, lpShares * 1e18 / _poolInfo[defaultWithdrawPid].lpShares, tokenAmounts, withdrawalType, tokenIndex), 'Zunami: user lps share should be at least required' ); uint256 userDeposit = (totalDeposited * lpShares) / totalSupply(); _burn(userAddr, lpShares); _poolInfo[defaultWithdrawPid].lpShares -= lpShares; totalDeposited -= userDeposit; emit Withdrawn(userAddr, withdrawalType, tokenAmounts, lpShares, tokenIndex); } /** * @dev add a new pool, deposits in the new pool are blocked for one day for safety * @param _strategyAddr - the new pool strategy address */ function addPool(address _strategyAddr) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_strategyAddr != address(0), 'Zunami: zero strategy addr'); uint256 startTime = block.timestamp + (launched ? MIN_LOCK_TIME : 0); _poolInfo.push( PoolInfo({ strategy: IStrategy(_strategyAddr), startTime: startTime, lpShares: 0 }) ); emit AddedPool(_poolInfo.length - 1, _strategyAddr, startTime); } /** * @dev set a default pool for deposit funds * @param _newPoolId - new pool id */ function setDefaultDepositPid(uint256 _newPoolId) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_newPoolId < _poolInfo.length, 'Zunami: incorrect default deposit pool id'); defaultDepositPid = _newPoolId; emit SetDefaultDepositPid(_newPoolId); } /** * @dev set a default pool for withdraw funds * @param _newPoolId - new pool id */ function setDefaultWithdrawPid(uint256 _newPoolId) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_newPoolId < _poolInfo.length, 'Zunami: incorrect default withdraw pool id'); defaultWithdrawPid = _newPoolId; emit SetDefaultWithdrawPid(_newPoolId); } function launch() external onlyRole(DEFAULT_ADMIN_ROLE) { launched = true; } /** * @dev dev can transfer funds from few strategy's to one strategy for better APY * @param _strategies - array of strategy's, from which funds are withdrawn * @param withdrawalsPercents - A percentage of the funds that should be transfered * @param _receiverStrategyId - number strategy, to which funds are deposited */ function moveFundsBatch( uint256[] memory _strategies, uint256[] memory withdrawalsPercents, uint256 _receiverStrategyId ) external onlyRole(DEFAULT_ADMIN_ROLE) { require( _strategies.length == withdrawalsPercents.length, 'Zunami: incorrect arguments for the moveFundsBatch' ); require(_receiverStrategyId < _poolInfo.length, 'Zunami: incorrect a reciver strategy ID'); uint256[POOL_ASSETS] memory tokenBalance; for (uint256 y = 0; y < POOL_ASSETS; y++) { tokenBalance[y] = IERC20Metadata(tokens[y]).balanceOf(address(this)); } uint256 pid; uint256 zunamiLp; for (uint256 i = 0; i < _strategies.length; i++) { pid = _strategies[i]; zunamiLp += _moveFunds(pid, withdrawalsPercents[i]); } uint256[POOL_ASSETS] memory tokensRemainder; for (uint256 y = 0; y < POOL_ASSETS; y++) { tokensRemainder[y] = IERC20Metadata(tokens[y]).balanceOf(address(this)) - tokenBalance[y]; if (tokensRemainder[y] > 0) { IERC20Metadata(tokens[y]).safeTransfer( address(_poolInfo[_receiverStrategyId].strategy), tokensRemainder[y] ); } } _poolInfo[_receiverStrategyId].lpShares += zunamiLp; require( _poolInfo[_receiverStrategyId].strategy.deposit(tokensRemainder) > 0, 'Zunami: Too low amount!' ); } function _moveFunds(uint256 pid, uint256 withdrawAmount) private returns (uint256) { uint256 currentLpAmount; if (withdrawAmount == FUNDS_DENOMINATOR) { _poolInfo[pid].strategy.withdrawAll(); currentLpAmount = _poolInfo[pid].lpShares; _poolInfo[pid].lpShares = 0; } else { currentLpAmount = (_poolInfo[pid].lpShares * withdrawAmount) / FUNDS_DENOMINATOR; uint256[POOL_ASSETS] memory minAmounts; _poolInfo[pid].strategy.withdraw( address(this), currentLpAmount * 1e18 / _poolInfo[pid].lpShares, minAmounts, IStrategy.WithdrawalType.Base, 0 ); _poolInfo[pid].lpShares = _poolInfo[pid].lpShares - currentLpAmount; } return currentLpAmount; } /** * @dev user remove his active pending deposit */ function pendingDepositRemove() external { for (uint256 i = 0; i < POOL_ASSETS; i++) { if (pendingDeposits[_msgSender()][i] > 0) { IERC20Metadata(tokens[i]).safeTransfer( _msgSender(), pendingDeposits[_msgSender()][i] ); } } delete pendingDeposits[_msgSender()]; } /** * @dev governance can withdraw all stuck funds in emergency case * @param _token - IERC20Metadata token that should be fully withdraw from Zunami */ function withdrawStuckToken(IERC20Metadata _token) external onlyRole(DEFAULT_ADMIN_ROLE) { uint256 tokenBalance = _token.balanceOf(address(this)); _token.safeTransfer(_msgSender(), tokenBalance); } /** * @dev governance can add new operator for complete pending deposits and withdrawals * @param _newOperator - address that governance add in list of operators */ function updateOperator(address _newOperator) external onlyRole(DEFAULT_ADMIN_ROLE) { _grantRole(OPERATOR_ROLE, _newOperator); } // Get bit value at position function checkBit(uint8 mask, uint8 bit) internal pure returns (bool) { return mask & (0x01 << bit) != 0; } }
/** * * @title Zunami Protocol * * @notice Contract for Convex&Curve protocols optimize. * Users can use this contract for optimize yield and gas. * * * @dev Zunami is main contract. * Contract does not store user funds. * All user funds goes to Convex&Curve pools. * */
NatSpecMultiLine
withdrawStuckToken
function withdrawStuckToken(IERC20Metadata _token) external onlyRole(DEFAULT_ADMIN_ROLE) { uint256 tokenBalance = _token.balanceOf(address(this)); _token.safeTransfer(_msgSender(), tokenBalance); }
/** * @dev governance can withdraw all stuck funds in emergency case * @param _token - IERC20Metadata token that should be fully withdraw from Zunami */
NatSpecMultiLine
v0.8.12+commit.f00d7308
{ "func_code_index": [ 22001, 22222 ] }
2,630
Zunami
contracts/Zunami.sol
0x9b43e47bec96a9345cd26fdde7efa5f8c06e126c
Solidity
Zunami
contract Zunami is ERC20, Pausable, AccessControl { using SafeERC20 for IERC20Metadata; bytes32 public constant OPERATOR_ROLE = keccak256('OPERATOR_ROLE'); struct PendingWithdrawal { uint256 lpShares; uint256[3] minAmounts; } struct PoolInfo { IStrategy strategy; uint256 startTime; uint256 lpShares; } uint8 public constant POOL_ASSETS = 3; uint256 public constant FEE_DENOMINATOR = 1000; uint256 public constant MIN_LOCK_TIME = 1 days; uint256 public constant FUNDS_DENOMINATOR = 10_000; uint8 public constant ALL_WITHDRAWAL_TYPES_MASK = uint8(7); // Binary 111 = 2^0 + 2^1 + 2^2; PoolInfo[] internal _poolInfo; uint256 public defaultDepositPid; uint256 public defaultWithdrawPid; uint8 public availableWithdrawalTypes; address[POOL_ASSETS] public tokens; uint256[POOL_ASSETS] public decimalsMultipliers; mapping(address => uint256[POOL_ASSETS]) public pendingDeposits; mapping(address => PendingWithdrawal) public pendingWithdrawals; uint256 public totalDeposited = 0; uint256 public managementFee = 100; // 10% bool public launched = false; event CreatedPendingDeposit(address indexed depositor, uint256[POOL_ASSETS] amounts); event CreatedPendingWithdrawal( address indexed withdrawer, uint256[POOL_ASSETS] amounts, uint256 lpShares ); event Deposited(address indexed depositor, uint256[POOL_ASSETS] amounts, uint256 lpShares); event Withdrawn(address indexed withdrawer, IStrategy.WithdrawalType withdrawalType, uint256[POOL_ASSETS] tokenAmounts, uint256 lpShares, uint128 tokenIndex); event AddedPool(uint256 pid, address strategyAddr, uint256 startTime); event FailedDeposit(address indexed depositor, uint256[POOL_ASSETS] amounts, uint256 lpShares); event FailedWithdrawal(address indexed withdrawer, uint256[POOL_ASSETS] amounts, uint256 lpShares); event SetDefaultDepositPid(uint256 pid); event SetDefaultWithdrawPid(uint256 pid); event ClaimedAllManagementFee(uint256 feeValue); event AutoCompoundAll(); modifier startedPool() { require(_poolInfo.length != 0, 'Zunami: pool not existed!'); require( block.timestamp >= _poolInfo[defaultDepositPid].startTime, 'Zunami: default deposit pool not started yet!' ); require( block.timestamp >= _poolInfo[defaultWithdrawPid].startTime, 'Zunami: default withdraw pool not started yet!' ); _; } constructor(address[POOL_ASSETS] memory _tokens) ERC20('ZunamiLP', 'ZLP') { tokens = _tokens; _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(OPERATOR_ROLE, msg.sender); for (uint256 i; i < POOL_ASSETS; i++) { uint256 decimals = IERC20Metadata(tokens[i]).decimals(); if (decimals < 18) { decimalsMultipliers[i] = 10**(18 - decimals); } else { decimalsMultipliers[i] = 1; } } availableWithdrawalTypes = ALL_WITHDRAWAL_TYPES_MASK; } function poolInfo(uint256 pid) external view returns (PoolInfo memory) { return _poolInfo[pid]; } function pause() external onlyRole(DEFAULT_ADMIN_ROLE) { _pause(); } function unpause() external onlyRole(DEFAULT_ADMIN_ROLE) { _unpause(); } function setAvailableWithdrawalTypes(uint8 newAvailableWithdrawalTypes) external onlyRole(DEFAULT_ADMIN_ROLE) { require(newAvailableWithdrawalTypes <= ALL_WITHDRAWAL_TYPES_MASK, 'Zunami: wrong available withdrawal types'); availableWithdrawalTypes = newAvailableWithdrawalTypes; } /** * @dev update managementFee, this is a Zunami commission from protocol profit * @param newManagementFee - minAmount 0, maxAmount FEE_DENOMINATOR - 1 */ function setManagementFee(uint256 newManagementFee) external onlyRole(DEFAULT_ADMIN_ROLE) { require(newManagementFee < FEE_DENOMINATOR, 'Zunami: wrong fee'); managementFee = newManagementFee; } /** * @dev Returns managementFee for strategy's when contract sell rewards * @return Returns commission on the amount of profit in the transaction * @param amount - amount of profit for calculate managementFee */ function calcManagementFee(uint256 amount) external view returns (uint256) { return (amount * managementFee) / FEE_DENOMINATOR; } /** * @dev Claims managementFee from all active strategies */ function claimAllManagementFee() external { uint256 feeTotalValue; for (uint256 i = 0; i < _poolInfo.length; i++) { feeTotalValue += _poolInfo[i].strategy.claimManagementFees(); } emit ClaimedAllManagementFee(feeTotalValue); } function autoCompoundAll() external { for (uint256 i = 0; i < _poolInfo.length; i++) { _poolInfo[i].strategy.autoCompound(); } emit AutoCompoundAll(); } /** * @dev Returns total holdings for all pools (strategy's) * @return Returns sum holdings (USD) for all pools */ function totalHoldings() public view returns (uint256) { uint256 length = _poolInfo.length; uint256 totalHold = 0; for (uint256 pid = 0; pid < length; pid++) { totalHold += _poolInfo[pid].strategy.totalHoldings(); } return totalHold; } /** * @dev Returns price depends on the income of users * @return Returns currently price of ZLP (1e18 = 1$) */ function lpPrice() external view returns (uint256) { return (totalHoldings() * 1e18) / totalSupply(); } /** * @dev Returns number of pools * @return number of pools */ function poolCount() external view returns (uint256) { return _poolInfo.length; } /** * @dev in this func user sends funds to the contract and then waits for the completion * of the transaction for all users * @param amounts - array of deposit amounts by user */ function delegateDeposit(uint256[3] memory amounts) external whenNotPaused { for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] > 0) { IERC20Metadata(tokens[i]).safeTransferFrom(_msgSender(), address(this), amounts[i]); pendingDeposits[_msgSender()][i] += amounts[i]; } } emit CreatedPendingDeposit(_msgSender(), amounts); } /** * @dev in this func user sends pending withdraw to the contract and then waits * for the completion of the transaction for all users * @param lpAmount - amount of ZLP for withdraw * @param minAmounts - array of amounts stablecoins that user want minimum receive */ function delegateWithdrawal(uint256 lpAmount, uint256[3] memory minAmounts) external whenNotPaused { PendingWithdrawal memory withdrawal; address userAddr = _msgSender(); require(lpAmount > 0, 'Zunami: lpAmount must be higher 0'); withdrawal.lpShares = lpAmount; withdrawal.minAmounts = minAmounts; pendingWithdrawals[userAddr] = withdrawal; emit CreatedPendingWithdrawal(userAddr, minAmounts, lpAmount); } /** * @dev Zunami protocol owner complete all active pending deposits of users * @param userList - dev send array of users from pending to complete */ function completeDeposits(address[] memory userList) external onlyRole(OPERATOR_ROLE) startedPool { IStrategy strategy = _poolInfo[defaultDepositPid].strategy; uint256 currentTotalHoldings = totalHoldings(); uint256 newHoldings = 0; uint256[3] memory totalAmounts; uint256[] memory userCompleteHoldings = new uint256[](userList.length); for (uint256 i = 0; i < userList.length; i++) { newHoldings = 0; for (uint256 x = 0; x < totalAmounts.length; x++) { uint256 userTokenDeposit = pendingDeposits[userList[i]][x]; totalAmounts[x] += userTokenDeposit; newHoldings += userTokenDeposit * decimalsMultipliers[x]; } userCompleteHoldings[i] = newHoldings; } newHoldings = 0; for (uint256 y = 0; y < POOL_ASSETS; y++) { uint256 totalTokenAmount = totalAmounts[y]; if (totalTokenAmount > 0) { newHoldings += totalTokenAmount * decimalsMultipliers[y]; IERC20Metadata(tokens[y]).safeTransfer(address(strategy), totalTokenAmount); } } uint256 totalDepositedNow = strategy.deposit(totalAmounts); require(totalDepositedNow > 0, 'Zunami: too low deposit!'); uint256 lpShares = 0; uint256 addedHoldings = 0; uint256 userDeposited = 0; for (uint256 z = 0; z < userList.length; z++) { userDeposited = (totalDepositedNow * userCompleteHoldings[z]) / newHoldings; address userAddr = userList[z]; if (totalSupply() == 0) { lpShares = userDeposited; } else { lpShares = (totalSupply() * userDeposited) / (currentTotalHoldings + addedHoldings); } addedHoldings += userDeposited; _mint(userAddr, lpShares); _poolInfo[defaultDepositPid].lpShares += lpShares; emit Deposited(userAddr, pendingDeposits[userAddr], lpShares); // remove deposit from list delete pendingDeposits[userAddr]; } totalDeposited += addedHoldings; } /** * @dev Zunami protocol owner complete all active pending withdrawals of users * @param userList - array of users from pending withdraw to complete */ function completeWithdrawals(address[] memory userList) external onlyRole(OPERATOR_ROLE) startedPool { require(userList.length > 0, 'Zunami: there are no pending withdrawals requests'); IStrategy strategy = _poolInfo[defaultWithdrawPid].strategy; address user; PendingWithdrawal memory withdrawal; for (uint256 i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; if (balanceOf(user) >= withdrawal.lpShares) { if ( !( strategy.withdraw( user, withdrawal.lpShares * 1e18 / _poolInfo[defaultWithdrawPid].lpShares, withdrawal.minAmounts, IStrategy.WithdrawalType.Base, 0 ) ) ) { emit FailedWithdrawal(user, withdrawal.minAmounts, withdrawal.lpShares); delete pendingWithdrawals[user]; continue; } uint256 userDeposit = (totalDeposited * withdrawal.lpShares) / totalSupply(); _burn(user, withdrawal.lpShares); _poolInfo[defaultWithdrawPid].lpShares -= withdrawal.lpShares; totalDeposited -= userDeposit; emit Withdrawn(user, IStrategy.WithdrawalType.Base, withdrawal.minAmounts, withdrawal.lpShares, 0); } delete pendingWithdrawals[user]; } } function completeWithdrawalsOptimized(address[] memory userList) external onlyRole(OPERATOR_ROLE) startedPool { require(userList.length > 0, 'Zunami: there are no pending withdrawals requests'); IStrategy strategy = _poolInfo[defaultWithdrawPid].strategy; uint256 lpSharesTotal; uint256[POOL_ASSETS] memory minAmountsTotal; uint256 i; address user; PendingWithdrawal memory withdrawal; for (i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; if (balanceOf(user) < withdrawal.lpShares) { emit FailedWithdrawal(user, withdrawal.minAmounts, withdrawal.lpShares); delete pendingWithdrawals[user]; continue; } lpSharesTotal += withdrawal.lpShares; minAmountsTotal[0] += withdrawal.minAmounts[0]; minAmountsTotal[1] += withdrawal.minAmounts[1]; minAmountsTotal[2] += withdrawal.minAmounts[2]; emit Withdrawn(user, IStrategy.WithdrawalType.Base, withdrawal.minAmounts, withdrawal.lpShares, 0); } require( lpSharesTotal <= _poolInfo[defaultWithdrawPid].lpShares, "Zunami: Insufficient pool LP shares"); uint256[POOL_ASSETS] memory prevBalances; for (i = 0; i < 3; i++) { prevBalances[i] = IERC20Metadata(tokens[i]).balanceOf(address(this)); } if( !strategy.withdraw(address(this), lpSharesTotal * 1e18 / _poolInfo[defaultWithdrawPid].lpShares, minAmountsTotal, IStrategy.WithdrawalType.Base, 0) ) { //TODO: do we really need to remove delegated requests for (i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; emit FailedWithdrawal(user, withdrawal.minAmounts, withdrawal.lpShares); delete pendingWithdrawals[user]; } return; } uint256[POOL_ASSETS] memory diffBalances; for (i = 0; i < 3; i++) { diffBalances[i] = IERC20Metadata(tokens[i]).balanceOf(address(this)) - prevBalances[i]; } for (i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; uint256 userDeposit = (totalDeposited * withdrawal.lpShares) / totalSupply(); _burn(user, withdrawal.lpShares); _poolInfo[defaultWithdrawPid].lpShares -= withdrawal.lpShares; totalDeposited -= userDeposit; for (uint256 j = 0; j < 3; j++) { IERC20Metadata(tokens[j]).safeTransfer( user, (diffBalances[j] * withdrawal.lpShares) / lpSharesTotal ); } delete pendingWithdrawals[user]; } } /** * @dev deposit in one tx, without waiting complete by dev * @return Returns amount of lpShares minted for user * @param amounts - user send amounts of stablecoins to deposit */ function deposit(uint256[POOL_ASSETS] memory amounts) external whenNotPaused startedPool returns (uint256) { IStrategy strategy = _poolInfo[defaultDepositPid].strategy; uint256 holdings = totalHoldings(); for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] > 0) { IERC20Metadata(tokens[i]).safeTransferFrom( _msgSender(), address(strategy), amounts[i] ); } } uint256 newDeposited = strategy.deposit(amounts); require(newDeposited > 0, 'Zunami: too low deposit!'); uint256 lpShares = 0; if (totalSupply() == 0) { lpShares = newDeposited; } else { lpShares = (totalSupply() * newDeposited) / holdings; } _mint(_msgSender(), lpShares); _poolInfo[defaultDepositPid].lpShares += lpShares; totalDeposited += newDeposited; emit Deposited(_msgSender(), amounts, lpShares); return lpShares; } /** * @dev withdraw in one tx, without waiting complete by dev * @param lpShares - amount of ZLP for withdraw * @param tokenAmounts - array of amounts stablecoins that user want minimum receive */ function withdraw( uint256 lpShares, uint256[POOL_ASSETS] memory tokenAmounts, IStrategy.WithdrawalType withdrawalType, uint128 tokenIndex ) external whenNotPaused startedPool { require( checkBit(availableWithdrawalTypes, uint8(withdrawalType)), 'Zunami: withdrawal type not available' ); IStrategy strategy = _poolInfo[defaultWithdrawPid].strategy; address userAddr = _msgSender(); require(balanceOf(userAddr) >= lpShares, 'Zunami: not enough LP balance'); require( strategy.withdraw(userAddr, lpShares * 1e18 / _poolInfo[defaultWithdrawPid].lpShares, tokenAmounts, withdrawalType, tokenIndex), 'Zunami: user lps share should be at least required' ); uint256 userDeposit = (totalDeposited * lpShares) / totalSupply(); _burn(userAddr, lpShares); _poolInfo[defaultWithdrawPid].lpShares -= lpShares; totalDeposited -= userDeposit; emit Withdrawn(userAddr, withdrawalType, tokenAmounts, lpShares, tokenIndex); } /** * @dev add a new pool, deposits in the new pool are blocked for one day for safety * @param _strategyAddr - the new pool strategy address */ function addPool(address _strategyAddr) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_strategyAddr != address(0), 'Zunami: zero strategy addr'); uint256 startTime = block.timestamp + (launched ? MIN_LOCK_TIME : 0); _poolInfo.push( PoolInfo({ strategy: IStrategy(_strategyAddr), startTime: startTime, lpShares: 0 }) ); emit AddedPool(_poolInfo.length - 1, _strategyAddr, startTime); } /** * @dev set a default pool for deposit funds * @param _newPoolId - new pool id */ function setDefaultDepositPid(uint256 _newPoolId) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_newPoolId < _poolInfo.length, 'Zunami: incorrect default deposit pool id'); defaultDepositPid = _newPoolId; emit SetDefaultDepositPid(_newPoolId); } /** * @dev set a default pool for withdraw funds * @param _newPoolId - new pool id */ function setDefaultWithdrawPid(uint256 _newPoolId) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_newPoolId < _poolInfo.length, 'Zunami: incorrect default withdraw pool id'); defaultWithdrawPid = _newPoolId; emit SetDefaultWithdrawPid(_newPoolId); } function launch() external onlyRole(DEFAULT_ADMIN_ROLE) { launched = true; } /** * @dev dev can transfer funds from few strategy's to one strategy for better APY * @param _strategies - array of strategy's, from which funds are withdrawn * @param withdrawalsPercents - A percentage of the funds that should be transfered * @param _receiverStrategyId - number strategy, to which funds are deposited */ function moveFundsBatch( uint256[] memory _strategies, uint256[] memory withdrawalsPercents, uint256 _receiverStrategyId ) external onlyRole(DEFAULT_ADMIN_ROLE) { require( _strategies.length == withdrawalsPercents.length, 'Zunami: incorrect arguments for the moveFundsBatch' ); require(_receiverStrategyId < _poolInfo.length, 'Zunami: incorrect a reciver strategy ID'); uint256[POOL_ASSETS] memory tokenBalance; for (uint256 y = 0; y < POOL_ASSETS; y++) { tokenBalance[y] = IERC20Metadata(tokens[y]).balanceOf(address(this)); } uint256 pid; uint256 zunamiLp; for (uint256 i = 0; i < _strategies.length; i++) { pid = _strategies[i]; zunamiLp += _moveFunds(pid, withdrawalsPercents[i]); } uint256[POOL_ASSETS] memory tokensRemainder; for (uint256 y = 0; y < POOL_ASSETS; y++) { tokensRemainder[y] = IERC20Metadata(tokens[y]).balanceOf(address(this)) - tokenBalance[y]; if (tokensRemainder[y] > 0) { IERC20Metadata(tokens[y]).safeTransfer( address(_poolInfo[_receiverStrategyId].strategy), tokensRemainder[y] ); } } _poolInfo[_receiverStrategyId].lpShares += zunamiLp; require( _poolInfo[_receiverStrategyId].strategy.deposit(tokensRemainder) > 0, 'Zunami: Too low amount!' ); } function _moveFunds(uint256 pid, uint256 withdrawAmount) private returns (uint256) { uint256 currentLpAmount; if (withdrawAmount == FUNDS_DENOMINATOR) { _poolInfo[pid].strategy.withdrawAll(); currentLpAmount = _poolInfo[pid].lpShares; _poolInfo[pid].lpShares = 0; } else { currentLpAmount = (_poolInfo[pid].lpShares * withdrawAmount) / FUNDS_DENOMINATOR; uint256[POOL_ASSETS] memory minAmounts; _poolInfo[pid].strategy.withdraw( address(this), currentLpAmount * 1e18 / _poolInfo[pid].lpShares, minAmounts, IStrategy.WithdrawalType.Base, 0 ); _poolInfo[pid].lpShares = _poolInfo[pid].lpShares - currentLpAmount; } return currentLpAmount; } /** * @dev user remove his active pending deposit */ function pendingDepositRemove() external { for (uint256 i = 0; i < POOL_ASSETS; i++) { if (pendingDeposits[_msgSender()][i] > 0) { IERC20Metadata(tokens[i]).safeTransfer( _msgSender(), pendingDeposits[_msgSender()][i] ); } } delete pendingDeposits[_msgSender()]; } /** * @dev governance can withdraw all stuck funds in emergency case * @param _token - IERC20Metadata token that should be fully withdraw from Zunami */ function withdrawStuckToken(IERC20Metadata _token) external onlyRole(DEFAULT_ADMIN_ROLE) { uint256 tokenBalance = _token.balanceOf(address(this)); _token.safeTransfer(_msgSender(), tokenBalance); } /** * @dev governance can add new operator for complete pending deposits and withdrawals * @param _newOperator - address that governance add in list of operators */ function updateOperator(address _newOperator) external onlyRole(DEFAULT_ADMIN_ROLE) { _grantRole(OPERATOR_ROLE, _newOperator); } // Get bit value at position function checkBit(uint8 mask, uint8 bit) internal pure returns (bool) { return mask & (0x01 << bit) != 0; } }
/** * * @title Zunami Protocol * * @notice Contract for Convex&Curve protocols optimize. * Users can use this contract for optimize yield and gas. * * * @dev Zunami is main contract. * Contract does not store user funds. * All user funds goes to Convex&Curve pools. * */
NatSpecMultiLine
updateOperator
function updateOperator(address _newOperator) external onlyRole(DEFAULT_ADMIN_ROLE) { _grantRole(OPERATOR_ROLE, _newOperator); }
/** * @dev governance can add new operator for complete pending deposits and withdrawals * @param _newOperator - address that governance add in list of operators */
NatSpecMultiLine
v0.8.12+commit.f00d7308
{ "func_code_index": [ 22408, 22552 ] }
2,631
Zunami
contracts/Zunami.sol
0x9b43e47bec96a9345cd26fdde7efa5f8c06e126c
Solidity
Zunami
contract Zunami is ERC20, Pausable, AccessControl { using SafeERC20 for IERC20Metadata; bytes32 public constant OPERATOR_ROLE = keccak256('OPERATOR_ROLE'); struct PendingWithdrawal { uint256 lpShares; uint256[3] minAmounts; } struct PoolInfo { IStrategy strategy; uint256 startTime; uint256 lpShares; } uint8 public constant POOL_ASSETS = 3; uint256 public constant FEE_DENOMINATOR = 1000; uint256 public constant MIN_LOCK_TIME = 1 days; uint256 public constant FUNDS_DENOMINATOR = 10_000; uint8 public constant ALL_WITHDRAWAL_TYPES_MASK = uint8(7); // Binary 111 = 2^0 + 2^1 + 2^2; PoolInfo[] internal _poolInfo; uint256 public defaultDepositPid; uint256 public defaultWithdrawPid; uint8 public availableWithdrawalTypes; address[POOL_ASSETS] public tokens; uint256[POOL_ASSETS] public decimalsMultipliers; mapping(address => uint256[POOL_ASSETS]) public pendingDeposits; mapping(address => PendingWithdrawal) public pendingWithdrawals; uint256 public totalDeposited = 0; uint256 public managementFee = 100; // 10% bool public launched = false; event CreatedPendingDeposit(address indexed depositor, uint256[POOL_ASSETS] amounts); event CreatedPendingWithdrawal( address indexed withdrawer, uint256[POOL_ASSETS] amounts, uint256 lpShares ); event Deposited(address indexed depositor, uint256[POOL_ASSETS] amounts, uint256 lpShares); event Withdrawn(address indexed withdrawer, IStrategy.WithdrawalType withdrawalType, uint256[POOL_ASSETS] tokenAmounts, uint256 lpShares, uint128 tokenIndex); event AddedPool(uint256 pid, address strategyAddr, uint256 startTime); event FailedDeposit(address indexed depositor, uint256[POOL_ASSETS] amounts, uint256 lpShares); event FailedWithdrawal(address indexed withdrawer, uint256[POOL_ASSETS] amounts, uint256 lpShares); event SetDefaultDepositPid(uint256 pid); event SetDefaultWithdrawPid(uint256 pid); event ClaimedAllManagementFee(uint256 feeValue); event AutoCompoundAll(); modifier startedPool() { require(_poolInfo.length != 0, 'Zunami: pool not existed!'); require( block.timestamp >= _poolInfo[defaultDepositPid].startTime, 'Zunami: default deposit pool not started yet!' ); require( block.timestamp >= _poolInfo[defaultWithdrawPid].startTime, 'Zunami: default withdraw pool not started yet!' ); _; } constructor(address[POOL_ASSETS] memory _tokens) ERC20('ZunamiLP', 'ZLP') { tokens = _tokens; _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(OPERATOR_ROLE, msg.sender); for (uint256 i; i < POOL_ASSETS; i++) { uint256 decimals = IERC20Metadata(tokens[i]).decimals(); if (decimals < 18) { decimalsMultipliers[i] = 10**(18 - decimals); } else { decimalsMultipliers[i] = 1; } } availableWithdrawalTypes = ALL_WITHDRAWAL_TYPES_MASK; } function poolInfo(uint256 pid) external view returns (PoolInfo memory) { return _poolInfo[pid]; } function pause() external onlyRole(DEFAULT_ADMIN_ROLE) { _pause(); } function unpause() external onlyRole(DEFAULT_ADMIN_ROLE) { _unpause(); } function setAvailableWithdrawalTypes(uint8 newAvailableWithdrawalTypes) external onlyRole(DEFAULT_ADMIN_ROLE) { require(newAvailableWithdrawalTypes <= ALL_WITHDRAWAL_TYPES_MASK, 'Zunami: wrong available withdrawal types'); availableWithdrawalTypes = newAvailableWithdrawalTypes; } /** * @dev update managementFee, this is a Zunami commission from protocol profit * @param newManagementFee - minAmount 0, maxAmount FEE_DENOMINATOR - 1 */ function setManagementFee(uint256 newManagementFee) external onlyRole(DEFAULT_ADMIN_ROLE) { require(newManagementFee < FEE_DENOMINATOR, 'Zunami: wrong fee'); managementFee = newManagementFee; } /** * @dev Returns managementFee for strategy's when contract sell rewards * @return Returns commission on the amount of profit in the transaction * @param amount - amount of profit for calculate managementFee */ function calcManagementFee(uint256 amount) external view returns (uint256) { return (amount * managementFee) / FEE_DENOMINATOR; } /** * @dev Claims managementFee from all active strategies */ function claimAllManagementFee() external { uint256 feeTotalValue; for (uint256 i = 0; i < _poolInfo.length; i++) { feeTotalValue += _poolInfo[i].strategy.claimManagementFees(); } emit ClaimedAllManagementFee(feeTotalValue); } function autoCompoundAll() external { for (uint256 i = 0; i < _poolInfo.length; i++) { _poolInfo[i].strategy.autoCompound(); } emit AutoCompoundAll(); } /** * @dev Returns total holdings for all pools (strategy's) * @return Returns sum holdings (USD) for all pools */ function totalHoldings() public view returns (uint256) { uint256 length = _poolInfo.length; uint256 totalHold = 0; for (uint256 pid = 0; pid < length; pid++) { totalHold += _poolInfo[pid].strategy.totalHoldings(); } return totalHold; } /** * @dev Returns price depends on the income of users * @return Returns currently price of ZLP (1e18 = 1$) */ function lpPrice() external view returns (uint256) { return (totalHoldings() * 1e18) / totalSupply(); } /** * @dev Returns number of pools * @return number of pools */ function poolCount() external view returns (uint256) { return _poolInfo.length; } /** * @dev in this func user sends funds to the contract and then waits for the completion * of the transaction for all users * @param amounts - array of deposit amounts by user */ function delegateDeposit(uint256[3] memory amounts) external whenNotPaused { for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] > 0) { IERC20Metadata(tokens[i]).safeTransferFrom(_msgSender(), address(this), amounts[i]); pendingDeposits[_msgSender()][i] += amounts[i]; } } emit CreatedPendingDeposit(_msgSender(), amounts); } /** * @dev in this func user sends pending withdraw to the contract and then waits * for the completion of the transaction for all users * @param lpAmount - amount of ZLP for withdraw * @param minAmounts - array of amounts stablecoins that user want minimum receive */ function delegateWithdrawal(uint256 lpAmount, uint256[3] memory minAmounts) external whenNotPaused { PendingWithdrawal memory withdrawal; address userAddr = _msgSender(); require(lpAmount > 0, 'Zunami: lpAmount must be higher 0'); withdrawal.lpShares = lpAmount; withdrawal.minAmounts = minAmounts; pendingWithdrawals[userAddr] = withdrawal; emit CreatedPendingWithdrawal(userAddr, minAmounts, lpAmount); } /** * @dev Zunami protocol owner complete all active pending deposits of users * @param userList - dev send array of users from pending to complete */ function completeDeposits(address[] memory userList) external onlyRole(OPERATOR_ROLE) startedPool { IStrategy strategy = _poolInfo[defaultDepositPid].strategy; uint256 currentTotalHoldings = totalHoldings(); uint256 newHoldings = 0; uint256[3] memory totalAmounts; uint256[] memory userCompleteHoldings = new uint256[](userList.length); for (uint256 i = 0; i < userList.length; i++) { newHoldings = 0; for (uint256 x = 0; x < totalAmounts.length; x++) { uint256 userTokenDeposit = pendingDeposits[userList[i]][x]; totalAmounts[x] += userTokenDeposit; newHoldings += userTokenDeposit * decimalsMultipliers[x]; } userCompleteHoldings[i] = newHoldings; } newHoldings = 0; for (uint256 y = 0; y < POOL_ASSETS; y++) { uint256 totalTokenAmount = totalAmounts[y]; if (totalTokenAmount > 0) { newHoldings += totalTokenAmount * decimalsMultipliers[y]; IERC20Metadata(tokens[y]).safeTransfer(address(strategy), totalTokenAmount); } } uint256 totalDepositedNow = strategy.deposit(totalAmounts); require(totalDepositedNow > 0, 'Zunami: too low deposit!'); uint256 lpShares = 0; uint256 addedHoldings = 0; uint256 userDeposited = 0; for (uint256 z = 0; z < userList.length; z++) { userDeposited = (totalDepositedNow * userCompleteHoldings[z]) / newHoldings; address userAddr = userList[z]; if (totalSupply() == 0) { lpShares = userDeposited; } else { lpShares = (totalSupply() * userDeposited) / (currentTotalHoldings + addedHoldings); } addedHoldings += userDeposited; _mint(userAddr, lpShares); _poolInfo[defaultDepositPid].lpShares += lpShares; emit Deposited(userAddr, pendingDeposits[userAddr], lpShares); // remove deposit from list delete pendingDeposits[userAddr]; } totalDeposited += addedHoldings; } /** * @dev Zunami protocol owner complete all active pending withdrawals of users * @param userList - array of users from pending withdraw to complete */ function completeWithdrawals(address[] memory userList) external onlyRole(OPERATOR_ROLE) startedPool { require(userList.length > 0, 'Zunami: there are no pending withdrawals requests'); IStrategy strategy = _poolInfo[defaultWithdrawPid].strategy; address user; PendingWithdrawal memory withdrawal; for (uint256 i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; if (balanceOf(user) >= withdrawal.lpShares) { if ( !( strategy.withdraw( user, withdrawal.lpShares * 1e18 / _poolInfo[defaultWithdrawPid].lpShares, withdrawal.minAmounts, IStrategy.WithdrawalType.Base, 0 ) ) ) { emit FailedWithdrawal(user, withdrawal.minAmounts, withdrawal.lpShares); delete pendingWithdrawals[user]; continue; } uint256 userDeposit = (totalDeposited * withdrawal.lpShares) / totalSupply(); _burn(user, withdrawal.lpShares); _poolInfo[defaultWithdrawPid].lpShares -= withdrawal.lpShares; totalDeposited -= userDeposit; emit Withdrawn(user, IStrategy.WithdrawalType.Base, withdrawal.minAmounts, withdrawal.lpShares, 0); } delete pendingWithdrawals[user]; } } function completeWithdrawalsOptimized(address[] memory userList) external onlyRole(OPERATOR_ROLE) startedPool { require(userList.length > 0, 'Zunami: there are no pending withdrawals requests'); IStrategy strategy = _poolInfo[defaultWithdrawPid].strategy; uint256 lpSharesTotal; uint256[POOL_ASSETS] memory minAmountsTotal; uint256 i; address user; PendingWithdrawal memory withdrawal; for (i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; if (balanceOf(user) < withdrawal.lpShares) { emit FailedWithdrawal(user, withdrawal.minAmounts, withdrawal.lpShares); delete pendingWithdrawals[user]; continue; } lpSharesTotal += withdrawal.lpShares; minAmountsTotal[0] += withdrawal.minAmounts[0]; minAmountsTotal[1] += withdrawal.minAmounts[1]; minAmountsTotal[2] += withdrawal.minAmounts[2]; emit Withdrawn(user, IStrategy.WithdrawalType.Base, withdrawal.minAmounts, withdrawal.lpShares, 0); } require( lpSharesTotal <= _poolInfo[defaultWithdrawPid].lpShares, "Zunami: Insufficient pool LP shares"); uint256[POOL_ASSETS] memory prevBalances; for (i = 0; i < 3; i++) { prevBalances[i] = IERC20Metadata(tokens[i]).balanceOf(address(this)); } if( !strategy.withdraw(address(this), lpSharesTotal * 1e18 / _poolInfo[defaultWithdrawPid].lpShares, minAmountsTotal, IStrategy.WithdrawalType.Base, 0) ) { //TODO: do we really need to remove delegated requests for (i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; emit FailedWithdrawal(user, withdrawal.minAmounts, withdrawal.lpShares); delete pendingWithdrawals[user]; } return; } uint256[POOL_ASSETS] memory diffBalances; for (i = 0; i < 3; i++) { diffBalances[i] = IERC20Metadata(tokens[i]).balanceOf(address(this)) - prevBalances[i]; } for (i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; uint256 userDeposit = (totalDeposited * withdrawal.lpShares) / totalSupply(); _burn(user, withdrawal.lpShares); _poolInfo[defaultWithdrawPid].lpShares -= withdrawal.lpShares; totalDeposited -= userDeposit; for (uint256 j = 0; j < 3; j++) { IERC20Metadata(tokens[j]).safeTransfer( user, (diffBalances[j] * withdrawal.lpShares) / lpSharesTotal ); } delete pendingWithdrawals[user]; } } /** * @dev deposit in one tx, without waiting complete by dev * @return Returns amount of lpShares minted for user * @param amounts - user send amounts of stablecoins to deposit */ function deposit(uint256[POOL_ASSETS] memory amounts) external whenNotPaused startedPool returns (uint256) { IStrategy strategy = _poolInfo[defaultDepositPid].strategy; uint256 holdings = totalHoldings(); for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] > 0) { IERC20Metadata(tokens[i]).safeTransferFrom( _msgSender(), address(strategy), amounts[i] ); } } uint256 newDeposited = strategy.deposit(amounts); require(newDeposited > 0, 'Zunami: too low deposit!'); uint256 lpShares = 0; if (totalSupply() == 0) { lpShares = newDeposited; } else { lpShares = (totalSupply() * newDeposited) / holdings; } _mint(_msgSender(), lpShares); _poolInfo[defaultDepositPid].lpShares += lpShares; totalDeposited += newDeposited; emit Deposited(_msgSender(), amounts, lpShares); return lpShares; } /** * @dev withdraw in one tx, without waiting complete by dev * @param lpShares - amount of ZLP for withdraw * @param tokenAmounts - array of amounts stablecoins that user want minimum receive */ function withdraw( uint256 lpShares, uint256[POOL_ASSETS] memory tokenAmounts, IStrategy.WithdrawalType withdrawalType, uint128 tokenIndex ) external whenNotPaused startedPool { require( checkBit(availableWithdrawalTypes, uint8(withdrawalType)), 'Zunami: withdrawal type not available' ); IStrategy strategy = _poolInfo[defaultWithdrawPid].strategy; address userAddr = _msgSender(); require(balanceOf(userAddr) >= lpShares, 'Zunami: not enough LP balance'); require( strategy.withdraw(userAddr, lpShares * 1e18 / _poolInfo[defaultWithdrawPid].lpShares, tokenAmounts, withdrawalType, tokenIndex), 'Zunami: user lps share should be at least required' ); uint256 userDeposit = (totalDeposited * lpShares) / totalSupply(); _burn(userAddr, lpShares); _poolInfo[defaultWithdrawPid].lpShares -= lpShares; totalDeposited -= userDeposit; emit Withdrawn(userAddr, withdrawalType, tokenAmounts, lpShares, tokenIndex); } /** * @dev add a new pool, deposits in the new pool are blocked for one day for safety * @param _strategyAddr - the new pool strategy address */ function addPool(address _strategyAddr) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_strategyAddr != address(0), 'Zunami: zero strategy addr'); uint256 startTime = block.timestamp + (launched ? MIN_LOCK_TIME : 0); _poolInfo.push( PoolInfo({ strategy: IStrategy(_strategyAddr), startTime: startTime, lpShares: 0 }) ); emit AddedPool(_poolInfo.length - 1, _strategyAddr, startTime); } /** * @dev set a default pool for deposit funds * @param _newPoolId - new pool id */ function setDefaultDepositPid(uint256 _newPoolId) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_newPoolId < _poolInfo.length, 'Zunami: incorrect default deposit pool id'); defaultDepositPid = _newPoolId; emit SetDefaultDepositPid(_newPoolId); } /** * @dev set a default pool for withdraw funds * @param _newPoolId - new pool id */ function setDefaultWithdrawPid(uint256 _newPoolId) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_newPoolId < _poolInfo.length, 'Zunami: incorrect default withdraw pool id'); defaultWithdrawPid = _newPoolId; emit SetDefaultWithdrawPid(_newPoolId); } function launch() external onlyRole(DEFAULT_ADMIN_ROLE) { launched = true; } /** * @dev dev can transfer funds from few strategy's to one strategy for better APY * @param _strategies - array of strategy's, from which funds are withdrawn * @param withdrawalsPercents - A percentage of the funds that should be transfered * @param _receiverStrategyId - number strategy, to which funds are deposited */ function moveFundsBatch( uint256[] memory _strategies, uint256[] memory withdrawalsPercents, uint256 _receiverStrategyId ) external onlyRole(DEFAULT_ADMIN_ROLE) { require( _strategies.length == withdrawalsPercents.length, 'Zunami: incorrect arguments for the moveFundsBatch' ); require(_receiverStrategyId < _poolInfo.length, 'Zunami: incorrect a reciver strategy ID'); uint256[POOL_ASSETS] memory tokenBalance; for (uint256 y = 0; y < POOL_ASSETS; y++) { tokenBalance[y] = IERC20Metadata(tokens[y]).balanceOf(address(this)); } uint256 pid; uint256 zunamiLp; for (uint256 i = 0; i < _strategies.length; i++) { pid = _strategies[i]; zunamiLp += _moveFunds(pid, withdrawalsPercents[i]); } uint256[POOL_ASSETS] memory tokensRemainder; for (uint256 y = 0; y < POOL_ASSETS; y++) { tokensRemainder[y] = IERC20Metadata(tokens[y]).balanceOf(address(this)) - tokenBalance[y]; if (tokensRemainder[y] > 0) { IERC20Metadata(tokens[y]).safeTransfer( address(_poolInfo[_receiverStrategyId].strategy), tokensRemainder[y] ); } } _poolInfo[_receiverStrategyId].lpShares += zunamiLp; require( _poolInfo[_receiverStrategyId].strategy.deposit(tokensRemainder) > 0, 'Zunami: Too low amount!' ); } function _moveFunds(uint256 pid, uint256 withdrawAmount) private returns (uint256) { uint256 currentLpAmount; if (withdrawAmount == FUNDS_DENOMINATOR) { _poolInfo[pid].strategy.withdrawAll(); currentLpAmount = _poolInfo[pid].lpShares; _poolInfo[pid].lpShares = 0; } else { currentLpAmount = (_poolInfo[pid].lpShares * withdrawAmount) / FUNDS_DENOMINATOR; uint256[POOL_ASSETS] memory minAmounts; _poolInfo[pid].strategy.withdraw( address(this), currentLpAmount * 1e18 / _poolInfo[pid].lpShares, minAmounts, IStrategy.WithdrawalType.Base, 0 ); _poolInfo[pid].lpShares = _poolInfo[pid].lpShares - currentLpAmount; } return currentLpAmount; } /** * @dev user remove his active pending deposit */ function pendingDepositRemove() external { for (uint256 i = 0; i < POOL_ASSETS; i++) { if (pendingDeposits[_msgSender()][i] > 0) { IERC20Metadata(tokens[i]).safeTransfer( _msgSender(), pendingDeposits[_msgSender()][i] ); } } delete pendingDeposits[_msgSender()]; } /** * @dev governance can withdraw all stuck funds in emergency case * @param _token - IERC20Metadata token that should be fully withdraw from Zunami */ function withdrawStuckToken(IERC20Metadata _token) external onlyRole(DEFAULT_ADMIN_ROLE) { uint256 tokenBalance = _token.balanceOf(address(this)); _token.safeTransfer(_msgSender(), tokenBalance); } /** * @dev governance can add new operator for complete pending deposits and withdrawals * @param _newOperator - address that governance add in list of operators */ function updateOperator(address _newOperator) external onlyRole(DEFAULT_ADMIN_ROLE) { _grantRole(OPERATOR_ROLE, _newOperator); } // Get bit value at position function checkBit(uint8 mask, uint8 bit) internal pure returns (bool) { return mask & (0x01 << bit) != 0; } }
/** * * @title Zunami Protocol * * @notice Contract for Convex&Curve protocols optimize. * Users can use this contract for optimize yield and gas. * * * @dev Zunami is main contract. * Contract does not store user funds. * All user funds goes to Convex&Curve pools. * */
NatSpecMultiLine
checkBit
function checkBit(uint8 mask, uint8 bit) internal pure returns (bool) { return mask & (0x01 << bit) != 0; }
// Get bit value at position
LineComment
v0.8.12+commit.f00d7308
{ "func_code_index": [ 22587, 22710 ] }
2,632
StickFighter
@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol
0x9b121e19fc09b777ffa6fbd58ab980d1cf0503c4
Solidity
ERC721Enumerable
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(); } }
/** * @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. */
NatSpecMultiLine
supportsInterface
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); }
/** * @dev See {IERC165-supportsInterface}. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
MIT
ipfs://5e5e7855cd66c8862cb436fbe3015780c3301ca66101dc7cadb46ef4ed076abe
{ "func_code_index": [ 605, 834 ] }
2,633
StickFighter
@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol
0x9b121e19fc09b777ffa6fbd58ab980d1cf0503c4
Solidity
ERC721Enumerable
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(); } }
/** * @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. */
NatSpecMultiLine
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-tokenOfOwnerByIndex}. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
MIT
ipfs://5e5e7855cd66c8862cb436fbe3015780c3301ca66101dc7cadb46ef4ed076abe
{ "func_code_index": [ 913, 1174 ] }
2,634
StickFighter
@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol
0x9b121e19fc09b777ffa6fbd58ab980d1cf0503c4
Solidity
ERC721Enumerable
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(); } }
/** * @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. */
NatSpecMultiLine
totalSupply
function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; }
/** * @dev See {IERC721Enumerable-totalSupply}. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
MIT
ipfs://5e5e7855cd66c8862cb436fbe3015780c3301ca66101dc7cadb46ef4ed076abe
{ "func_code_index": [ 1245, 1363 ] }
2,635
StickFighter
@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol
0x9b121e19fc09b777ffa6fbd58ab980d1cf0503c4
Solidity
ERC721Enumerable
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(); } }
/** * @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. */
NatSpecMultiLine
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 See {IERC721Enumerable-tokenByIndex}. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
MIT
ipfs://5e5e7855cd66c8862cb436fbe3015780c3301ca66101dc7cadb46ef4ed076abe
{ "func_code_index": [ 1435, 1673 ] }
2,636
StickFighter
@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol
0x9b121e19fc09b777ffa6fbd58ab980d1cf0503c4
Solidity
ERC721Enumerable
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(); } }
/** * @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. */
NatSpecMultiLine
_beforeTokenTransfer
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 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]. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
MIT
ipfs://5e5e7855cd66c8862cb436fbe3015780c3301ca66101dc7cadb46ef4ed076abe
{ "func_code_index": [ 2281, 2875 ] }
2,637
StickFighter
@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol
0x9b121e19fc09b777ffa6fbd58ab980d1cf0503c4
Solidity
ERC721Enumerable
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(); } }
/** * @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. */
NatSpecMultiLine
_addTokenToOwnerEnumeration
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 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 */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
MIT
ipfs://5e5e7855cd66c8862cb436fbe3015780c3301ca66101dc7cadb46ef4ed076abe
{ "func_code_index": [ 3171, 3397 ] }
2,638
StickFighter
@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol
0x9b121e19fc09b777ffa6fbd58ab980d1cf0503c4
Solidity
ERC721Enumerable
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(); } }
/** * @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. */
NatSpecMultiLine
_addTokenToAllTokensEnumeration
function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); }
/** * @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 */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
MIT
ipfs://5e5e7855cd66c8862cb436fbe3015780c3301ca66101dc7cadb46ef4ed076abe
{ "func_code_index": [ 3593, 3762 ] }
2,639
StickFighter
@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol
0x9b121e19fc09b777ffa6fbd58ab980d1cf0503c4
Solidity
ERC721Enumerable
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(); } }
/** * @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. */
NatSpecMultiLine
_removeTokenFromOwnerEnumeration
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 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 */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
MIT
ipfs://5e5e7855cd66c8862cb436fbe3015780c3301ca66101dc7cadb46ef4ed076abe
{ "func_code_index": [ 4384, 5377 ] }
2,640
StickFighter
@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol
0x9b121e19fc09b777ffa6fbd58ab980d1cf0503c4
Solidity
ERC721Enumerable
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(); } }
/** * @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. */
NatSpecMultiLine
_removeTokenFromAllTokensEnumeration
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(); }
/** * @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 */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
MIT
ipfs://5e5e7855cd66c8862cb436fbe3015780c3301ca66101dc7cadb46ef4ed076abe
{ "func_code_index": [ 5667, 6751 ] }
2,641
StickFighter
@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol
0x9b121e19fc09b777ffa6fbd58ab980d1cf0503c4
Solidity
StickFighter
contract StickFighter is ERC721Enumerable, Ownable { using Strings for uint256; event Mint(address indexed sender, uint256 startWith, uint256 times); //supply counters total max supply = totalcount - 1 uint256 public totalMints; uint256 public totalCount = 10001; //Max mints per batch uint256 public maxBatch = 10; //Token price of each token converted to WEI uint256 public price = 0.05 * 10 ** 18; //Token price of each token in the pre sale converted to WEI //The presale is reserved for the OG holders uint256 public presalePrice = 0.0 ether; //String for the baseURI string public baseURI; //Booleans for the sale and the presale bool private saleActive; bool private presaleActive; //List of addresses that have a number of reserved tokens for presale mapping (address => uint16) public presaleAddresses; //constructor args constructor(string memory name_, string memory symbol_, string memory baseURI_) ERC721(name_, symbol_) { baseURI = baseURI_; } //basic functions. function _baseURI() internal view virtual override returns (string memory){ return baseURI; } function setBaseURI(string memory _newURI) public onlyOwner { baseURI = _newURI; } //Returns a tokenURI of a specific token function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token."); string memory baseURI2 = _baseURI(); return bytes(baseURI2).length > 0 ? string(abi.encodePacked(baseURI2, tokenId.toString(), ".json")) : '.json'; } //Function to activate or deactivate the sale function setSaleActive(bool _start) public onlyOwner { saleActive = _start; } //Function to activate or deactivate the presale function setPresaleActive(bool _start) public onlyOwner { presaleActive = _start; } function tokensOfOwner(address owner) public view returns (uint256[] memory) { uint256 count = balanceOf(owner); uint256[] memory ids = new uint256[](count); for (uint256 i = 0; i < count; i++) { ids[i] = tokenOfOwnerByIndex(owner, i); } return ids; } //Exclusive Presale mint for the OG's || Moet nog testen of het goe dgaat met de total suplly function mintPresaleToken(uint16 _amount) public payable { require( presaleActive, "Presale is not active" ); uint16 reservedAmt = presaleAddresses[msg.sender]; require( reservedAmt > 0, "No tokens reserved for your address" ); require( _amount < reservedAmt, "max reserved token supply reached!" ); require( totalMints + _amount < totalCount, "Cannot mint more than max supply" ); require( msg.value == presalePrice * _amount, "Wrong amount of ETH sent" ); presaleAddresses[msg.sender] = reservedAmt - _amount; for(uint16 i; i < _amount; i++){ _safeMint( msg.sender, 1 + totalMints++); } } //Mint function function mint(uint16 _amount) public payable { require( saleActive,"Sale is not active" ); require( _amount < maxBatch, "You can only Mint 10 tokens at once" ); require( totalMints + _amount < totalCount,"Cannot mint more than max supply" ); require( msg.value == price * _amount,"Wrong amount of ETH sent" ); for(uint16 i; i < _amount; i++){ _safeMint( msg.sender, 1+ totalMints++); } } //Set reserved presale spots for OG's function setPresaleReservedAddresses(address[] memory _a, uint16[] memory _amount) public onlyOwner { uint16 length = uint16(_a.length); for(uint16 i; i < length; i++){ presaleAddresses[_a[i]] = _amount[i]; } } }
_baseURI
function _baseURI() internal view virtual override returns (string memory){ return baseURI; }
//basic functions.
LineComment
v0.8.7+commit.e28d00a7
MIT
ipfs://5e5e7855cd66c8862cb436fbe3015780c3301ca66101dc7cadb46ef4ed076abe
{ "func_code_index": [ 1127, 1239 ] }
2,642
StickFighter
@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol
0x9b121e19fc09b777ffa6fbd58ab980d1cf0503c4
Solidity
StickFighter
contract StickFighter is ERC721Enumerable, Ownable { using Strings for uint256; event Mint(address indexed sender, uint256 startWith, uint256 times); //supply counters total max supply = totalcount - 1 uint256 public totalMints; uint256 public totalCount = 10001; //Max mints per batch uint256 public maxBatch = 10; //Token price of each token converted to WEI uint256 public price = 0.05 * 10 ** 18; //Token price of each token in the pre sale converted to WEI //The presale is reserved for the OG holders uint256 public presalePrice = 0.0 ether; //String for the baseURI string public baseURI; //Booleans for the sale and the presale bool private saleActive; bool private presaleActive; //List of addresses that have a number of reserved tokens for presale mapping (address => uint16) public presaleAddresses; //constructor args constructor(string memory name_, string memory symbol_, string memory baseURI_) ERC721(name_, symbol_) { baseURI = baseURI_; } //basic functions. function _baseURI() internal view virtual override returns (string memory){ return baseURI; } function setBaseURI(string memory _newURI) public onlyOwner { baseURI = _newURI; } //Returns a tokenURI of a specific token function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token."); string memory baseURI2 = _baseURI(); return bytes(baseURI2).length > 0 ? string(abi.encodePacked(baseURI2, tokenId.toString(), ".json")) : '.json'; } //Function to activate or deactivate the sale function setSaleActive(bool _start) public onlyOwner { saleActive = _start; } //Function to activate or deactivate the presale function setPresaleActive(bool _start) public onlyOwner { presaleActive = _start; } function tokensOfOwner(address owner) public view returns (uint256[] memory) { uint256 count = balanceOf(owner); uint256[] memory ids = new uint256[](count); for (uint256 i = 0; i < count; i++) { ids[i] = tokenOfOwnerByIndex(owner, i); } return ids; } //Exclusive Presale mint for the OG's || Moet nog testen of het goe dgaat met de total suplly function mintPresaleToken(uint16 _amount) public payable { require( presaleActive, "Presale is not active" ); uint16 reservedAmt = presaleAddresses[msg.sender]; require( reservedAmt > 0, "No tokens reserved for your address" ); require( _amount < reservedAmt, "max reserved token supply reached!" ); require( totalMints + _amount < totalCount, "Cannot mint more than max supply" ); require( msg.value == presalePrice * _amount, "Wrong amount of ETH sent" ); presaleAddresses[msg.sender] = reservedAmt - _amount; for(uint16 i; i < _amount; i++){ _safeMint( msg.sender, 1 + totalMints++); } } //Mint function function mint(uint16 _amount) public payable { require( saleActive,"Sale is not active" ); require( _amount < maxBatch, "You can only Mint 10 tokens at once" ); require( totalMints + _amount < totalCount,"Cannot mint more than max supply" ); require( msg.value == price * _amount,"Wrong amount of ETH sent" ); for(uint16 i; i < _amount; i++){ _safeMint( msg.sender, 1+ totalMints++); } } //Set reserved presale spots for OG's function setPresaleReservedAddresses(address[] memory _a, uint16[] memory _amount) public onlyOwner { uint16 length = uint16(_a.length); for(uint16 i; i < length; i++){ presaleAddresses[_a[i]] = _amount[i]; } } }
tokenURI
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token."); string memory baseURI2 = _baseURI(); return bytes(baseURI2).length > 0 ? string(abi.encodePacked(baseURI2, tokenId.toString(), ".json")) : '.json'; }
//Returns a tokenURI of a specific token
LineComment
v0.8.7+commit.e28d00a7
MIT
ipfs://5e5e7855cd66c8862cb436fbe3015780c3301ca66101dc7cadb46ef4ed076abe
{ "func_code_index": [ 1390, 1760 ] }
2,643
StickFighter
@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol
0x9b121e19fc09b777ffa6fbd58ab980d1cf0503c4
Solidity
StickFighter
contract StickFighter is ERC721Enumerable, Ownable { using Strings for uint256; event Mint(address indexed sender, uint256 startWith, uint256 times); //supply counters total max supply = totalcount - 1 uint256 public totalMints; uint256 public totalCount = 10001; //Max mints per batch uint256 public maxBatch = 10; //Token price of each token converted to WEI uint256 public price = 0.05 * 10 ** 18; //Token price of each token in the pre sale converted to WEI //The presale is reserved for the OG holders uint256 public presalePrice = 0.0 ether; //String for the baseURI string public baseURI; //Booleans for the sale and the presale bool private saleActive; bool private presaleActive; //List of addresses that have a number of reserved tokens for presale mapping (address => uint16) public presaleAddresses; //constructor args constructor(string memory name_, string memory symbol_, string memory baseURI_) ERC721(name_, symbol_) { baseURI = baseURI_; } //basic functions. function _baseURI() internal view virtual override returns (string memory){ return baseURI; } function setBaseURI(string memory _newURI) public onlyOwner { baseURI = _newURI; } //Returns a tokenURI of a specific token function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token."); string memory baseURI2 = _baseURI(); return bytes(baseURI2).length > 0 ? string(abi.encodePacked(baseURI2, tokenId.toString(), ".json")) : '.json'; } //Function to activate or deactivate the sale function setSaleActive(bool _start) public onlyOwner { saleActive = _start; } //Function to activate or deactivate the presale function setPresaleActive(bool _start) public onlyOwner { presaleActive = _start; } function tokensOfOwner(address owner) public view returns (uint256[] memory) { uint256 count = balanceOf(owner); uint256[] memory ids = new uint256[](count); for (uint256 i = 0; i < count; i++) { ids[i] = tokenOfOwnerByIndex(owner, i); } return ids; } //Exclusive Presale mint for the OG's || Moet nog testen of het goe dgaat met de total suplly function mintPresaleToken(uint16 _amount) public payable { require( presaleActive, "Presale is not active" ); uint16 reservedAmt = presaleAddresses[msg.sender]; require( reservedAmt > 0, "No tokens reserved for your address" ); require( _amount < reservedAmt, "max reserved token supply reached!" ); require( totalMints + _amount < totalCount, "Cannot mint more than max supply" ); require( msg.value == presalePrice * _amount, "Wrong amount of ETH sent" ); presaleAddresses[msg.sender] = reservedAmt - _amount; for(uint16 i; i < _amount; i++){ _safeMint( msg.sender, 1 + totalMints++); } } //Mint function function mint(uint16 _amount) public payable { require( saleActive,"Sale is not active" ); require( _amount < maxBatch, "You can only Mint 10 tokens at once" ); require( totalMints + _amount < totalCount,"Cannot mint more than max supply" ); require( msg.value == price * _amount,"Wrong amount of ETH sent" ); for(uint16 i; i < _amount; i++){ _safeMint( msg.sender, 1+ totalMints++); } } //Set reserved presale spots for OG's function setPresaleReservedAddresses(address[] memory _a, uint16[] memory _amount) public onlyOwner { uint16 length = uint16(_a.length); for(uint16 i; i < length; i++){ presaleAddresses[_a[i]] = _amount[i]; } } }
setSaleActive
function setSaleActive(bool _start) public onlyOwner { saleActive = _start; }
//Function to activate or deactivate the sale
LineComment
v0.8.7+commit.e28d00a7
MIT
ipfs://5e5e7855cd66c8862cb436fbe3015780c3301ca66101dc7cadb46ef4ed076abe
{ "func_code_index": [ 1814, 1910 ] }
2,644
StickFighter
@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol
0x9b121e19fc09b777ffa6fbd58ab980d1cf0503c4
Solidity
StickFighter
contract StickFighter is ERC721Enumerable, Ownable { using Strings for uint256; event Mint(address indexed sender, uint256 startWith, uint256 times); //supply counters total max supply = totalcount - 1 uint256 public totalMints; uint256 public totalCount = 10001; //Max mints per batch uint256 public maxBatch = 10; //Token price of each token converted to WEI uint256 public price = 0.05 * 10 ** 18; //Token price of each token in the pre sale converted to WEI //The presale is reserved for the OG holders uint256 public presalePrice = 0.0 ether; //String for the baseURI string public baseURI; //Booleans for the sale and the presale bool private saleActive; bool private presaleActive; //List of addresses that have a number of reserved tokens for presale mapping (address => uint16) public presaleAddresses; //constructor args constructor(string memory name_, string memory symbol_, string memory baseURI_) ERC721(name_, symbol_) { baseURI = baseURI_; } //basic functions. function _baseURI() internal view virtual override returns (string memory){ return baseURI; } function setBaseURI(string memory _newURI) public onlyOwner { baseURI = _newURI; } //Returns a tokenURI of a specific token function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token."); string memory baseURI2 = _baseURI(); return bytes(baseURI2).length > 0 ? string(abi.encodePacked(baseURI2, tokenId.toString(), ".json")) : '.json'; } //Function to activate or deactivate the sale function setSaleActive(bool _start) public onlyOwner { saleActive = _start; } //Function to activate or deactivate the presale function setPresaleActive(bool _start) public onlyOwner { presaleActive = _start; } function tokensOfOwner(address owner) public view returns (uint256[] memory) { uint256 count = balanceOf(owner); uint256[] memory ids = new uint256[](count); for (uint256 i = 0; i < count; i++) { ids[i] = tokenOfOwnerByIndex(owner, i); } return ids; } //Exclusive Presale mint for the OG's || Moet nog testen of het goe dgaat met de total suplly function mintPresaleToken(uint16 _amount) public payable { require( presaleActive, "Presale is not active" ); uint16 reservedAmt = presaleAddresses[msg.sender]; require( reservedAmt > 0, "No tokens reserved for your address" ); require( _amount < reservedAmt, "max reserved token supply reached!" ); require( totalMints + _amount < totalCount, "Cannot mint more than max supply" ); require( msg.value == presalePrice * _amount, "Wrong amount of ETH sent" ); presaleAddresses[msg.sender] = reservedAmt - _amount; for(uint16 i; i < _amount; i++){ _safeMint( msg.sender, 1 + totalMints++); } } //Mint function function mint(uint16 _amount) public payable { require( saleActive,"Sale is not active" ); require( _amount < maxBatch, "You can only Mint 10 tokens at once" ); require( totalMints + _amount < totalCount,"Cannot mint more than max supply" ); require( msg.value == price * _amount,"Wrong amount of ETH sent" ); for(uint16 i; i < _amount; i++){ _safeMint( msg.sender, 1+ totalMints++); } } //Set reserved presale spots for OG's function setPresaleReservedAddresses(address[] memory _a, uint16[] memory _amount) public onlyOwner { uint16 length = uint16(_a.length); for(uint16 i; i < length; i++){ presaleAddresses[_a[i]] = _amount[i]; } } }
setPresaleActive
function setPresaleActive(bool _start) public onlyOwner { presaleActive = _start; }
//Function to activate or deactivate the presale
LineComment
v0.8.7+commit.e28d00a7
MIT
ipfs://5e5e7855cd66c8862cb436fbe3015780c3301ca66101dc7cadb46ef4ed076abe
{ "func_code_index": [ 1967, 2069 ] }
2,645
StickFighter
@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol
0x9b121e19fc09b777ffa6fbd58ab980d1cf0503c4
Solidity
StickFighter
contract StickFighter is ERC721Enumerable, Ownable { using Strings for uint256; event Mint(address indexed sender, uint256 startWith, uint256 times); //supply counters total max supply = totalcount - 1 uint256 public totalMints; uint256 public totalCount = 10001; //Max mints per batch uint256 public maxBatch = 10; //Token price of each token converted to WEI uint256 public price = 0.05 * 10 ** 18; //Token price of each token in the pre sale converted to WEI //The presale is reserved for the OG holders uint256 public presalePrice = 0.0 ether; //String for the baseURI string public baseURI; //Booleans for the sale and the presale bool private saleActive; bool private presaleActive; //List of addresses that have a number of reserved tokens for presale mapping (address => uint16) public presaleAddresses; //constructor args constructor(string memory name_, string memory symbol_, string memory baseURI_) ERC721(name_, symbol_) { baseURI = baseURI_; } //basic functions. function _baseURI() internal view virtual override returns (string memory){ return baseURI; } function setBaseURI(string memory _newURI) public onlyOwner { baseURI = _newURI; } //Returns a tokenURI of a specific token function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token."); string memory baseURI2 = _baseURI(); return bytes(baseURI2).length > 0 ? string(abi.encodePacked(baseURI2, tokenId.toString(), ".json")) : '.json'; } //Function to activate or deactivate the sale function setSaleActive(bool _start) public onlyOwner { saleActive = _start; } //Function to activate or deactivate the presale function setPresaleActive(bool _start) public onlyOwner { presaleActive = _start; } function tokensOfOwner(address owner) public view returns (uint256[] memory) { uint256 count = balanceOf(owner); uint256[] memory ids = new uint256[](count); for (uint256 i = 0; i < count; i++) { ids[i] = tokenOfOwnerByIndex(owner, i); } return ids; } //Exclusive Presale mint for the OG's || Moet nog testen of het goe dgaat met de total suplly function mintPresaleToken(uint16 _amount) public payable { require( presaleActive, "Presale is not active" ); uint16 reservedAmt = presaleAddresses[msg.sender]; require( reservedAmt > 0, "No tokens reserved for your address" ); require( _amount < reservedAmt, "max reserved token supply reached!" ); require( totalMints + _amount < totalCount, "Cannot mint more than max supply" ); require( msg.value == presalePrice * _amount, "Wrong amount of ETH sent" ); presaleAddresses[msg.sender] = reservedAmt - _amount; for(uint16 i; i < _amount; i++){ _safeMint( msg.sender, 1 + totalMints++); } } //Mint function function mint(uint16 _amount) public payable { require( saleActive,"Sale is not active" ); require( _amount < maxBatch, "You can only Mint 10 tokens at once" ); require( totalMints + _amount < totalCount,"Cannot mint more than max supply" ); require( msg.value == price * _amount,"Wrong amount of ETH sent" ); for(uint16 i; i < _amount; i++){ _safeMint( msg.sender, 1+ totalMints++); } } //Set reserved presale spots for OG's function setPresaleReservedAddresses(address[] memory _a, uint16[] memory _amount) public onlyOwner { uint16 length = uint16(_a.length); for(uint16 i; i < length; i++){ presaleAddresses[_a[i]] = _amount[i]; } } }
mintPresaleToken
function mintPresaleToken(uint16 _amount) public payable { require( presaleActive, "Presale is not active" ); uint16 reservedAmt = presaleAddresses[msg.sender]; require( reservedAmt > 0, "No tokens reserved for your address" ); require( _amount < reservedAmt, "max reserved token supply reached!" ); require( totalMints + _amount < totalCount, "Cannot mint more than max supply" ); require( msg.value == presalePrice * _amount, "Wrong amount of ETH sent" ); presaleAddresses[msg.sender] = reservedAmt - _amount; for(uint16 i; i < _amount; i++){ _safeMint( msg.sender, 1 + totalMints++); } }
//Exclusive Presale mint for the OG's || Moet nog testen of het goe dgaat met de total suplly
LineComment
v0.8.7+commit.e28d00a7
MIT
ipfs://5e5e7855cd66c8862cb436fbe3015780c3301ca66101dc7cadb46ef4ed076abe
{ "func_code_index": [ 2531, 3267 ] }
2,646
StickFighter
@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol
0x9b121e19fc09b777ffa6fbd58ab980d1cf0503c4
Solidity
StickFighter
contract StickFighter is ERC721Enumerable, Ownable { using Strings for uint256; event Mint(address indexed sender, uint256 startWith, uint256 times); //supply counters total max supply = totalcount - 1 uint256 public totalMints; uint256 public totalCount = 10001; //Max mints per batch uint256 public maxBatch = 10; //Token price of each token converted to WEI uint256 public price = 0.05 * 10 ** 18; //Token price of each token in the pre sale converted to WEI //The presale is reserved for the OG holders uint256 public presalePrice = 0.0 ether; //String for the baseURI string public baseURI; //Booleans for the sale and the presale bool private saleActive; bool private presaleActive; //List of addresses that have a number of reserved tokens for presale mapping (address => uint16) public presaleAddresses; //constructor args constructor(string memory name_, string memory symbol_, string memory baseURI_) ERC721(name_, symbol_) { baseURI = baseURI_; } //basic functions. function _baseURI() internal view virtual override returns (string memory){ return baseURI; } function setBaseURI(string memory _newURI) public onlyOwner { baseURI = _newURI; } //Returns a tokenURI of a specific token function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token."); string memory baseURI2 = _baseURI(); return bytes(baseURI2).length > 0 ? string(abi.encodePacked(baseURI2, tokenId.toString(), ".json")) : '.json'; } //Function to activate or deactivate the sale function setSaleActive(bool _start) public onlyOwner { saleActive = _start; } //Function to activate or deactivate the presale function setPresaleActive(bool _start) public onlyOwner { presaleActive = _start; } function tokensOfOwner(address owner) public view returns (uint256[] memory) { uint256 count = balanceOf(owner); uint256[] memory ids = new uint256[](count); for (uint256 i = 0; i < count; i++) { ids[i] = tokenOfOwnerByIndex(owner, i); } return ids; } //Exclusive Presale mint for the OG's || Moet nog testen of het goe dgaat met de total suplly function mintPresaleToken(uint16 _amount) public payable { require( presaleActive, "Presale is not active" ); uint16 reservedAmt = presaleAddresses[msg.sender]; require( reservedAmt > 0, "No tokens reserved for your address" ); require( _amount < reservedAmt, "max reserved token supply reached!" ); require( totalMints + _amount < totalCount, "Cannot mint more than max supply" ); require( msg.value == presalePrice * _amount, "Wrong amount of ETH sent" ); presaleAddresses[msg.sender] = reservedAmt - _amount; for(uint16 i; i < _amount; i++){ _safeMint( msg.sender, 1 + totalMints++); } } //Mint function function mint(uint16 _amount) public payable { require( saleActive,"Sale is not active" ); require( _amount < maxBatch, "You can only Mint 10 tokens at once" ); require( totalMints + _amount < totalCount,"Cannot mint more than max supply" ); require( msg.value == price * _amount,"Wrong amount of ETH sent" ); for(uint16 i; i < _amount; i++){ _safeMint( msg.sender, 1+ totalMints++); } } //Set reserved presale spots for OG's function setPresaleReservedAddresses(address[] memory _a, uint16[] memory _amount) public onlyOwner { uint16 length = uint16(_a.length); for(uint16 i; i < length; i++){ presaleAddresses[_a[i]] = _amount[i]; } } }
mint
function mint(uint16 _amount) public payable { require( saleActive,"Sale is not active" ); require( _amount < maxBatch, "You can only Mint 10 tokens at once" ); require( totalMints + _amount < totalCount,"Cannot mint more than max supply" ); require( msg.value == price * _amount,"Wrong amount of ETH sent" ); for(uint16 i; i < _amount; i++){ _safeMint( msg.sender, 1+ totalMints++); } }
//Mint function
LineComment
v0.8.7+commit.e28d00a7
MIT
ipfs://5e5e7855cd66c8862cb436fbe3015780c3301ca66101dc7cadb46ef4ed076abe
{ "func_code_index": [ 3291, 3755 ] }
2,647
StickFighter
@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol
0x9b121e19fc09b777ffa6fbd58ab980d1cf0503c4
Solidity
StickFighter
contract StickFighter is ERC721Enumerable, Ownable { using Strings for uint256; event Mint(address indexed sender, uint256 startWith, uint256 times); //supply counters total max supply = totalcount - 1 uint256 public totalMints; uint256 public totalCount = 10001; //Max mints per batch uint256 public maxBatch = 10; //Token price of each token converted to WEI uint256 public price = 0.05 * 10 ** 18; //Token price of each token in the pre sale converted to WEI //The presale is reserved for the OG holders uint256 public presalePrice = 0.0 ether; //String for the baseURI string public baseURI; //Booleans for the sale and the presale bool private saleActive; bool private presaleActive; //List of addresses that have a number of reserved tokens for presale mapping (address => uint16) public presaleAddresses; //constructor args constructor(string memory name_, string memory symbol_, string memory baseURI_) ERC721(name_, symbol_) { baseURI = baseURI_; } //basic functions. function _baseURI() internal view virtual override returns (string memory){ return baseURI; } function setBaseURI(string memory _newURI) public onlyOwner { baseURI = _newURI; } //Returns a tokenURI of a specific token function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token."); string memory baseURI2 = _baseURI(); return bytes(baseURI2).length > 0 ? string(abi.encodePacked(baseURI2, tokenId.toString(), ".json")) : '.json'; } //Function to activate or deactivate the sale function setSaleActive(bool _start) public onlyOwner { saleActive = _start; } //Function to activate or deactivate the presale function setPresaleActive(bool _start) public onlyOwner { presaleActive = _start; } function tokensOfOwner(address owner) public view returns (uint256[] memory) { uint256 count = balanceOf(owner); uint256[] memory ids = new uint256[](count); for (uint256 i = 0; i < count; i++) { ids[i] = tokenOfOwnerByIndex(owner, i); } return ids; } //Exclusive Presale mint for the OG's || Moet nog testen of het goe dgaat met de total suplly function mintPresaleToken(uint16 _amount) public payable { require( presaleActive, "Presale is not active" ); uint16 reservedAmt = presaleAddresses[msg.sender]; require( reservedAmt > 0, "No tokens reserved for your address" ); require( _amount < reservedAmt, "max reserved token supply reached!" ); require( totalMints + _amount < totalCount, "Cannot mint more than max supply" ); require( msg.value == presalePrice * _amount, "Wrong amount of ETH sent" ); presaleAddresses[msg.sender] = reservedAmt - _amount; for(uint16 i; i < _amount; i++){ _safeMint( msg.sender, 1 + totalMints++); } } //Mint function function mint(uint16 _amount) public payable { require( saleActive,"Sale is not active" ); require( _amount < maxBatch, "You can only Mint 10 tokens at once" ); require( totalMints + _amount < totalCount,"Cannot mint more than max supply" ); require( msg.value == price * _amount,"Wrong amount of ETH sent" ); for(uint16 i; i < _amount; i++){ _safeMint( msg.sender, 1+ totalMints++); } } //Set reserved presale spots for OG's function setPresaleReservedAddresses(address[] memory _a, uint16[] memory _amount) public onlyOwner { uint16 length = uint16(_a.length); for(uint16 i; i < length; i++){ presaleAddresses[_a[i]] = _amount[i]; } } }
setPresaleReservedAddresses
function setPresaleReservedAddresses(address[] memory _a, uint16[] memory _amount) public onlyOwner { uint16 length = uint16(_a.length); for(uint16 i; i < length; i++){ presaleAddresses[_a[i]] = _amount[i]; } }
//Set reserved presale spots for OG's
LineComment
v0.8.7+commit.e28d00a7
MIT
ipfs://5e5e7855cd66c8862cb436fbe3015780c3301ca66101dc7cadb46ef4ed076abe
{ "func_code_index": [ 3801, 4061 ] }
2,648
ArticCoin
ArticCoin.sol
0x10a0f62ee681d9267229db60031b58c484099f1b
Solidity
ArticCoin
contract ArticCoin { // Public variables of the token string public name = "ArticCoin"; string public symbol = "ART"; uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it 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 notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ function ArticCoin( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = 10000000000000000000000000 * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = 10000000000000000000000000; // Give the creator all initial tokens name = "ArticCoin"; // Set the name for display purposes symbol = "ART"; // Set the symbol for display purposes } /** * 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 != 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] -= _value; // Add the same to the recipient balanceOf[_to] += _value; 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 { _transfer(msg.sender, _to, _value); } /** * 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 returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _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 returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply Burn(_from, _value); return true; } }
ArticCoin
function ArticCoin( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = 10000000000000000000000000 * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = 10000000000000000000000000; // Give the creator all initial tokens name = "ArticCoin"; // Set the name for display purposes symbol = "ART"; // Set the symbol for display purposes }
/** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */
NatSpecMultiLine
v0.4.20+commit.3155dd80
bzzr://af44b56a8e0e5bcf8b02875b79a32237ec64c94fbc9d35451128d56f2901577e
{ "func_code_index": [ 861, 1429 ] }
2,649
ArticCoin
ArticCoin.sol
0x10a0f62ee681d9267229db60031b58c484099f1b
Solidity
ArticCoin
contract ArticCoin { // Public variables of the token string public name = "ArticCoin"; string public symbol = "ART"; uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it 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 notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ function ArticCoin( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = 10000000000000000000000000 * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = 10000000000000000000000000; // Give the creator all initial tokens name = "ArticCoin"; // Set the name for display purposes symbol = "ART"; // Set the symbol for display purposes } /** * 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 != 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] -= _value; // Add the same to the recipient balanceOf[_to] += _value; 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 { _transfer(msg.sender, _to, _value); } /** * 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 returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _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 returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply Burn(_from, _value); return true; } }
_transfer
function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 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] -= _value; // Add the same to the recipient balanceOf[_to] += _value; 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); }
/** * Internal transfer, only can be called by this contract */
NatSpecMultiLine
v0.4.20+commit.3155dd80
bzzr://af44b56a8e0e5bcf8b02875b79a32237ec64c94fbc9d35451128d56f2901577e
{ "func_code_index": [ 1513, 2355 ] }
2,650
ArticCoin
ArticCoin.sol
0x10a0f62ee681d9267229db60031b58c484099f1b
Solidity
ArticCoin
contract ArticCoin { // Public variables of the token string public name = "ArticCoin"; string public symbol = "ART"; uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it 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 notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ function ArticCoin( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = 10000000000000000000000000 * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = 10000000000000000000000000; // Give the creator all initial tokens name = "ArticCoin"; // Set the name for display purposes symbol = "ART"; // Set the symbol for display purposes } /** * 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 != 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] -= _value; // Add the same to the recipient balanceOf[_to] += _value; 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 { _transfer(msg.sender, _to, _value); } /** * 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 returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _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 returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply Burn(_from, _value); return true; } }
transfer
function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); }
/** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */
NatSpecMultiLine
v0.4.20+commit.3155dd80
bzzr://af44b56a8e0e5bcf8b02875b79a32237ec64c94fbc9d35451128d56f2901577e
{ "func_code_index": [ 2561, 2673 ] }
2,651
ArticCoin
ArticCoin.sol
0x10a0f62ee681d9267229db60031b58c484099f1b
Solidity
ArticCoin
contract ArticCoin { // Public variables of the token string public name = "ArticCoin"; string public symbol = "ART"; uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it 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 notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ function ArticCoin( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = 10000000000000000000000000 * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = 10000000000000000000000000; // Give the creator all initial tokens name = "ArticCoin"; // Set the name for display purposes symbol = "ART"; // Set the symbol for display purposes } /** * 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 != 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] -= _value; // Add the same to the recipient balanceOf[_to] += _value; 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 { _transfer(msg.sender, _to, _value); } /** * 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 returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _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 returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply Burn(_from, _value); return true; } }
transferFrom
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _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 */
NatSpecMultiLine
v0.4.20+commit.3155dd80
bzzr://af44b56a8e0e5bcf8b02875b79a32237ec64c94fbc9d35451128d56f2901577e
{ "func_code_index": [ 2948, 3249 ] }
2,652
ArticCoin
ArticCoin.sol
0x10a0f62ee681d9267229db60031b58c484099f1b
Solidity
ArticCoin
contract ArticCoin { // Public variables of the token string public name = "ArticCoin"; string public symbol = "ART"; uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it 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 notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ function ArticCoin( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = 10000000000000000000000000 * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = 10000000000000000000000000; // Give the creator all initial tokens name = "ArticCoin"; // Set the name for display purposes symbol = "ART"; // Set the symbol for display purposes } /** * 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 != 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] -= _value; // Add the same to the recipient balanceOf[_to] += _value; 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 { _transfer(msg.sender, _to, _value); } /** * 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 returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _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 returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply Burn(_from, _value); return true; } }
approve
function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _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 */
NatSpecMultiLine
v0.4.20+commit.3155dd80
bzzr://af44b56a8e0e5bcf8b02875b79a32237ec64c94fbc9d35451128d56f2901577e
{ "func_code_index": [ 3513, 3689 ] }
2,653
ArticCoin
ArticCoin.sol
0x10a0f62ee681d9267229db60031b58c484099f1b
Solidity
ArticCoin
contract ArticCoin { // Public variables of the token string public name = "ArticCoin"; string public symbol = "ART"; uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it 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 notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ function ArticCoin( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = 10000000000000000000000000 * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = 10000000000000000000000000; // Give the creator all initial tokens name = "ArticCoin"; // Set the name for display purposes symbol = "ART"; // Set the symbol for display purposes } /** * 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 != 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] -= _value; // Add the same to the recipient balanceOf[_to] += _value; 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 { _transfer(msg.sender, _to, _value); } /** * 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 returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _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 returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply Burn(_from, _value); return true; } }
approveAndCall
function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } }
/** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */
NatSpecMultiLine
v0.4.20+commit.3155dd80
bzzr://af44b56a8e0e5bcf8b02875b79a32237ec64c94fbc9d35451128d56f2901577e
{ "func_code_index": [ 4083, 4435 ] }
2,654
ArticCoin
ArticCoin.sol
0x10a0f62ee681d9267229db60031b58c484099f1b
Solidity
ArticCoin
contract ArticCoin { // Public variables of the token string public name = "ArticCoin"; string public symbol = "ART"; uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it 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 notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ function ArticCoin( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = 10000000000000000000000000 * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = 10000000000000000000000000; // Give the creator all initial tokens name = "ArticCoin"; // Set the name for display purposes symbol = "ART"; // Set the symbol for display purposes } /** * 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 != 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] -= _value; // Add the same to the recipient balanceOf[_to] += _value; 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 { _transfer(msg.sender, _to, _value); } /** * 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 returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _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 returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply Burn(_from, _value); return true; } }
burn
function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply Burn(msg.sender, _value); return true; }
/** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */
NatSpecMultiLine
v0.4.20+commit.3155dd80
bzzr://af44b56a8e0e5bcf8b02875b79a32237ec64c94fbc9d35451128d56f2901577e
{ "func_code_index": [ 4605, 4979 ] }
2,655
ArticCoin
ArticCoin.sol
0x10a0f62ee681d9267229db60031b58c484099f1b
Solidity
ArticCoin
contract ArticCoin { // Public variables of the token string public name = "ArticCoin"; string public symbol = "ART"; uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it 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 notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ function ArticCoin( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = 10000000000000000000000000 * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = 10000000000000000000000000; // Give the creator all initial tokens name = "ArticCoin"; // Set the name for display purposes symbol = "ART"; // Set the symbol for display purposes } /** * 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 != 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] -= _value; // Add the same to the recipient balanceOf[_to] += _value; 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 { _transfer(msg.sender, _to, _value); } /** * 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 returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _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 returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply Burn(_from, _value); return true; } }
burnFrom
function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply Burn(_from, _value); return true; }
/** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */
NatSpecMultiLine
v0.4.20+commit.3155dd80
bzzr://af44b56a8e0e5bcf8b02875b79a32237ec64c94fbc9d35451128d56f2901577e
{ "func_code_index": [ 5237, 5848 ] }
2,656
NotifyHelperStateful
contracts/NotifyHelperStateful.sol
0x71316a3465e0fbcd08e665d6675caa8f7b1dd40a
Solidity
NotifyHelperStateful
contract NotifyHelperStateful is Controllable { using SafeMath for uint256; using SafeERC20 for IERC20; event ChangerSet(address indexed account, bool value); event NotifierSet(address indexed account, bool value); event Vesting(address pool, uint256 amount); event PoolChanged(address indexed pool, uint256 percentage, uint256 notificationType, bool vests); enum NotificationType { VOID, IFARM, FARM, TRANSFER, PROFIT_SHARE } struct Notification { address poolAddress; NotificationType notificationType; uint256 percentage; bool vests; } struct WorkingNotification { address[] pools; uint256[] amounts; uint256 checksum; uint256 counter; } uint256 public VESTING_DENOMINATOR = 3; uint256 public VESTING_NUMERATOR = 2; mapping (address => bool) changer; mapping (address => bool) notifier; address public notifyHelperRegular; address public notifyHelperIFARM; address public farm; Notification[] public notifications; mapping (address => uint256) public poolToIndex; mapping (uint256 => uint256) public numbers; // NotificationType to the number of pools address public reserve; address public vestingEscrow; uint256 public totalPercentage; // maintain state to not have to calculate during emissions modifier onlyChanger { require(changer[msg.sender] || msg.sender == governance(), "Only changer"); _; } modifier onlyNotifier { require(notifier[msg.sender], "Only notifier"); _; } constructor(address _storage, address _notifyHelperRegular, address _farm, address _notifyHelperIFARM, address _escrow, address _reserve) Controllable(_storage) public { // used for getting a reference to FeeRewardForwarder notifyHelperRegular = _notifyHelperRegular; farm = _farm; notifyHelperIFARM = _notifyHelperIFARM; vestingEscrow = _escrow; reserve = _reserve; require(_reserve != address(0), "invalid reserve"); require(_escrow != address(0), "invalid escrow"); } /// Whitelisted entities can notify pools based on the state, both for FARM and iFARM /// The only whitelisted entity here would be the minter helper function notifyPools(uint256 total, uint256 timestamp) public onlyNotifier { // transfer the tokens from the msg.sender to here IERC20(farm).safeTransferFrom(msg.sender, address(this), total); // prepare the notification data WorkingNotification memory iFARM = WorkingNotification( new address[](numbers[uint256(NotificationType.IFARM)]), new uint256[](numbers[uint256(NotificationType.IFARM)]), 0, 0 ); WorkingNotification memory regular = WorkingNotification( new address[](numbers[uint256(NotificationType.FARM)]), new uint256[](numbers[uint256(NotificationType.FARM)]), 0, 0 ); uint256 profitShareForWeek = 0; uint256 vestingAmount = 0; for (uint256 i = 0; i < notifications.length; i++) { Notification storage notification = notifications[i]; if (notification.notificationType == NotificationType.PROFIT_SHARE) { // profit share profitShareForWeek = total.mul(notification.percentage).div(totalPercentage); } else if (notification.notificationType == NotificationType.TRANSFER) { // simple transfer IERC20(farm).safeTransfer( notification.poolAddress, total.mul(notification.percentage).div(totalPercentage) ); } else { // FARM or iFARM notification WorkingNotification memory toUse = notification.notificationType == NotificationType.FARM ? regular : iFARM; toUse.amounts[toUse.counter] = total.mul(notification.percentage).div(totalPercentage); if (notification.vests) { uint256 toVest = toUse.amounts[toUse.counter].mul(VESTING_NUMERATOR).div(VESTING_DENOMINATOR); toUse.amounts[toUse.counter] = toUse.amounts[toUse.counter].sub(toVest); vestingAmount = vestingAmount.add(toVest); emit Vesting(notification.poolAddress, toVest); } toUse.pools[toUse.counter] = notification.poolAddress; toUse.checksum = toUse.checksum.add(toUse.amounts[toUse.counter]); toUse.counter = toUse.counter.add(1); } } // handle vesting if (vestingAmount > 0) { IERC20(farm).safeTransfer(vestingEscrow, vestingAmount); } // iFARM notifications IERC20(farm).approve(notifyHelperIFARM, iFARM.checksum); INotifyHelperIFARM(notifyHelperIFARM).notifyPools(iFARM.amounts, iFARM.pools, iFARM.checksum); // regular notifications IERC20(farm).approve(notifyHelperRegular, regular.checksum.add(profitShareForWeek)); if (profitShareForWeek > 0) { INotifyHelperRegular(notifyHelperRegular).notifyPoolsIncludingProfitShare( regular.amounts, regular.pools, profitShareForWeek, timestamp, regular.checksum.add(profitShareForWeek) ); } else { INotifyHelperRegular(notifyHelperRegular).notifyPools( regular.amounts, regular.pools, regular.checksum ); } // send rest to the reserve uint256 remainingBalance = IERC20(farm).balanceOf(address(this)); if (remainingBalance > 0) { IERC20(farm).safeTransfer(reserve, remainingBalance); } } /// Returning the governance function transferGovernance(address target, address newStorage) external onlyGovernance { Governable(target).setStorage(newStorage); } /// The governance configures whitelists function setChanger(address who, bool value) external onlyGovernance { changer[who] = value; emit ChangerSet(who, value); } /// The governance configures whitelists function setNotifier(address who, bool value) external onlyGovernance { notifier[who] = value; emit NotifierSet(who, value); } /// Whitelisted entity makes changes to the notifications function setPoolBatch(address[] calldata poolAddress, uint256[] calldata poolPercentage, NotificationType[] calldata notificationType, bool[] calldata vests) external onlyChanger { for (uint256 i = 0; i < poolAddress.length; i++) { setPool(poolAddress[i], poolPercentage[i], notificationType[i], vests[i]); } } /// Pool management, adds, updates or removes a transfer/notification function setPool(address poolAddress, uint256 poolPercentage, NotificationType notificationType, bool vests) public onlyChanger { require(notificationType != NotificationType.VOID, "Use valid indication"); if (notificationExists(poolAddress) && poolPercentage == 0) { // remove removeNotification(poolAddress); } else if (notificationExists(poolAddress)) { // update updateNotification(poolAddress, notificationType, poolPercentage, vests); } else if (poolPercentage > 0) { // add because it does not exist addNotification(poolAddress, poolPercentage, notificationType, vests); } emit PoolChanged(poolAddress, poolPercentage, uint256(notificationType), vests); } /// Configuration method for vesting for governance function setVestingEscrow(address _escrow) external onlyGovernance { vestingEscrow = _escrow; } /// Configuration method for vesting for governance function setVesting(uint256 _numerator, uint256 _denominator) external onlyGovernance { VESTING_DENOMINATOR = _numerator; VESTING_NUMERATOR = _denominator; } function notificationExists(address poolAddress) public view returns(bool) { if (notifications.length == 0) return false; if (poolToIndex[poolAddress] != 0) return true; return (notifications[0].poolAddress == poolAddress); } function removeNotification(address poolAddress) internal { require(notificationExists(poolAddress), "notification does not exist"); uint256 index = poolToIndex[poolAddress]; Notification storage notification = notifications[index]; totalPercentage = totalPercentage.sub(notification.percentage); numbers[uint256(notification.notificationType)] = numbers[uint256(notification.notificationType)].sub(1); // move the last element here and pop from the array notifications[index] = notifications[notifications.length.sub(1)]; poolToIndex[notifications[index].poolAddress] = index; poolToIndex[poolAddress] = 0; notifications.pop(); require(!notificationExists(poolAddress), "notification was not removed"); } function updateNotification(address poolAddress, NotificationType notificationType, uint256 percentage, bool vesting) internal { require(notificationExists(poolAddress), "notification does not exist"); require(percentage > 0, "notification is 0"); uint256 index = poolToIndex[poolAddress]; totalPercentage = totalPercentage.sub(notifications[index].percentage).add(percentage); notifications[index].percentage = percentage; notifications[index].vests = vesting; if (notifications[index].notificationType != notificationType) { numbers[uint256(notifications[index].notificationType)] = numbers[uint256(notifications[index].notificationType)].sub(1); notifications[index].notificationType = notificationType; numbers[uint256(notifications[index].notificationType)] = numbers[uint256(notifications[index].notificationType)].add(1); require(numbers[uint256(NotificationType.PROFIT_SHARE)] <= 1, "At most one profit share"); } } function addNotification(address poolAddress, uint256 percentage, NotificationType notificationType, bool vesting) internal { require(!notificationExists(poolAddress), "notification exists"); require(percentage > 0, "notification is 0"); Notification memory notification = Notification(poolAddress, notificationType, percentage, vesting); notifications.push(notification); totalPercentage = totalPercentage.add(notification.percentage); numbers[uint256(notification.notificationType)] = numbers[uint256(notification.notificationType)].add(1); poolToIndex[notification.poolAddress] = notifications.length.sub(1); require(numbers[uint256(NotificationType.PROFIT_SHARE)] <= 1, "At most one profit share"); require(notificationExists(poolAddress), "notification was not added"); } /// emergency draining of tokens and ETH as there should be none staying here function emergencyDrain(address token, uint256 amount) public onlyGovernance { if (token == address(0)) { msg.sender.transfer(amount); } else { IERC20(token).safeTransfer(msg.sender, amount); } } /// configuration check method function getConfig(uint256 totalAmount) external view returns(address[] memory, uint256[] memory, uint256[] memory) { address[] memory pools = new address[](notifications.length); uint256[] memory percentages = new uint256[](notifications.length); uint256[] memory amounts = new uint256[](notifications.length); for (uint256 i = 0; i < notifications.length; i++) { Notification storage notification = notifications[i]; pools[i] = notification.poolAddress; percentages[i] = notification.percentage.mul(1000000).div(totalPercentage); amounts[i] = notification.percentage.mul(totalAmount).div(totalPercentage); } return (pools, percentages, amounts); } }
notifyPools
function notifyPools(uint256 total, uint256 timestamp) public onlyNotifier { // transfer the tokens from the msg.sender to here IERC20(farm).safeTransferFrom(msg.sender, address(this), total); // prepare the notification data WorkingNotification memory iFARM = WorkingNotification( new address[](numbers[uint256(NotificationType.IFARM)]), new uint256[](numbers[uint256(NotificationType.IFARM)]), 0, 0 ); WorkingNotification memory regular = WorkingNotification( new address[](numbers[uint256(NotificationType.FARM)]), new uint256[](numbers[uint256(NotificationType.FARM)]), 0, 0 ); uint256 profitShareForWeek = 0; uint256 vestingAmount = 0; for (uint256 i = 0; i < notifications.length; i++) { Notification storage notification = notifications[i]; if (notification.notificationType == NotificationType.PROFIT_SHARE) { // profit share profitShareForWeek = total.mul(notification.percentage).div(totalPercentage); } else if (notification.notificationType == NotificationType.TRANSFER) { // simple transfer IERC20(farm).safeTransfer( notification.poolAddress, total.mul(notification.percentage).div(totalPercentage) ); } else { // FARM or iFARM notification WorkingNotification memory toUse = notification.notificationType == NotificationType.FARM ? regular : iFARM; toUse.amounts[toUse.counter] = total.mul(notification.percentage).div(totalPercentage); if (notification.vests) { uint256 toVest = toUse.amounts[toUse.counter].mul(VESTING_NUMERATOR).div(VESTING_DENOMINATOR); toUse.amounts[toUse.counter] = toUse.amounts[toUse.counter].sub(toVest); vestingAmount = vestingAmount.add(toVest); emit Vesting(notification.poolAddress, toVest); } toUse.pools[toUse.counter] = notification.poolAddress; toUse.checksum = toUse.checksum.add(toUse.amounts[toUse.counter]); toUse.counter = toUse.counter.add(1); } } // handle vesting if (vestingAmount > 0) { IERC20(farm).safeTransfer(vestingEscrow, vestingAmount); } // iFARM notifications IERC20(farm).approve(notifyHelperIFARM, iFARM.checksum); INotifyHelperIFARM(notifyHelperIFARM).notifyPools(iFARM.amounts, iFARM.pools, iFARM.checksum); // regular notifications IERC20(farm).approve(notifyHelperRegular, regular.checksum.add(profitShareForWeek)); if (profitShareForWeek > 0) { INotifyHelperRegular(notifyHelperRegular).notifyPoolsIncludingProfitShare( regular.amounts, regular.pools, profitShareForWeek, timestamp, regular.checksum.add(profitShareForWeek) ); } else { INotifyHelperRegular(notifyHelperRegular).notifyPools( regular.amounts, regular.pools, regular.checksum ); } // send rest to the reserve uint256 remainingBalance = IERC20(farm).balanceOf(address(this)); if (remainingBalance > 0) { IERC20(farm).safeTransfer(reserve, remainingBalance); } }
/// Whitelisted entities can notify pools based on the state, both for FARM and iFARM /// The only whitelisted entity here would be the minter helper
NatSpecSingleLine
v0.5.16+commit.9c3226ce
{ "func_code_index": [ 2169, 5275 ] }
2,657
NotifyHelperStateful
contracts/NotifyHelperStateful.sol
0x71316a3465e0fbcd08e665d6675caa8f7b1dd40a
Solidity
NotifyHelperStateful
contract NotifyHelperStateful is Controllable { using SafeMath for uint256; using SafeERC20 for IERC20; event ChangerSet(address indexed account, bool value); event NotifierSet(address indexed account, bool value); event Vesting(address pool, uint256 amount); event PoolChanged(address indexed pool, uint256 percentage, uint256 notificationType, bool vests); enum NotificationType { VOID, IFARM, FARM, TRANSFER, PROFIT_SHARE } struct Notification { address poolAddress; NotificationType notificationType; uint256 percentage; bool vests; } struct WorkingNotification { address[] pools; uint256[] amounts; uint256 checksum; uint256 counter; } uint256 public VESTING_DENOMINATOR = 3; uint256 public VESTING_NUMERATOR = 2; mapping (address => bool) changer; mapping (address => bool) notifier; address public notifyHelperRegular; address public notifyHelperIFARM; address public farm; Notification[] public notifications; mapping (address => uint256) public poolToIndex; mapping (uint256 => uint256) public numbers; // NotificationType to the number of pools address public reserve; address public vestingEscrow; uint256 public totalPercentage; // maintain state to not have to calculate during emissions modifier onlyChanger { require(changer[msg.sender] || msg.sender == governance(), "Only changer"); _; } modifier onlyNotifier { require(notifier[msg.sender], "Only notifier"); _; } constructor(address _storage, address _notifyHelperRegular, address _farm, address _notifyHelperIFARM, address _escrow, address _reserve) Controllable(_storage) public { // used for getting a reference to FeeRewardForwarder notifyHelperRegular = _notifyHelperRegular; farm = _farm; notifyHelperIFARM = _notifyHelperIFARM; vestingEscrow = _escrow; reserve = _reserve; require(_reserve != address(0), "invalid reserve"); require(_escrow != address(0), "invalid escrow"); } /// Whitelisted entities can notify pools based on the state, both for FARM and iFARM /// The only whitelisted entity here would be the minter helper function notifyPools(uint256 total, uint256 timestamp) public onlyNotifier { // transfer the tokens from the msg.sender to here IERC20(farm).safeTransferFrom(msg.sender, address(this), total); // prepare the notification data WorkingNotification memory iFARM = WorkingNotification( new address[](numbers[uint256(NotificationType.IFARM)]), new uint256[](numbers[uint256(NotificationType.IFARM)]), 0, 0 ); WorkingNotification memory regular = WorkingNotification( new address[](numbers[uint256(NotificationType.FARM)]), new uint256[](numbers[uint256(NotificationType.FARM)]), 0, 0 ); uint256 profitShareForWeek = 0; uint256 vestingAmount = 0; for (uint256 i = 0; i < notifications.length; i++) { Notification storage notification = notifications[i]; if (notification.notificationType == NotificationType.PROFIT_SHARE) { // profit share profitShareForWeek = total.mul(notification.percentage).div(totalPercentage); } else if (notification.notificationType == NotificationType.TRANSFER) { // simple transfer IERC20(farm).safeTransfer( notification.poolAddress, total.mul(notification.percentage).div(totalPercentage) ); } else { // FARM or iFARM notification WorkingNotification memory toUse = notification.notificationType == NotificationType.FARM ? regular : iFARM; toUse.amounts[toUse.counter] = total.mul(notification.percentage).div(totalPercentage); if (notification.vests) { uint256 toVest = toUse.amounts[toUse.counter].mul(VESTING_NUMERATOR).div(VESTING_DENOMINATOR); toUse.amounts[toUse.counter] = toUse.amounts[toUse.counter].sub(toVest); vestingAmount = vestingAmount.add(toVest); emit Vesting(notification.poolAddress, toVest); } toUse.pools[toUse.counter] = notification.poolAddress; toUse.checksum = toUse.checksum.add(toUse.amounts[toUse.counter]); toUse.counter = toUse.counter.add(1); } } // handle vesting if (vestingAmount > 0) { IERC20(farm).safeTransfer(vestingEscrow, vestingAmount); } // iFARM notifications IERC20(farm).approve(notifyHelperIFARM, iFARM.checksum); INotifyHelperIFARM(notifyHelperIFARM).notifyPools(iFARM.amounts, iFARM.pools, iFARM.checksum); // regular notifications IERC20(farm).approve(notifyHelperRegular, regular.checksum.add(profitShareForWeek)); if (profitShareForWeek > 0) { INotifyHelperRegular(notifyHelperRegular).notifyPoolsIncludingProfitShare( regular.amounts, regular.pools, profitShareForWeek, timestamp, regular.checksum.add(profitShareForWeek) ); } else { INotifyHelperRegular(notifyHelperRegular).notifyPools( regular.amounts, regular.pools, regular.checksum ); } // send rest to the reserve uint256 remainingBalance = IERC20(farm).balanceOf(address(this)); if (remainingBalance > 0) { IERC20(farm).safeTransfer(reserve, remainingBalance); } } /// Returning the governance function transferGovernance(address target, address newStorage) external onlyGovernance { Governable(target).setStorage(newStorage); } /// The governance configures whitelists function setChanger(address who, bool value) external onlyGovernance { changer[who] = value; emit ChangerSet(who, value); } /// The governance configures whitelists function setNotifier(address who, bool value) external onlyGovernance { notifier[who] = value; emit NotifierSet(who, value); } /// Whitelisted entity makes changes to the notifications function setPoolBatch(address[] calldata poolAddress, uint256[] calldata poolPercentage, NotificationType[] calldata notificationType, bool[] calldata vests) external onlyChanger { for (uint256 i = 0; i < poolAddress.length; i++) { setPool(poolAddress[i], poolPercentage[i], notificationType[i], vests[i]); } } /// Pool management, adds, updates or removes a transfer/notification function setPool(address poolAddress, uint256 poolPercentage, NotificationType notificationType, bool vests) public onlyChanger { require(notificationType != NotificationType.VOID, "Use valid indication"); if (notificationExists(poolAddress) && poolPercentage == 0) { // remove removeNotification(poolAddress); } else if (notificationExists(poolAddress)) { // update updateNotification(poolAddress, notificationType, poolPercentage, vests); } else if (poolPercentage > 0) { // add because it does not exist addNotification(poolAddress, poolPercentage, notificationType, vests); } emit PoolChanged(poolAddress, poolPercentage, uint256(notificationType), vests); } /// Configuration method for vesting for governance function setVestingEscrow(address _escrow) external onlyGovernance { vestingEscrow = _escrow; } /// Configuration method for vesting for governance function setVesting(uint256 _numerator, uint256 _denominator) external onlyGovernance { VESTING_DENOMINATOR = _numerator; VESTING_NUMERATOR = _denominator; } function notificationExists(address poolAddress) public view returns(bool) { if (notifications.length == 0) return false; if (poolToIndex[poolAddress] != 0) return true; return (notifications[0].poolAddress == poolAddress); } function removeNotification(address poolAddress) internal { require(notificationExists(poolAddress), "notification does not exist"); uint256 index = poolToIndex[poolAddress]; Notification storage notification = notifications[index]; totalPercentage = totalPercentage.sub(notification.percentage); numbers[uint256(notification.notificationType)] = numbers[uint256(notification.notificationType)].sub(1); // move the last element here and pop from the array notifications[index] = notifications[notifications.length.sub(1)]; poolToIndex[notifications[index].poolAddress] = index; poolToIndex[poolAddress] = 0; notifications.pop(); require(!notificationExists(poolAddress), "notification was not removed"); } function updateNotification(address poolAddress, NotificationType notificationType, uint256 percentage, bool vesting) internal { require(notificationExists(poolAddress), "notification does not exist"); require(percentage > 0, "notification is 0"); uint256 index = poolToIndex[poolAddress]; totalPercentage = totalPercentage.sub(notifications[index].percentage).add(percentage); notifications[index].percentage = percentage; notifications[index].vests = vesting; if (notifications[index].notificationType != notificationType) { numbers[uint256(notifications[index].notificationType)] = numbers[uint256(notifications[index].notificationType)].sub(1); notifications[index].notificationType = notificationType; numbers[uint256(notifications[index].notificationType)] = numbers[uint256(notifications[index].notificationType)].add(1); require(numbers[uint256(NotificationType.PROFIT_SHARE)] <= 1, "At most one profit share"); } } function addNotification(address poolAddress, uint256 percentage, NotificationType notificationType, bool vesting) internal { require(!notificationExists(poolAddress), "notification exists"); require(percentage > 0, "notification is 0"); Notification memory notification = Notification(poolAddress, notificationType, percentage, vesting); notifications.push(notification); totalPercentage = totalPercentage.add(notification.percentage); numbers[uint256(notification.notificationType)] = numbers[uint256(notification.notificationType)].add(1); poolToIndex[notification.poolAddress] = notifications.length.sub(1); require(numbers[uint256(NotificationType.PROFIT_SHARE)] <= 1, "At most one profit share"); require(notificationExists(poolAddress), "notification was not added"); } /// emergency draining of tokens and ETH as there should be none staying here function emergencyDrain(address token, uint256 amount) public onlyGovernance { if (token == address(0)) { msg.sender.transfer(amount); } else { IERC20(token).safeTransfer(msg.sender, amount); } } /// configuration check method function getConfig(uint256 totalAmount) external view returns(address[] memory, uint256[] memory, uint256[] memory) { address[] memory pools = new address[](notifications.length); uint256[] memory percentages = new uint256[](notifications.length); uint256[] memory amounts = new uint256[](notifications.length); for (uint256 i = 0; i < notifications.length; i++) { Notification storage notification = notifications[i]; pools[i] = notification.poolAddress; percentages[i] = notification.percentage.mul(1000000).div(totalPercentage); amounts[i] = notification.percentage.mul(totalAmount).div(totalPercentage); } return (pools, percentages, amounts); } }
transferGovernance
function transferGovernance(address target, address newStorage) external onlyGovernance { Governable(target).setStorage(newStorage); }
/// Returning the governance
NatSpecSingleLine
v0.5.16+commit.9c3226ce
{ "func_code_index": [ 5308, 5450 ] }
2,658
NotifyHelperStateful
contracts/NotifyHelperStateful.sol
0x71316a3465e0fbcd08e665d6675caa8f7b1dd40a
Solidity
NotifyHelperStateful
contract NotifyHelperStateful is Controllable { using SafeMath for uint256; using SafeERC20 for IERC20; event ChangerSet(address indexed account, bool value); event NotifierSet(address indexed account, bool value); event Vesting(address pool, uint256 amount); event PoolChanged(address indexed pool, uint256 percentage, uint256 notificationType, bool vests); enum NotificationType { VOID, IFARM, FARM, TRANSFER, PROFIT_SHARE } struct Notification { address poolAddress; NotificationType notificationType; uint256 percentage; bool vests; } struct WorkingNotification { address[] pools; uint256[] amounts; uint256 checksum; uint256 counter; } uint256 public VESTING_DENOMINATOR = 3; uint256 public VESTING_NUMERATOR = 2; mapping (address => bool) changer; mapping (address => bool) notifier; address public notifyHelperRegular; address public notifyHelperIFARM; address public farm; Notification[] public notifications; mapping (address => uint256) public poolToIndex; mapping (uint256 => uint256) public numbers; // NotificationType to the number of pools address public reserve; address public vestingEscrow; uint256 public totalPercentage; // maintain state to not have to calculate during emissions modifier onlyChanger { require(changer[msg.sender] || msg.sender == governance(), "Only changer"); _; } modifier onlyNotifier { require(notifier[msg.sender], "Only notifier"); _; } constructor(address _storage, address _notifyHelperRegular, address _farm, address _notifyHelperIFARM, address _escrow, address _reserve) Controllable(_storage) public { // used for getting a reference to FeeRewardForwarder notifyHelperRegular = _notifyHelperRegular; farm = _farm; notifyHelperIFARM = _notifyHelperIFARM; vestingEscrow = _escrow; reserve = _reserve; require(_reserve != address(0), "invalid reserve"); require(_escrow != address(0), "invalid escrow"); } /// Whitelisted entities can notify pools based on the state, both for FARM and iFARM /// The only whitelisted entity here would be the minter helper function notifyPools(uint256 total, uint256 timestamp) public onlyNotifier { // transfer the tokens from the msg.sender to here IERC20(farm).safeTransferFrom(msg.sender, address(this), total); // prepare the notification data WorkingNotification memory iFARM = WorkingNotification( new address[](numbers[uint256(NotificationType.IFARM)]), new uint256[](numbers[uint256(NotificationType.IFARM)]), 0, 0 ); WorkingNotification memory regular = WorkingNotification( new address[](numbers[uint256(NotificationType.FARM)]), new uint256[](numbers[uint256(NotificationType.FARM)]), 0, 0 ); uint256 profitShareForWeek = 0; uint256 vestingAmount = 0; for (uint256 i = 0; i < notifications.length; i++) { Notification storage notification = notifications[i]; if (notification.notificationType == NotificationType.PROFIT_SHARE) { // profit share profitShareForWeek = total.mul(notification.percentage).div(totalPercentage); } else if (notification.notificationType == NotificationType.TRANSFER) { // simple transfer IERC20(farm).safeTransfer( notification.poolAddress, total.mul(notification.percentage).div(totalPercentage) ); } else { // FARM or iFARM notification WorkingNotification memory toUse = notification.notificationType == NotificationType.FARM ? regular : iFARM; toUse.amounts[toUse.counter] = total.mul(notification.percentage).div(totalPercentage); if (notification.vests) { uint256 toVest = toUse.amounts[toUse.counter].mul(VESTING_NUMERATOR).div(VESTING_DENOMINATOR); toUse.amounts[toUse.counter] = toUse.amounts[toUse.counter].sub(toVest); vestingAmount = vestingAmount.add(toVest); emit Vesting(notification.poolAddress, toVest); } toUse.pools[toUse.counter] = notification.poolAddress; toUse.checksum = toUse.checksum.add(toUse.amounts[toUse.counter]); toUse.counter = toUse.counter.add(1); } } // handle vesting if (vestingAmount > 0) { IERC20(farm).safeTransfer(vestingEscrow, vestingAmount); } // iFARM notifications IERC20(farm).approve(notifyHelperIFARM, iFARM.checksum); INotifyHelperIFARM(notifyHelperIFARM).notifyPools(iFARM.amounts, iFARM.pools, iFARM.checksum); // regular notifications IERC20(farm).approve(notifyHelperRegular, regular.checksum.add(profitShareForWeek)); if (profitShareForWeek > 0) { INotifyHelperRegular(notifyHelperRegular).notifyPoolsIncludingProfitShare( regular.amounts, regular.pools, profitShareForWeek, timestamp, regular.checksum.add(profitShareForWeek) ); } else { INotifyHelperRegular(notifyHelperRegular).notifyPools( regular.amounts, regular.pools, regular.checksum ); } // send rest to the reserve uint256 remainingBalance = IERC20(farm).balanceOf(address(this)); if (remainingBalance > 0) { IERC20(farm).safeTransfer(reserve, remainingBalance); } } /// Returning the governance function transferGovernance(address target, address newStorage) external onlyGovernance { Governable(target).setStorage(newStorage); } /// The governance configures whitelists function setChanger(address who, bool value) external onlyGovernance { changer[who] = value; emit ChangerSet(who, value); } /// The governance configures whitelists function setNotifier(address who, bool value) external onlyGovernance { notifier[who] = value; emit NotifierSet(who, value); } /// Whitelisted entity makes changes to the notifications function setPoolBatch(address[] calldata poolAddress, uint256[] calldata poolPercentage, NotificationType[] calldata notificationType, bool[] calldata vests) external onlyChanger { for (uint256 i = 0; i < poolAddress.length; i++) { setPool(poolAddress[i], poolPercentage[i], notificationType[i], vests[i]); } } /// Pool management, adds, updates or removes a transfer/notification function setPool(address poolAddress, uint256 poolPercentage, NotificationType notificationType, bool vests) public onlyChanger { require(notificationType != NotificationType.VOID, "Use valid indication"); if (notificationExists(poolAddress) && poolPercentage == 0) { // remove removeNotification(poolAddress); } else if (notificationExists(poolAddress)) { // update updateNotification(poolAddress, notificationType, poolPercentage, vests); } else if (poolPercentage > 0) { // add because it does not exist addNotification(poolAddress, poolPercentage, notificationType, vests); } emit PoolChanged(poolAddress, poolPercentage, uint256(notificationType), vests); } /// Configuration method for vesting for governance function setVestingEscrow(address _escrow) external onlyGovernance { vestingEscrow = _escrow; } /// Configuration method for vesting for governance function setVesting(uint256 _numerator, uint256 _denominator) external onlyGovernance { VESTING_DENOMINATOR = _numerator; VESTING_NUMERATOR = _denominator; } function notificationExists(address poolAddress) public view returns(bool) { if (notifications.length == 0) return false; if (poolToIndex[poolAddress] != 0) return true; return (notifications[0].poolAddress == poolAddress); } function removeNotification(address poolAddress) internal { require(notificationExists(poolAddress), "notification does not exist"); uint256 index = poolToIndex[poolAddress]; Notification storage notification = notifications[index]; totalPercentage = totalPercentage.sub(notification.percentage); numbers[uint256(notification.notificationType)] = numbers[uint256(notification.notificationType)].sub(1); // move the last element here and pop from the array notifications[index] = notifications[notifications.length.sub(1)]; poolToIndex[notifications[index].poolAddress] = index; poolToIndex[poolAddress] = 0; notifications.pop(); require(!notificationExists(poolAddress), "notification was not removed"); } function updateNotification(address poolAddress, NotificationType notificationType, uint256 percentage, bool vesting) internal { require(notificationExists(poolAddress), "notification does not exist"); require(percentage > 0, "notification is 0"); uint256 index = poolToIndex[poolAddress]; totalPercentage = totalPercentage.sub(notifications[index].percentage).add(percentage); notifications[index].percentage = percentage; notifications[index].vests = vesting; if (notifications[index].notificationType != notificationType) { numbers[uint256(notifications[index].notificationType)] = numbers[uint256(notifications[index].notificationType)].sub(1); notifications[index].notificationType = notificationType; numbers[uint256(notifications[index].notificationType)] = numbers[uint256(notifications[index].notificationType)].add(1); require(numbers[uint256(NotificationType.PROFIT_SHARE)] <= 1, "At most one profit share"); } } function addNotification(address poolAddress, uint256 percentage, NotificationType notificationType, bool vesting) internal { require(!notificationExists(poolAddress), "notification exists"); require(percentage > 0, "notification is 0"); Notification memory notification = Notification(poolAddress, notificationType, percentage, vesting); notifications.push(notification); totalPercentage = totalPercentage.add(notification.percentage); numbers[uint256(notification.notificationType)] = numbers[uint256(notification.notificationType)].add(1); poolToIndex[notification.poolAddress] = notifications.length.sub(1); require(numbers[uint256(NotificationType.PROFIT_SHARE)] <= 1, "At most one profit share"); require(notificationExists(poolAddress), "notification was not added"); } /// emergency draining of tokens and ETH as there should be none staying here function emergencyDrain(address token, uint256 amount) public onlyGovernance { if (token == address(0)) { msg.sender.transfer(amount); } else { IERC20(token).safeTransfer(msg.sender, amount); } } /// configuration check method function getConfig(uint256 totalAmount) external view returns(address[] memory, uint256[] memory, uint256[] memory) { address[] memory pools = new address[](notifications.length); uint256[] memory percentages = new uint256[](notifications.length); uint256[] memory amounts = new uint256[](notifications.length); for (uint256 i = 0; i < notifications.length; i++) { Notification storage notification = notifications[i]; pools[i] = notification.poolAddress; percentages[i] = notification.percentage.mul(1000000).div(totalPercentage); amounts[i] = notification.percentage.mul(totalAmount).div(totalPercentage); } return (pools, percentages, amounts); } }
setChanger
function setChanger(address who, bool value) external onlyGovernance { changer[who] = value; emit ChangerSet(who, value); }
/// The governance configures whitelists
NatSpecSingleLine
v0.5.16+commit.9c3226ce
{ "func_code_index": [ 5495, 5630 ] }
2,659
NotifyHelperStateful
contracts/NotifyHelperStateful.sol
0x71316a3465e0fbcd08e665d6675caa8f7b1dd40a
Solidity
NotifyHelperStateful
contract NotifyHelperStateful is Controllable { using SafeMath for uint256; using SafeERC20 for IERC20; event ChangerSet(address indexed account, bool value); event NotifierSet(address indexed account, bool value); event Vesting(address pool, uint256 amount); event PoolChanged(address indexed pool, uint256 percentage, uint256 notificationType, bool vests); enum NotificationType { VOID, IFARM, FARM, TRANSFER, PROFIT_SHARE } struct Notification { address poolAddress; NotificationType notificationType; uint256 percentage; bool vests; } struct WorkingNotification { address[] pools; uint256[] amounts; uint256 checksum; uint256 counter; } uint256 public VESTING_DENOMINATOR = 3; uint256 public VESTING_NUMERATOR = 2; mapping (address => bool) changer; mapping (address => bool) notifier; address public notifyHelperRegular; address public notifyHelperIFARM; address public farm; Notification[] public notifications; mapping (address => uint256) public poolToIndex; mapping (uint256 => uint256) public numbers; // NotificationType to the number of pools address public reserve; address public vestingEscrow; uint256 public totalPercentage; // maintain state to not have to calculate during emissions modifier onlyChanger { require(changer[msg.sender] || msg.sender == governance(), "Only changer"); _; } modifier onlyNotifier { require(notifier[msg.sender], "Only notifier"); _; } constructor(address _storage, address _notifyHelperRegular, address _farm, address _notifyHelperIFARM, address _escrow, address _reserve) Controllable(_storage) public { // used for getting a reference to FeeRewardForwarder notifyHelperRegular = _notifyHelperRegular; farm = _farm; notifyHelperIFARM = _notifyHelperIFARM; vestingEscrow = _escrow; reserve = _reserve; require(_reserve != address(0), "invalid reserve"); require(_escrow != address(0), "invalid escrow"); } /// Whitelisted entities can notify pools based on the state, both for FARM and iFARM /// The only whitelisted entity here would be the minter helper function notifyPools(uint256 total, uint256 timestamp) public onlyNotifier { // transfer the tokens from the msg.sender to here IERC20(farm).safeTransferFrom(msg.sender, address(this), total); // prepare the notification data WorkingNotification memory iFARM = WorkingNotification( new address[](numbers[uint256(NotificationType.IFARM)]), new uint256[](numbers[uint256(NotificationType.IFARM)]), 0, 0 ); WorkingNotification memory regular = WorkingNotification( new address[](numbers[uint256(NotificationType.FARM)]), new uint256[](numbers[uint256(NotificationType.FARM)]), 0, 0 ); uint256 profitShareForWeek = 0; uint256 vestingAmount = 0; for (uint256 i = 0; i < notifications.length; i++) { Notification storage notification = notifications[i]; if (notification.notificationType == NotificationType.PROFIT_SHARE) { // profit share profitShareForWeek = total.mul(notification.percentage).div(totalPercentage); } else if (notification.notificationType == NotificationType.TRANSFER) { // simple transfer IERC20(farm).safeTransfer( notification.poolAddress, total.mul(notification.percentage).div(totalPercentage) ); } else { // FARM or iFARM notification WorkingNotification memory toUse = notification.notificationType == NotificationType.FARM ? regular : iFARM; toUse.amounts[toUse.counter] = total.mul(notification.percentage).div(totalPercentage); if (notification.vests) { uint256 toVest = toUse.amounts[toUse.counter].mul(VESTING_NUMERATOR).div(VESTING_DENOMINATOR); toUse.amounts[toUse.counter] = toUse.amounts[toUse.counter].sub(toVest); vestingAmount = vestingAmount.add(toVest); emit Vesting(notification.poolAddress, toVest); } toUse.pools[toUse.counter] = notification.poolAddress; toUse.checksum = toUse.checksum.add(toUse.amounts[toUse.counter]); toUse.counter = toUse.counter.add(1); } } // handle vesting if (vestingAmount > 0) { IERC20(farm).safeTransfer(vestingEscrow, vestingAmount); } // iFARM notifications IERC20(farm).approve(notifyHelperIFARM, iFARM.checksum); INotifyHelperIFARM(notifyHelperIFARM).notifyPools(iFARM.amounts, iFARM.pools, iFARM.checksum); // regular notifications IERC20(farm).approve(notifyHelperRegular, regular.checksum.add(profitShareForWeek)); if (profitShareForWeek > 0) { INotifyHelperRegular(notifyHelperRegular).notifyPoolsIncludingProfitShare( regular.amounts, regular.pools, profitShareForWeek, timestamp, regular.checksum.add(profitShareForWeek) ); } else { INotifyHelperRegular(notifyHelperRegular).notifyPools( regular.amounts, regular.pools, regular.checksum ); } // send rest to the reserve uint256 remainingBalance = IERC20(farm).balanceOf(address(this)); if (remainingBalance > 0) { IERC20(farm).safeTransfer(reserve, remainingBalance); } } /// Returning the governance function transferGovernance(address target, address newStorage) external onlyGovernance { Governable(target).setStorage(newStorage); } /// The governance configures whitelists function setChanger(address who, bool value) external onlyGovernance { changer[who] = value; emit ChangerSet(who, value); } /// The governance configures whitelists function setNotifier(address who, bool value) external onlyGovernance { notifier[who] = value; emit NotifierSet(who, value); } /// Whitelisted entity makes changes to the notifications function setPoolBatch(address[] calldata poolAddress, uint256[] calldata poolPercentage, NotificationType[] calldata notificationType, bool[] calldata vests) external onlyChanger { for (uint256 i = 0; i < poolAddress.length; i++) { setPool(poolAddress[i], poolPercentage[i], notificationType[i], vests[i]); } } /// Pool management, adds, updates or removes a transfer/notification function setPool(address poolAddress, uint256 poolPercentage, NotificationType notificationType, bool vests) public onlyChanger { require(notificationType != NotificationType.VOID, "Use valid indication"); if (notificationExists(poolAddress) && poolPercentage == 0) { // remove removeNotification(poolAddress); } else if (notificationExists(poolAddress)) { // update updateNotification(poolAddress, notificationType, poolPercentage, vests); } else if (poolPercentage > 0) { // add because it does not exist addNotification(poolAddress, poolPercentage, notificationType, vests); } emit PoolChanged(poolAddress, poolPercentage, uint256(notificationType), vests); } /// Configuration method for vesting for governance function setVestingEscrow(address _escrow) external onlyGovernance { vestingEscrow = _escrow; } /// Configuration method for vesting for governance function setVesting(uint256 _numerator, uint256 _denominator) external onlyGovernance { VESTING_DENOMINATOR = _numerator; VESTING_NUMERATOR = _denominator; } function notificationExists(address poolAddress) public view returns(bool) { if (notifications.length == 0) return false; if (poolToIndex[poolAddress] != 0) return true; return (notifications[0].poolAddress == poolAddress); } function removeNotification(address poolAddress) internal { require(notificationExists(poolAddress), "notification does not exist"); uint256 index = poolToIndex[poolAddress]; Notification storage notification = notifications[index]; totalPercentage = totalPercentage.sub(notification.percentage); numbers[uint256(notification.notificationType)] = numbers[uint256(notification.notificationType)].sub(1); // move the last element here and pop from the array notifications[index] = notifications[notifications.length.sub(1)]; poolToIndex[notifications[index].poolAddress] = index; poolToIndex[poolAddress] = 0; notifications.pop(); require(!notificationExists(poolAddress), "notification was not removed"); } function updateNotification(address poolAddress, NotificationType notificationType, uint256 percentage, bool vesting) internal { require(notificationExists(poolAddress), "notification does not exist"); require(percentage > 0, "notification is 0"); uint256 index = poolToIndex[poolAddress]; totalPercentage = totalPercentage.sub(notifications[index].percentage).add(percentage); notifications[index].percentage = percentage; notifications[index].vests = vesting; if (notifications[index].notificationType != notificationType) { numbers[uint256(notifications[index].notificationType)] = numbers[uint256(notifications[index].notificationType)].sub(1); notifications[index].notificationType = notificationType; numbers[uint256(notifications[index].notificationType)] = numbers[uint256(notifications[index].notificationType)].add(1); require(numbers[uint256(NotificationType.PROFIT_SHARE)] <= 1, "At most one profit share"); } } function addNotification(address poolAddress, uint256 percentage, NotificationType notificationType, bool vesting) internal { require(!notificationExists(poolAddress), "notification exists"); require(percentage > 0, "notification is 0"); Notification memory notification = Notification(poolAddress, notificationType, percentage, vesting); notifications.push(notification); totalPercentage = totalPercentage.add(notification.percentage); numbers[uint256(notification.notificationType)] = numbers[uint256(notification.notificationType)].add(1); poolToIndex[notification.poolAddress] = notifications.length.sub(1); require(numbers[uint256(NotificationType.PROFIT_SHARE)] <= 1, "At most one profit share"); require(notificationExists(poolAddress), "notification was not added"); } /// emergency draining of tokens and ETH as there should be none staying here function emergencyDrain(address token, uint256 amount) public onlyGovernance { if (token == address(0)) { msg.sender.transfer(amount); } else { IERC20(token).safeTransfer(msg.sender, amount); } } /// configuration check method function getConfig(uint256 totalAmount) external view returns(address[] memory, uint256[] memory, uint256[] memory) { address[] memory pools = new address[](notifications.length); uint256[] memory percentages = new uint256[](notifications.length); uint256[] memory amounts = new uint256[](notifications.length); for (uint256 i = 0; i < notifications.length; i++) { Notification storage notification = notifications[i]; pools[i] = notification.poolAddress; percentages[i] = notification.percentage.mul(1000000).div(totalPercentage); amounts[i] = notification.percentage.mul(totalAmount).div(totalPercentage); } return (pools, percentages, amounts); } }
setNotifier
function setNotifier(address who, bool value) external onlyGovernance { notifier[who] = value; emit NotifierSet(who, value); }
/// The governance configures whitelists
NatSpecSingleLine
v0.5.16+commit.9c3226ce
{ "func_code_index": [ 5675, 5813 ] }
2,660
NotifyHelperStateful
contracts/NotifyHelperStateful.sol
0x71316a3465e0fbcd08e665d6675caa8f7b1dd40a
Solidity
NotifyHelperStateful
contract NotifyHelperStateful is Controllable { using SafeMath for uint256; using SafeERC20 for IERC20; event ChangerSet(address indexed account, bool value); event NotifierSet(address indexed account, bool value); event Vesting(address pool, uint256 amount); event PoolChanged(address indexed pool, uint256 percentage, uint256 notificationType, bool vests); enum NotificationType { VOID, IFARM, FARM, TRANSFER, PROFIT_SHARE } struct Notification { address poolAddress; NotificationType notificationType; uint256 percentage; bool vests; } struct WorkingNotification { address[] pools; uint256[] amounts; uint256 checksum; uint256 counter; } uint256 public VESTING_DENOMINATOR = 3; uint256 public VESTING_NUMERATOR = 2; mapping (address => bool) changer; mapping (address => bool) notifier; address public notifyHelperRegular; address public notifyHelperIFARM; address public farm; Notification[] public notifications; mapping (address => uint256) public poolToIndex; mapping (uint256 => uint256) public numbers; // NotificationType to the number of pools address public reserve; address public vestingEscrow; uint256 public totalPercentage; // maintain state to not have to calculate during emissions modifier onlyChanger { require(changer[msg.sender] || msg.sender == governance(), "Only changer"); _; } modifier onlyNotifier { require(notifier[msg.sender], "Only notifier"); _; } constructor(address _storage, address _notifyHelperRegular, address _farm, address _notifyHelperIFARM, address _escrow, address _reserve) Controllable(_storage) public { // used for getting a reference to FeeRewardForwarder notifyHelperRegular = _notifyHelperRegular; farm = _farm; notifyHelperIFARM = _notifyHelperIFARM; vestingEscrow = _escrow; reserve = _reserve; require(_reserve != address(0), "invalid reserve"); require(_escrow != address(0), "invalid escrow"); } /// Whitelisted entities can notify pools based on the state, both for FARM and iFARM /// The only whitelisted entity here would be the minter helper function notifyPools(uint256 total, uint256 timestamp) public onlyNotifier { // transfer the tokens from the msg.sender to here IERC20(farm).safeTransferFrom(msg.sender, address(this), total); // prepare the notification data WorkingNotification memory iFARM = WorkingNotification( new address[](numbers[uint256(NotificationType.IFARM)]), new uint256[](numbers[uint256(NotificationType.IFARM)]), 0, 0 ); WorkingNotification memory regular = WorkingNotification( new address[](numbers[uint256(NotificationType.FARM)]), new uint256[](numbers[uint256(NotificationType.FARM)]), 0, 0 ); uint256 profitShareForWeek = 0; uint256 vestingAmount = 0; for (uint256 i = 0; i < notifications.length; i++) { Notification storage notification = notifications[i]; if (notification.notificationType == NotificationType.PROFIT_SHARE) { // profit share profitShareForWeek = total.mul(notification.percentage).div(totalPercentage); } else if (notification.notificationType == NotificationType.TRANSFER) { // simple transfer IERC20(farm).safeTransfer( notification.poolAddress, total.mul(notification.percentage).div(totalPercentage) ); } else { // FARM or iFARM notification WorkingNotification memory toUse = notification.notificationType == NotificationType.FARM ? regular : iFARM; toUse.amounts[toUse.counter] = total.mul(notification.percentage).div(totalPercentage); if (notification.vests) { uint256 toVest = toUse.amounts[toUse.counter].mul(VESTING_NUMERATOR).div(VESTING_DENOMINATOR); toUse.amounts[toUse.counter] = toUse.amounts[toUse.counter].sub(toVest); vestingAmount = vestingAmount.add(toVest); emit Vesting(notification.poolAddress, toVest); } toUse.pools[toUse.counter] = notification.poolAddress; toUse.checksum = toUse.checksum.add(toUse.amounts[toUse.counter]); toUse.counter = toUse.counter.add(1); } } // handle vesting if (vestingAmount > 0) { IERC20(farm).safeTransfer(vestingEscrow, vestingAmount); } // iFARM notifications IERC20(farm).approve(notifyHelperIFARM, iFARM.checksum); INotifyHelperIFARM(notifyHelperIFARM).notifyPools(iFARM.amounts, iFARM.pools, iFARM.checksum); // regular notifications IERC20(farm).approve(notifyHelperRegular, regular.checksum.add(profitShareForWeek)); if (profitShareForWeek > 0) { INotifyHelperRegular(notifyHelperRegular).notifyPoolsIncludingProfitShare( regular.amounts, regular.pools, profitShareForWeek, timestamp, regular.checksum.add(profitShareForWeek) ); } else { INotifyHelperRegular(notifyHelperRegular).notifyPools( regular.amounts, regular.pools, regular.checksum ); } // send rest to the reserve uint256 remainingBalance = IERC20(farm).balanceOf(address(this)); if (remainingBalance > 0) { IERC20(farm).safeTransfer(reserve, remainingBalance); } } /// Returning the governance function transferGovernance(address target, address newStorage) external onlyGovernance { Governable(target).setStorage(newStorage); } /// The governance configures whitelists function setChanger(address who, bool value) external onlyGovernance { changer[who] = value; emit ChangerSet(who, value); } /// The governance configures whitelists function setNotifier(address who, bool value) external onlyGovernance { notifier[who] = value; emit NotifierSet(who, value); } /// Whitelisted entity makes changes to the notifications function setPoolBatch(address[] calldata poolAddress, uint256[] calldata poolPercentage, NotificationType[] calldata notificationType, bool[] calldata vests) external onlyChanger { for (uint256 i = 0; i < poolAddress.length; i++) { setPool(poolAddress[i], poolPercentage[i], notificationType[i], vests[i]); } } /// Pool management, adds, updates or removes a transfer/notification function setPool(address poolAddress, uint256 poolPercentage, NotificationType notificationType, bool vests) public onlyChanger { require(notificationType != NotificationType.VOID, "Use valid indication"); if (notificationExists(poolAddress) && poolPercentage == 0) { // remove removeNotification(poolAddress); } else if (notificationExists(poolAddress)) { // update updateNotification(poolAddress, notificationType, poolPercentage, vests); } else if (poolPercentage > 0) { // add because it does not exist addNotification(poolAddress, poolPercentage, notificationType, vests); } emit PoolChanged(poolAddress, poolPercentage, uint256(notificationType), vests); } /// Configuration method for vesting for governance function setVestingEscrow(address _escrow) external onlyGovernance { vestingEscrow = _escrow; } /// Configuration method for vesting for governance function setVesting(uint256 _numerator, uint256 _denominator) external onlyGovernance { VESTING_DENOMINATOR = _numerator; VESTING_NUMERATOR = _denominator; } function notificationExists(address poolAddress) public view returns(bool) { if (notifications.length == 0) return false; if (poolToIndex[poolAddress] != 0) return true; return (notifications[0].poolAddress == poolAddress); } function removeNotification(address poolAddress) internal { require(notificationExists(poolAddress), "notification does not exist"); uint256 index = poolToIndex[poolAddress]; Notification storage notification = notifications[index]; totalPercentage = totalPercentage.sub(notification.percentage); numbers[uint256(notification.notificationType)] = numbers[uint256(notification.notificationType)].sub(1); // move the last element here and pop from the array notifications[index] = notifications[notifications.length.sub(1)]; poolToIndex[notifications[index].poolAddress] = index; poolToIndex[poolAddress] = 0; notifications.pop(); require(!notificationExists(poolAddress), "notification was not removed"); } function updateNotification(address poolAddress, NotificationType notificationType, uint256 percentage, bool vesting) internal { require(notificationExists(poolAddress), "notification does not exist"); require(percentage > 0, "notification is 0"); uint256 index = poolToIndex[poolAddress]; totalPercentage = totalPercentage.sub(notifications[index].percentage).add(percentage); notifications[index].percentage = percentage; notifications[index].vests = vesting; if (notifications[index].notificationType != notificationType) { numbers[uint256(notifications[index].notificationType)] = numbers[uint256(notifications[index].notificationType)].sub(1); notifications[index].notificationType = notificationType; numbers[uint256(notifications[index].notificationType)] = numbers[uint256(notifications[index].notificationType)].add(1); require(numbers[uint256(NotificationType.PROFIT_SHARE)] <= 1, "At most one profit share"); } } function addNotification(address poolAddress, uint256 percentage, NotificationType notificationType, bool vesting) internal { require(!notificationExists(poolAddress), "notification exists"); require(percentage > 0, "notification is 0"); Notification memory notification = Notification(poolAddress, notificationType, percentage, vesting); notifications.push(notification); totalPercentage = totalPercentage.add(notification.percentage); numbers[uint256(notification.notificationType)] = numbers[uint256(notification.notificationType)].add(1); poolToIndex[notification.poolAddress] = notifications.length.sub(1); require(numbers[uint256(NotificationType.PROFIT_SHARE)] <= 1, "At most one profit share"); require(notificationExists(poolAddress), "notification was not added"); } /// emergency draining of tokens and ETH as there should be none staying here function emergencyDrain(address token, uint256 amount) public onlyGovernance { if (token == address(0)) { msg.sender.transfer(amount); } else { IERC20(token).safeTransfer(msg.sender, amount); } } /// configuration check method function getConfig(uint256 totalAmount) external view returns(address[] memory, uint256[] memory, uint256[] memory) { address[] memory pools = new address[](notifications.length); uint256[] memory percentages = new uint256[](notifications.length); uint256[] memory amounts = new uint256[](notifications.length); for (uint256 i = 0; i < notifications.length; i++) { Notification storage notification = notifications[i]; pools[i] = notification.poolAddress; percentages[i] = notification.percentage.mul(1000000).div(totalPercentage); amounts[i] = notification.percentage.mul(totalAmount).div(totalPercentage); } return (pools, percentages, amounts); } }
setPoolBatch
function setPoolBatch(address[] calldata poolAddress, uint256[] calldata poolPercentage, NotificationType[] calldata notificationType, bool[] calldata vests) external onlyChanger { for (uint256 i = 0; i < poolAddress.length; i++) { setPool(poolAddress[i], poolPercentage[i], notificationType[i], vests[i]); } }
/// Whitelisted entity makes changes to the notifications
NatSpecSingleLine
v0.5.16+commit.9c3226ce
{ "func_code_index": [ 5875, 6203 ] }
2,661
NotifyHelperStateful
contracts/NotifyHelperStateful.sol
0x71316a3465e0fbcd08e665d6675caa8f7b1dd40a
Solidity
NotifyHelperStateful
contract NotifyHelperStateful is Controllable { using SafeMath for uint256; using SafeERC20 for IERC20; event ChangerSet(address indexed account, bool value); event NotifierSet(address indexed account, bool value); event Vesting(address pool, uint256 amount); event PoolChanged(address indexed pool, uint256 percentage, uint256 notificationType, bool vests); enum NotificationType { VOID, IFARM, FARM, TRANSFER, PROFIT_SHARE } struct Notification { address poolAddress; NotificationType notificationType; uint256 percentage; bool vests; } struct WorkingNotification { address[] pools; uint256[] amounts; uint256 checksum; uint256 counter; } uint256 public VESTING_DENOMINATOR = 3; uint256 public VESTING_NUMERATOR = 2; mapping (address => bool) changer; mapping (address => bool) notifier; address public notifyHelperRegular; address public notifyHelperIFARM; address public farm; Notification[] public notifications; mapping (address => uint256) public poolToIndex; mapping (uint256 => uint256) public numbers; // NotificationType to the number of pools address public reserve; address public vestingEscrow; uint256 public totalPercentage; // maintain state to not have to calculate during emissions modifier onlyChanger { require(changer[msg.sender] || msg.sender == governance(), "Only changer"); _; } modifier onlyNotifier { require(notifier[msg.sender], "Only notifier"); _; } constructor(address _storage, address _notifyHelperRegular, address _farm, address _notifyHelperIFARM, address _escrow, address _reserve) Controllable(_storage) public { // used for getting a reference to FeeRewardForwarder notifyHelperRegular = _notifyHelperRegular; farm = _farm; notifyHelperIFARM = _notifyHelperIFARM; vestingEscrow = _escrow; reserve = _reserve; require(_reserve != address(0), "invalid reserve"); require(_escrow != address(0), "invalid escrow"); } /// Whitelisted entities can notify pools based on the state, both for FARM and iFARM /// The only whitelisted entity here would be the minter helper function notifyPools(uint256 total, uint256 timestamp) public onlyNotifier { // transfer the tokens from the msg.sender to here IERC20(farm).safeTransferFrom(msg.sender, address(this), total); // prepare the notification data WorkingNotification memory iFARM = WorkingNotification( new address[](numbers[uint256(NotificationType.IFARM)]), new uint256[](numbers[uint256(NotificationType.IFARM)]), 0, 0 ); WorkingNotification memory regular = WorkingNotification( new address[](numbers[uint256(NotificationType.FARM)]), new uint256[](numbers[uint256(NotificationType.FARM)]), 0, 0 ); uint256 profitShareForWeek = 0; uint256 vestingAmount = 0; for (uint256 i = 0; i < notifications.length; i++) { Notification storage notification = notifications[i]; if (notification.notificationType == NotificationType.PROFIT_SHARE) { // profit share profitShareForWeek = total.mul(notification.percentage).div(totalPercentage); } else if (notification.notificationType == NotificationType.TRANSFER) { // simple transfer IERC20(farm).safeTransfer( notification.poolAddress, total.mul(notification.percentage).div(totalPercentage) ); } else { // FARM or iFARM notification WorkingNotification memory toUse = notification.notificationType == NotificationType.FARM ? regular : iFARM; toUse.amounts[toUse.counter] = total.mul(notification.percentage).div(totalPercentage); if (notification.vests) { uint256 toVest = toUse.amounts[toUse.counter].mul(VESTING_NUMERATOR).div(VESTING_DENOMINATOR); toUse.amounts[toUse.counter] = toUse.amounts[toUse.counter].sub(toVest); vestingAmount = vestingAmount.add(toVest); emit Vesting(notification.poolAddress, toVest); } toUse.pools[toUse.counter] = notification.poolAddress; toUse.checksum = toUse.checksum.add(toUse.amounts[toUse.counter]); toUse.counter = toUse.counter.add(1); } } // handle vesting if (vestingAmount > 0) { IERC20(farm).safeTransfer(vestingEscrow, vestingAmount); } // iFARM notifications IERC20(farm).approve(notifyHelperIFARM, iFARM.checksum); INotifyHelperIFARM(notifyHelperIFARM).notifyPools(iFARM.amounts, iFARM.pools, iFARM.checksum); // regular notifications IERC20(farm).approve(notifyHelperRegular, regular.checksum.add(profitShareForWeek)); if (profitShareForWeek > 0) { INotifyHelperRegular(notifyHelperRegular).notifyPoolsIncludingProfitShare( regular.amounts, regular.pools, profitShareForWeek, timestamp, regular.checksum.add(profitShareForWeek) ); } else { INotifyHelperRegular(notifyHelperRegular).notifyPools( regular.amounts, regular.pools, regular.checksum ); } // send rest to the reserve uint256 remainingBalance = IERC20(farm).balanceOf(address(this)); if (remainingBalance > 0) { IERC20(farm).safeTransfer(reserve, remainingBalance); } } /// Returning the governance function transferGovernance(address target, address newStorage) external onlyGovernance { Governable(target).setStorage(newStorage); } /// The governance configures whitelists function setChanger(address who, bool value) external onlyGovernance { changer[who] = value; emit ChangerSet(who, value); } /// The governance configures whitelists function setNotifier(address who, bool value) external onlyGovernance { notifier[who] = value; emit NotifierSet(who, value); } /// Whitelisted entity makes changes to the notifications function setPoolBatch(address[] calldata poolAddress, uint256[] calldata poolPercentage, NotificationType[] calldata notificationType, bool[] calldata vests) external onlyChanger { for (uint256 i = 0; i < poolAddress.length; i++) { setPool(poolAddress[i], poolPercentage[i], notificationType[i], vests[i]); } } /// Pool management, adds, updates or removes a transfer/notification function setPool(address poolAddress, uint256 poolPercentage, NotificationType notificationType, bool vests) public onlyChanger { require(notificationType != NotificationType.VOID, "Use valid indication"); if (notificationExists(poolAddress) && poolPercentage == 0) { // remove removeNotification(poolAddress); } else if (notificationExists(poolAddress)) { // update updateNotification(poolAddress, notificationType, poolPercentage, vests); } else if (poolPercentage > 0) { // add because it does not exist addNotification(poolAddress, poolPercentage, notificationType, vests); } emit PoolChanged(poolAddress, poolPercentage, uint256(notificationType), vests); } /// Configuration method for vesting for governance function setVestingEscrow(address _escrow) external onlyGovernance { vestingEscrow = _escrow; } /// Configuration method for vesting for governance function setVesting(uint256 _numerator, uint256 _denominator) external onlyGovernance { VESTING_DENOMINATOR = _numerator; VESTING_NUMERATOR = _denominator; } function notificationExists(address poolAddress) public view returns(bool) { if (notifications.length == 0) return false; if (poolToIndex[poolAddress] != 0) return true; return (notifications[0].poolAddress == poolAddress); } function removeNotification(address poolAddress) internal { require(notificationExists(poolAddress), "notification does not exist"); uint256 index = poolToIndex[poolAddress]; Notification storage notification = notifications[index]; totalPercentage = totalPercentage.sub(notification.percentage); numbers[uint256(notification.notificationType)] = numbers[uint256(notification.notificationType)].sub(1); // move the last element here and pop from the array notifications[index] = notifications[notifications.length.sub(1)]; poolToIndex[notifications[index].poolAddress] = index; poolToIndex[poolAddress] = 0; notifications.pop(); require(!notificationExists(poolAddress), "notification was not removed"); } function updateNotification(address poolAddress, NotificationType notificationType, uint256 percentage, bool vesting) internal { require(notificationExists(poolAddress), "notification does not exist"); require(percentage > 0, "notification is 0"); uint256 index = poolToIndex[poolAddress]; totalPercentage = totalPercentage.sub(notifications[index].percentage).add(percentage); notifications[index].percentage = percentage; notifications[index].vests = vesting; if (notifications[index].notificationType != notificationType) { numbers[uint256(notifications[index].notificationType)] = numbers[uint256(notifications[index].notificationType)].sub(1); notifications[index].notificationType = notificationType; numbers[uint256(notifications[index].notificationType)] = numbers[uint256(notifications[index].notificationType)].add(1); require(numbers[uint256(NotificationType.PROFIT_SHARE)] <= 1, "At most one profit share"); } } function addNotification(address poolAddress, uint256 percentage, NotificationType notificationType, bool vesting) internal { require(!notificationExists(poolAddress), "notification exists"); require(percentage > 0, "notification is 0"); Notification memory notification = Notification(poolAddress, notificationType, percentage, vesting); notifications.push(notification); totalPercentage = totalPercentage.add(notification.percentage); numbers[uint256(notification.notificationType)] = numbers[uint256(notification.notificationType)].add(1); poolToIndex[notification.poolAddress] = notifications.length.sub(1); require(numbers[uint256(NotificationType.PROFIT_SHARE)] <= 1, "At most one profit share"); require(notificationExists(poolAddress), "notification was not added"); } /// emergency draining of tokens and ETH as there should be none staying here function emergencyDrain(address token, uint256 amount) public onlyGovernance { if (token == address(0)) { msg.sender.transfer(amount); } else { IERC20(token).safeTransfer(msg.sender, amount); } } /// configuration check method function getConfig(uint256 totalAmount) external view returns(address[] memory, uint256[] memory, uint256[] memory) { address[] memory pools = new address[](notifications.length); uint256[] memory percentages = new uint256[](notifications.length); uint256[] memory amounts = new uint256[](notifications.length); for (uint256 i = 0; i < notifications.length; i++) { Notification storage notification = notifications[i]; pools[i] = notification.poolAddress; percentages[i] = notification.percentage.mul(1000000).div(totalPercentage); amounts[i] = notification.percentage.mul(totalAmount).div(totalPercentage); } return (pools, percentages, amounts); } }
setPool
function setPool(address poolAddress, uint256 poolPercentage, NotificationType notificationType, bool vests) public onlyChanger { require(notificationType != NotificationType.VOID, "Use valid indication"); if (notificationExists(poolAddress) && poolPercentage == 0) { // remove removeNotification(poolAddress); } else if (notificationExists(poolAddress)) { // update updateNotification(poolAddress, notificationType, poolPercentage, vests); } else if (poolPercentage > 0) { // add because it does not exist addNotification(poolAddress, poolPercentage, notificationType, vests); } emit PoolChanged(poolAddress, poolPercentage, uint256(notificationType), vests); }
/// Pool management, adds, updates or removes a transfer/notification
NatSpecSingleLine
v0.5.16+commit.9c3226ce
{ "func_code_index": [ 6277, 7003 ] }
2,662
NotifyHelperStateful
contracts/NotifyHelperStateful.sol
0x71316a3465e0fbcd08e665d6675caa8f7b1dd40a
Solidity
NotifyHelperStateful
contract NotifyHelperStateful is Controllable { using SafeMath for uint256; using SafeERC20 for IERC20; event ChangerSet(address indexed account, bool value); event NotifierSet(address indexed account, bool value); event Vesting(address pool, uint256 amount); event PoolChanged(address indexed pool, uint256 percentage, uint256 notificationType, bool vests); enum NotificationType { VOID, IFARM, FARM, TRANSFER, PROFIT_SHARE } struct Notification { address poolAddress; NotificationType notificationType; uint256 percentage; bool vests; } struct WorkingNotification { address[] pools; uint256[] amounts; uint256 checksum; uint256 counter; } uint256 public VESTING_DENOMINATOR = 3; uint256 public VESTING_NUMERATOR = 2; mapping (address => bool) changer; mapping (address => bool) notifier; address public notifyHelperRegular; address public notifyHelperIFARM; address public farm; Notification[] public notifications; mapping (address => uint256) public poolToIndex; mapping (uint256 => uint256) public numbers; // NotificationType to the number of pools address public reserve; address public vestingEscrow; uint256 public totalPercentage; // maintain state to not have to calculate during emissions modifier onlyChanger { require(changer[msg.sender] || msg.sender == governance(), "Only changer"); _; } modifier onlyNotifier { require(notifier[msg.sender], "Only notifier"); _; } constructor(address _storage, address _notifyHelperRegular, address _farm, address _notifyHelperIFARM, address _escrow, address _reserve) Controllable(_storage) public { // used for getting a reference to FeeRewardForwarder notifyHelperRegular = _notifyHelperRegular; farm = _farm; notifyHelperIFARM = _notifyHelperIFARM; vestingEscrow = _escrow; reserve = _reserve; require(_reserve != address(0), "invalid reserve"); require(_escrow != address(0), "invalid escrow"); } /// Whitelisted entities can notify pools based on the state, both for FARM and iFARM /// The only whitelisted entity here would be the minter helper function notifyPools(uint256 total, uint256 timestamp) public onlyNotifier { // transfer the tokens from the msg.sender to here IERC20(farm).safeTransferFrom(msg.sender, address(this), total); // prepare the notification data WorkingNotification memory iFARM = WorkingNotification( new address[](numbers[uint256(NotificationType.IFARM)]), new uint256[](numbers[uint256(NotificationType.IFARM)]), 0, 0 ); WorkingNotification memory regular = WorkingNotification( new address[](numbers[uint256(NotificationType.FARM)]), new uint256[](numbers[uint256(NotificationType.FARM)]), 0, 0 ); uint256 profitShareForWeek = 0; uint256 vestingAmount = 0; for (uint256 i = 0; i < notifications.length; i++) { Notification storage notification = notifications[i]; if (notification.notificationType == NotificationType.PROFIT_SHARE) { // profit share profitShareForWeek = total.mul(notification.percentage).div(totalPercentage); } else if (notification.notificationType == NotificationType.TRANSFER) { // simple transfer IERC20(farm).safeTransfer( notification.poolAddress, total.mul(notification.percentage).div(totalPercentage) ); } else { // FARM or iFARM notification WorkingNotification memory toUse = notification.notificationType == NotificationType.FARM ? regular : iFARM; toUse.amounts[toUse.counter] = total.mul(notification.percentage).div(totalPercentage); if (notification.vests) { uint256 toVest = toUse.amounts[toUse.counter].mul(VESTING_NUMERATOR).div(VESTING_DENOMINATOR); toUse.amounts[toUse.counter] = toUse.amounts[toUse.counter].sub(toVest); vestingAmount = vestingAmount.add(toVest); emit Vesting(notification.poolAddress, toVest); } toUse.pools[toUse.counter] = notification.poolAddress; toUse.checksum = toUse.checksum.add(toUse.amounts[toUse.counter]); toUse.counter = toUse.counter.add(1); } } // handle vesting if (vestingAmount > 0) { IERC20(farm).safeTransfer(vestingEscrow, vestingAmount); } // iFARM notifications IERC20(farm).approve(notifyHelperIFARM, iFARM.checksum); INotifyHelperIFARM(notifyHelperIFARM).notifyPools(iFARM.amounts, iFARM.pools, iFARM.checksum); // regular notifications IERC20(farm).approve(notifyHelperRegular, regular.checksum.add(profitShareForWeek)); if (profitShareForWeek > 0) { INotifyHelperRegular(notifyHelperRegular).notifyPoolsIncludingProfitShare( regular.amounts, regular.pools, profitShareForWeek, timestamp, regular.checksum.add(profitShareForWeek) ); } else { INotifyHelperRegular(notifyHelperRegular).notifyPools( regular.amounts, regular.pools, regular.checksum ); } // send rest to the reserve uint256 remainingBalance = IERC20(farm).balanceOf(address(this)); if (remainingBalance > 0) { IERC20(farm).safeTransfer(reserve, remainingBalance); } } /// Returning the governance function transferGovernance(address target, address newStorage) external onlyGovernance { Governable(target).setStorage(newStorage); } /// The governance configures whitelists function setChanger(address who, bool value) external onlyGovernance { changer[who] = value; emit ChangerSet(who, value); } /// The governance configures whitelists function setNotifier(address who, bool value) external onlyGovernance { notifier[who] = value; emit NotifierSet(who, value); } /// Whitelisted entity makes changes to the notifications function setPoolBatch(address[] calldata poolAddress, uint256[] calldata poolPercentage, NotificationType[] calldata notificationType, bool[] calldata vests) external onlyChanger { for (uint256 i = 0; i < poolAddress.length; i++) { setPool(poolAddress[i], poolPercentage[i], notificationType[i], vests[i]); } } /// Pool management, adds, updates or removes a transfer/notification function setPool(address poolAddress, uint256 poolPercentage, NotificationType notificationType, bool vests) public onlyChanger { require(notificationType != NotificationType.VOID, "Use valid indication"); if (notificationExists(poolAddress) && poolPercentage == 0) { // remove removeNotification(poolAddress); } else if (notificationExists(poolAddress)) { // update updateNotification(poolAddress, notificationType, poolPercentage, vests); } else if (poolPercentage > 0) { // add because it does not exist addNotification(poolAddress, poolPercentage, notificationType, vests); } emit PoolChanged(poolAddress, poolPercentage, uint256(notificationType), vests); } /// Configuration method for vesting for governance function setVestingEscrow(address _escrow) external onlyGovernance { vestingEscrow = _escrow; } /// Configuration method for vesting for governance function setVesting(uint256 _numerator, uint256 _denominator) external onlyGovernance { VESTING_DENOMINATOR = _numerator; VESTING_NUMERATOR = _denominator; } function notificationExists(address poolAddress) public view returns(bool) { if (notifications.length == 0) return false; if (poolToIndex[poolAddress] != 0) return true; return (notifications[0].poolAddress == poolAddress); } function removeNotification(address poolAddress) internal { require(notificationExists(poolAddress), "notification does not exist"); uint256 index = poolToIndex[poolAddress]; Notification storage notification = notifications[index]; totalPercentage = totalPercentage.sub(notification.percentage); numbers[uint256(notification.notificationType)] = numbers[uint256(notification.notificationType)].sub(1); // move the last element here and pop from the array notifications[index] = notifications[notifications.length.sub(1)]; poolToIndex[notifications[index].poolAddress] = index; poolToIndex[poolAddress] = 0; notifications.pop(); require(!notificationExists(poolAddress), "notification was not removed"); } function updateNotification(address poolAddress, NotificationType notificationType, uint256 percentage, bool vesting) internal { require(notificationExists(poolAddress), "notification does not exist"); require(percentage > 0, "notification is 0"); uint256 index = poolToIndex[poolAddress]; totalPercentage = totalPercentage.sub(notifications[index].percentage).add(percentage); notifications[index].percentage = percentage; notifications[index].vests = vesting; if (notifications[index].notificationType != notificationType) { numbers[uint256(notifications[index].notificationType)] = numbers[uint256(notifications[index].notificationType)].sub(1); notifications[index].notificationType = notificationType; numbers[uint256(notifications[index].notificationType)] = numbers[uint256(notifications[index].notificationType)].add(1); require(numbers[uint256(NotificationType.PROFIT_SHARE)] <= 1, "At most one profit share"); } } function addNotification(address poolAddress, uint256 percentage, NotificationType notificationType, bool vesting) internal { require(!notificationExists(poolAddress), "notification exists"); require(percentage > 0, "notification is 0"); Notification memory notification = Notification(poolAddress, notificationType, percentage, vesting); notifications.push(notification); totalPercentage = totalPercentage.add(notification.percentage); numbers[uint256(notification.notificationType)] = numbers[uint256(notification.notificationType)].add(1); poolToIndex[notification.poolAddress] = notifications.length.sub(1); require(numbers[uint256(NotificationType.PROFIT_SHARE)] <= 1, "At most one profit share"); require(notificationExists(poolAddress), "notification was not added"); } /// emergency draining of tokens and ETH as there should be none staying here function emergencyDrain(address token, uint256 amount) public onlyGovernance { if (token == address(0)) { msg.sender.transfer(amount); } else { IERC20(token).safeTransfer(msg.sender, amount); } } /// configuration check method function getConfig(uint256 totalAmount) external view returns(address[] memory, uint256[] memory, uint256[] memory) { address[] memory pools = new address[](notifications.length); uint256[] memory percentages = new uint256[](notifications.length); uint256[] memory amounts = new uint256[](notifications.length); for (uint256 i = 0; i < notifications.length; i++) { Notification storage notification = notifications[i]; pools[i] = notification.poolAddress; percentages[i] = notification.percentage.mul(1000000).div(totalPercentage); amounts[i] = notification.percentage.mul(totalAmount).div(totalPercentage); } return (pools, percentages, amounts); } }
setVestingEscrow
function setVestingEscrow(address _escrow) external onlyGovernance { vestingEscrow = _escrow; }
/// Configuration method for vesting for governance
NatSpecSingleLine
v0.5.16+commit.9c3226ce
{ "func_code_index": [ 7059, 7162 ] }
2,663
NotifyHelperStateful
contracts/NotifyHelperStateful.sol
0x71316a3465e0fbcd08e665d6675caa8f7b1dd40a
Solidity
NotifyHelperStateful
contract NotifyHelperStateful is Controllable { using SafeMath for uint256; using SafeERC20 for IERC20; event ChangerSet(address indexed account, bool value); event NotifierSet(address indexed account, bool value); event Vesting(address pool, uint256 amount); event PoolChanged(address indexed pool, uint256 percentage, uint256 notificationType, bool vests); enum NotificationType { VOID, IFARM, FARM, TRANSFER, PROFIT_SHARE } struct Notification { address poolAddress; NotificationType notificationType; uint256 percentage; bool vests; } struct WorkingNotification { address[] pools; uint256[] amounts; uint256 checksum; uint256 counter; } uint256 public VESTING_DENOMINATOR = 3; uint256 public VESTING_NUMERATOR = 2; mapping (address => bool) changer; mapping (address => bool) notifier; address public notifyHelperRegular; address public notifyHelperIFARM; address public farm; Notification[] public notifications; mapping (address => uint256) public poolToIndex; mapping (uint256 => uint256) public numbers; // NotificationType to the number of pools address public reserve; address public vestingEscrow; uint256 public totalPercentage; // maintain state to not have to calculate during emissions modifier onlyChanger { require(changer[msg.sender] || msg.sender == governance(), "Only changer"); _; } modifier onlyNotifier { require(notifier[msg.sender], "Only notifier"); _; } constructor(address _storage, address _notifyHelperRegular, address _farm, address _notifyHelperIFARM, address _escrow, address _reserve) Controllable(_storage) public { // used for getting a reference to FeeRewardForwarder notifyHelperRegular = _notifyHelperRegular; farm = _farm; notifyHelperIFARM = _notifyHelperIFARM; vestingEscrow = _escrow; reserve = _reserve; require(_reserve != address(0), "invalid reserve"); require(_escrow != address(0), "invalid escrow"); } /// Whitelisted entities can notify pools based on the state, both for FARM and iFARM /// The only whitelisted entity here would be the minter helper function notifyPools(uint256 total, uint256 timestamp) public onlyNotifier { // transfer the tokens from the msg.sender to here IERC20(farm).safeTransferFrom(msg.sender, address(this), total); // prepare the notification data WorkingNotification memory iFARM = WorkingNotification( new address[](numbers[uint256(NotificationType.IFARM)]), new uint256[](numbers[uint256(NotificationType.IFARM)]), 0, 0 ); WorkingNotification memory regular = WorkingNotification( new address[](numbers[uint256(NotificationType.FARM)]), new uint256[](numbers[uint256(NotificationType.FARM)]), 0, 0 ); uint256 profitShareForWeek = 0; uint256 vestingAmount = 0; for (uint256 i = 0; i < notifications.length; i++) { Notification storage notification = notifications[i]; if (notification.notificationType == NotificationType.PROFIT_SHARE) { // profit share profitShareForWeek = total.mul(notification.percentage).div(totalPercentage); } else if (notification.notificationType == NotificationType.TRANSFER) { // simple transfer IERC20(farm).safeTransfer( notification.poolAddress, total.mul(notification.percentage).div(totalPercentage) ); } else { // FARM or iFARM notification WorkingNotification memory toUse = notification.notificationType == NotificationType.FARM ? regular : iFARM; toUse.amounts[toUse.counter] = total.mul(notification.percentage).div(totalPercentage); if (notification.vests) { uint256 toVest = toUse.amounts[toUse.counter].mul(VESTING_NUMERATOR).div(VESTING_DENOMINATOR); toUse.amounts[toUse.counter] = toUse.amounts[toUse.counter].sub(toVest); vestingAmount = vestingAmount.add(toVest); emit Vesting(notification.poolAddress, toVest); } toUse.pools[toUse.counter] = notification.poolAddress; toUse.checksum = toUse.checksum.add(toUse.amounts[toUse.counter]); toUse.counter = toUse.counter.add(1); } } // handle vesting if (vestingAmount > 0) { IERC20(farm).safeTransfer(vestingEscrow, vestingAmount); } // iFARM notifications IERC20(farm).approve(notifyHelperIFARM, iFARM.checksum); INotifyHelperIFARM(notifyHelperIFARM).notifyPools(iFARM.amounts, iFARM.pools, iFARM.checksum); // regular notifications IERC20(farm).approve(notifyHelperRegular, regular.checksum.add(profitShareForWeek)); if (profitShareForWeek > 0) { INotifyHelperRegular(notifyHelperRegular).notifyPoolsIncludingProfitShare( regular.amounts, regular.pools, profitShareForWeek, timestamp, regular.checksum.add(profitShareForWeek) ); } else { INotifyHelperRegular(notifyHelperRegular).notifyPools( regular.amounts, regular.pools, regular.checksum ); } // send rest to the reserve uint256 remainingBalance = IERC20(farm).balanceOf(address(this)); if (remainingBalance > 0) { IERC20(farm).safeTransfer(reserve, remainingBalance); } } /// Returning the governance function transferGovernance(address target, address newStorage) external onlyGovernance { Governable(target).setStorage(newStorage); } /// The governance configures whitelists function setChanger(address who, bool value) external onlyGovernance { changer[who] = value; emit ChangerSet(who, value); } /// The governance configures whitelists function setNotifier(address who, bool value) external onlyGovernance { notifier[who] = value; emit NotifierSet(who, value); } /// Whitelisted entity makes changes to the notifications function setPoolBatch(address[] calldata poolAddress, uint256[] calldata poolPercentage, NotificationType[] calldata notificationType, bool[] calldata vests) external onlyChanger { for (uint256 i = 0; i < poolAddress.length; i++) { setPool(poolAddress[i], poolPercentage[i], notificationType[i], vests[i]); } } /// Pool management, adds, updates or removes a transfer/notification function setPool(address poolAddress, uint256 poolPercentage, NotificationType notificationType, bool vests) public onlyChanger { require(notificationType != NotificationType.VOID, "Use valid indication"); if (notificationExists(poolAddress) && poolPercentage == 0) { // remove removeNotification(poolAddress); } else if (notificationExists(poolAddress)) { // update updateNotification(poolAddress, notificationType, poolPercentage, vests); } else if (poolPercentage > 0) { // add because it does not exist addNotification(poolAddress, poolPercentage, notificationType, vests); } emit PoolChanged(poolAddress, poolPercentage, uint256(notificationType), vests); } /// Configuration method for vesting for governance function setVestingEscrow(address _escrow) external onlyGovernance { vestingEscrow = _escrow; } /// Configuration method for vesting for governance function setVesting(uint256 _numerator, uint256 _denominator) external onlyGovernance { VESTING_DENOMINATOR = _numerator; VESTING_NUMERATOR = _denominator; } function notificationExists(address poolAddress) public view returns(bool) { if (notifications.length == 0) return false; if (poolToIndex[poolAddress] != 0) return true; return (notifications[0].poolAddress == poolAddress); } function removeNotification(address poolAddress) internal { require(notificationExists(poolAddress), "notification does not exist"); uint256 index = poolToIndex[poolAddress]; Notification storage notification = notifications[index]; totalPercentage = totalPercentage.sub(notification.percentage); numbers[uint256(notification.notificationType)] = numbers[uint256(notification.notificationType)].sub(1); // move the last element here and pop from the array notifications[index] = notifications[notifications.length.sub(1)]; poolToIndex[notifications[index].poolAddress] = index; poolToIndex[poolAddress] = 0; notifications.pop(); require(!notificationExists(poolAddress), "notification was not removed"); } function updateNotification(address poolAddress, NotificationType notificationType, uint256 percentage, bool vesting) internal { require(notificationExists(poolAddress), "notification does not exist"); require(percentage > 0, "notification is 0"); uint256 index = poolToIndex[poolAddress]; totalPercentage = totalPercentage.sub(notifications[index].percentage).add(percentage); notifications[index].percentage = percentage; notifications[index].vests = vesting; if (notifications[index].notificationType != notificationType) { numbers[uint256(notifications[index].notificationType)] = numbers[uint256(notifications[index].notificationType)].sub(1); notifications[index].notificationType = notificationType; numbers[uint256(notifications[index].notificationType)] = numbers[uint256(notifications[index].notificationType)].add(1); require(numbers[uint256(NotificationType.PROFIT_SHARE)] <= 1, "At most one profit share"); } } function addNotification(address poolAddress, uint256 percentage, NotificationType notificationType, bool vesting) internal { require(!notificationExists(poolAddress), "notification exists"); require(percentage > 0, "notification is 0"); Notification memory notification = Notification(poolAddress, notificationType, percentage, vesting); notifications.push(notification); totalPercentage = totalPercentage.add(notification.percentage); numbers[uint256(notification.notificationType)] = numbers[uint256(notification.notificationType)].add(1); poolToIndex[notification.poolAddress] = notifications.length.sub(1); require(numbers[uint256(NotificationType.PROFIT_SHARE)] <= 1, "At most one profit share"); require(notificationExists(poolAddress), "notification was not added"); } /// emergency draining of tokens and ETH as there should be none staying here function emergencyDrain(address token, uint256 amount) public onlyGovernance { if (token == address(0)) { msg.sender.transfer(amount); } else { IERC20(token).safeTransfer(msg.sender, amount); } } /// configuration check method function getConfig(uint256 totalAmount) external view returns(address[] memory, uint256[] memory, uint256[] memory) { address[] memory pools = new address[](notifications.length); uint256[] memory percentages = new uint256[](notifications.length); uint256[] memory amounts = new uint256[](notifications.length); for (uint256 i = 0; i < notifications.length; i++) { Notification storage notification = notifications[i]; pools[i] = notification.poolAddress; percentages[i] = notification.percentage.mul(1000000).div(totalPercentage); amounts[i] = notification.percentage.mul(totalAmount).div(totalPercentage); } return (pools, percentages, amounts); } }
setVesting
function setVesting(uint256 _numerator, uint256 _denominator) external onlyGovernance { VESTING_DENOMINATOR = _numerator; VESTING_NUMERATOR = _denominator; }
/// Configuration method for vesting for governance
NatSpecSingleLine
v0.5.16+commit.9c3226ce
{ "func_code_index": [ 7218, 7387 ] }
2,664
NotifyHelperStateful
contracts/NotifyHelperStateful.sol
0x71316a3465e0fbcd08e665d6675caa8f7b1dd40a
Solidity
NotifyHelperStateful
contract NotifyHelperStateful is Controllable { using SafeMath for uint256; using SafeERC20 for IERC20; event ChangerSet(address indexed account, bool value); event NotifierSet(address indexed account, bool value); event Vesting(address pool, uint256 amount); event PoolChanged(address indexed pool, uint256 percentage, uint256 notificationType, bool vests); enum NotificationType { VOID, IFARM, FARM, TRANSFER, PROFIT_SHARE } struct Notification { address poolAddress; NotificationType notificationType; uint256 percentage; bool vests; } struct WorkingNotification { address[] pools; uint256[] amounts; uint256 checksum; uint256 counter; } uint256 public VESTING_DENOMINATOR = 3; uint256 public VESTING_NUMERATOR = 2; mapping (address => bool) changer; mapping (address => bool) notifier; address public notifyHelperRegular; address public notifyHelperIFARM; address public farm; Notification[] public notifications; mapping (address => uint256) public poolToIndex; mapping (uint256 => uint256) public numbers; // NotificationType to the number of pools address public reserve; address public vestingEscrow; uint256 public totalPercentage; // maintain state to not have to calculate during emissions modifier onlyChanger { require(changer[msg.sender] || msg.sender == governance(), "Only changer"); _; } modifier onlyNotifier { require(notifier[msg.sender], "Only notifier"); _; } constructor(address _storage, address _notifyHelperRegular, address _farm, address _notifyHelperIFARM, address _escrow, address _reserve) Controllable(_storage) public { // used for getting a reference to FeeRewardForwarder notifyHelperRegular = _notifyHelperRegular; farm = _farm; notifyHelperIFARM = _notifyHelperIFARM; vestingEscrow = _escrow; reserve = _reserve; require(_reserve != address(0), "invalid reserve"); require(_escrow != address(0), "invalid escrow"); } /// Whitelisted entities can notify pools based on the state, both for FARM and iFARM /// The only whitelisted entity here would be the minter helper function notifyPools(uint256 total, uint256 timestamp) public onlyNotifier { // transfer the tokens from the msg.sender to here IERC20(farm).safeTransferFrom(msg.sender, address(this), total); // prepare the notification data WorkingNotification memory iFARM = WorkingNotification( new address[](numbers[uint256(NotificationType.IFARM)]), new uint256[](numbers[uint256(NotificationType.IFARM)]), 0, 0 ); WorkingNotification memory regular = WorkingNotification( new address[](numbers[uint256(NotificationType.FARM)]), new uint256[](numbers[uint256(NotificationType.FARM)]), 0, 0 ); uint256 profitShareForWeek = 0; uint256 vestingAmount = 0; for (uint256 i = 0; i < notifications.length; i++) { Notification storage notification = notifications[i]; if (notification.notificationType == NotificationType.PROFIT_SHARE) { // profit share profitShareForWeek = total.mul(notification.percentage).div(totalPercentage); } else if (notification.notificationType == NotificationType.TRANSFER) { // simple transfer IERC20(farm).safeTransfer( notification.poolAddress, total.mul(notification.percentage).div(totalPercentage) ); } else { // FARM or iFARM notification WorkingNotification memory toUse = notification.notificationType == NotificationType.FARM ? regular : iFARM; toUse.amounts[toUse.counter] = total.mul(notification.percentage).div(totalPercentage); if (notification.vests) { uint256 toVest = toUse.amounts[toUse.counter].mul(VESTING_NUMERATOR).div(VESTING_DENOMINATOR); toUse.amounts[toUse.counter] = toUse.amounts[toUse.counter].sub(toVest); vestingAmount = vestingAmount.add(toVest); emit Vesting(notification.poolAddress, toVest); } toUse.pools[toUse.counter] = notification.poolAddress; toUse.checksum = toUse.checksum.add(toUse.amounts[toUse.counter]); toUse.counter = toUse.counter.add(1); } } // handle vesting if (vestingAmount > 0) { IERC20(farm).safeTransfer(vestingEscrow, vestingAmount); } // iFARM notifications IERC20(farm).approve(notifyHelperIFARM, iFARM.checksum); INotifyHelperIFARM(notifyHelperIFARM).notifyPools(iFARM.amounts, iFARM.pools, iFARM.checksum); // regular notifications IERC20(farm).approve(notifyHelperRegular, regular.checksum.add(profitShareForWeek)); if (profitShareForWeek > 0) { INotifyHelperRegular(notifyHelperRegular).notifyPoolsIncludingProfitShare( regular.amounts, regular.pools, profitShareForWeek, timestamp, regular.checksum.add(profitShareForWeek) ); } else { INotifyHelperRegular(notifyHelperRegular).notifyPools( regular.amounts, regular.pools, regular.checksum ); } // send rest to the reserve uint256 remainingBalance = IERC20(farm).balanceOf(address(this)); if (remainingBalance > 0) { IERC20(farm).safeTransfer(reserve, remainingBalance); } } /// Returning the governance function transferGovernance(address target, address newStorage) external onlyGovernance { Governable(target).setStorage(newStorage); } /// The governance configures whitelists function setChanger(address who, bool value) external onlyGovernance { changer[who] = value; emit ChangerSet(who, value); } /// The governance configures whitelists function setNotifier(address who, bool value) external onlyGovernance { notifier[who] = value; emit NotifierSet(who, value); } /// Whitelisted entity makes changes to the notifications function setPoolBatch(address[] calldata poolAddress, uint256[] calldata poolPercentage, NotificationType[] calldata notificationType, bool[] calldata vests) external onlyChanger { for (uint256 i = 0; i < poolAddress.length; i++) { setPool(poolAddress[i], poolPercentage[i], notificationType[i], vests[i]); } } /// Pool management, adds, updates or removes a transfer/notification function setPool(address poolAddress, uint256 poolPercentage, NotificationType notificationType, bool vests) public onlyChanger { require(notificationType != NotificationType.VOID, "Use valid indication"); if (notificationExists(poolAddress) && poolPercentage == 0) { // remove removeNotification(poolAddress); } else if (notificationExists(poolAddress)) { // update updateNotification(poolAddress, notificationType, poolPercentage, vests); } else if (poolPercentage > 0) { // add because it does not exist addNotification(poolAddress, poolPercentage, notificationType, vests); } emit PoolChanged(poolAddress, poolPercentage, uint256(notificationType), vests); } /// Configuration method for vesting for governance function setVestingEscrow(address _escrow) external onlyGovernance { vestingEscrow = _escrow; } /// Configuration method for vesting for governance function setVesting(uint256 _numerator, uint256 _denominator) external onlyGovernance { VESTING_DENOMINATOR = _numerator; VESTING_NUMERATOR = _denominator; } function notificationExists(address poolAddress) public view returns(bool) { if (notifications.length == 0) return false; if (poolToIndex[poolAddress] != 0) return true; return (notifications[0].poolAddress == poolAddress); } function removeNotification(address poolAddress) internal { require(notificationExists(poolAddress), "notification does not exist"); uint256 index = poolToIndex[poolAddress]; Notification storage notification = notifications[index]; totalPercentage = totalPercentage.sub(notification.percentage); numbers[uint256(notification.notificationType)] = numbers[uint256(notification.notificationType)].sub(1); // move the last element here and pop from the array notifications[index] = notifications[notifications.length.sub(1)]; poolToIndex[notifications[index].poolAddress] = index; poolToIndex[poolAddress] = 0; notifications.pop(); require(!notificationExists(poolAddress), "notification was not removed"); } function updateNotification(address poolAddress, NotificationType notificationType, uint256 percentage, bool vesting) internal { require(notificationExists(poolAddress), "notification does not exist"); require(percentage > 0, "notification is 0"); uint256 index = poolToIndex[poolAddress]; totalPercentage = totalPercentage.sub(notifications[index].percentage).add(percentage); notifications[index].percentage = percentage; notifications[index].vests = vesting; if (notifications[index].notificationType != notificationType) { numbers[uint256(notifications[index].notificationType)] = numbers[uint256(notifications[index].notificationType)].sub(1); notifications[index].notificationType = notificationType; numbers[uint256(notifications[index].notificationType)] = numbers[uint256(notifications[index].notificationType)].add(1); require(numbers[uint256(NotificationType.PROFIT_SHARE)] <= 1, "At most one profit share"); } } function addNotification(address poolAddress, uint256 percentage, NotificationType notificationType, bool vesting) internal { require(!notificationExists(poolAddress), "notification exists"); require(percentage > 0, "notification is 0"); Notification memory notification = Notification(poolAddress, notificationType, percentage, vesting); notifications.push(notification); totalPercentage = totalPercentage.add(notification.percentage); numbers[uint256(notification.notificationType)] = numbers[uint256(notification.notificationType)].add(1); poolToIndex[notification.poolAddress] = notifications.length.sub(1); require(numbers[uint256(NotificationType.PROFIT_SHARE)] <= 1, "At most one profit share"); require(notificationExists(poolAddress), "notification was not added"); } /// emergency draining of tokens and ETH as there should be none staying here function emergencyDrain(address token, uint256 amount) public onlyGovernance { if (token == address(0)) { msg.sender.transfer(amount); } else { IERC20(token).safeTransfer(msg.sender, amount); } } /// configuration check method function getConfig(uint256 totalAmount) external view returns(address[] memory, uint256[] memory, uint256[] memory) { address[] memory pools = new address[](notifications.length); uint256[] memory percentages = new uint256[](notifications.length); uint256[] memory amounts = new uint256[](notifications.length); for (uint256 i = 0; i < notifications.length; i++) { Notification storage notification = notifications[i]; pools[i] = notification.poolAddress; percentages[i] = notification.percentage.mul(1000000).div(totalPercentage); amounts[i] = notification.percentage.mul(totalAmount).div(totalPercentage); } return (pools, percentages, amounts); } }
emergencyDrain
function emergencyDrain(address token, uint256 amount) public onlyGovernance { if (token == address(0)) { msg.sender.transfer(amount); } else { IERC20(token).safeTransfer(msg.sender, amount); } }
/// emergency draining of tokens and ETH as there should be none staying here
NatSpecSingleLine
v0.5.16+commit.9c3226ce
{ "func_code_index": [ 10272, 10495 ] }
2,665
NotifyHelperStateful
contracts/NotifyHelperStateful.sol
0x71316a3465e0fbcd08e665d6675caa8f7b1dd40a
Solidity
NotifyHelperStateful
contract NotifyHelperStateful is Controllable { using SafeMath for uint256; using SafeERC20 for IERC20; event ChangerSet(address indexed account, bool value); event NotifierSet(address indexed account, bool value); event Vesting(address pool, uint256 amount); event PoolChanged(address indexed pool, uint256 percentage, uint256 notificationType, bool vests); enum NotificationType { VOID, IFARM, FARM, TRANSFER, PROFIT_SHARE } struct Notification { address poolAddress; NotificationType notificationType; uint256 percentage; bool vests; } struct WorkingNotification { address[] pools; uint256[] amounts; uint256 checksum; uint256 counter; } uint256 public VESTING_DENOMINATOR = 3; uint256 public VESTING_NUMERATOR = 2; mapping (address => bool) changer; mapping (address => bool) notifier; address public notifyHelperRegular; address public notifyHelperIFARM; address public farm; Notification[] public notifications; mapping (address => uint256) public poolToIndex; mapping (uint256 => uint256) public numbers; // NotificationType to the number of pools address public reserve; address public vestingEscrow; uint256 public totalPercentage; // maintain state to not have to calculate during emissions modifier onlyChanger { require(changer[msg.sender] || msg.sender == governance(), "Only changer"); _; } modifier onlyNotifier { require(notifier[msg.sender], "Only notifier"); _; } constructor(address _storage, address _notifyHelperRegular, address _farm, address _notifyHelperIFARM, address _escrow, address _reserve) Controllable(_storage) public { // used for getting a reference to FeeRewardForwarder notifyHelperRegular = _notifyHelperRegular; farm = _farm; notifyHelperIFARM = _notifyHelperIFARM; vestingEscrow = _escrow; reserve = _reserve; require(_reserve != address(0), "invalid reserve"); require(_escrow != address(0), "invalid escrow"); } /// Whitelisted entities can notify pools based on the state, both for FARM and iFARM /// The only whitelisted entity here would be the minter helper function notifyPools(uint256 total, uint256 timestamp) public onlyNotifier { // transfer the tokens from the msg.sender to here IERC20(farm).safeTransferFrom(msg.sender, address(this), total); // prepare the notification data WorkingNotification memory iFARM = WorkingNotification( new address[](numbers[uint256(NotificationType.IFARM)]), new uint256[](numbers[uint256(NotificationType.IFARM)]), 0, 0 ); WorkingNotification memory regular = WorkingNotification( new address[](numbers[uint256(NotificationType.FARM)]), new uint256[](numbers[uint256(NotificationType.FARM)]), 0, 0 ); uint256 profitShareForWeek = 0; uint256 vestingAmount = 0; for (uint256 i = 0; i < notifications.length; i++) { Notification storage notification = notifications[i]; if (notification.notificationType == NotificationType.PROFIT_SHARE) { // profit share profitShareForWeek = total.mul(notification.percentage).div(totalPercentage); } else if (notification.notificationType == NotificationType.TRANSFER) { // simple transfer IERC20(farm).safeTransfer( notification.poolAddress, total.mul(notification.percentage).div(totalPercentage) ); } else { // FARM or iFARM notification WorkingNotification memory toUse = notification.notificationType == NotificationType.FARM ? regular : iFARM; toUse.amounts[toUse.counter] = total.mul(notification.percentage).div(totalPercentage); if (notification.vests) { uint256 toVest = toUse.amounts[toUse.counter].mul(VESTING_NUMERATOR).div(VESTING_DENOMINATOR); toUse.amounts[toUse.counter] = toUse.amounts[toUse.counter].sub(toVest); vestingAmount = vestingAmount.add(toVest); emit Vesting(notification.poolAddress, toVest); } toUse.pools[toUse.counter] = notification.poolAddress; toUse.checksum = toUse.checksum.add(toUse.amounts[toUse.counter]); toUse.counter = toUse.counter.add(1); } } // handle vesting if (vestingAmount > 0) { IERC20(farm).safeTransfer(vestingEscrow, vestingAmount); } // iFARM notifications IERC20(farm).approve(notifyHelperIFARM, iFARM.checksum); INotifyHelperIFARM(notifyHelperIFARM).notifyPools(iFARM.amounts, iFARM.pools, iFARM.checksum); // regular notifications IERC20(farm).approve(notifyHelperRegular, regular.checksum.add(profitShareForWeek)); if (profitShareForWeek > 0) { INotifyHelperRegular(notifyHelperRegular).notifyPoolsIncludingProfitShare( regular.amounts, regular.pools, profitShareForWeek, timestamp, regular.checksum.add(profitShareForWeek) ); } else { INotifyHelperRegular(notifyHelperRegular).notifyPools( regular.amounts, regular.pools, regular.checksum ); } // send rest to the reserve uint256 remainingBalance = IERC20(farm).balanceOf(address(this)); if (remainingBalance > 0) { IERC20(farm).safeTransfer(reserve, remainingBalance); } } /// Returning the governance function transferGovernance(address target, address newStorage) external onlyGovernance { Governable(target).setStorage(newStorage); } /// The governance configures whitelists function setChanger(address who, bool value) external onlyGovernance { changer[who] = value; emit ChangerSet(who, value); } /// The governance configures whitelists function setNotifier(address who, bool value) external onlyGovernance { notifier[who] = value; emit NotifierSet(who, value); } /// Whitelisted entity makes changes to the notifications function setPoolBatch(address[] calldata poolAddress, uint256[] calldata poolPercentage, NotificationType[] calldata notificationType, bool[] calldata vests) external onlyChanger { for (uint256 i = 0; i < poolAddress.length; i++) { setPool(poolAddress[i], poolPercentage[i], notificationType[i], vests[i]); } } /// Pool management, adds, updates or removes a transfer/notification function setPool(address poolAddress, uint256 poolPercentage, NotificationType notificationType, bool vests) public onlyChanger { require(notificationType != NotificationType.VOID, "Use valid indication"); if (notificationExists(poolAddress) && poolPercentage == 0) { // remove removeNotification(poolAddress); } else if (notificationExists(poolAddress)) { // update updateNotification(poolAddress, notificationType, poolPercentage, vests); } else if (poolPercentage > 0) { // add because it does not exist addNotification(poolAddress, poolPercentage, notificationType, vests); } emit PoolChanged(poolAddress, poolPercentage, uint256(notificationType), vests); } /// Configuration method for vesting for governance function setVestingEscrow(address _escrow) external onlyGovernance { vestingEscrow = _escrow; } /// Configuration method for vesting for governance function setVesting(uint256 _numerator, uint256 _denominator) external onlyGovernance { VESTING_DENOMINATOR = _numerator; VESTING_NUMERATOR = _denominator; } function notificationExists(address poolAddress) public view returns(bool) { if (notifications.length == 0) return false; if (poolToIndex[poolAddress] != 0) return true; return (notifications[0].poolAddress == poolAddress); } function removeNotification(address poolAddress) internal { require(notificationExists(poolAddress), "notification does not exist"); uint256 index = poolToIndex[poolAddress]; Notification storage notification = notifications[index]; totalPercentage = totalPercentage.sub(notification.percentage); numbers[uint256(notification.notificationType)] = numbers[uint256(notification.notificationType)].sub(1); // move the last element here and pop from the array notifications[index] = notifications[notifications.length.sub(1)]; poolToIndex[notifications[index].poolAddress] = index; poolToIndex[poolAddress] = 0; notifications.pop(); require(!notificationExists(poolAddress), "notification was not removed"); } function updateNotification(address poolAddress, NotificationType notificationType, uint256 percentage, bool vesting) internal { require(notificationExists(poolAddress), "notification does not exist"); require(percentage > 0, "notification is 0"); uint256 index = poolToIndex[poolAddress]; totalPercentage = totalPercentage.sub(notifications[index].percentage).add(percentage); notifications[index].percentage = percentage; notifications[index].vests = vesting; if (notifications[index].notificationType != notificationType) { numbers[uint256(notifications[index].notificationType)] = numbers[uint256(notifications[index].notificationType)].sub(1); notifications[index].notificationType = notificationType; numbers[uint256(notifications[index].notificationType)] = numbers[uint256(notifications[index].notificationType)].add(1); require(numbers[uint256(NotificationType.PROFIT_SHARE)] <= 1, "At most one profit share"); } } function addNotification(address poolAddress, uint256 percentage, NotificationType notificationType, bool vesting) internal { require(!notificationExists(poolAddress), "notification exists"); require(percentage > 0, "notification is 0"); Notification memory notification = Notification(poolAddress, notificationType, percentage, vesting); notifications.push(notification); totalPercentage = totalPercentage.add(notification.percentage); numbers[uint256(notification.notificationType)] = numbers[uint256(notification.notificationType)].add(1); poolToIndex[notification.poolAddress] = notifications.length.sub(1); require(numbers[uint256(NotificationType.PROFIT_SHARE)] <= 1, "At most one profit share"); require(notificationExists(poolAddress), "notification was not added"); } /// emergency draining of tokens and ETH as there should be none staying here function emergencyDrain(address token, uint256 amount) public onlyGovernance { if (token == address(0)) { msg.sender.transfer(amount); } else { IERC20(token).safeTransfer(msg.sender, amount); } } /// configuration check method function getConfig(uint256 totalAmount) external view returns(address[] memory, uint256[] memory, uint256[] memory) { address[] memory pools = new address[](notifications.length); uint256[] memory percentages = new uint256[](notifications.length); uint256[] memory amounts = new uint256[](notifications.length); for (uint256 i = 0; i < notifications.length; i++) { Notification storage notification = notifications[i]; pools[i] = notification.poolAddress; percentages[i] = notification.percentage.mul(1000000).div(totalPercentage); amounts[i] = notification.percentage.mul(totalAmount).div(totalPercentage); } return (pools, percentages, amounts); } }
getConfig
function getConfig(uint256 totalAmount) external view returns(address[] memory, uint256[] memory, uint256[] memory) { address[] memory pools = new address[](notifications.length); uint256[] memory percentages = new uint256[](notifications.length); uint256[] memory amounts = new uint256[](notifications.length); for (uint256 i = 0; i < notifications.length; i++) { Notification storage notification = notifications[i]; pools[i] = notification.poolAddress; percentages[i] = notification.percentage.mul(1000000).div(totalPercentage); amounts[i] = notification.percentage.mul(totalAmount).div(totalPercentage); } return (pools, percentages, amounts); }
/// configuration check method
NatSpecSingleLine
v0.5.16+commit.9c3226ce
{ "func_code_index": [ 10530, 11231 ] }
2,666
USDSat
USDSat.sol
0xbeda58401038c864c9fc9145f28e47b7b00a0e86
Solidity
USDSat
contract USDSat is USDSatMetadata, ERC721, ERC721Enumerable, Ownable, ReentrancyGuard { string SYMBOL = "USDSat"; string NAME = "Dollars Nakamoto"; string ContractCID; /// @notice Address used to sign NFT on mint address public ADDRESS_SIGN = 0x1Af70e564847bE46e4bA286c0b0066Da8372F902; /// @notice Ether shareholder address address public ADDRESS_PBOY = 0x709e17B3Ec505F80eAb064d0F2A71c743cE225B3; /// @notice Ether shareholder address address public ADDRESS_JOLAN = 0x51BdFa2Cbb25591AF58b202aCdcdB33325a325c2; /// @notice Equity per shareholder in % uint256 public SHARE_PBOY = 90; /// @notice Equity per shareholder in % uint256 public SHARE_JOLAN = 10; /// @notice Mapping used to represent allowed addresses to call { mintGenesis } mapping (address => bool) public _allowList; /// @notice Represent the current epoch uint256 public epoch = 0; /// @notice Represent the maximum epoch possible uint256 public epochMax = 10; /// @notice Represent the block length of an epoch uint256 public epochLen = 41016; /// @notice Index of the NFT /// @dev Start at 1 because var++ uint256 public tokenId = 1; /// @notice Index of the Genesis NFT /// @dev Start at 0 because ++var uint256 public genesisId = 0; /// @notice Index of the Generation NFT /// @dev Start at 0 because ++var uint256 public generationId = 0; /// @notice Maximum total supply uint256 public maxTokenSupply = 2100; /// @notice Maximum Genesis supply uint256 public maxGenesisSupply = 210; /// @notice Maximum supply per generation uint256 public maxGenerationSupply = 210; /// @notice Price of the Genesis NFT (Generations NFT are free) uint256 public genesisPrice = 0.5 ether; /// @notice Define the ending block uint256 public blockOmega; /// @notice Define the starting block uint256 public blockGenesis; /// @notice Define in which block the Meta must occur uint256 public blockMeta; /// @notice Used to inflate blockMeta each epoch incrementation uint256 public inflateRatio = 2; /// @notice Open Genesis mint when true bool public genesisMintAllowed = false; /// @notice Open Generation mint when true bool public generationMintAllowed = false; /// @notice Multi dimensionnal mapping to keep a track of the minting reentrancy over epoch mapping(uint256 => mapping(uint256 => bool)) public epochMintingRegistry; event Omega(uint256 _blockNumber); event Genesis(uint256 indexed _epoch, uint256 _blockNumber); event Meta(uint256 indexed _epoch, uint256 _blockNumber); event Withdraw(uint256 indexed _share, address _shareholder); event Shareholder(uint256 indexed _sharePercent, address _shareholder); event Securized(uint256 indexed _epoch, uint256 _epochLen, uint256 _blockMeta, uint256 _inflateRatio); event PermanentURI(string _value, uint256 indexed _id); event Minted(uint256 indexed _epoch, uint256 indexed _tokenId, address indexed _owner); event Signed(uint256 indexed _epoch, uint256 indexed _tokenId, uint256 indexed _blockNumber); constructor() ERC721(NAME, SYMBOL) {} // Withdraw functions ************************************************* /// @notice Allow Pboy to modify ADDRESS_PBOY /// This function is dedicated to the represented shareholder according to require(). function setPboy(address PBOY) public { require(msg.sender == ADDRESS_PBOY, "error msg.sender"); ADDRESS_PBOY = PBOY; emit Shareholder(SHARE_PBOY, ADDRESS_PBOY); } /// @notice Allow Jolan to modify ADDRESS_JOLAN /// This function is dedicated to the represented shareholder according to require(). function setJolan(address JOLAN) public { require(msg.sender == ADDRESS_JOLAN, "error msg.sender"); ADDRESS_JOLAN = JOLAN; emit Shareholder(SHARE_JOLAN, ADDRESS_JOLAN); } /// @notice Used to withdraw ETH balance of the contract, this function is dedicated /// to contract owner according to { onlyOwner } modifier. function withdrawEquity() public onlyOwner nonReentrant { uint256 balance = address(this).balance; address[2] memory shareholders = [ ADDRESS_PBOY, ADDRESS_JOLAN ]; uint256[2] memory _shares = [ SHARE_PBOY * balance / 100, SHARE_JOLAN * balance / 100 ]; uint i = 0; while (i < 2) { require(payable(shareholders[i]).send(_shares[i])); emit Withdraw(_shares[i], shareholders[i]); i++; } } // Epoch functions **************************************************** /// @notice Used to manage authorization and reentrancy of the genesis NFT mint /// @param _genesisId Used to increment { genesisId } and write { epochMintingRegistry } function genesisController(uint256 _genesisId) private { require(epoch == 0, "error epoch"); require(genesisId <= maxGenesisSupply, "error genesisId"); require(!epochMintingRegistry[epoch][_genesisId], "error epochMintingRegistry"); /// @dev Set { _genesisId } for { epoch } as true epochMintingRegistry[epoch][_genesisId] = true; /// @dev When { genesisId } reaches { maxGenesisSupply } the function /// will compute the data to increment the epoch according /// /// { blockGenesis } is set only once, at this time /// { blockMeta } is set to { blockGenesis } because epoch=0 /// Then it is computed into the function epochRegulator() /// /// Once the epoch is regulated, the new generation start /// straight away, { generationMintAllowed } is set to true if (genesisId == maxGenesisSupply) { blockGenesis = block.number; blockMeta = blockGenesis; emit Genesis(epoch, blockGenesis); epochRegulator(); } } /// @notice Used to manage authorization and reentrancy of the Generation NFT mint /// @param _genesisId Used to write { epochMintingRegistry } and verify minting allowance function generationController(uint256 _genesisId) private { require(blockGenesis > 0, "error blockGenesis"); require(blockMeta > 0, "error blockMeta"); require(blockOmega > 0, "error blockOmega"); /// @dev If { block.number } >= { blockMeta } the function /// will compute the data to increment the epoch according /// /// Once the epoch is regulated, the new generation start /// straight away, { generationMintAllowed } is set to true /// /// { generationId } is reset to 1 if (block.number >= blockMeta) { epochRegulator(); generationId = 1; } /// @dev Be sure the mint is open if condition are favorable if (block.number < blockMeta && generationId <= maxGenerationSupply) { generationMintAllowed = true; } require(maxTokenSupply >= tokenId, "error maxTokenSupply"); require(epoch > 0 && epoch < epochMax, "error epoch"); require(ownerOf(_genesisId) == msg.sender, "error ownerOf"); require(generationMintAllowed, "error generationMintAllowed"); require(generationId <= maxGenerationSupply, "error generationId"); require(epochMintingRegistry[0][_genesisId], "error epochMintingRegistry"); require(!epochMintingRegistry[epoch][_genesisId], "error epochMintingRegistry"); /// @dev Set { _genesisId } for { epoch } as true epochMintingRegistry[epoch][_genesisId] = true; /// @dev If { generationId } reaches { maxGenerationSupply } the modifier /// will set { generationMintAllowed } to false to stop the mint /// on this generation /// /// { generationId } is reset to 0 /// /// This condition will not block the function because as long as /// { block.number } >= { blockMeta } minting will reopen /// according and this condition will become obsolete until /// the condition is reached again if (generationId == maxGenerationSupply) { generationMintAllowed = false; generationId = 0; } } /// @notice Used to protect epoch block length from difficulty bomb of the /// Ethereum network. A difficulty bomb heavily increases the difficulty /// on the network, likely also causing an increase in block time. /// If the block time increases too much, the epoch generation could become /// exponentially higher than what is desired, ending with an undesired Ice-Age. /// To protect against this, the emergencySecure() function is allowed to /// manually reconfigure the epoch block length and the block Meta /// to match the network conditions if necessary. /// /// It can also be useful if the block time decreases for some reason with consensus change. /// /// This function is dedicated to contract owner according to { onlyOwner } modifier function emergencySecure(uint256 _epoch, uint256 _epochLen, uint256 _blockMeta, uint256 _inflateRatio) public onlyOwner { require(epoch > 0, "error epoch"); require(_epoch > 0, "error _epoch"); require(maxTokenSupply >= tokenId, "error maxTokenSupply"); epoch = _epoch; epochLen = _epochLen; blockMeta = _blockMeta; inflateRatio = _inflateRatio; computeBlockOmega(); emit Securized(epoch, epochLen, blockMeta, inflateRatio); } /// @notice Used to compute blockOmega() function, { blockOmega } represents /// the block when it won't ever be possible to mint another Dollars Nakamoto NFT. /// It is possible to be computed because of the deterministic state of the current protocol /// The following algorithm simulate the 10 epochs of the protocol block computation to result blockOmega function computeBlockOmega() private { uint256 i = 0; uint256 _blockMeta = 0; uint256 _epochLen = epochLen; while (i < epochMax) { if (i > 0) _epochLen *= inflateRatio; if (i == 9) { blockOmega = blockGenesis + _blockMeta; emit Omega(blockOmega); break; } _blockMeta += _epochLen; i++; } } /// @notice Used to regulate the epoch incrementation and block computation, known as Metas /// @dev When epoch=0, the { blockOmega } will be computed /// When epoch!=0 the block length { epochLen } will be multiplied /// by { inflateRatio } thus making the block length required for each /// epoch longer according /// /// { blockMeta } += { epochLen } result the exact block of the next Meta /// Allow generation mint after incrementing the epoch function epochRegulator() private { if (epoch == 0) computeBlockOmega(); if (epoch > 0) epochLen *= inflateRatio; blockMeta += epochLen; emit Meta(epoch, blockMeta); epoch++; if (block.number >= blockMeta && epoch < epochMax) { epochRegulator(); } generationMintAllowed = true; } // Mint functions ***************************************************** /// @notice Used to add/remove address from { _allowList } function setBatchGenesisAllowance(address[] memory batch) public onlyOwner { uint len = batch.length; require(len > 0, "error len"); uint i = 0; while (i < len) { _allowList[batch[i]] = _allowList[batch[i]] ? false : true; i++; } } /// @notice Used to transfer { _allowList } slot to another address function transferListSlot(address to) public { require(epoch == 0, "error epoch"); require(_allowList[msg.sender], "error msg.sender"); require(!_allowList[to], "error to"); _allowList[msg.sender] = false; _allowList[to] = true; } /// @notice Used to open the mint of Genesis NFT function setGenesisMint() public onlyOwner { genesisMintAllowed = true; } /// @notice Used to gift Genesis NFT, this function is dedicated /// to contract owner according to { onlyOwner } modifier function giftGenesis(address to) public onlyOwner { uint256 _genesisId = ++genesisId; setMetadata(tokenId, _genesisId, epoch); genesisController(_genesisId); mintUSDSat(to, tokenId++); } /// @notice Used to mint Genesis NFT, this function is payable /// the price of this function is equal to { genesisPrice }, /// require to be present on { _allowList } to call function mintGenesis() public payable { uint256 _genesisId = ++genesisId; setMetadata(tokenId, _genesisId, epoch); genesisController(_genesisId); require(genesisMintAllowed, "error genesisMintAllowed"); require(_allowList[msg.sender], "error allowList"); require(genesisPrice == msg.value, "error genesisPrice"); _allowList[msg.sender] = false; mintUSDSat(msg.sender, tokenId++); } /// @notice Used to gift Generation NFT, you need a Genesis NFT to call this function function giftGenerations(uint256 _genesisId, address to) public { ++generationId; generationController(_genesisId); setMetadata(tokenId, _genesisId, epoch); mintUSDSat(to, tokenId++); } /// @notice Used to mint Generation NFT, you need a Genesis NFT to call this function function mintGenerations(uint256 _genesisId) public { ++generationId; generationController(_genesisId); setMetadata(tokenId, _genesisId, epoch); mintUSDSat(msg.sender, tokenId++); } /// @notice Token is minted on { ADDRESS_SIGN } and instantly transferred to { msg.sender } as { to }, /// this is to ensure the token creation is signed with { ADDRESS_SIGN } /// This function is private and can be only called by the contract function mintUSDSat(address to, uint256 _tokenId) private { emit PermanentURI(_compileMetadata(_tokenId), _tokenId); _safeMint(ADDRESS_SIGN, _tokenId); emit Signed(epoch, _tokenId, block.number); _safeTransfer(ADDRESS_SIGN, to, _tokenId, ""); emit Minted(epoch, _tokenId, to); } // Contract URI functions ********************************************* /// @notice Used to set the { ContractCID } metadata from ipfs, /// this function is dedicated to contract owner according /// to { onlyOwner } modifier function setContractCID(string memory CID) public onlyOwner { ContractCID = string(abi.encodePacked("ipfs://", CID)); } /// @notice Used to render { ContractCID } as { contractURI } according to /// Opensea contract metadata standard function contractURI() public view virtual returns (string memory) { return ContractCID; } // Utilitaries functions ********************************************** /// @notice Used to fetch all entry for { epoch } into { epochMintingRegistry } function getMapRegisteryForEpoch(uint256 _epoch) public view returns (bool[210] memory result) { uint i = 1; while (i <= maxGenesisSupply) { result[i] = epochMintingRegistry[_epoch][i]; i++; } } /// @notice Used to fetch all { tokenIds } from { owner } function exposeHeldIds(address owner) public view returns(uint[] memory) { uint tokenCount = balanceOf(owner); uint[] memory tokenIds = new uint[](tokenCount); uint i = 0; while (i < tokenCount) { tokenIds[i] = tokenOfOwnerByIndex(owner, i); i++; } return tokenIds; } // ERC721 Spec functions ********************************************** /// @notice Used to render metadata as { tokenURI } according to ERC721 standard function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token"); return _compileMetadata(_tokenId); } /// @dev ERC721 required override function _beforeTokenTransfer(address from, address to, uint256 _tokenId) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, _tokenId); } /// @dev ERC721 required override function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } }
/// ``.. /// `.` `````.``.-````-`` `.` /// ` ``````.`..///.-..----. --..--`.-....`..-.```` ``` /// `` `.`..--...`:::/::-``..``..:-.://///---..-....----- /// ``-:::/+++:::/-.-///://oso+::++/--:--../+:/:..:-....-://:/:-`` /// `-+/++/+o+://+::-:soo+oosss+s+//o:/:--`--:://://:ooso/-.--.-:-.` /// ``.+ooso++o+:+:+sosyhsyshhddyo+:/sds/yoo++/+:--/--.--:..--..``.```` /// ``:++/---:+/::::///oyhhyy+++:hddhhNNho///ohosyhs+/-:/+/---.....-.. ` /// ``-:-...-/+///++///+o+:-:o+o/oydmNmNNdddhsoyo/oyyyho///:-.--.-.``. `` /// ```--`..-:+/:--:::-.-///++++ydsdNNMNdmMNMmNysddyoooosso+//-.-`....````` ..` /// .```:-:::/-.-+o++/+:/+/o/hNNNNhmdNMMNNMMdyydNNmdyys+++oo++-`--.:.-.`````... /// ..--.`-..`.-`-hh++-/:+shho+hsysyyhhhmNNmmNMMmNNNdmmy+:+sh/o+y/+-`+./::.```` ` /// -/` ``.-``.//o++y+//ssyh+hhdmmdmmddmhdmNdmdsh+oNNMmmddoodh/s:yss.--+.//+`.` `. /// `.`-.` -`..+h+yo++ooyyyyyoyhy+shmNNmmdhhdhyyhymdyyhdmshoohs+y:oy+/+o/:/++.`- .` /// ``.`.``-.-++syyyhhhhhhhhmhysosyyoooosssdhhhdmmdhdmdsy+ss+/+ho/hody-s+-:+::--`` ` /// .`` ``-//s+:ohmdmddNmNmhhshhddNNNhyyhhhdNNhmNNmNNmmyso+yhhso++hhdy.:/ ::-:--``.` /// .```.-`.//shdmNNmddyysohmMmdmNNmmNshdmNhso+-/ohNoyhmmsysosd++hy/osss/.:-o/-.:/--. /// ``..:++-+hhy/syhhhdhdNNddNMmNsNMNyyso+//:-.`-/..+hmdsmdy+ossos:+o/h/+..//-s.`.:::o/ /// `.-.oy//hm+o:-..-+/shdNNNNNNhsNdo/oyoyyhoh+/so//+/mNmyhh+/s+dy/+s::+:`-`-:s--:-.::+`-` /// .`:h-`+y+./oyhhdddhyohMMNmmNmdhoo/oyyhddhmNNNmhsoodmdhs+///++:+-:.:/--/-/o/--+//...:` /// ``+o``yoodNNNNNMhdyyo+ymhsymyshhyys+sssssNmdmmdmy+oso/++:://+/-`::-:--:/::+.//o:-.--: /// `:-:-`oNhyhdNNNmyys+/:://oohy++/+hmmmmNNNNhohydmmyhy++////ooy./----.-:---/::-o+:...-/ /// ``-.-` yms+mmNmMMmNho/:o++++hhh++:mMmNmmmNMNdhdms+ysyy//:-+o:.-.`.``.-:/::-:-+/y/.- -` /// ..:` hh+oNNmMNNNmss/:-+oyhs+o+.-yhdNmdhmmydmms+o///:///+/+--/`-``.o::/:-o//-/y::/.- /// `.-``hh+yNdmdohdy:++/./myhds/./shNhhyy++o:oyos/s+:s//+////.:- ...`--`..`-.:--o:+::` /// `-/+yyho.`.-+oso///+/Nmddh//y+:s:.../soy+:o+.:sdyo++++o:.-. `.:.:-```:.`:``/o:`:` /// ./.`..sMN+:::yh+s+ysyhhddh+ymdsd/:/+o+ysydhohoh/o+/so++o+/o.--..`-:::``:-`+-`:+--.` /// ``:``..-NNy++/yyysohmo+NNmy/+:+hMNmy+yydmNMNddhs:yyydmmmso:o///..-.-+-:o:/.o/-/+-`` /// ``+.`..-mMhsyo+++oo+yoshyyo+/`+hNmhyy+sdmdssssho-MMMNMNh//+/oo+/+:-....`.s+/`..-` /// .+ `oNMmdhhsohhmmydmNms/yy.oNmmdy+++/+ss+odNm+mNmdddo-s+:+/++/-:--//`/o+s/.-`` /// `/` dNNNhooddNmNymMNNdsoo+y+shhhmyymhss+hddms+hdhmdo+/+-/oo+/.///+sh:-/-s/` /// `::`hdNmh+ooNmdohNNMMmsooohh+oysydhdooo/syysodmNmys+/o+//+y/:.+/hmso.-//s- /// -+ohdmmhyhdysysyyhmysoyddhhoo+shdhdyddmddmNmmhssds/::/oo/..:/+Nmo+`-:so /// .oyhdmmNNdm+s:/:os/+/ssyyds+/ssdNNyhdmmhdmmdymymy///o:/``/+-dmdoo++:o` /// `ysyMNhhmoo+h-:/+o/+:.:/:/+doo+dNdhddmhmmmy++yhds/+-+::..o/+Nmosyhs+- /// s+dNNyNhsdhNhsy:+:oo/soo+dNmmooyosohMhsymmhyy+++:+:/+/-/o+yNh+hMNs. /// +yhNNMd+dmydmdy/+/sshydmhdNNmNooyhhhhshohmNh+:+oso++ssy+/odyhhNmh` /// `yyhdms+dMh+oyshhyhysdmNd+ohyNN+++mNddmNy+yo//+o/hddddymmyhosNmms` /// oydos:oMmhoyyhysssysdmMmNmhNmNNh/+mmNmddh+/+o+::+s+hmhmdyNNNNy: /// `/dNm/+Ndhy+oshdhhdyo::ohmdyhhNysy:smshmdo/o:so//:s++ymhyohdy-` /// `sNNN/hNm/:do+o:+/++++s:/+shyymmddy/ydmmh/s/+oss//oysy++o+o+` /// oNNMNmm:/hyy/:/o/+hhsosysoo-ohhhss/hmmhd/dyh++/soyooy++o+:. /// :/dMNh/smhh+//+s+--:+/so+ohhy/:sydmmmmm+/mdddhy++/ohs//-o/` /// `/odmhyhsyh++/-:+:::/:/o/:ooddy/+yodNNh+ydhmmmy++/hhyo+://` /// `:os/+o//oshss/yhs+//:+/-/:soooo/+sso+dddydss+:+sy///+:++ /// ./o/s//hhNho+shyyyoyyso+/ys+/+-:y+:/soooyyh++sNyo++/:/+ /// -/:osmmhyo:++++/+/osshdssooo/:/h//://++oyhsshmdo+//s/- /// .osmhydh::/+++/o+ohhysddyoo++os+-+++///yhhhmNs+o/:// /// -.++yss//////+/+/+soo++shyhsyy+::/:+y+yhdmdoo//:/:- /// ``.oss/:////++://+o//:://+oo-:o++/shhhmmh+o+++///-` /// ..:+++oo/+///ys:///://+::-sy+osh+osdyo+o/::/s:/y-` /// `odoyhds+/yysyydss+///+/:+oshdmNo+:+/oo/+++++:hy//` /// `://hyoyy/o/++shhy:+y:/:o/+omNmhsoohhsso+++:+o+sy:/++ /// -/---oddooss+oosy+ohNdo+++oyNhsdo/++shhhoo:s+oydmyo//o+ /// :y.`.``yyd++shoyydhhyymdhyyhyhhs+////+/+s/+:odmmyso.:ohy. /// .yy/o-..+h/+o/+//++ssoohhhssso+++:/:/yy+//sydmNddo+/./ohy+. /// .dmmhs+osdoos///o//++/+shdsoshoys+ssss++shmNNNyyds+:-s-//:+. /// -shmNmyhddsyss++/+ysddhyyydhdmyssNddyydyhNmdNmddso/::s:--`.-.` /// `+dmNhhdmddsooyyooossysshdhmoss+/+mNdyymydMdyMdyoo+/--/:/:`...-.` /// .:smNNMmsMNNmdhyyo/yymmdmdyo+ooooshysyysNNNmmmNyss/+o-`-:-/:```.`` ``` /// `.-+o/sdNNNmhdddNmmdsso/sdshyyyyhsdddyohymdmNdmmmmmyoo+/.... -os.`.``-.`` /// `/-:-/+.hymmmmdhmyNdMNmmhhs+sosoyhddyddmmho/ooymhddhdhyos-.oy..-:o+:..`` ```` ` /// ..::``--.-hoymmdNNNNNNMmhyNh+oo+soyNdmNmmmysooooymhy+so++yo..:+.--`..:.`.` `-- ``.` ` /// ```-.-.``..`:ddymmmNNdmNNNNmhN: -/oys/sdmmNdydsydmhhsmdso+/yo:/-..`.``.` ``:.`.````-. ` /// ````-:/.```:::syyydmddNhNNdsdMMs`./oddmd./odNdy+yssss++ooo/o+//-`:/:..:`-.```/-:.`.```..`` ` /// ```..-`` --.`.--o+sNhoyMmho+omhmo+Ns::dhdmmdy:.oNoyhhs+/o+o++s+hhoo+.`-:....``.-:-`..-````.-``.`` /// @title Dollars Nakamoto by Pascal Boyart /// @author jolan.eth /// @notice This contract will allow you to yield farm Dollars Nakamoto NFT. /// During epoch 0 you will be able to mint a Genesis NFT, /// Over time, epoch will increment allowing you to mint more editions. /// Minting generations editions is allowed only 1 time per epoch and per Genesis NFT. /// Generations editions do not allow you to mint other generations.
NatSpecSingleLine
setPboy
function setPboy(address PBOY) public { require(msg.sender == ADDRESS_PBOY, "error msg.sender"); ADDRESS_PBOY = PBOY; emit Shareholder(SHARE_PBOY, ADDRESS_PBOY); }
/// @notice Allow Pboy to modify ADDRESS_PBOY /// This function is dedicated to the represented shareholder according to require().
NatSpecSingleLine
v0.8.10+commit.fc410830
MIT
ipfs://627efb7c58e0f1a820013031c32ab417b2b86eb0e16948f99bf7e29ad6e50407
{ "func_code_index": [ 3575, 3780 ] }
2,667
USDSat
USDSat.sol
0xbeda58401038c864c9fc9145f28e47b7b00a0e86
Solidity
USDSat
contract USDSat is USDSatMetadata, ERC721, ERC721Enumerable, Ownable, ReentrancyGuard { string SYMBOL = "USDSat"; string NAME = "Dollars Nakamoto"; string ContractCID; /// @notice Address used to sign NFT on mint address public ADDRESS_SIGN = 0x1Af70e564847bE46e4bA286c0b0066Da8372F902; /// @notice Ether shareholder address address public ADDRESS_PBOY = 0x709e17B3Ec505F80eAb064d0F2A71c743cE225B3; /// @notice Ether shareholder address address public ADDRESS_JOLAN = 0x51BdFa2Cbb25591AF58b202aCdcdB33325a325c2; /// @notice Equity per shareholder in % uint256 public SHARE_PBOY = 90; /// @notice Equity per shareholder in % uint256 public SHARE_JOLAN = 10; /// @notice Mapping used to represent allowed addresses to call { mintGenesis } mapping (address => bool) public _allowList; /// @notice Represent the current epoch uint256 public epoch = 0; /// @notice Represent the maximum epoch possible uint256 public epochMax = 10; /// @notice Represent the block length of an epoch uint256 public epochLen = 41016; /// @notice Index of the NFT /// @dev Start at 1 because var++ uint256 public tokenId = 1; /// @notice Index of the Genesis NFT /// @dev Start at 0 because ++var uint256 public genesisId = 0; /// @notice Index of the Generation NFT /// @dev Start at 0 because ++var uint256 public generationId = 0; /// @notice Maximum total supply uint256 public maxTokenSupply = 2100; /// @notice Maximum Genesis supply uint256 public maxGenesisSupply = 210; /// @notice Maximum supply per generation uint256 public maxGenerationSupply = 210; /// @notice Price of the Genesis NFT (Generations NFT are free) uint256 public genesisPrice = 0.5 ether; /// @notice Define the ending block uint256 public blockOmega; /// @notice Define the starting block uint256 public blockGenesis; /// @notice Define in which block the Meta must occur uint256 public blockMeta; /// @notice Used to inflate blockMeta each epoch incrementation uint256 public inflateRatio = 2; /// @notice Open Genesis mint when true bool public genesisMintAllowed = false; /// @notice Open Generation mint when true bool public generationMintAllowed = false; /// @notice Multi dimensionnal mapping to keep a track of the minting reentrancy over epoch mapping(uint256 => mapping(uint256 => bool)) public epochMintingRegistry; event Omega(uint256 _blockNumber); event Genesis(uint256 indexed _epoch, uint256 _blockNumber); event Meta(uint256 indexed _epoch, uint256 _blockNumber); event Withdraw(uint256 indexed _share, address _shareholder); event Shareholder(uint256 indexed _sharePercent, address _shareholder); event Securized(uint256 indexed _epoch, uint256 _epochLen, uint256 _blockMeta, uint256 _inflateRatio); event PermanentURI(string _value, uint256 indexed _id); event Minted(uint256 indexed _epoch, uint256 indexed _tokenId, address indexed _owner); event Signed(uint256 indexed _epoch, uint256 indexed _tokenId, uint256 indexed _blockNumber); constructor() ERC721(NAME, SYMBOL) {} // Withdraw functions ************************************************* /// @notice Allow Pboy to modify ADDRESS_PBOY /// This function is dedicated to the represented shareholder according to require(). function setPboy(address PBOY) public { require(msg.sender == ADDRESS_PBOY, "error msg.sender"); ADDRESS_PBOY = PBOY; emit Shareholder(SHARE_PBOY, ADDRESS_PBOY); } /// @notice Allow Jolan to modify ADDRESS_JOLAN /// This function is dedicated to the represented shareholder according to require(). function setJolan(address JOLAN) public { require(msg.sender == ADDRESS_JOLAN, "error msg.sender"); ADDRESS_JOLAN = JOLAN; emit Shareholder(SHARE_JOLAN, ADDRESS_JOLAN); } /// @notice Used to withdraw ETH balance of the contract, this function is dedicated /// to contract owner according to { onlyOwner } modifier. function withdrawEquity() public onlyOwner nonReentrant { uint256 balance = address(this).balance; address[2] memory shareholders = [ ADDRESS_PBOY, ADDRESS_JOLAN ]; uint256[2] memory _shares = [ SHARE_PBOY * balance / 100, SHARE_JOLAN * balance / 100 ]; uint i = 0; while (i < 2) { require(payable(shareholders[i]).send(_shares[i])); emit Withdraw(_shares[i], shareholders[i]); i++; } } // Epoch functions **************************************************** /// @notice Used to manage authorization and reentrancy of the genesis NFT mint /// @param _genesisId Used to increment { genesisId } and write { epochMintingRegistry } function genesisController(uint256 _genesisId) private { require(epoch == 0, "error epoch"); require(genesisId <= maxGenesisSupply, "error genesisId"); require(!epochMintingRegistry[epoch][_genesisId], "error epochMintingRegistry"); /// @dev Set { _genesisId } for { epoch } as true epochMintingRegistry[epoch][_genesisId] = true; /// @dev When { genesisId } reaches { maxGenesisSupply } the function /// will compute the data to increment the epoch according /// /// { blockGenesis } is set only once, at this time /// { blockMeta } is set to { blockGenesis } because epoch=0 /// Then it is computed into the function epochRegulator() /// /// Once the epoch is regulated, the new generation start /// straight away, { generationMintAllowed } is set to true if (genesisId == maxGenesisSupply) { blockGenesis = block.number; blockMeta = blockGenesis; emit Genesis(epoch, blockGenesis); epochRegulator(); } } /// @notice Used to manage authorization and reentrancy of the Generation NFT mint /// @param _genesisId Used to write { epochMintingRegistry } and verify minting allowance function generationController(uint256 _genesisId) private { require(blockGenesis > 0, "error blockGenesis"); require(blockMeta > 0, "error blockMeta"); require(blockOmega > 0, "error blockOmega"); /// @dev If { block.number } >= { blockMeta } the function /// will compute the data to increment the epoch according /// /// Once the epoch is regulated, the new generation start /// straight away, { generationMintAllowed } is set to true /// /// { generationId } is reset to 1 if (block.number >= blockMeta) { epochRegulator(); generationId = 1; } /// @dev Be sure the mint is open if condition are favorable if (block.number < blockMeta && generationId <= maxGenerationSupply) { generationMintAllowed = true; } require(maxTokenSupply >= tokenId, "error maxTokenSupply"); require(epoch > 0 && epoch < epochMax, "error epoch"); require(ownerOf(_genesisId) == msg.sender, "error ownerOf"); require(generationMintAllowed, "error generationMintAllowed"); require(generationId <= maxGenerationSupply, "error generationId"); require(epochMintingRegistry[0][_genesisId], "error epochMintingRegistry"); require(!epochMintingRegistry[epoch][_genesisId], "error epochMintingRegistry"); /// @dev Set { _genesisId } for { epoch } as true epochMintingRegistry[epoch][_genesisId] = true; /// @dev If { generationId } reaches { maxGenerationSupply } the modifier /// will set { generationMintAllowed } to false to stop the mint /// on this generation /// /// { generationId } is reset to 0 /// /// This condition will not block the function because as long as /// { block.number } >= { blockMeta } minting will reopen /// according and this condition will become obsolete until /// the condition is reached again if (generationId == maxGenerationSupply) { generationMintAllowed = false; generationId = 0; } } /// @notice Used to protect epoch block length from difficulty bomb of the /// Ethereum network. A difficulty bomb heavily increases the difficulty /// on the network, likely also causing an increase in block time. /// If the block time increases too much, the epoch generation could become /// exponentially higher than what is desired, ending with an undesired Ice-Age. /// To protect against this, the emergencySecure() function is allowed to /// manually reconfigure the epoch block length and the block Meta /// to match the network conditions if necessary. /// /// It can also be useful if the block time decreases for some reason with consensus change. /// /// This function is dedicated to contract owner according to { onlyOwner } modifier function emergencySecure(uint256 _epoch, uint256 _epochLen, uint256 _blockMeta, uint256 _inflateRatio) public onlyOwner { require(epoch > 0, "error epoch"); require(_epoch > 0, "error _epoch"); require(maxTokenSupply >= tokenId, "error maxTokenSupply"); epoch = _epoch; epochLen = _epochLen; blockMeta = _blockMeta; inflateRatio = _inflateRatio; computeBlockOmega(); emit Securized(epoch, epochLen, blockMeta, inflateRatio); } /// @notice Used to compute blockOmega() function, { blockOmega } represents /// the block when it won't ever be possible to mint another Dollars Nakamoto NFT. /// It is possible to be computed because of the deterministic state of the current protocol /// The following algorithm simulate the 10 epochs of the protocol block computation to result blockOmega function computeBlockOmega() private { uint256 i = 0; uint256 _blockMeta = 0; uint256 _epochLen = epochLen; while (i < epochMax) { if (i > 0) _epochLen *= inflateRatio; if (i == 9) { blockOmega = blockGenesis + _blockMeta; emit Omega(blockOmega); break; } _blockMeta += _epochLen; i++; } } /// @notice Used to regulate the epoch incrementation and block computation, known as Metas /// @dev When epoch=0, the { blockOmega } will be computed /// When epoch!=0 the block length { epochLen } will be multiplied /// by { inflateRatio } thus making the block length required for each /// epoch longer according /// /// { blockMeta } += { epochLen } result the exact block of the next Meta /// Allow generation mint after incrementing the epoch function epochRegulator() private { if (epoch == 0) computeBlockOmega(); if (epoch > 0) epochLen *= inflateRatio; blockMeta += epochLen; emit Meta(epoch, blockMeta); epoch++; if (block.number >= blockMeta && epoch < epochMax) { epochRegulator(); } generationMintAllowed = true; } // Mint functions ***************************************************** /// @notice Used to add/remove address from { _allowList } function setBatchGenesisAllowance(address[] memory batch) public onlyOwner { uint len = batch.length; require(len > 0, "error len"); uint i = 0; while (i < len) { _allowList[batch[i]] = _allowList[batch[i]] ? false : true; i++; } } /// @notice Used to transfer { _allowList } slot to another address function transferListSlot(address to) public { require(epoch == 0, "error epoch"); require(_allowList[msg.sender], "error msg.sender"); require(!_allowList[to], "error to"); _allowList[msg.sender] = false; _allowList[to] = true; } /// @notice Used to open the mint of Genesis NFT function setGenesisMint() public onlyOwner { genesisMintAllowed = true; } /// @notice Used to gift Genesis NFT, this function is dedicated /// to contract owner according to { onlyOwner } modifier function giftGenesis(address to) public onlyOwner { uint256 _genesisId = ++genesisId; setMetadata(tokenId, _genesisId, epoch); genesisController(_genesisId); mintUSDSat(to, tokenId++); } /// @notice Used to mint Genesis NFT, this function is payable /// the price of this function is equal to { genesisPrice }, /// require to be present on { _allowList } to call function mintGenesis() public payable { uint256 _genesisId = ++genesisId; setMetadata(tokenId, _genesisId, epoch); genesisController(_genesisId); require(genesisMintAllowed, "error genesisMintAllowed"); require(_allowList[msg.sender], "error allowList"); require(genesisPrice == msg.value, "error genesisPrice"); _allowList[msg.sender] = false; mintUSDSat(msg.sender, tokenId++); } /// @notice Used to gift Generation NFT, you need a Genesis NFT to call this function function giftGenerations(uint256 _genesisId, address to) public { ++generationId; generationController(_genesisId); setMetadata(tokenId, _genesisId, epoch); mintUSDSat(to, tokenId++); } /// @notice Used to mint Generation NFT, you need a Genesis NFT to call this function function mintGenerations(uint256 _genesisId) public { ++generationId; generationController(_genesisId); setMetadata(tokenId, _genesisId, epoch); mintUSDSat(msg.sender, tokenId++); } /// @notice Token is minted on { ADDRESS_SIGN } and instantly transferred to { msg.sender } as { to }, /// this is to ensure the token creation is signed with { ADDRESS_SIGN } /// This function is private and can be only called by the contract function mintUSDSat(address to, uint256 _tokenId) private { emit PermanentURI(_compileMetadata(_tokenId), _tokenId); _safeMint(ADDRESS_SIGN, _tokenId); emit Signed(epoch, _tokenId, block.number); _safeTransfer(ADDRESS_SIGN, to, _tokenId, ""); emit Minted(epoch, _tokenId, to); } // Contract URI functions ********************************************* /// @notice Used to set the { ContractCID } metadata from ipfs, /// this function is dedicated to contract owner according /// to { onlyOwner } modifier function setContractCID(string memory CID) public onlyOwner { ContractCID = string(abi.encodePacked("ipfs://", CID)); } /// @notice Used to render { ContractCID } as { contractURI } according to /// Opensea contract metadata standard function contractURI() public view virtual returns (string memory) { return ContractCID; } // Utilitaries functions ********************************************** /// @notice Used to fetch all entry for { epoch } into { epochMintingRegistry } function getMapRegisteryForEpoch(uint256 _epoch) public view returns (bool[210] memory result) { uint i = 1; while (i <= maxGenesisSupply) { result[i] = epochMintingRegistry[_epoch][i]; i++; } } /// @notice Used to fetch all { tokenIds } from { owner } function exposeHeldIds(address owner) public view returns(uint[] memory) { uint tokenCount = balanceOf(owner); uint[] memory tokenIds = new uint[](tokenCount); uint i = 0; while (i < tokenCount) { tokenIds[i] = tokenOfOwnerByIndex(owner, i); i++; } return tokenIds; } // ERC721 Spec functions ********************************************** /// @notice Used to render metadata as { tokenURI } according to ERC721 standard function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token"); return _compileMetadata(_tokenId); } /// @dev ERC721 required override function _beforeTokenTransfer(address from, address to, uint256 _tokenId) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, _tokenId); } /// @dev ERC721 required override function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } }
/// ``.. /// `.` `````.``.-````-`` `.` /// ` ``````.`..///.-..----. --..--`.-....`..-.```` ``` /// `` `.`..--...`:::/::-``..``..:-.://///---..-....----- /// ``-:::/+++:::/-.-///://oso+::++/--:--../+:/:..:-....-://:/:-`` /// `-+/++/+o+://+::-:soo+oosss+s+//o:/:--`--:://://:ooso/-.--.-:-.` /// ``.+ooso++o+:+:+sosyhsyshhddyo+:/sds/yoo++/+:--/--.--:..--..``.```` /// ``:++/---:+/::::///oyhhyy+++:hddhhNNho///ohosyhs+/-:/+/---.....-.. ` /// ``-:-...-/+///++///+o+:-:o+o/oydmNmNNdddhsoyo/oyyyho///:-.--.-.``. `` /// ```--`..-:+/:--:::-.-///++++ydsdNNMNdmMNMmNysddyoooosso+//-.-`....````` ..` /// .```:-:::/-.-+o++/+:/+/o/hNNNNhmdNMMNNMMdyydNNmdyys+++oo++-`--.:.-.`````... /// ..--.`-..`.-`-hh++-/:+shho+hsysyyhhhmNNmmNMMmNNNdmmy+:+sh/o+y/+-`+./::.```` ` /// -/` ``.-``.//o++y+//ssyh+hhdmmdmmddmhdmNdmdsh+oNNMmmddoodh/s:yss.--+.//+`.` `. /// `.`-.` -`..+h+yo++ooyyyyyoyhy+shmNNmmdhhdhyyhymdyyhdmshoohs+y:oy+/+o/:/++.`- .` /// ``.`.``-.-++syyyhhhhhhhhmhysosyyoooosssdhhhdmmdhdmdsy+ss+/+ho/hody-s+-:+::--`` ` /// .`` ``-//s+:ohmdmddNmNmhhshhddNNNhyyhhhdNNhmNNmNNmmyso+yhhso++hhdy.:/ ::-:--``.` /// .```.-`.//shdmNNmddyysohmMmdmNNmmNshdmNhso+-/ohNoyhmmsysosd++hy/osss/.:-o/-.:/--. /// ``..:++-+hhy/syhhhdhdNNddNMmNsNMNyyso+//:-.`-/..+hmdsmdy+ossos:+o/h/+..//-s.`.:::o/ /// `.-.oy//hm+o:-..-+/shdNNNNNNhsNdo/oyoyyhoh+/so//+/mNmyhh+/s+dy/+s::+:`-`-:s--:-.::+`-` /// .`:h-`+y+./oyhhdddhyohMMNmmNmdhoo/oyyhddhmNNNmhsoodmdhs+///++:+-:.:/--/-/o/--+//...:` /// ``+o``yoodNNNNNMhdyyo+ymhsymyshhyys+sssssNmdmmdmy+oso/++:://+/-`::-:--:/::+.//o:-.--: /// `:-:-`oNhyhdNNNmyys+/:://oohy++/+hmmmmNNNNhohydmmyhy++////ooy./----.-:---/::-o+:...-/ /// ``-.-` yms+mmNmMMmNho/:o++++hhh++:mMmNmmmNMNdhdms+ysyy//:-+o:.-.`.``.-:/::-:-+/y/.- -` /// ..:` hh+oNNmMNNNmss/:-+oyhs+o+.-yhdNmdhmmydmms+o///:///+/+--/`-``.o::/:-o//-/y::/.- /// `.-``hh+yNdmdohdy:++/./myhds/./shNhhyy++o:oyos/s+:s//+////.:- ...`--`..`-.:--o:+::` /// `-/+yyho.`.-+oso///+/Nmddh//y+:s:.../soy+:o+.:sdyo++++o:.-. `.:.:-```:.`:``/o:`:` /// ./.`..sMN+:::yh+s+ysyhhddh+ymdsd/:/+o+ysydhohoh/o+/so++o+/o.--..`-:::``:-`+-`:+--.` /// ``:``..-NNy++/yyysohmo+NNmy/+:+hMNmy+yydmNMNddhs:yyydmmmso:o///..-.-+-:o:/.o/-/+-`` /// ``+.`..-mMhsyo+++oo+yoshyyo+/`+hNmhyy+sdmdssssho-MMMNMNh//+/oo+/+:-....`.s+/`..-` /// .+ `oNMmdhhsohhmmydmNms/yy.oNmmdy+++/+ss+odNm+mNmdddo-s+:+/++/-:--//`/o+s/.-`` /// `/` dNNNhooddNmNymMNNdsoo+y+shhhmyymhss+hddms+hdhmdo+/+-/oo+/.///+sh:-/-s/` /// `::`hdNmh+ooNmdohNNMMmsooohh+oysydhdooo/syysodmNmys+/o+//+y/:.+/hmso.-//s- /// -+ohdmmhyhdysysyyhmysoyddhhoo+shdhdyddmddmNmmhssds/::/oo/..:/+Nmo+`-:so /// .oyhdmmNNdm+s:/:os/+/ssyyds+/ssdNNyhdmmhdmmdymymy///o:/``/+-dmdoo++:o` /// `ysyMNhhmoo+h-:/+o/+:.:/:/+doo+dNdhddmhmmmy++yhds/+-+::..o/+Nmosyhs+- /// s+dNNyNhsdhNhsy:+:oo/soo+dNmmooyosohMhsymmhyy+++:+:/+/-/o+yNh+hMNs. /// +yhNNMd+dmydmdy/+/sshydmhdNNmNooyhhhhshohmNh+:+oso++ssy+/odyhhNmh` /// `yyhdms+dMh+oyshhyhysdmNd+ohyNN+++mNddmNy+yo//+o/hddddymmyhosNmms` /// oydos:oMmhoyyhysssysdmMmNmhNmNNh/+mmNmddh+/+o+::+s+hmhmdyNNNNy: /// `/dNm/+Ndhy+oshdhhdyo::ohmdyhhNysy:smshmdo/o:so//:s++ymhyohdy-` /// `sNNN/hNm/:do+o:+/++++s:/+shyymmddy/ydmmh/s/+oss//oysy++o+o+` /// oNNMNmm:/hyy/:/o/+hhsosysoo-ohhhss/hmmhd/dyh++/soyooy++o+:. /// :/dMNh/smhh+//+s+--:+/so+ohhy/:sydmmmmm+/mdddhy++/ohs//-o/` /// `/odmhyhsyh++/-:+:::/:/o/:ooddy/+yodNNh+ydhmmmy++/hhyo+://` /// `:os/+o//oshss/yhs+//:+/-/:soooo/+sso+dddydss+:+sy///+:++ /// ./o/s//hhNho+shyyyoyyso+/ys+/+-:y+:/soooyyh++sNyo++/:/+ /// -/:osmmhyo:++++/+/osshdssooo/:/h//://++oyhsshmdo+//s/- /// .osmhydh::/+++/o+ohhysddyoo++os+-+++///yhhhmNs+o/:// /// -.++yss//////+/+/+soo++shyhsyy+::/:+y+yhdmdoo//:/:- /// ``.oss/:////++://+o//:://+oo-:o++/shhhmmh+o+++///-` /// ..:+++oo/+///ys:///://+::-sy+osh+osdyo+o/::/s:/y-` /// `odoyhds+/yysyydss+///+/:+oshdmNo+:+/oo/+++++:hy//` /// `://hyoyy/o/++shhy:+y:/:o/+omNmhsoohhsso+++:+o+sy:/++ /// -/---oddooss+oosy+ohNdo+++oyNhsdo/++shhhoo:s+oydmyo//o+ /// :y.`.``yyd++shoyydhhyymdhyyhyhhs+////+/+s/+:odmmyso.:ohy. /// .yy/o-..+h/+o/+//++ssoohhhssso+++:/:/yy+//sydmNddo+/./ohy+. /// .dmmhs+osdoos///o//++/+shdsoshoys+ssss++shmNNNyyds+:-s-//:+. /// -shmNmyhddsyss++/+ysddhyyydhdmyssNddyydyhNmdNmddso/::s:--`.-.` /// `+dmNhhdmddsooyyooossysshdhmoss+/+mNdyymydMdyMdyoo+/--/:/:`...-.` /// .:smNNMmsMNNmdhyyo/yymmdmdyo+ooooshysyysNNNmmmNyss/+o-`-:-/:```.`` ``` /// `.-+o/sdNNNmhdddNmmdsso/sdshyyyyhsdddyohymdmNdmmmmmyoo+/.... -os.`.``-.`` /// `/-:-/+.hymmmmdhmyNdMNmmhhs+sosoyhddyddmmho/ooymhddhdhyos-.oy..-:o+:..`` ```` ` /// ..::``--.-hoymmdNNNNNNMmhyNh+oo+soyNdmNmmmysooooymhy+so++yo..:+.--`..:.`.` `-- ``.` ` /// ```-.-.``..`:ddymmmNNdmNNNNmhN: -/oys/sdmmNdydsydmhhsmdso+/yo:/-..`.``.` ``:.`.````-. ` /// ````-:/.```:::syyydmddNhNNdsdMMs`./oddmd./odNdy+yssss++ooo/o+//-`:/:..:`-.```/-:.`.```..`` ` /// ```..-`` --.`.--o+sNhoyMmho+omhmo+Ns::dhdmmdy:.oNoyhhs+/o+o++s+hhoo+.`-:....``.-:-`..-````.-``.`` /// @title Dollars Nakamoto by Pascal Boyart /// @author jolan.eth /// @notice This contract will allow you to yield farm Dollars Nakamoto NFT. /// During epoch 0 you will be able to mint a Genesis NFT, /// Over time, epoch will increment allowing you to mint more editions. /// Minting generations editions is allowed only 1 time per epoch and per Genesis NFT. /// Generations editions do not allow you to mint other generations.
NatSpecSingleLine
setJolan
function setJolan(address JOLAN) public { require(msg.sender == ADDRESS_JOLAN, "error msg.sender"); ADDRESS_JOLAN = JOLAN; emit Shareholder(SHARE_JOLAN, ADDRESS_JOLAN); }
/// @notice Allow Jolan to modify ADDRESS_JOLAN /// This function is dedicated to the represented shareholder according to require().
NatSpecSingleLine
v0.8.10+commit.fc410830
MIT
ipfs://627efb7c58e0f1a820013031c32ab417b2b86eb0e16948f99bf7e29ad6e50407
{ "func_code_index": [ 3935, 4147 ] }
2,668
USDSat
USDSat.sol
0xbeda58401038c864c9fc9145f28e47b7b00a0e86
Solidity
USDSat
contract USDSat is USDSatMetadata, ERC721, ERC721Enumerable, Ownable, ReentrancyGuard { string SYMBOL = "USDSat"; string NAME = "Dollars Nakamoto"; string ContractCID; /// @notice Address used to sign NFT on mint address public ADDRESS_SIGN = 0x1Af70e564847bE46e4bA286c0b0066Da8372F902; /// @notice Ether shareholder address address public ADDRESS_PBOY = 0x709e17B3Ec505F80eAb064d0F2A71c743cE225B3; /// @notice Ether shareholder address address public ADDRESS_JOLAN = 0x51BdFa2Cbb25591AF58b202aCdcdB33325a325c2; /// @notice Equity per shareholder in % uint256 public SHARE_PBOY = 90; /// @notice Equity per shareholder in % uint256 public SHARE_JOLAN = 10; /// @notice Mapping used to represent allowed addresses to call { mintGenesis } mapping (address => bool) public _allowList; /// @notice Represent the current epoch uint256 public epoch = 0; /// @notice Represent the maximum epoch possible uint256 public epochMax = 10; /// @notice Represent the block length of an epoch uint256 public epochLen = 41016; /// @notice Index of the NFT /// @dev Start at 1 because var++ uint256 public tokenId = 1; /// @notice Index of the Genesis NFT /// @dev Start at 0 because ++var uint256 public genesisId = 0; /// @notice Index of the Generation NFT /// @dev Start at 0 because ++var uint256 public generationId = 0; /// @notice Maximum total supply uint256 public maxTokenSupply = 2100; /// @notice Maximum Genesis supply uint256 public maxGenesisSupply = 210; /// @notice Maximum supply per generation uint256 public maxGenerationSupply = 210; /// @notice Price of the Genesis NFT (Generations NFT are free) uint256 public genesisPrice = 0.5 ether; /// @notice Define the ending block uint256 public blockOmega; /// @notice Define the starting block uint256 public blockGenesis; /// @notice Define in which block the Meta must occur uint256 public blockMeta; /// @notice Used to inflate blockMeta each epoch incrementation uint256 public inflateRatio = 2; /// @notice Open Genesis mint when true bool public genesisMintAllowed = false; /// @notice Open Generation mint when true bool public generationMintAllowed = false; /// @notice Multi dimensionnal mapping to keep a track of the minting reentrancy over epoch mapping(uint256 => mapping(uint256 => bool)) public epochMintingRegistry; event Omega(uint256 _blockNumber); event Genesis(uint256 indexed _epoch, uint256 _blockNumber); event Meta(uint256 indexed _epoch, uint256 _blockNumber); event Withdraw(uint256 indexed _share, address _shareholder); event Shareholder(uint256 indexed _sharePercent, address _shareholder); event Securized(uint256 indexed _epoch, uint256 _epochLen, uint256 _blockMeta, uint256 _inflateRatio); event PermanentURI(string _value, uint256 indexed _id); event Minted(uint256 indexed _epoch, uint256 indexed _tokenId, address indexed _owner); event Signed(uint256 indexed _epoch, uint256 indexed _tokenId, uint256 indexed _blockNumber); constructor() ERC721(NAME, SYMBOL) {} // Withdraw functions ************************************************* /// @notice Allow Pboy to modify ADDRESS_PBOY /// This function is dedicated to the represented shareholder according to require(). function setPboy(address PBOY) public { require(msg.sender == ADDRESS_PBOY, "error msg.sender"); ADDRESS_PBOY = PBOY; emit Shareholder(SHARE_PBOY, ADDRESS_PBOY); } /// @notice Allow Jolan to modify ADDRESS_JOLAN /// This function is dedicated to the represented shareholder according to require(). function setJolan(address JOLAN) public { require(msg.sender == ADDRESS_JOLAN, "error msg.sender"); ADDRESS_JOLAN = JOLAN; emit Shareholder(SHARE_JOLAN, ADDRESS_JOLAN); } /// @notice Used to withdraw ETH balance of the contract, this function is dedicated /// to contract owner according to { onlyOwner } modifier. function withdrawEquity() public onlyOwner nonReentrant { uint256 balance = address(this).balance; address[2] memory shareholders = [ ADDRESS_PBOY, ADDRESS_JOLAN ]; uint256[2] memory _shares = [ SHARE_PBOY * balance / 100, SHARE_JOLAN * balance / 100 ]; uint i = 0; while (i < 2) { require(payable(shareholders[i]).send(_shares[i])); emit Withdraw(_shares[i], shareholders[i]); i++; } } // Epoch functions **************************************************** /// @notice Used to manage authorization and reentrancy of the genesis NFT mint /// @param _genesisId Used to increment { genesisId } and write { epochMintingRegistry } function genesisController(uint256 _genesisId) private { require(epoch == 0, "error epoch"); require(genesisId <= maxGenesisSupply, "error genesisId"); require(!epochMintingRegistry[epoch][_genesisId], "error epochMintingRegistry"); /// @dev Set { _genesisId } for { epoch } as true epochMintingRegistry[epoch][_genesisId] = true; /// @dev When { genesisId } reaches { maxGenesisSupply } the function /// will compute the data to increment the epoch according /// /// { blockGenesis } is set only once, at this time /// { blockMeta } is set to { blockGenesis } because epoch=0 /// Then it is computed into the function epochRegulator() /// /// Once the epoch is regulated, the new generation start /// straight away, { generationMintAllowed } is set to true if (genesisId == maxGenesisSupply) { blockGenesis = block.number; blockMeta = blockGenesis; emit Genesis(epoch, blockGenesis); epochRegulator(); } } /// @notice Used to manage authorization and reentrancy of the Generation NFT mint /// @param _genesisId Used to write { epochMintingRegistry } and verify minting allowance function generationController(uint256 _genesisId) private { require(blockGenesis > 0, "error blockGenesis"); require(blockMeta > 0, "error blockMeta"); require(blockOmega > 0, "error blockOmega"); /// @dev If { block.number } >= { blockMeta } the function /// will compute the data to increment the epoch according /// /// Once the epoch is regulated, the new generation start /// straight away, { generationMintAllowed } is set to true /// /// { generationId } is reset to 1 if (block.number >= blockMeta) { epochRegulator(); generationId = 1; } /// @dev Be sure the mint is open if condition are favorable if (block.number < blockMeta && generationId <= maxGenerationSupply) { generationMintAllowed = true; } require(maxTokenSupply >= tokenId, "error maxTokenSupply"); require(epoch > 0 && epoch < epochMax, "error epoch"); require(ownerOf(_genesisId) == msg.sender, "error ownerOf"); require(generationMintAllowed, "error generationMintAllowed"); require(generationId <= maxGenerationSupply, "error generationId"); require(epochMintingRegistry[0][_genesisId], "error epochMintingRegistry"); require(!epochMintingRegistry[epoch][_genesisId], "error epochMintingRegistry"); /// @dev Set { _genesisId } for { epoch } as true epochMintingRegistry[epoch][_genesisId] = true; /// @dev If { generationId } reaches { maxGenerationSupply } the modifier /// will set { generationMintAllowed } to false to stop the mint /// on this generation /// /// { generationId } is reset to 0 /// /// This condition will not block the function because as long as /// { block.number } >= { blockMeta } minting will reopen /// according and this condition will become obsolete until /// the condition is reached again if (generationId == maxGenerationSupply) { generationMintAllowed = false; generationId = 0; } } /// @notice Used to protect epoch block length from difficulty bomb of the /// Ethereum network. A difficulty bomb heavily increases the difficulty /// on the network, likely also causing an increase in block time. /// If the block time increases too much, the epoch generation could become /// exponentially higher than what is desired, ending with an undesired Ice-Age. /// To protect against this, the emergencySecure() function is allowed to /// manually reconfigure the epoch block length and the block Meta /// to match the network conditions if necessary. /// /// It can also be useful if the block time decreases for some reason with consensus change. /// /// This function is dedicated to contract owner according to { onlyOwner } modifier function emergencySecure(uint256 _epoch, uint256 _epochLen, uint256 _blockMeta, uint256 _inflateRatio) public onlyOwner { require(epoch > 0, "error epoch"); require(_epoch > 0, "error _epoch"); require(maxTokenSupply >= tokenId, "error maxTokenSupply"); epoch = _epoch; epochLen = _epochLen; blockMeta = _blockMeta; inflateRatio = _inflateRatio; computeBlockOmega(); emit Securized(epoch, epochLen, blockMeta, inflateRatio); } /// @notice Used to compute blockOmega() function, { blockOmega } represents /// the block when it won't ever be possible to mint another Dollars Nakamoto NFT. /// It is possible to be computed because of the deterministic state of the current protocol /// The following algorithm simulate the 10 epochs of the protocol block computation to result blockOmega function computeBlockOmega() private { uint256 i = 0; uint256 _blockMeta = 0; uint256 _epochLen = epochLen; while (i < epochMax) { if (i > 0) _epochLen *= inflateRatio; if (i == 9) { blockOmega = blockGenesis + _blockMeta; emit Omega(blockOmega); break; } _blockMeta += _epochLen; i++; } } /// @notice Used to regulate the epoch incrementation and block computation, known as Metas /// @dev When epoch=0, the { blockOmega } will be computed /// When epoch!=0 the block length { epochLen } will be multiplied /// by { inflateRatio } thus making the block length required for each /// epoch longer according /// /// { blockMeta } += { epochLen } result the exact block of the next Meta /// Allow generation mint after incrementing the epoch function epochRegulator() private { if (epoch == 0) computeBlockOmega(); if (epoch > 0) epochLen *= inflateRatio; blockMeta += epochLen; emit Meta(epoch, blockMeta); epoch++; if (block.number >= blockMeta && epoch < epochMax) { epochRegulator(); } generationMintAllowed = true; } // Mint functions ***************************************************** /// @notice Used to add/remove address from { _allowList } function setBatchGenesisAllowance(address[] memory batch) public onlyOwner { uint len = batch.length; require(len > 0, "error len"); uint i = 0; while (i < len) { _allowList[batch[i]] = _allowList[batch[i]] ? false : true; i++; } } /// @notice Used to transfer { _allowList } slot to another address function transferListSlot(address to) public { require(epoch == 0, "error epoch"); require(_allowList[msg.sender], "error msg.sender"); require(!_allowList[to], "error to"); _allowList[msg.sender] = false; _allowList[to] = true; } /// @notice Used to open the mint of Genesis NFT function setGenesisMint() public onlyOwner { genesisMintAllowed = true; } /// @notice Used to gift Genesis NFT, this function is dedicated /// to contract owner according to { onlyOwner } modifier function giftGenesis(address to) public onlyOwner { uint256 _genesisId = ++genesisId; setMetadata(tokenId, _genesisId, epoch); genesisController(_genesisId); mintUSDSat(to, tokenId++); } /// @notice Used to mint Genesis NFT, this function is payable /// the price of this function is equal to { genesisPrice }, /// require to be present on { _allowList } to call function mintGenesis() public payable { uint256 _genesisId = ++genesisId; setMetadata(tokenId, _genesisId, epoch); genesisController(_genesisId); require(genesisMintAllowed, "error genesisMintAllowed"); require(_allowList[msg.sender], "error allowList"); require(genesisPrice == msg.value, "error genesisPrice"); _allowList[msg.sender] = false; mintUSDSat(msg.sender, tokenId++); } /// @notice Used to gift Generation NFT, you need a Genesis NFT to call this function function giftGenerations(uint256 _genesisId, address to) public { ++generationId; generationController(_genesisId); setMetadata(tokenId, _genesisId, epoch); mintUSDSat(to, tokenId++); } /// @notice Used to mint Generation NFT, you need a Genesis NFT to call this function function mintGenerations(uint256 _genesisId) public { ++generationId; generationController(_genesisId); setMetadata(tokenId, _genesisId, epoch); mintUSDSat(msg.sender, tokenId++); } /// @notice Token is minted on { ADDRESS_SIGN } and instantly transferred to { msg.sender } as { to }, /// this is to ensure the token creation is signed with { ADDRESS_SIGN } /// This function is private and can be only called by the contract function mintUSDSat(address to, uint256 _tokenId) private { emit PermanentURI(_compileMetadata(_tokenId), _tokenId); _safeMint(ADDRESS_SIGN, _tokenId); emit Signed(epoch, _tokenId, block.number); _safeTransfer(ADDRESS_SIGN, to, _tokenId, ""); emit Minted(epoch, _tokenId, to); } // Contract URI functions ********************************************* /// @notice Used to set the { ContractCID } metadata from ipfs, /// this function is dedicated to contract owner according /// to { onlyOwner } modifier function setContractCID(string memory CID) public onlyOwner { ContractCID = string(abi.encodePacked("ipfs://", CID)); } /// @notice Used to render { ContractCID } as { contractURI } according to /// Opensea contract metadata standard function contractURI() public view virtual returns (string memory) { return ContractCID; } // Utilitaries functions ********************************************** /// @notice Used to fetch all entry for { epoch } into { epochMintingRegistry } function getMapRegisteryForEpoch(uint256 _epoch) public view returns (bool[210] memory result) { uint i = 1; while (i <= maxGenesisSupply) { result[i] = epochMintingRegistry[_epoch][i]; i++; } } /// @notice Used to fetch all { tokenIds } from { owner } function exposeHeldIds(address owner) public view returns(uint[] memory) { uint tokenCount = balanceOf(owner); uint[] memory tokenIds = new uint[](tokenCount); uint i = 0; while (i < tokenCount) { tokenIds[i] = tokenOfOwnerByIndex(owner, i); i++; } return tokenIds; } // ERC721 Spec functions ********************************************** /// @notice Used to render metadata as { tokenURI } according to ERC721 standard function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token"); return _compileMetadata(_tokenId); } /// @dev ERC721 required override function _beforeTokenTransfer(address from, address to, uint256 _tokenId) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, _tokenId); } /// @dev ERC721 required override function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } }
/// ``.. /// `.` `````.``.-````-`` `.` /// ` ``````.`..///.-..----. --..--`.-....`..-.```` ``` /// `` `.`..--...`:::/::-``..``..:-.://///---..-....----- /// ``-:::/+++:::/-.-///://oso+::++/--:--../+:/:..:-....-://:/:-`` /// `-+/++/+o+://+::-:soo+oosss+s+//o:/:--`--:://://:ooso/-.--.-:-.` /// ``.+ooso++o+:+:+sosyhsyshhddyo+:/sds/yoo++/+:--/--.--:..--..``.```` /// ``:++/---:+/::::///oyhhyy+++:hddhhNNho///ohosyhs+/-:/+/---.....-.. ` /// ``-:-...-/+///++///+o+:-:o+o/oydmNmNNdddhsoyo/oyyyho///:-.--.-.``. `` /// ```--`..-:+/:--:::-.-///++++ydsdNNMNdmMNMmNysddyoooosso+//-.-`....````` ..` /// .```:-:::/-.-+o++/+:/+/o/hNNNNhmdNMMNNMMdyydNNmdyys+++oo++-`--.:.-.`````... /// ..--.`-..`.-`-hh++-/:+shho+hsysyyhhhmNNmmNMMmNNNdmmy+:+sh/o+y/+-`+./::.```` ` /// -/` ``.-``.//o++y+//ssyh+hhdmmdmmddmhdmNdmdsh+oNNMmmddoodh/s:yss.--+.//+`.` `. /// `.`-.` -`..+h+yo++ooyyyyyoyhy+shmNNmmdhhdhyyhymdyyhdmshoohs+y:oy+/+o/:/++.`- .` /// ``.`.``-.-++syyyhhhhhhhhmhysosyyoooosssdhhhdmmdhdmdsy+ss+/+ho/hody-s+-:+::--`` ` /// .`` ``-//s+:ohmdmddNmNmhhshhddNNNhyyhhhdNNhmNNmNNmmyso+yhhso++hhdy.:/ ::-:--``.` /// .```.-`.//shdmNNmddyysohmMmdmNNmmNshdmNhso+-/ohNoyhmmsysosd++hy/osss/.:-o/-.:/--. /// ``..:++-+hhy/syhhhdhdNNddNMmNsNMNyyso+//:-.`-/..+hmdsmdy+ossos:+o/h/+..//-s.`.:::o/ /// `.-.oy//hm+o:-..-+/shdNNNNNNhsNdo/oyoyyhoh+/so//+/mNmyhh+/s+dy/+s::+:`-`-:s--:-.::+`-` /// .`:h-`+y+./oyhhdddhyohMMNmmNmdhoo/oyyhddhmNNNmhsoodmdhs+///++:+-:.:/--/-/o/--+//...:` /// ``+o``yoodNNNNNMhdyyo+ymhsymyshhyys+sssssNmdmmdmy+oso/++:://+/-`::-:--:/::+.//o:-.--: /// `:-:-`oNhyhdNNNmyys+/:://oohy++/+hmmmmNNNNhohydmmyhy++////ooy./----.-:---/::-o+:...-/ /// ``-.-` yms+mmNmMMmNho/:o++++hhh++:mMmNmmmNMNdhdms+ysyy//:-+o:.-.`.``.-:/::-:-+/y/.- -` /// ..:` hh+oNNmMNNNmss/:-+oyhs+o+.-yhdNmdhmmydmms+o///:///+/+--/`-``.o::/:-o//-/y::/.- /// `.-``hh+yNdmdohdy:++/./myhds/./shNhhyy++o:oyos/s+:s//+////.:- ...`--`..`-.:--o:+::` /// `-/+yyho.`.-+oso///+/Nmddh//y+:s:.../soy+:o+.:sdyo++++o:.-. `.:.:-```:.`:``/o:`:` /// ./.`..sMN+:::yh+s+ysyhhddh+ymdsd/:/+o+ysydhohoh/o+/so++o+/o.--..`-:::``:-`+-`:+--.` /// ``:``..-NNy++/yyysohmo+NNmy/+:+hMNmy+yydmNMNddhs:yyydmmmso:o///..-.-+-:o:/.o/-/+-`` /// ``+.`..-mMhsyo+++oo+yoshyyo+/`+hNmhyy+sdmdssssho-MMMNMNh//+/oo+/+:-....`.s+/`..-` /// .+ `oNMmdhhsohhmmydmNms/yy.oNmmdy+++/+ss+odNm+mNmdddo-s+:+/++/-:--//`/o+s/.-`` /// `/` dNNNhooddNmNymMNNdsoo+y+shhhmyymhss+hddms+hdhmdo+/+-/oo+/.///+sh:-/-s/` /// `::`hdNmh+ooNmdohNNMMmsooohh+oysydhdooo/syysodmNmys+/o+//+y/:.+/hmso.-//s- /// -+ohdmmhyhdysysyyhmysoyddhhoo+shdhdyddmddmNmmhssds/::/oo/..:/+Nmo+`-:so /// .oyhdmmNNdm+s:/:os/+/ssyyds+/ssdNNyhdmmhdmmdymymy///o:/``/+-dmdoo++:o` /// `ysyMNhhmoo+h-:/+o/+:.:/:/+doo+dNdhddmhmmmy++yhds/+-+::..o/+Nmosyhs+- /// s+dNNyNhsdhNhsy:+:oo/soo+dNmmooyosohMhsymmhyy+++:+:/+/-/o+yNh+hMNs. /// +yhNNMd+dmydmdy/+/sshydmhdNNmNooyhhhhshohmNh+:+oso++ssy+/odyhhNmh` /// `yyhdms+dMh+oyshhyhysdmNd+ohyNN+++mNddmNy+yo//+o/hddddymmyhosNmms` /// oydos:oMmhoyyhysssysdmMmNmhNmNNh/+mmNmddh+/+o+::+s+hmhmdyNNNNy: /// `/dNm/+Ndhy+oshdhhdyo::ohmdyhhNysy:smshmdo/o:so//:s++ymhyohdy-` /// `sNNN/hNm/:do+o:+/++++s:/+shyymmddy/ydmmh/s/+oss//oysy++o+o+` /// oNNMNmm:/hyy/:/o/+hhsosysoo-ohhhss/hmmhd/dyh++/soyooy++o+:. /// :/dMNh/smhh+//+s+--:+/so+ohhy/:sydmmmmm+/mdddhy++/ohs//-o/` /// `/odmhyhsyh++/-:+:::/:/o/:ooddy/+yodNNh+ydhmmmy++/hhyo+://` /// `:os/+o//oshss/yhs+//:+/-/:soooo/+sso+dddydss+:+sy///+:++ /// ./o/s//hhNho+shyyyoyyso+/ys+/+-:y+:/soooyyh++sNyo++/:/+ /// -/:osmmhyo:++++/+/osshdssooo/:/h//://++oyhsshmdo+//s/- /// .osmhydh::/+++/o+ohhysddyoo++os+-+++///yhhhmNs+o/:// /// -.++yss//////+/+/+soo++shyhsyy+::/:+y+yhdmdoo//:/:- /// ``.oss/:////++://+o//:://+oo-:o++/shhhmmh+o+++///-` /// ..:+++oo/+///ys:///://+::-sy+osh+osdyo+o/::/s:/y-` /// `odoyhds+/yysyydss+///+/:+oshdmNo+:+/oo/+++++:hy//` /// `://hyoyy/o/++shhy:+y:/:o/+omNmhsoohhsso+++:+o+sy:/++ /// -/---oddooss+oosy+ohNdo+++oyNhsdo/++shhhoo:s+oydmyo//o+ /// :y.`.``yyd++shoyydhhyymdhyyhyhhs+////+/+s/+:odmmyso.:ohy. /// .yy/o-..+h/+o/+//++ssoohhhssso+++:/:/yy+//sydmNddo+/./ohy+. /// .dmmhs+osdoos///o//++/+shdsoshoys+ssss++shmNNNyyds+:-s-//:+. /// -shmNmyhddsyss++/+ysddhyyydhdmyssNddyydyhNmdNmddso/::s:--`.-.` /// `+dmNhhdmddsooyyooossysshdhmoss+/+mNdyymydMdyMdyoo+/--/:/:`...-.` /// .:smNNMmsMNNmdhyyo/yymmdmdyo+ooooshysyysNNNmmmNyss/+o-`-:-/:```.`` ``` /// `.-+o/sdNNNmhdddNmmdsso/sdshyyyyhsdddyohymdmNdmmmmmyoo+/.... -os.`.``-.`` /// `/-:-/+.hymmmmdhmyNdMNmmhhs+sosoyhddyddmmho/ooymhddhdhyos-.oy..-:o+:..`` ```` ` /// ..::``--.-hoymmdNNNNNNMmhyNh+oo+soyNdmNmmmysooooymhy+so++yo..:+.--`..:.`.` `-- ``.` ` /// ```-.-.``..`:ddymmmNNdmNNNNmhN: -/oys/sdmmNdydsydmhhsmdso+/yo:/-..`.``.` ``:.`.````-. ` /// ````-:/.```:::syyydmddNhNNdsdMMs`./oddmd./odNdy+yssss++ooo/o+//-`:/:..:`-.```/-:.`.```..`` ` /// ```..-`` --.`.--o+sNhoyMmho+omhmo+Ns::dhdmmdy:.oNoyhhs+/o+o++s+hhoo+.`-:....``.-:-`..-````.-``.`` /// @title Dollars Nakamoto by Pascal Boyart /// @author jolan.eth /// @notice This contract will allow you to yield farm Dollars Nakamoto NFT. /// During epoch 0 you will be able to mint a Genesis NFT, /// Over time, epoch will increment allowing you to mint more editions. /// Minting generations editions is allowed only 1 time per epoch and per Genesis NFT. /// Generations editions do not allow you to mint other generations.
NatSpecSingleLine
withdrawEquity
function withdrawEquity() public onlyOwner nonReentrant { uint256 balance = address(this).balance; address[2] memory shareholders = [ ADDRESS_PBOY, ADDRESS_JOLAN ]; uint256[2] memory _shares = [ SHARE_PBOY * balance / 100, SHARE_JOLAN * balance / 100 ]; uint i = 0; while (i < 2) { require(payable(shareholders[i]).send(_shares[i])); emit Withdraw(_shares[i], shareholders[i]); i++; } }
/// @notice Used to withdraw ETH balance of the contract, this function is dedicated /// to contract owner according to { onlyOwner } modifier.
NatSpecSingleLine
v0.8.10+commit.fc410830
MIT
ipfs://627efb7c58e0f1a820013031c32ab417b2b86eb0e16948f99bf7e29ad6e50407
{ "func_code_index": [ 4312, 4882 ] }
2,669
USDSat
USDSat.sol
0xbeda58401038c864c9fc9145f28e47b7b00a0e86
Solidity
USDSat
contract USDSat is USDSatMetadata, ERC721, ERC721Enumerable, Ownable, ReentrancyGuard { string SYMBOL = "USDSat"; string NAME = "Dollars Nakamoto"; string ContractCID; /// @notice Address used to sign NFT on mint address public ADDRESS_SIGN = 0x1Af70e564847bE46e4bA286c0b0066Da8372F902; /// @notice Ether shareholder address address public ADDRESS_PBOY = 0x709e17B3Ec505F80eAb064d0F2A71c743cE225B3; /// @notice Ether shareholder address address public ADDRESS_JOLAN = 0x51BdFa2Cbb25591AF58b202aCdcdB33325a325c2; /// @notice Equity per shareholder in % uint256 public SHARE_PBOY = 90; /// @notice Equity per shareholder in % uint256 public SHARE_JOLAN = 10; /// @notice Mapping used to represent allowed addresses to call { mintGenesis } mapping (address => bool) public _allowList; /// @notice Represent the current epoch uint256 public epoch = 0; /// @notice Represent the maximum epoch possible uint256 public epochMax = 10; /// @notice Represent the block length of an epoch uint256 public epochLen = 41016; /// @notice Index of the NFT /// @dev Start at 1 because var++ uint256 public tokenId = 1; /// @notice Index of the Genesis NFT /// @dev Start at 0 because ++var uint256 public genesisId = 0; /// @notice Index of the Generation NFT /// @dev Start at 0 because ++var uint256 public generationId = 0; /// @notice Maximum total supply uint256 public maxTokenSupply = 2100; /// @notice Maximum Genesis supply uint256 public maxGenesisSupply = 210; /// @notice Maximum supply per generation uint256 public maxGenerationSupply = 210; /// @notice Price of the Genesis NFT (Generations NFT are free) uint256 public genesisPrice = 0.5 ether; /// @notice Define the ending block uint256 public blockOmega; /// @notice Define the starting block uint256 public blockGenesis; /// @notice Define in which block the Meta must occur uint256 public blockMeta; /// @notice Used to inflate blockMeta each epoch incrementation uint256 public inflateRatio = 2; /// @notice Open Genesis mint when true bool public genesisMintAllowed = false; /// @notice Open Generation mint when true bool public generationMintAllowed = false; /// @notice Multi dimensionnal mapping to keep a track of the minting reentrancy over epoch mapping(uint256 => mapping(uint256 => bool)) public epochMintingRegistry; event Omega(uint256 _blockNumber); event Genesis(uint256 indexed _epoch, uint256 _blockNumber); event Meta(uint256 indexed _epoch, uint256 _blockNumber); event Withdraw(uint256 indexed _share, address _shareholder); event Shareholder(uint256 indexed _sharePercent, address _shareholder); event Securized(uint256 indexed _epoch, uint256 _epochLen, uint256 _blockMeta, uint256 _inflateRatio); event PermanentURI(string _value, uint256 indexed _id); event Minted(uint256 indexed _epoch, uint256 indexed _tokenId, address indexed _owner); event Signed(uint256 indexed _epoch, uint256 indexed _tokenId, uint256 indexed _blockNumber); constructor() ERC721(NAME, SYMBOL) {} // Withdraw functions ************************************************* /// @notice Allow Pboy to modify ADDRESS_PBOY /// This function is dedicated to the represented shareholder according to require(). function setPboy(address PBOY) public { require(msg.sender == ADDRESS_PBOY, "error msg.sender"); ADDRESS_PBOY = PBOY; emit Shareholder(SHARE_PBOY, ADDRESS_PBOY); } /// @notice Allow Jolan to modify ADDRESS_JOLAN /// This function is dedicated to the represented shareholder according to require(). function setJolan(address JOLAN) public { require(msg.sender == ADDRESS_JOLAN, "error msg.sender"); ADDRESS_JOLAN = JOLAN; emit Shareholder(SHARE_JOLAN, ADDRESS_JOLAN); } /// @notice Used to withdraw ETH balance of the contract, this function is dedicated /// to contract owner according to { onlyOwner } modifier. function withdrawEquity() public onlyOwner nonReentrant { uint256 balance = address(this).balance; address[2] memory shareholders = [ ADDRESS_PBOY, ADDRESS_JOLAN ]; uint256[2] memory _shares = [ SHARE_PBOY * balance / 100, SHARE_JOLAN * balance / 100 ]; uint i = 0; while (i < 2) { require(payable(shareholders[i]).send(_shares[i])); emit Withdraw(_shares[i], shareholders[i]); i++; } } // Epoch functions **************************************************** /// @notice Used to manage authorization and reentrancy of the genesis NFT mint /// @param _genesisId Used to increment { genesisId } and write { epochMintingRegistry } function genesisController(uint256 _genesisId) private { require(epoch == 0, "error epoch"); require(genesisId <= maxGenesisSupply, "error genesisId"); require(!epochMintingRegistry[epoch][_genesisId], "error epochMintingRegistry"); /// @dev Set { _genesisId } for { epoch } as true epochMintingRegistry[epoch][_genesisId] = true; /// @dev When { genesisId } reaches { maxGenesisSupply } the function /// will compute the data to increment the epoch according /// /// { blockGenesis } is set only once, at this time /// { blockMeta } is set to { blockGenesis } because epoch=0 /// Then it is computed into the function epochRegulator() /// /// Once the epoch is regulated, the new generation start /// straight away, { generationMintAllowed } is set to true if (genesisId == maxGenesisSupply) { blockGenesis = block.number; blockMeta = blockGenesis; emit Genesis(epoch, blockGenesis); epochRegulator(); } } /// @notice Used to manage authorization and reentrancy of the Generation NFT mint /// @param _genesisId Used to write { epochMintingRegistry } and verify minting allowance function generationController(uint256 _genesisId) private { require(blockGenesis > 0, "error blockGenesis"); require(blockMeta > 0, "error blockMeta"); require(blockOmega > 0, "error blockOmega"); /// @dev If { block.number } >= { blockMeta } the function /// will compute the data to increment the epoch according /// /// Once the epoch is regulated, the new generation start /// straight away, { generationMintAllowed } is set to true /// /// { generationId } is reset to 1 if (block.number >= blockMeta) { epochRegulator(); generationId = 1; } /// @dev Be sure the mint is open if condition are favorable if (block.number < blockMeta && generationId <= maxGenerationSupply) { generationMintAllowed = true; } require(maxTokenSupply >= tokenId, "error maxTokenSupply"); require(epoch > 0 && epoch < epochMax, "error epoch"); require(ownerOf(_genesisId) == msg.sender, "error ownerOf"); require(generationMintAllowed, "error generationMintAllowed"); require(generationId <= maxGenerationSupply, "error generationId"); require(epochMintingRegistry[0][_genesisId], "error epochMintingRegistry"); require(!epochMintingRegistry[epoch][_genesisId], "error epochMintingRegistry"); /// @dev Set { _genesisId } for { epoch } as true epochMintingRegistry[epoch][_genesisId] = true; /// @dev If { generationId } reaches { maxGenerationSupply } the modifier /// will set { generationMintAllowed } to false to stop the mint /// on this generation /// /// { generationId } is reset to 0 /// /// This condition will not block the function because as long as /// { block.number } >= { blockMeta } minting will reopen /// according and this condition will become obsolete until /// the condition is reached again if (generationId == maxGenerationSupply) { generationMintAllowed = false; generationId = 0; } } /// @notice Used to protect epoch block length from difficulty bomb of the /// Ethereum network. A difficulty bomb heavily increases the difficulty /// on the network, likely also causing an increase in block time. /// If the block time increases too much, the epoch generation could become /// exponentially higher than what is desired, ending with an undesired Ice-Age. /// To protect against this, the emergencySecure() function is allowed to /// manually reconfigure the epoch block length and the block Meta /// to match the network conditions if necessary. /// /// It can also be useful if the block time decreases for some reason with consensus change. /// /// This function is dedicated to contract owner according to { onlyOwner } modifier function emergencySecure(uint256 _epoch, uint256 _epochLen, uint256 _blockMeta, uint256 _inflateRatio) public onlyOwner { require(epoch > 0, "error epoch"); require(_epoch > 0, "error _epoch"); require(maxTokenSupply >= tokenId, "error maxTokenSupply"); epoch = _epoch; epochLen = _epochLen; blockMeta = _blockMeta; inflateRatio = _inflateRatio; computeBlockOmega(); emit Securized(epoch, epochLen, blockMeta, inflateRatio); } /// @notice Used to compute blockOmega() function, { blockOmega } represents /// the block when it won't ever be possible to mint another Dollars Nakamoto NFT. /// It is possible to be computed because of the deterministic state of the current protocol /// The following algorithm simulate the 10 epochs of the protocol block computation to result blockOmega function computeBlockOmega() private { uint256 i = 0; uint256 _blockMeta = 0; uint256 _epochLen = epochLen; while (i < epochMax) { if (i > 0) _epochLen *= inflateRatio; if (i == 9) { blockOmega = blockGenesis + _blockMeta; emit Omega(blockOmega); break; } _blockMeta += _epochLen; i++; } } /// @notice Used to regulate the epoch incrementation and block computation, known as Metas /// @dev When epoch=0, the { blockOmega } will be computed /// When epoch!=0 the block length { epochLen } will be multiplied /// by { inflateRatio } thus making the block length required for each /// epoch longer according /// /// { blockMeta } += { epochLen } result the exact block of the next Meta /// Allow generation mint after incrementing the epoch function epochRegulator() private { if (epoch == 0) computeBlockOmega(); if (epoch > 0) epochLen *= inflateRatio; blockMeta += epochLen; emit Meta(epoch, blockMeta); epoch++; if (block.number >= blockMeta && epoch < epochMax) { epochRegulator(); } generationMintAllowed = true; } // Mint functions ***************************************************** /// @notice Used to add/remove address from { _allowList } function setBatchGenesisAllowance(address[] memory batch) public onlyOwner { uint len = batch.length; require(len > 0, "error len"); uint i = 0; while (i < len) { _allowList[batch[i]] = _allowList[batch[i]] ? false : true; i++; } } /// @notice Used to transfer { _allowList } slot to another address function transferListSlot(address to) public { require(epoch == 0, "error epoch"); require(_allowList[msg.sender], "error msg.sender"); require(!_allowList[to], "error to"); _allowList[msg.sender] = false; _allowList[to] = true; } /// @notice Used to open the mint of Genesis NFT function setGenesisMint() public onlyOwner { genesisMintAllowed = true; } /// @notice Used to gift Genesis NFT, this function is dedicated /// to contract owner according to { onlyOwner } modifier function giftGenesis(address to) public onlyOwner { uint256 _genesisId = ++genesisId; setMetadata(tokenId, _genesisId, epoch); genesisController(_genesisId); mintUSDSat(to, tokenId++); } /// @notice Used to mint Genesis NFT, this function is payable /// the price of this function is equal to { genesisPrice }, /// require to be present on { _allowList } to call function mintGenesis() public payable { uint256 _genesisId = ++genesisId; setMetadata(tokenId, _genesisId, epoch); genesisController(_genesisId); require(genesisMintAllowed, "error genesisMintAllowed"); require(_allowList[msg.sender], "error allowList"); require(genesisPrice == msg.value, "error genesisPrice"); _allowList[msg.sender] = false; mintUSDSat(msg.sender, tokenId++); } /// @notice Used to gift Generation NFT, you need a Genesis NFT to call this function function giftGenerations(uint256 _genesisId, address to) public { ++generationId; generationController(_genesisId); setMetadata(tokenId, _genesisId, epoch); mintUSDSat(to, tokenId++); } /// @notice Used to mint Generation NFT, you need a Genesis NFT to call this function function mintGenerations(uint256 _genesisId) public { ++generationId; generationController(_genesisId); setMetadata(tokenId, _genesisId, epoch); mintUSDSat(msg.sender, tokenId++); } /// @notice Token is minted on { ADDRESS_SIGN } and instantly transferred to { msg.sender } as { to }, /// this is to ensure the token creation is signed with { ADDRESS_SIGN } /// This function is private and can be only called by the contract function mintUSDSat(address to, uint256 _tokenId) private { emit PermanentURI(_compileMetadata(_tokenId), _tokenId); _safeMint(ADDRESS_SIGN, _tokenId); emit Signed(epoch, _tokenId, block.number); _safeTransfer(ADDRESS_SIGN, to, _tokenId, ""); emit Minted(epoch, _tokenId, to); } // Contract URI functions ********************************************* /// @notice Used to set the { ContractCID } metadata from ipfs, /// this function is dedicated to contract owner according /// to { onlyOwner } modifier function setContractCID(string memory CID) public onlyOwner { ContractCID = string(abi.encodePacked("ipfs://", CID)); } /// @notice Used to render { ContractCID } as { contractURI } according to /// Opensea contract metadata standard function contractURI() public view virtual returns (string memory) { return ContractCID; } // Utilitaries functions ********************************************** /// @notice Used to fetch all entry for { epoch } into { epochMintingRegistry } function getMapRegisteryForEpoch(uint256 _epoch) public view returns (bool[210] memory result) { uint i = 1; while (i <= maxGenesisSupply) { result[i] = epochMintingRegistry[_epoch][i]; i++; } } /// @notice Used to fetch all { tokenIds } from { owner } function exposeHeldIds(address owner) public view returns(uint[] memory) { uint tokenCount = balanceOf(owner); uint[] memory tokenIds = new uint[](tokenCount); uint i = 0; while (i < tokenCount) { tokenIds[i] = tokenOfOwnerByIndex(owner, i); i++; } return tokenIds; } // ERC721 Spec functions ********************************************** /// @notice Used to render metadata as { tokenURI } according to ERC721 standard function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token"); return _compileMetadata(_tokenId); } /// @dev ERC721 required override function _beforeTokenTransfer(address from, address to, uint256 _tokenId) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, _tokenId); } /// @dev ERC721 required override function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } }
/// ``.. /// `.` `````.``.-````-`` `.` /// ` ``````.`..///.-..----. --..--`.-....`..-.```` ``` /// `` `.`..--...`:::/::-``..``..:-.://///---..-....----- /// ``-:::/+++:::/-.-///://oso+::++/--:--../+:/:..:-....-://:/:-`` /// `-+/++/+o+://+::-:soo+oosss+s+//o:/:--`--:://://:ooso/-.--.-:-.` /// ``.+ooso++o+:+:+sosyhsyshhddyo+:/sds/yoo++/+:--/--.--:..--..``.```` /// ``:++/---:+/::::///oyhhyy+++:hddhhNNho///ohosyhs+/-:/+/---.....-.. ` /// ``-:-...-/+///++///+o+:-:o+o/oydmNmNNdddhsoyo/oyyyho///:-.--.-.``. `` /// ```--`..-:+/:--:::-.-///++++ydsdNNMNdmMNMmNysddyoooosso+//-.-`....````` ..` /// .```:-:::/-.-+o++/+:/+/o/hNNNNhmdNMMNNMMdyydNNmdyys+++oo++-`--.:.-.`````... /// ..--.`-..`.-`-hh++-/:+shho+hsysyyhhhmNNmmNMMmNNNdmmy+:+sh/o+y/+-`+./::.```` ` /// -/` ``.-``.//o++y+//ssyh+hhdmmdmmddmhdmNdmdsh+oNNMmmddoodh/s:yss.--+.//+`.` `. /// `.`-.` -`..+h+yo++ooyyyyyoyhy+shmNNmmdhhdhyyhymdyyhdmshoohs+y:oy+/+o/:/++.`- .` /// ``.`.``-.-++syyyhhhhhhhhmhysosyyoooosssdhhhdmmdhdmdsy+ss+/+ho/hody-s+-:+::--`` ` /// .`` ``-//s+:ohmdmddNmNmhhshhddNNNhyyhhhdNNhmNNmNNmmyso+yhhso++hhdy.:/ ::-:--``.` /// .```.-`.//shdmNNmddyysohmMmdmNNmmNshdmNhso+-/ohNoyhmmsysosd++hy/osss/.:-o/-.:/--. /// ``..:++-+hhy/syhhhdhdNNddNMmNsNMNyyso+//:-.`-/..+hmdsmdy+ossos:+o/h/+..//-s.`.:::o/ /// `.-.oy//hm+o:-..-+/shdNNNNNNhsNdo/oyoyyhoh+/so//+/mNmyhh+/s+dy/+s::+:`-`-:s--:-.::+`-` /// .`:h-`+y+./oyhhdddhyohMMNmmNmdhoo/oyyhddhmNNNmhsoodmdhs+///++:+-:.:/--/-/o/--+//...:` /// ``+o``yoodNNNNNMhdyyo+ymhsymyshhyys+sssssNmdmmdmy+oso/++:://+/-`::-:--:/::+.//o:-.--: /// `:-:-`oNhyhdNNNmyys+/:://oohy++/+hmmmmNNNNhohydmmyhy++////ooy./----.-:---/::-o+:...-/ /// ``-.-` yms+mmNmMMmNho/:o++++hhh++:mMmNmmmNMNdhdms+ysyy//:-+o:.-.`.``.-:/::-:-+/y/.- -` /// ..:` hh+oNNmMNNNmss/:-+oyhs+o+.-yhdNmdhmmydmms+o///:///+/+--/`-``.o::/:-o//-/y::/.- /// `.-``hh+yNdmdohdy:++/./myhds/./shNhhyy++o:oyos/s+:s//+////.:- ...`--`..`-.:--o:+::` /// `-/+yyho.`.-+oso///+/Nmddh//y+:s:.../soy+:o+.:sdyo++++o:.-. `.:.:-```:.`:``/o:`:` /// ./.`..sMN+:::yh+s+ysyhhddh+ymdsd/:/+o+ysydhohoh/o+/so++o+/o.--..`-:::``:-`+-`:+--.` /// ``:``..-NNy++/yyysohmo+NNmy/+:+hMNmy+yydmNMNddhs:yyydmmmso:o///..-.-+-:o:/.o/-/+-`` /// ``+.`..-mMhsyo+++oo+yoshyyo+/`+hNmhyy+sdmdssssho-MMMNMNh//+/oo+/+:-....`.s+/`..-` /// .+ `oNMmdhhsohhmmydmNms/yy.oNmmdy+++/+ss+odNm+mNmdddo-s+:+/++/-:--//`/o+s/.-`` /// `/` dNNNhooddNmNymMNNdsoo+y+shhhmyymhss+hddms+hdhmdo+/+-/oo+/.///+sh:-/-s/` /// `::`hdNmh+ooNmdohNNMMmsooohh+oysydhdooo/syysodmNmys+/o+//+y/:.+/hmso.-//s- /// -+ohdmmhyhdysysyyhmysoyddhhoo+shdhdyddmddmNmmhssds/::/oo/..:/+Nmo+`-:so /// .oyhdmmNNdm+s:/:os/+/ssyyds+/ssdNNyhdmmhdmmdymymy///o:/``/+-dmdoo++:o` /// `ysyMNhhmoo+h-:/+o/+:.:/:/+doo+dNdhddmhmmmy++yhds/+-+::..o/+Nmosyhs+- /// s+dNNyNhsdhNhsy:+:oo/soo+dNmmooyosohMhsymmhyy+++:+:/+/-/o+yNh+hMNs. /// +yhNNMd+dmydmdy/+/sshydmhdNNmNooyhhhhshohmNh+:+oso++ssy+/odyhhNmh` /// `yyhdms+dMh+oyshhyhysdmNd+ohyNN+++mNddmNy+yo//+o/hddddymmyhosNmms` /// oydos:oMmhoyyhysssysdmMmNmhNmNNh/+mmNmddh+/+o+::+s+hmhmdyNNNNy: /// `/dNm/+Ndhy+oshdhhdyo::ohmdyhhNysy:smshmdo/o:so//:s++ymhyohdy-` /// `sNNN/hNm/:do+o:+/++++s:/+shyymmddy/ydmmh/s/+oss//oysy++o+o+` /// oNNMNmm:/hyy/:/o/+hhsosysoo-ohhhss/hmmhd/dyh++/soyooy++o+:. /// :/dMNh/smhh+//+s+--:+/so+ohhy/:sydmmmmm+/mdddhy++/ohs//-o/` /// `/odmhyhsyh++/-:+:::/:/o/:ooddy/+yodNNh+ydhmmmy++/hhyo+://` /// `:os/+o//oshss/yhs+//:+/-/:soooo/+sso+dddydss+:+sy///+:++ /// ./o/s//hhNho+shyyyoyyso+/ys+/+-:y+:/soooyyh++sNyo++/:/+ /// -/:osmmhyo:++++/+/osshdssooo/:/h//://++oyhsshmdo+//s/- /// .osmhydh::/+++/o+ohhysddyoo++os+-+++///yhhhmNs+o/:// /// -.++yss//////+/+/+soo++shyhsyy+::/:+y+yhdmdoo//:/:- /// ``.oss/:////++://+o//:://+oo-:o++/shhhmmh+o+++///-` /// ..:+++oo/+///ys:///://+::-sy+osh+osdyo+o/::/s:/y-` /// `odoyhds+/yysyydss+///+/:+oshdmNo+:+/oo/+++++:hy//` /// `://hyoyy/o/++shhy:+y:/:o/+omNmhsoohhsso+++:+o+sy:/++ /// -/---oddooss+oosy+ohNdo+++oyNhsdo/++shhhoo:s+oydmyo//o+ /// :y.`.``yyd++shoyydhhyymdhyyhyhhs+////+/+s/+:odmmyso.:ohy. /// .yy/o-..+h/+o/+//++ssoohhhssso+++:/:/yy+//sydmNddo+/./ohy+. /// .dmmhs+osdoos///o//++/+shdsoshoys+ssss++shmNNNyyds+:-s-//:+. /// -shmNmyhddsyss++/+ysddhyyydhdmyssNddyydyhNmdNmddso/::s:--`.-.` /// `+dmNhhdmddsooyyooossysshdhmoss+/+mNdyymydMdyMdyoo+/--/:/:`...-.` /// .:smNNMmsMNNmdhyyo/yymmdmdyo+ooooshysyysNNNmmmNyss/+o-`-:-/:```.`` ``` /// `.-+o/sdNNNmhdddNmmdsso/sdshyyyyhsdddyohymdmNdmmmmmyoo+/.... -os.`.``-.`` /// `/-:-/+.hymmmmdhmyNdMNmmhhs+sosoyhddyddmmho/ooymhddhdhyos-.oy..-:o+:..`` ```` ` /// ..::``--.-hoymmdNNNNNNMmhyNh+oo+soyNdmNmmmysooooymhy+so++yo..:+.--`..:.`.` `-- ``.` ` /// ```-.-.``..`:ddymmmNNdmNNNNmhN: -/oys/sdmmNdydsydmhhsmdso+/yo:/-..`.``.` ``:.`.````-. ` /// ````-:/.```:::syyydmddNhNNdsdMMs`./oddmd./odNdy+yssss++ooo/o+//-`:/:..:`-.```/-:.`.```..`` ` /// ```..-`` --.`.--o+sNhoyMmho+omhmo+Ns::dhdmmdy:.oNoyhhs+/o+o++s+hhoo+.`-:....``.-:-`..-````.-``.`` /// @title Dollars Nakamoto by Pascal Boyart /// @author jolan.eth /// @notice This contract will allow you to yield farm Dollars Nakamoto NFT. /// During epoch 0 you will be able to mint a Genesis NFT, /// Over time, epoch will increment allowing you to mint more editions. /// Minting generations editions is allowed only 1 time per epoch and per Genesis NFT. /// Generations editions do not allow you to mint other generations.
NatSpecSingleLine
genesisController
function genesisController(uint256 _genesisId) private { require(epoch == 0, "error epoch"); require(genesisId <= maxGenesisSupply, "error genesisId"); require(!epochMintingRegistry[epoch][_genesisId], "error epochMintingRegistry"); /// @dev Set { _genesisId } for { epoch } as true epochMintingRegistry[epoch][_genesisId] = true; /// @dev When { genesisId } reaches { maxGenesisSupply } the function /// will compute the data to increment the epoch according /// /// { blockGenesis } is set only once, at this time /// { blockMeta } is set to { blockGenesis } because epoch=0 /// Then it is computed into the function epochRegulator() /// /// Once the epoch is regulated, the new generation start /// straight away, { generationMintAllowed } is set to true if (genesisId == maxGenesisSupply) { blockGenesis = block.number; blockMeta = blockGenesis; emit Genesis(epoch, blockGenesis); epochRegulator(); } }
/// @notice Used to manage authorization and reentrancy of the genesis NFT mint /// @param _genesisId Used to increment { genesisId } and write { epochMintingRegistry }
NatSpecSingleLine
v0.8.10+commit.fc410830
MIT
ipfs://627efb7c58e0f1a820013031c32ab417b2b86eb0e16948f99bf7e29ad6e50407
{ "func_code_index": [ 5144, 6309 ] }
2,670
USDSat
USDSat.sol
0xbeda58401038c864c9fc9145f28e47b7b00a0e86
Solidity
USDSat
contract USDSat is USDSatMetadata, ERC721, ERC721Enumerable, Ownable, ReentrancyGuard { string SYMBOL = "USDSat"; string NAME = "Dollars Nakamoto"; string ContractCID; /// @notice Address used to sign NFT on mint address public ADDRESS_SIGN = 0x1Af70e564847bE46e4bA286c0b0066Da8372F902; /// @notice Ether shareholder address address public ADDRESS_PBOY = 0x709e17B3Ec505F80eAb064d0F2A71c743cE225B3; /// @notice Ether shareholder address address public ADDRESS_JOLAN = 0x51BdFa2Cbb25591AF58b202aCdcdB33325a325c2; /// @notice Equity per shareholder in % uint256 public SHARE_PBOY = 90; /// @notice Equity per shareholder in % uint256 public SHARE_JOLAN = 10; /// @notice Mapping used to represent allowed addresses to call { mintGenesis } mapping (address => bool) public _allowList; /// @notice Represent the current epoch uint256 public epoch = 0; /// @notice Represent the maximum epoch possible uint256 public epochMax = 10; /// @notice Represent the block length of an epoch uint256 public epochLen = 41016; /// @notice Index of the NFT /// @dev Start at 1 because var++ uint256 public tokenId = 1; /// @notice Index of the Genesis NFT /// @dev Start at 0 because ++var uint256 public genesisId = 0; /// @notice Index of the Generation NFT /// @dev Start at 0 because ++var uint256 public generationId = 0; /// @notice Maximum total supply uint256 public maxTokenSupply = 2100; /// @notice Maximum Genesis supply uint256 public maxGenesisSupply = 210; /// @notice Maximum supply per generation uint256 public maxGenerationSupply = 210; /// @notice Price of the Genesis NFT (Generations NFT are free) uint256 public genesisPrice = 0.5 ether; /// @notice Define the ending block uint256 public blockOmega; /// @notice Define the starting block uint256 public blockGenesis; /// @notice Define in which block the Meta must occur uint256 public blockMeta; /// @notice Used to inflate blockMeta each epoch incrementation uint256 public inflateRatio = 2; /// @notice Open Genesis mint when true bool public genesisMintAllowed = false; /// @notice Open Generation mint when true bool public generationMintAllowed = false; /// @notice Multi dimensionnal mapping to keep a track of the minting reentrancy over epoch mapping(uint256 => mapping(uint256 => bool)) public epochMintingRegistry; event Omega(uint256 _blockNumber); event Genesis(uint256 indexed _epoch, uint256 _blockNumber); event Meta(uint256 indexed _epoch, uint256 _blockNumber); event Withdraw(uint256 indexed _share, address _shareholder); event Shareholder(uint256 indexed _sharePercent, address _shareholder); event Securized(uint256 indexed _epoch, uint256 _epochLen, uint256 _blockMeta, uint256 _inflateRatio); event PermanentURI(string _value, uint256 indexed _id); event Minted(uint256 indexed _epoch, uint256 indexed _tokenId, address indexed _owner); event Signed(uint256 indexed _epoch, uint256 indexed _tokenId, uint256 indexed _blockNumber); constructor() ERC721(NAME, SYMBOL) {} // Withdraw functions ************************************************* /// @notice Allow Pboy to modify ADDRESS_PBOY /// This function is dedicated to the represented shareholder according to require(). function setPboy(address PBOY) public { require(msg.sender == ADDRESS_PBOY, "error msg.sender"); ADDRESS_PBOY = PBOY; emit Shareholder(SHARE_PBOY, ADDRESS_PBOY); } /// @notice Allow Jolan to modify ADDRESS_JOLAN /// This function is dedicated to the represented shareholder according to require(). function setJolan(address JOLAN) public { require(msg.sender == ADDRESS_JOLAN, "error msg.sender"); ADDRESS_JOLAN = JOLAN; emit Shareholder(SHARE_JOLAN, ADDRESS_JOLAN); } /// @notice Used to withdraw ETH balance of the contract, this function is dedicated /// to contract owner according to { onlyOwner } modifier. function withdrawEquity() public onlyOwner nonReentrant { uint256 balance = address(this).balance; address[2] memory shareholders = [ ADDRESS_PBOY, ADDRESS_JOLAN ]; uint256[2] memory _shares = [ SHARE_PBOY * balance / 100, SHARE_JOLAN * balance / 100 ]; uint i = 0; while (i < 2) { require(payable(shareholders[i]).send(_shares[i])); emit Withdraw(_shares[i], shareholders[i]); i++; } } // Epoch functions **************************************************** /// @notice Used to manage authorization and reentrancy of the genesis NFT mint /// @param _genesisId Used to increment { genesisId } and write { epochMintingRegistry } function genesisController(uint256 _genesisId) private { require(epoch == 0, "error epoch"); require(genesisId <= maxGenesisSupply, "error genesisId"); require(!epochMintingRegistry[epoch][_genesisId], "error epochMintingRegistry"); /// @dev Set { _genesisId } for { epoch } as true epochMintingRegistry[epoch][_genesisId] = true; /// @dev When { genesisId } reaches { maxGenesisSupply } the function /// will compute the data to increment the epoch according /// /// { blockGenesis } is set only once, at this time /// { blockMeta } is set to { blockGenesis } because epoch=0 /// Then it is computed into the function epochRegulator() /// /// Once the epoch is regulated, the new generation start /// straight away, { generationMintAllowed } is set to true if (genesisId == maxGenesisSupply) { blockGenesis = block.number; blockMeta = blockGenesis; emit Genesis(epoch, blockGenesis); epochRegulator(); } } /// @notice Used to manage authorization and reentrancy of the Generation NFT mint /// @param _genesisId Used to write { epochMintingRegistry } and verify minting allowance function generationController(uint256 _genesisId) private { require(blockGenesis > 0, "error blockGenesis"); require(blockMeta > 0, "error blockMeta"); require(blockOmega > 0, "error blockOmega"); /// @dev If { block.number } >= { blockMeta } the function /// will compute the data to increment the epoch according /// /// Once the epoch is regulated, the new generation start /// straight away, { generationMintAllowed } is set to true /// /// { generationId } is reset to 1 if (block.number >= blockMeta) { epochRegulator(); generationId = 1; } /// @dev Be sure the mint is open if condition are favorable if (block.number < blockMeta && generationId <= maxGenerationSupply) { generationMintAllowed = true; } require(maxTokenSupply >= tokenId, "error maxTokenSupply"); require(epoch > 0 && epoch < epochMax, "error epoch"); require(ownerOf(_genesisId) == msg.sender, "error ownerOf"); require(generationMintAllowed, "error generationMintAllowed"); require(generationId <= maxGenerationSupply, "error generationId"); require(epochMintingRegistry[0][_genesisId], "error epochMintingRegistry"); require(!epochMintingRegistry[epoch][_genesisId], "error epochMintingRegistry"); /// @dev Set { _genesisId } for { epoch } as true epochMintingRegistry[epoch][_genesisId] = true; /// @dev If { generationId } reaches { maxGenerationSupply } the modifier /// will set { generationMintAllowed } to false to stop the mint /// on this generation /// /// { generationId } is reset to 0 /// /// This condition will not block the function because as long as /// { block.number } >= { blockMeta } minting will reopen /// according and this condition will become obsolete until /// the condition is reached again if (generationId == maxGenerationSupply) { generationMintAllowed = false; generationId = 0; } } /// @notice Used to protect epoch block length from difficulty bomb of the /// Ethereum network. A difficulty bomb heavily increases the difficulty /// on the network, likely also causing an increase in block time. /// If the block time increases too much, the epoch generation could become /// exponentially higher than what is desired, ending with an undesired Ice-Age. /// To protect against this, the emergencySecure() function is allowed to /// manually reconfigure the epoch block length and the block Meta /// to match the network conditions if necessary. /// /// It can also be useful if the block time decreases for some reason with consensus change. /// /// This function is dedicated to contract owner according to { onlyOwner } modifier function emergencySecure(uint256 _epoch, uint256 _epochLen, uint256 _blockMeta, uint256 _inflateRatio) public onlyOwner { require(epoch > 0, "error epoch"); require(_epoch > 0, "error _epoch"); require(maxTokenSupply >= tokenId, "error maxTokenSupply"); epoch = _epoch; epochLen = _epochLen; blockMeta = _blockMeta; inflateRatio = _inflateRatio; computeBlockOmega(); emit Securized(epoch, epochLen, blockMeta, inflateRatio); } /// @notice Used to compute blockOmega() function, { blockOmega } represents /// the block when it won't ever be possible to mint another Dollars Nakamoto NFT. /// It is possible to be computed because of the deterministic state of the current protocol /// The following algorithm simulate the 10 epochs of the protocol block computation to result blockOmega function computeBlockOmega() private { uint256 i = 0; uint256 _blockMeta = 0; uint256 _epochLen = epochLen; while (i < epochMax) { if (i > 0) _epochLen *= inflateRatio; if (i == 9) { blockOmega = blockGenesis + _blockMeta; emit Omega(blockOmega); break; } _blockMeta += _epochLen; i++; } } /// @notice Used to regulate the epoch incrementation and block computation, known as Metas /// @dev When epoch=0, the { blockOmega } will be computed /// When epoch!=0 the block length { epochLen } will be multiplied /// by { inflateRatio } thus making the block length required for each /// epoch longer according /// /// { blockMeta } += { epochLen } result the exact block of the next Meta /// Allow generation mint after incrementing the epoch function epochRegulator() private { if (epoch == 0) computeBlockOmega(); if (epoch > 0) epochLen *= inflateRatio; blockMeta += epochLen; emit Meta(epoch, blockMeta); epoch++; if (block.number >= blockMeta && epoch < epochMax) { epochRegulator(); } generationMintAllowed = true; } // Mint functions ***************************************************** /// @notice Used to add/remove address from { _allowList } function setBatchGenesisAllowance(address[] memory batch) public onlyOwner { uint len = batch.length; require(len > 0, "error len"); uint i = 0; while (i < len) { _allowList[batch[i]] = _allowList[batch[i]] ? false : true; i++; } } /// @notice Used to transfer { _allowList } slot to another address function transferListSlot(address to) public { require(epoch == 0, "error epoch"); require(_allowList[msg.sender], "error msg.sender"); require(!_allowList[to], "error to"); _allowList[msg.sender] = false; _allowList[to] = true; } /// @notice Used to open the mint of Genesis NFT function setGenesisMint() public onlyOwner { genesisMintAllowed = true; } /// @notice Used to gift Genesis NFT, this function is dedicated /// to contract owner according to { onlyOwner } modifier function giftGenesis(address to) public onlyOwner { uint256 _genesisId = ++genesisId; setMetadata(tokenId, _genesisId, epoch); genesisController(_genesisId); mintUSDSat(to, tokenId++); } /// @notice Used to mint Genesis NFT, this function is payable /// the price of this function is equal to { genesisPrice }, /// require to be present on { _allowList } to call function mintGenesis() public payable { uint256 _genesisId = ++genesisId; setMetadata(tokenId, _genesisId, epoch); genesisController(_genesisId); require(genesisMintAllowed, "error genesisMintAllowed"); require(_allowList[msg.sender], "error allowList"); require(genesisPrice == msg.value, "error genesisPrice"); _allowList[msg.sender] = false; mintUSDSat(msg.sender, tokenId++); } /// @notice Used to gift Generation NFT, you need a Genesis NFT to call this function function giftGenerations(uint256 _genesisId, address to) public { ++generationId; generationController(_genesisId); setMetadata(tokenId, _genesisId, epoch); mintUSDSat(to, tokenId++); } /// @notice Used to mint Generation NFT, you need a Genesis NFT to call this function function mintGenerations(uint256 _genesisId) public { ++generationId; generationController(_genesisId); setMetadata(tokenId, _genesisId, epoch); mintUSDSat(msg.sender, tokenId++); } /// @notice Token is minted on { ADDRESS_SIGN } and instantly transferred to { msg.sender } as { to }, /// this is to ensure the token creation is signed with { ADDRESS_SIGN } /// This function is private and can be only called by the contract function mintUSDSat(address to, uint256 _tokenId) private { emit PermanentURI(_compileMetadata(_tokenId), _tokenId); _safeMint(ADDRESS_SIGN, _tokenId); emit Signed(epoch, _tokenId, block.number); _safeTransfer(ADDRESS_SIGN, to, _tokenId, ""); emit Minted(epoch, _tokenId, to); } // Contract URI functions ********************************************* /// @notice Used to set the { ContractCID } metadata from ipfs, /// this function is dedicated to contract owner according /// to { onlyOwner } modifier function setContractCID(string memory CID) public onlyOwner { ContractCID = string(abi.encodePacked("ipfs://", CID)); } /// @notice Used to render { ContractCID } as { contractURI } according to /// Opensea contract metadata standard function contractURI() public view virtual returns (string memory) { return ContractCID; } // Utilitaries functions ********************************************** /// @notice Used to fetch all entry for { epoch } into { epochMintingRegistry } function getMapRegisteryForEpoch(uint256 _epoch) public view returns (bool[210] memory result) { uint i = 1; while (i <= maxGenesisSupply) { result[i] = epochMintingRegistry[_epoch][i]; i++; } } /// @notice Used to fetch all { tokenIds } from { owner } function exposeHeldIds(address owner) public view returns(uint[] memory) { uint tokenCount = balanceOf(owner); uint[] memory tokenIds = new uint[](tokenCount); uint i = 0; while (i < tokenCount) { tokenIds[i] = tokenOfOwnerByIndex(owner, i); i++; } return tokenIds; } // ERC721 Spec functions ********************************************** /// @notice Used to render metadata as { tokenURI } according to ERC721 standard function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token"); return _compileMetadata(_tokenId); } /// @dev ERC721 required override function _beforeTokenTransfer(address from, address to, uint256 _tokenId) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, _tokenId); } /// @dev ERC721 required override function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } }
/// ``.. /// `.` `````.``.-````-`` `.` /// ` ``````.`..///.-..----. --..--`.-....`..-.```` ``` /// `` `.`..--...`:::/::-``..``..:-.://///---..-....----- /// ``-:::/+++:::/-.-///://oso+::++/--:--../+:/:..:-....-://:/:-`` /// `-+/++/+o+://+::-:soo+oosss+s+//o:/:--`--:://://:ooso/-.--.-:-.` /// ``.+ooso++o+:+:+sosyhsyshhddyo+:/sds/yoo++/+:--/--.--:..--..``.```` /// ``:++/---:+/::::///oyhhyy+++:hddhhNNho///ohosyhs+/-:/+/---.....-.. ` /// ``-:-...-/+///++///+o+:-:o+o/oydmNmNNdddhsoyo/oyyyho///:-.--.-.``. `` /// ```--`..-:+/:--:::-.-///++++ydsdNNMNdmMNMmNysddyoooosso+//-.-`....````` ..` /// .```:-:::/-.-+o++/+:/+/o/hNNNNhmdNMMNNMMdyydNNmdyys+++oo++-`--.:.-.`````... /// ..--.`-..`.-`-hh++-/:+shho+hsysyyhhhmNNmmNMMmNNNdmmy+:+sh/o+y/+-`+./::.```` ` /// -/` ``.-``.//o++y+//ssyh+hhdmmdmmddmhdmNdmdsh+oNNMmmddoodh/s:yss.--+.//+`.` `. /// `.`-.` -`..+h+yo++ooyyyyyoyhy+shmNNmmdhhdhyyhymdyyhdmshoohs+y:oy+/+o/:/++.`- .` /// ``.`.``-.-++syyyhhhhhhhhmhysosyyoooosssdhhhdmmdhdmdsy+ss+/+ho/hody-s+-:+::--`` ` /// .`` ``-//s+:ohmdmddNmNmhhshhddNNNhyyhhhdNNhmNNmNNmmyso+yhhso++hhdy.:/ ::-:--``.` /// .```.-`.//shdmNNmddyysohmMmdmNNmmNshdmNhso+-/ohNoyhmmsysosd++hy/osss/.:-o/-.:/--. /// ``..:++-+hhy/syhhhdhdNNddNMmNsNMNyyso+//:-.`-/..+hmdsmdy+ossos:+o/h/+..//-s.`.:::o/ /// `.-.oy//hm+o:-..-+/shdNNNNNNhsNdo/oyoyyhoh+/so//+/mNmyhh+/s+dy/+s::+:`-`-:s--:-.::+`-` /// .`:h-`+y+./oyhhdddhyohMMNmmNmdhoo/oyyhddhmNNNmhsoodmdhs+///++:+-:.:/--/-/o/--+//...:` /// ``+o``yoodNNNNNMhdyyo+ymhsymyshhyys+sssssNmdmmdmy+oso/++:://+/-`::-:--:/::+.//o:-.--: /// `:-:-`oNhyhdNNNmyys+/:://oohy++/+hmmmmNNNNhohydmmyhy++////ooy./----.-:---/::-o+:...-/ /// ``-.-` yms+mmNmMMmNho/:o++++hhh++:mMmNmmmNMNdhdms+ysyy//:-+o:.-.`.``.-:/::-:-+/y/.- -` /// ..:` hh+oNNmMNNNmss/:-+oyhs+o+.-yhdNmdhmmydmms+o///:///+/+--/`-``.o::/:-o//-/y::/.- /// `.-``hh+yNdmdohdy:++/./myhds/./shNhhyy++o:oyos/s+:s//+////.:- ...`--`..`-.:--o:+::` /// `-/+yyho.`.-+oso///+/Nmddh//y+:s:.../soy+:o+.:sdyo++++o:.-. `.:.:-```:.`:``/o:`:` /// ./.`..sMN+:::yh+s+ysyhhddh+ymdsd/:/+o+ysydhohoh/o+/so++o+/o.--..`-:::``:-`+-`:+--.` /// ``:``..-NNy++/yyysohmo+NNmy/+:+hMNmy+yydmNMNddhs:yyydmmmso:o///..-.-+-:o:/.o/-/+-`` /// ``+.`..-mMhsyo+++oo+yoshyyo+/`+hNmhyy+sdmdssssho-MMMNMNh//+/oo+/+:-....`.s+/`..-` /// .+ `oNMmdhhsohhmmydmNms/yy.oNmmdy+++/+ss+odNm+mNmdddo-s+:+/++/-:--//`/o+s/.-`` /// `/` dNNNhooddNmNymMNNdsoo+y+shhhmyymhss+hddms+hdhmdo+/+-/oo+/.///+sh:-/-s/` /// `::`hdNmh+ooNmdohNNMMmsooohh+oysydhdooo/syysodmNmys+/o+//+y/:.+/hmso.-//s- /// -+ohdmmhyhdysysyyhmysoyddhhoo+shdhdyddmddmNmmhssds/::/oo/..:/+Nmo+`-:so /// .oyhdmmNNdm+s:/:os/+/ssyyds+/ssdNNyhdmmhdmmdymymy///o:/``/+-dmdoo++:o` /// `ysyMNhhmoo+h-:/+o/+:.:/:/+doo+dNdhddmhmmmy++yhds/+-+::..o/+Nmosyhs+- /// s+dNNyNhsdhNhsy:+:oo/soo+dNmmooyosohMhsymmhyy+++:+:/+/-/o+yNh+hMNs. /// +yhNNMd+dmydmdy/+/sshydmhdNNmNooyhhhhshohmNh+:+oso++ssy+/odyhhNmh` /// `yyhdms+dMh+oyshhyhysdmNd+ohyNN+++mNddmNy+yo//+o/hddddymmyhosNmms` /// oydos:oMmhoyyhysssysdmMmNmhNmNNh/+mmNmddh+/+o+::+s+hmhmdyNNNNy: /// `/dNm/+Ndhy+oshdhhdyo::ohmdyhhNysy:smshmdo/o:so//:s++ymhyohdy-` /// `sNNN/hNm/:do+o:+/++++s:/+shyymmddy/ydmmh/s/+oss//oysy++o+o+` /// oNNMNmm:/hyy/:/o/+hhsosysoo-ohhhss/hmmhd/dyh++/soyooy++o+:. /// :/dMNh/smhh+//+s+--:+/so+ohhy/:sydmmmmm+/mdddhy++/ohs//-o/` /// `/odmhyhsyh++/-:+:::/:/o/:ooddy/+yodNNh+ydhmmmy++/hhyo+://` /// `:os/+o//oshss/yhs+//:+/-/:soooo/+sso+dddydss+:+sy///+:++ /// ./o/s//hhNho+shyyyoyyso+/ys+/+-:y+:/soooyyh++sNyo++/:/+ /// -/:osmmhyo:++++/+/osshdssooo/:/h//://++oyhsshmdo+//s/- /// .osmhydh::/+++/o+ohhysddyoo++os+-+++///yhhhmNs+o/:// /// -.++yss//////+/+/+soo++shyhsyy+::/:+y+yhdmdoo//:/:- /// ``.oss/:////++://+o//:://+oo-:o++/shhhmmh+o+++///-` /// ..:+++oo/+///ys:///://+::-sy+osh+osdyo+o/::/s:/y-` /// `odoyhds+/yysyydss+///+/:+oshdmNo+:+/oo/+++++:hy//` /// `://hyoyy/o/++shhy:+y:/:o/+omNmhsoohhsso+++:+o+sy:/++ /// -/---oddooss+oosy+ohNdo+++oyNhsdo/++shhhoo:s+oydmyo//o+ /// :y.`.``yyd++shoyydhhyymdhyyhyhhs+////+/+s/+:odmmyso.:ohy. /// .yy/o-..+h/+o/+//++ssoohhhssso+++:/:/yy+//sydmNddo+/./ohy+. /// .dmmhs+osdoos///o//++/+shdsoshoys+ssss++shmNNNyyds+:-s-//:+. /// -shmNmyhddsyss++/+ysddhyyydhdmyssNddyydyhNmdNmddso/::s:--`.-.` /// `+dmNhhdmddsooyyooossysshdhmoss+/+mNdyymydMdyMdyoo+/--/:/:`...-.` /// .:smNNMmsMNNmdhyyo/yymmdmdyo+ooooshysyysNNNmmmNyss/+o-`-:-/:```.`` ``` /// `.-+o/sdNNNmhdddNmmdsso/sdshyyyyhsdddyohymdmNdmmmmmyoo+/.... -os.`.``-.`` /// `/-:-/+.hymmmmdhmyNdMNmmhhs+sosoyhddyddmmho/ooymhddhdhyos-.oy..-:o+:..`` ```` ` /// ..::``--.-hoymmdNNNNNNMmhyNh+oo+soyNdmNmmmysooooymhy+so++yo..:+.--`..:.`.` `-- ``.` ` /// ```-.-.``..`:ddymmmNNdmNNNNmhN: -/oys/sdmmNdydsydmhhsmdso+/yo:/-..`.``.` ``:.`.````-. ` /// ````-:/.```:::syyydmddNhNNdsdMMs`./oddmd./odNdy+yssss++ooo/o+//-`:/:..:`-.```/-:.`.```..`` ` /// ```..-`` --.`.--o+sNhoyMmho+omhmo+Ns::dhdmmdy:.oNoyhhs+/o+o++s+hhoo+.`-:....``.-:-`..-````.-``.`` /// @title Dollars Nakamoto by Pascal Boyart /// @author jolan.eth /// @notice This contract will allow you to yield farm Dollars Nakamoto NFT. /// During epoch 0 you will be able to mint a Genesis NFT, /// Over time, epoch will increment allowing you to mint more editions. /// Minting generations editions is allowed only 1 time per epoch and per Genesis NFT. /// Generations editions do not allow you to mint other generations.
NatSpecSingleLine
generationController
function generationController(uint256 _genesisId) private { require(blockGenesis > 0, "error blockGenesis"); require(blockMeta > 0, "error blockMeta"); require(blockOmega > 0, "error blockOmega"); /// @dev If { block.number } >= { blockMeta } the function /// will compute the data to increment the epoch according /// /// Once the epoch is regulated, the new generation start /// straight away, { generationMintAllowed } is set to true /// /// { generationId } is reset to 1 if (block.number >= blockMeta) { epochRegulator(); generationId = 1; } /// @dev Be sure the mint is open if condition are favorable if (block.number < blockMeta && generationId <= maxGenerationSupply) { generationMintAllowed = true; } require(maxTokenSupply >= tokenId, "error maxTokenSupply"); require(epoch > 0 && epoch < epochMax, "error epoch"); require(ownerOf(_genesisId) == msg.sender, "error ownerOf"); require(generationMintAllowed, "error generationMintAllowed"); require(generationId <= maxGenerationSupply, "error generationId"); require(epochMintingRegistry[0][_genesisId], "error epochMintingRegistry"); require(!epochMintingRegistry[epoch][_genesisId], "error epochMintingRegistry"); /// @dev Set { _genesisId } for { epoch } as true epochMintingRegistry[epoch][_genesisId] = true; /// @dev If { generationId } reaches { maxGenerationSupply } the modifier /// will set { generationMintAllowed } to false to stop the mint /// on this generation /// /// { generationId } is reset to 0 /// /// This condition will not block the function because as long as /// { block.number } >= { blockMeta } minting will reopen /// according and this condition will become obsolete until /// the condition is reached again if (generationId == maxGenerationSupply) { generationMintAllowed = false; generationId = 0; } }
/// @notice Used to manage authorization and reentrancy of the Generation NFT mint /// @param _genesisId Used to write { epochMintingRegistry } and verify minting allowance
NatSpecSingleLine
v0.8.10+commit.fc410830
MIT
ipfs://627efb7c58e0f1a820013031c32ab417b2b86eb0e16948f99bf7e29ad6e50407
{ "func_code_index": [ 6496, 8757 ] }
2,671
USDSat
USDSat.sol
0xbeda58401038c864c9fc9145f28e47b7b00a0e86
Solidity
USDSat
contract USDSat is USDSatMetadata, ERC721, ERC721Enumerable, Ownable, ReentrancyGuard { string SYMBOL = "USDSat"; string NAME = "Dollars Nakamoto"; string ContractCID; /// @notice Address used to sign NFT on mint address public ADDRESS_SIGN = 0x1Af70e564847bE46e4bA286c0b0066Da8372F902; /// @notice Ether shareholder address address public ADDRESS_PBOY = 0x709e17B3Ec505F80eAb064d0F2A71c743cE225B3; /// @notice Ether shareholder address address public ADDRESS_JOLAN = 0x51BdFa2Cbb25591AF58b202aCdcdB33325a325c2; /// @notice Equity per shareholder in % uint256 public SHARE_PBOY = 90; /// @notice Equity per shareholder in % uint256 public SHARE_JOLAN = 10; /// @notice Mapping used to represent allowed addresses to call { mintGenesis } mapping (address => bool) public _allowList; /// @notice Represent the current epoch uint256 public epoch = 0; /// @notice Represent the maximum epoch possible uint256 public epochMax = 10; /// @notice Represent the block length of an epoch uint256 public epochLen = 41016; /// @notice Index of the NFT /// @dev Start at 1 because var++ uint256 public tokenId = 1; /// @notice Index of the Genesis NFT /// @dev Start at 0 because ++var uint256 public genesisId = 0; /// @notice Index of the Generation NFT /// @dev Start at 0 because ++var uint256 public generationId = 0; /// @notice Maximum total supply uint256 public maxTokenSupply = 2100; /// @notice Maximum Genesis supply uint256 public maxGenesisSupply = 210; /// @notice Maximum supply per generation uint256 public maxGenerationSupply = 210; /// @notice Price of the Genesis NFT (Generations NFT are free) uint256 public genesisPrice = 0.5 ether; /// @notice Define the ending block uint256 public blockOmega; /// @notice Define the starting block uint256 public blockGenesis; /// @notice Define in which block the Meta must occur uint256 public blockMeta; /// @notice Used to inflate blockMeta each epoch incrementation uint256 public inflateRatio = 2; /// @notice Open Genesis mint when true bool public genesisMintAllowed = false; /// @notice Open Generation mint when true bool public generationMintAllowed = false; /// @notice Multi dimensionnal mapping to keep a track of the minting reentrancy over epoch mapping(uint256 => mapping(uint256 => bool)) public epochMintingRegistry; event Omega(uint256 _blockNumber); event Genesis(uint256 indexed _epoch, uint256 _blockNumber); event Meta(uint256 indexed _epoch, uint256 _blockNumber); event Withdraw(uint256 indexed _share, address _shareholder); event Shareholder(uint256 indexed _sharePercent, address _shareholder); event Securized(uint256 indexed _epoch, uint256 _epochLen, uint256 _blockMeta, uint256 _inflateRatio); event PermanentURI(string _value, uint256 indexed _id); event Minted(uint256 indexed _epoch, uint256 indexed _tokenId, address indexed _owner); event Signed(uint256 indexed _epoch, uint256 indexed _tokenId, uint256 indexed _blockNumber); constructor() ERC721(NAME, SYMBOL) {} // Withdraw functions ************************************************* /// @notice Allow Pboy to modify ADDRESS_PBOY /// This function is dedicated to the represented shareholder according to require(). function setPboy(address PBOY) public { require(msg.sender == ADDRESS_PBOY, "error msg.sender"); ADDRESS_PBOY = PBOY; emit Shareholder(SHARE_PBOY, ADDRESS_PBOY); } /// @notice Allow Jolan to modify ADDRESS_JOLAN /// This function is dedicated to the represented shareholder according to require(). function setJolan(address JOLAN) public { require(msg.sender == ADDRESS_JOLAN, "error msg.sender"); ADDRESS_JOLAN = JOLAN; emit Shareholder(SHARE_JOLAN, ADDRESS_JOLAN); } /// @notice Used to withdraw ETH balance of the contract, this function is dedicated /// to contract owner according to { onlyOwner } modifier. function withdrawEquity() public onlyOwner nonReentrant { uint256 balance = address(this).balance; address[2] memory shareholders = [ ADDRESS_PBOY, ADDRESS_JOLAN ]; uint256[2] memory _shares = [ SHARE_PBOY * balance / 100, SHARE_JOLAN * balance / 100 ]; uint i = 0; while (i < 2) { require(payable(shareholders[i]).send(_shares[i])); emit Withdraw(_shares[i], shareholders[i]); i++; } } // Epoch functions **************************************************** /// @notice Used to manage authorization and reentrancy of the genesis NFT mint /// @param _genesisId Used to increment { genesisId } and write { epochMintingRegistry } function genesisController(uint256 _genesisId) private { require(epoch == 0, "error epoch"); require(genesisId <= maxGenesisSupply, "error genesisId"); require(!epochMintingRegistry[epoch][_genesisId], "error epochMintingRegistry"); /// @dev Set { _genesisId } for { epoch } as true epochMintingRegistry[epoch][_genesisId] = true; /// @dev When { genesisId } reaches { maxGenesisSupply } the function /// will compute the data to increment the epoch according /// /// { blockGenesis } is set only once, at this time /// { blockMeta } is set to { blockGenesis } because epoch=0 /// Then it is computed into the function epochRegulator() /// /// Once the epoch is regulated, the new generation start /// straight away, { generationMintAllowed } is set to true if (genesisId == maxGenesisSupply) { blockGenesis = block.number; blockMeta = blockGenesis; emit Genesis(epoch, blockGenesis); epochRegulator(); } } /// @notice Used to manage authorization and reentrancy of the Generation NFT mint /// @param _genesisId Used to write { epochMintingRegistry } and verify minting allowance function generationController(uint256 _genesisId) private { require(blockGenesis > 0, "error blockGenesis"); require(blockMeta > 0, "error blockMeta"); require(blockOmega > 0, "error blockOmega"); /// @dev If { block.number } >= { blockMeta } the function /// will compute the data to increment the epoch according /// /// Once the epoch is regulated, the new generation start /// straight away, { generationMintAllowed } is set to true /// /// { generationId } is reset to 1 if (block.number >= blockMeta) { epochRegulator(); generationId = 1; } /// @dev Be sure the mint is open if condition are favorable if (block.number < blockMeta && generationId <= maxGenerationSupply) { generationMintAllowed = true; } require(maxTokenSupply >= tokenId, "error maxTokenSupply"); require(epoch > 0 && epoch < epochMax, "error epoch"); require(ownerOf(_genesisId) == msg.sender, "error ownerOf"); require(generationMintAllowed, "error generationMintAllowed"); require(generationId <= maxGenerationSupply, "error generationId"); require(epochMintingRegistry[0][_genesisId], "error epochMintingRegistry"); require(!epochMintingRegistry[epoch][_genesisId], "error epochMintingRegistry"); /// @dev Set { _genesisId } for { epoch } as true epochMintingRegistry[epoch][_genesisId] = true; /// @dev If { generationId } reaches { maxGenerationSupply } the modifier /// will set { generationMintAllowed } to false to stop the mint /// on this generation /// /// { generationId } is reset to 0 /// /// This condition will not block the function because as long as /// { block.number } >= { blockMeta } minting will reopen /// according and this condition will become obsolete until /// the condition is reached again if (generationId == maxGenerationSupply) { generationMintAllowed = false; generationId = 0; } } /// @notice Used to protect epoch block length from difficulty bomb of the /// Ethereum network. A difficulty bomb heavily increases the difficulty /// on the network, likely also causing an increase in block time. /// If the block time increases too much, the epoch generation could become /// exponentially higher than what is desired, ending with an undesired Ice-Age. /// To protect against this, the emergencySecure() function is allowed to /// manually reconfigure the epoch block length and the block Meta /// to match the network conditions if necessary. /// /// It can also be useful if the block time decreases for some reason with consensus change. /// /// This function is dedicated to contract owner according to { onlyOwner } modifier function emergencySecure(uint256 _epoch, uint256 _epochLen, uint256 _blockMeta, uint256 _inflateRatio) public onlyOwner { require(epoch > 0, "error epoch"); require(_epoch > 0, "error _epoch"); require(maxTokenSupply >= tokenId, "error maxTokenSupply"); epoch = _epoch; epochLen = _epochLen; blockMeta = _blockMeta; inflateRatio = _inflateRatio; computeBlockOmega(); emit Securized(epoch, epochLen, blockMeta, inflateRatio); } /// @notice Used to compute blockOmega() function, { blockOmega } represents /// the block when it won't ever be possible to mint another Dollars Nakamoto NFT. /// It is possible to be computed because of the deterministic state of the current protocol /// The following algorithm simulate the 10 epochs of the protocol block computation to result blockOmega function computeBlockOmega() private { uint256 i = 0; uint256 _blockMeta = 0; uint256 _epochLen = epochLen; while (i < epochMax) { if (i > 0) _epochLen *= inflateRatio; if (i == 9) { blockOmega = blockGenesis + _blockMeta; emit Omega(blockOmega); break; } _blockMeta += _epochLen; i++; } } /// @notice Used to regulate the epoch incrementation and block computation, known as Metas /// @dev When epoch=0, the { blockOmega } will be computed /// When epoch!=0 the block length { epochLen } will be multiplied /// by { inflateRatio } thus making the block length required for each /// epoch longer according /// /// { blockMeta } += { epochLen } result the exact block of the next Meta /// Allow generation mint after incrementing the epoch function epochRegulator() private { if (epoch == 0) computeBlockOmega(); if (epoch > 0) epochLen *= inflateRatio; blockMeta += epochLen; emit Meta(epoch, blockMeta); epoch++; if (block.number >= blockMeta && epoch < epochMax) { epochRegulator(); } generationMintAllowed = true; } // Mint functions ***************************************************** /// @notice Used to add/remove address from { _allowList } function setBatchGenesisAllowance(address[] memory batch) public onlyOwner { uint len = batch.length; require(len > 0, "error len"); uint i = 0; while (i < len) { _allowList[batch[i]] = _allowList[batch[i]] ? false : true; i++; } } /// @notice Used to transfer { _allowList } slot to another address function transferListSlot(address to) public { require(epoch == 0, "error epoch"); require(_allowList[msg.sender], "error msg.sender"); require(!_allowList[to], "error to"); _allowList[msg.sender] = false; _allowList[to] = true; } /// @notice Used to open the mint of Genesis NFT function setGenesisMint() public onlyOwner { genesisMintAllowed = true; } /// @notice Used to gift Genesis NFT, this function is dedicated /// to contract owner according to { onlyOwner } modifier function giftGenesis(address to) public onlyOwner { uint256 _genesisId = ++genesisId; setMetadata(tokenId, _genesisId, epoch); genesisController(_genesisId); mintUSDSat(to, tokenId++); } /// @notice Used to mint Genesis NFT, this function is payable /// the price of this function is equal to { genesisPrice }, /// require to be present on { _allowList } to call function mintGenesis() public payable { uint256 _genesisId = ++genesisId; setMetadata(tokenId, _genesisId, epoch); genesisController(_genesisId); require(genesisMintAllowed, "error genesisMintAllowed"); require(_allowList[msg.sender], "error allowList"); require(genesisPrice == msg.value, "error genesisPrice"); _allowList[msg.sender] = false; mintUSDSat(msg.sender, tokenId++); } /// @notice Used to gift Generation NFT, you need a Genesis NFT to call this function function giftGenerations(uint256 _genesisId, address to) public { ++generationId; generationController(_genesisId); setMetadata(tokenId, _genesisId, epoch); mintUSDSat(to, tokenId++); } /// @notice Used to mint Generation NFT, you need a Genesis NFT to call this function function mintGenerations(uint256 _genesisId) public { ++generationId; generationController(_genesisId); setMetadata(tokenId, _genesisId, epoch); mintUSDSat(msg.sender, tokenId++); } /// @notice Token is minted on { ADDRESS_SIGN } and instantly transferred to { msg.sender } as { to }, /// this is to ensure the token creation is signed with { ADDRESS_SIGN } /// This function is private and can be only called by the contract function mintUSDSat(address to, uint256 _tokenId) private { emit PermanentURI(_compileMetadata(_tokenId), _tokenId); _safeMint(ADDRESS_SIGN, _tokenId); emit Signed(epoch, _tokenId, block.number); _safeTransfer(ADDRESS_SIGN, to, _tokenId, ""); emit Minted(epoch, _tokenId, to); } // Contract URI functions ********************************************* /// @notice Used to set the { ContractCID } metadata from ipfs, /// this function is dedicated to contract owner according /// to { onlyOwner } modifier function setContractCID(string memory CID) public onlyOwner { ContractCID = string(abi.encodePacked("ipfs://", CID)); } /// @notice Used to render { ContractCID } as { contractURI } according to /// Opensea contract metadata standard function contractURI() public view virtual returns (string memory) { return ContractCID; } // Utilitaries functions ********************************************** /// @notice Used to fetch all entry for { epoch } into { epochMintingRegistry } function getMapRegisteryForEpoch(uint256 _epoch) public view returns (bool[210] memory result) { uint i = 1; while (i <= maxGenesisSupply) { result[i] = epochMintingRegistry[_epoch][i]; i++; } } /// @notice Used to fetch all { tokenIds } from { owner } function exposeHeldIds(address owner) public view returns(uint[] memory) { uint tokenCount = balanceOf(owner); uint[] memory tokenIds = new uint[](tokenCount); uint i = 0; while (i < tokenCount) { tokenIds[i] = tokenOfOwnerByIndex(owner, i); i++; } return tokenIds; } // ERC721 Spec functions ********************************************** /// @notice Used to render metadata as { tokenURI } according to ERC721 standard function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token"); return _compileMetadata(_tokenId); } /// @dev ERC721 required override function _beforeTokenTransfer(address from, address to, uint256 _tokenId) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, _tokenId); } /// @dev ERC721 required override function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } }
/// ``.. /// `.` `````.``.-````-`` `.` /// ` ``````.`..///.-..----. --..--`.-....`..-.```` ``` /// `` `.`..--...`:::/::-``..``..:-.://///---..-....----- /// ``-:::/+++:::/-.-///://oso+::++/--:--../+:/:..:-....-://:/:-`` /// `-+/++/+o+://+::-:soo+oosss+s+//o:/:--`--:://://:ooso/-.--.-:-.` /// ``.+ooso++o+:+:+sosyhsyshhddyo+:/sds/yoo++/+:--/--.--:..--..``.```` /// ``:++/---:+/::::///oyhhyy+++:hddhhNNho///ohosyhs+/-:/+/---.....-.. ` /// ``-:-...-/+///++///+o+:-:o+o/oydmNmNNdddhsoyo/oyyyho///:-.--.-.``. `` /// ```--`..-:+/:--:::-.-///++++ydsdNNMNdmMNMmNysddyoooosso+//-.-`....````` ..` /// .```:-:::/-.-+o++/+:/+/o/hNNNNhmdNMMNNMMdyydNNmdyys+++oo++-`--.:.-.`````... /// ..--.`-..`.-`-hh++-/:+shho+hsysyyhhhmNNmmNMMmNNNdmmy+:+sh/o+y/+-`+./::.```` ` /// -/` ``.-``.//o++y+//ssyh+hhdmmdmmddmhdmNdmdsh+oNNMmmddoodh/s:yss.--+.//+`.` `. /// `.`-.` -`..+h+yo++ooyyyyyoyhy+shmNNmmdhhdhyyhymdyyhdmshoohs+y:oy+/+o/:/++.`- .` /// ``.`.``-.-++syyyhhhhhhhhmhysosyyoooosssdhhhdmmdhdmdsy+ss+/+ho/hody-s+-:+::--`` ` /// .`` ``-//s+:ohmdmddNmNmhhshhddNNNhyyhhhdNNhmNNmNNmmyso+yhhso++hhdy.:/ ::-:--``.` /// .```.-`.//shdmNNmddyysohmMmdmNNmmNshdmNhso+-/ohNoyhmmsysosd++hy/osss/.:-o/-.:/--. /// ``..:++-+hhy/syhhhdhdNNddNMmNsNMNyyso+//:-.`-/..+hmdsmdy+ossos:+o/h/+..//-s.`.:::o/ /// `.-.oy//hm+o:-..-+/shdNNNNNNhsNdo/oyoyyhoh+/so//+/mNmyhh+/s+dy/+s::+:`-`-:s--:-.::+`-` /// .`:h-`+y+./oyhhdddhyohMMNmmNmdhoo/oyyhddhmNNNmhsoodmdhs+///++:+-:.:/--/-/o/--+//...:` /// ``+o``yoodNNNNNMhdyyo+ymhsymyshhyys+sssssNmdmmdmy+oso/++:://+/-`::-:--:/::+.//o:-.--: /// `:-:-`oNhyhdNNNmyys+/:://oohy++/+hmmmmNNNNhohydmmyhy++////ooy./----.-:---/::-o+:...-/ /// ``-.-` yms+mmNmMMmNho/:o++++hhh++:mMmNmmmNMNdhdms+ysyy//:-+o:.-.`.``.-:/::-:-+/y/.- -` /// ..:` hh+oNNmMNNNmss/:-+oyhs+o+.-yhdNmdhmmydmms+o///:///+/+--/`-``.o::/:-o//-/y::/.- /// `.-``hh+yNdmdohdy:++/./myhds/./shNhhyy++o:oyos/s+:s//+////.:- ...`--`..`-.:--o:+::` /// `-/+yyho.`.-+oso///+/Nmddh//y+:s:.../soy+:o+.:sdyo++++o:.-. `.:.:-```:.`:``/o:`:` /// ./.`..sMN+:::yh+s+ysyhhddh+ymdsd/:/+o+ysydhohoh/o+/so++o+/o.--..`-:::``:-`+-`:+--.` /// ``:``..-NNy++/yyysohmo+NNmy/+:+hMNmy+yydmNMNddhs:yyydmmmso:o///..-.-+-:o:/.o/-/+-`` /// ``+.`..-mMhsyo+++oo+yoshyyo+/`+hNmhyy+sdmdssssho-MMMNMNh//+/oo+/+:-....`.s+/`..-` /// .+ `oNMmdhhsohhmmydmNms/yy.oNmmdy+++/+ss+odNm+mNmdddo-s+:+/++/-:--//`/o+s/.-`` /// `/` dNNNhooddNmNymMNNdsoo+y+shhhmyymhss+hddms+hdhmdo+/+-/oo+/.///+sh:-/-s/` /// `::`hdNmh+ooNmdohNNMMmsooohh+oysydhdooo/syysodmNmys+/o+//+y/:.+/hmso.-//s- /// -+ohdmmhyhdysysyyhmysoyddhhoo+shdhdyddmddmNmmhssds/::/oo/..:/+Nmo+`-:so /// .oyhdmmNNdm+s:/:os/+/ssyyds+/ssdNNyhdmmhdmmdymymy///o:/``/+-dmdoo++:o` /// `ysyMNhhmoo+h-:/+o/+:.:/:/+doo+dNdhddmhmmmy++yhds/+-+::..o/+Nmosyhs+- /// s+dNNyNhsdhNhsy:+:oo/soo+dNmmooyosohMhsymmhyy+++:+:/+/-/o+yNh+hMNs. /// +yhNNMd+dmydmdy/+/sshydmhdNNmNooyhhhhshohmNh+:+oso++ssy+/odyhhNmh` /// `yyhdms+dMh+oyshhyhysdmNd+ohyNN+++mNddmNy+yo//+o/hddddymmyhosNmms` /// oydos:oMmhoyyhysssysdmMmNmhNmNNh/+mmNmddh+/+o+::+s+hmhmdyNNNNy: /// `/dNm/+Ndhy+oshdhhdyo::ohmdyhhNysy:smshmdo/o:so//:s++ymhyohdy-` /// `sNNN/hNm/:do+o:+/++++s:/+shyymmddy/ydmmh/s/+oss//oysy++o+o+` /// oNNMNmm:/hyy/:/o/+hhsosysoo-ohhhss/hmmhd/dyh++/soyooy++o+:. /// :/dMNh/smhh+//+s+--:+/so+ohhy/:sydmmmmm+/mdddhy++/ohs//-o/` /// `/odmhyhsyh++/-:+:::/:/o/:ooddy/+yodNNh+ydhmmmy++/hhyo+://` /// `:os/+o//oshss/yhs+//:+/-/:soooo/+sso+dddydss+:+sy///+:++ /// ./o/s//hhNho+shyyyoyyso+/ys+/+-:y+:/soooyyh++sNyo++/:/+ /// -/:osmmhyo:++++/+/osshdssooo/:/h//://++oyhsshmdo+//s/- /// .osmhydh::/+++/o+ohhysddyoo++os+-+++///yhhhmNs+o/:// /// -.++yss//////+/+/+soo++shyhsyy+::/:+y+yhdmdoo//:/:- /// ``.oss/:////++://+o//:://+oo-:o++/shhhmmh+o+++///-` /// ..:+++oo/+///ys:///://+::-sy+osh+osdyo+o/::/s:/y-` /// `odoyhds+/yysyydss+///+/:+oshdmNo+:+/oo/+++++:hy//` /// `://hyoyy/o/++shhy:+y:/:o/+omNmhsoohhsso+++:+o+sy:/++ /// -/---oddooss+oosy+ohNdo+++oyNhsdo/++shhhoo:s+oydmyo//o+ /// :y.`.``yyd++shoyydhhyymdhyyhyhhs+////+/+s/+:odmmyso.:ohy. /// .yy/o-..+h/+o/+//++ssoohhhssso+++:/:/yy+//sydmNddo+/./ohy+. /// .dmmhs+osdoos///o//++/+shdsoshoys+ssss++shmNNNyyds+:-s-//:+. /// -shmNmyhddsyss++/+ysddhyyydhdmyssNddyydyhNmdNmddso/::s:--`.-.` /// `+dmNhhdmddsooyyooossysshdhmoss+/+mNdyymydMdyMdyoo+/--/:/:`...-.` /// .:smNNMmsMNNmdhyyo/yymmdmdyo+ooooshysyysNNNmmmNyss/+o-`-:-/:```.`` ``` /// `.-+o/sdNNNmhdddNmmdsso/sdshyyyyhsdddyohymdmNdmmmmmyoo+/.... -os.`.``-.`` /// `/-:-/+.hymmmmdhmyNdMNmmhhs+sosoyhddyddmmho/ooymhddhdhyos-.oy..-:o+:..`` ```` ` /// ..::``--.-hoymmdNNNNNNMmhyNh+oo+soyNdmNmmmysooooymhy+so++yo..:+.--`..:.`.` `-- ``.` ` /// ```-.-.``..`:ddymmmNNdmNNNNmhN: -/oys/sdmmNdydsydmhhsmdso+/yo:/-..`.``.` ``:.`.````-. ` /// ````-:/.```:::syyydmddNhNNdsdMMs`./oddmd./odNdy+yssss++ooo/o+//-`:/:..:`-.```/-:.`.```..`` ` /// ```..-`` --.`.--o+sNhoyMmho+omhmo+Ns::dhdmmdy:.oNoyhhs+/o+o++s+hhoo+.`-:....``.-:-`..-````.-``.`` /// @title Dollars Nakamoto by Pascal Boyart /// @author jolan.eth /// @notice This contract will allow you to yield farm Dollars Nakamoto NFT. /// During epoch 0 you will be able to mint a Genesis NFT, /// Over time, epoch will increment allowing you to mint more editions. /// Minting generations editions is allowed only 1 time per epoch and per Genesis NFT. /// Generations editions do not allow you to mint other generations.
NatSpecSingleLine
emergencySecure
function emergencySecure(uint256 _epoch, uint256 _epochLen, uint256 _blockMeta, uint256 _inflateRatio) public onlyOwner { require(epoch > 0, "error epoch"); require(_epoch > 0, "error _epoch"); require(maxTokenSupply >= tokenId, "error maxTokenSupply"); epoch = _epoch; epochLen = _epochLen; blockMeta = _blockMeta; inflateRatio = _inflateRatio; computeBlockOmega(); emit Securized(epoch, epochLen, blockMeta, inflateRatio); }
/// @notice Used to protect epoch block length from difficulty bomb of the /// Ethereum network. A difficulty bomb heavily increases the difficulty /// on the network, likely also causing an increase in block time. /// If the block time increases too much, the epoch generation could become /// exponentially higher than what is desired, ending with an undesired Ice-Age. /// To protect against this, the emergencySecure() function is allowed to /// manually reconfigure the epoch block length and the block Meta /// to match the network conditions if necessary. /// /// It can also be useful if the block time decreases for some reason with consensus change. /// /// This function is dedicated to contract owner according to { onlyOwner } modifier
NatSpecSingleLine
v0.8.10+commit.fc410830
MIT
ipfs://627efb7c58e0f1a820013031c32ab417b2b86eb0e16948f99bf7e29ad6e50407
{ "func_code_index": [ 9641, 10167 ] }
2,672
USDSat
USDSat.sol
0xbeda58401038c864c9fc9145f28e47b7b00a0e86
Solidity
USDSat
contract USDSat is USDSatMetadata, ERC721, ERC721Enumerable, Ownable, ReentrancyGuard { string SYMBOL = "USDSat"; string NAME = "Dollars Nakamoto"; string ContractCID; /// @notice Address used to sign NFT on mint address public ADDRESS_SIGN = 0x1Af70e564847bE46e4bA286c0b0066Da8372F902; /// @notice Ether shareholder address address public ADDRESS_PBOY = 0x709e17B3Ec505F80eAb064d0F2A71c743cE225B3; /// @notice Ether shareholder address address public ADDRESS_JOLAN = 0x51BdFa2Cbb25591AF58b202aCdcdB33325a325c2; /// @notice Equity per shareholder in % uint256 public SHARE_PBOY = 90; /// @notice Equity per shareholder in % uint256 public SHARE_JOLAN = 10; /// @notice Mapping used to represent allowed addresses to call { mintGenesis } mapping (address => bool) public _allowList; /// @notice Represent the current epoch uint256 public epoch = 0; /// @notice Represent the maximum epoch possible uint256 public epochMax = 10; /// @notice Represent the block length of an epoch uint256 public epochLen = 41016; /// @notice Index of the NFT /// @dev Start at 1 because var++ uint256 public tokenId = 1; /// @notice Index of the Genesis NFT /// @dev Start at 0 because ++var uint256 public genesisId = 0; /// @notice Index of the Generation NFT /// @dev Start at 0 because ++var uint256 public generationId = 0; /// @notice Maximum total supply uint256 public maxTokenSupply = 2100; /// @notice Maximum Genesis supply uint256 public maxGenesisSupply = 210; /// @notice Maximum supply per generation uint256 public maxGenerationSupply = 210; /// @notice Price of the Genesis NFT (Generations NFT are free) uint256 public genesisPrice = 0.5 ether; /// @notice Define the ending block uint256 public blockOmega; /// @notice Define the starting block uint256 public blockGenesis; /// @notice Define in which block the Meta must occur uint256 public blockMeta; /// @notice Used to inflate blockMeta each epoch incrementation uint256 public inflateRatio = 2; /// @notice Open Genesis mint when true bool public genesisMintAllowed = false; /// @notice Open Generation mint when true bool public generationMintAllowed = false; /// @notice Multi dimensionnal mapping to keep a track of the minting reentrancy over epoch mapping(uint256 => mapping(uint256 => bool)) public epochMintingRegistry; event Omega(uint256 _blockNumber); event Genesis(uint256 indexed _epoch, uint256 _blockNumber); event Meta(uint256 indexed _epoch, uint256 _blockNumber); event Withdraw(uint256 indexed _share, address _shareholder); event Shareholder(uint256 indexed _sharePercent, address _shareholder); event Securized(uint256 indexed _epoch, uint256 _epochLen, uint256 _blockMeta, uint256 _inflateRatio); event PermanentURI(string _value, uint256 indexed _id); event Minted(uint256 indexed _epoch, uint256 indexed _tokenId, address indexed _owner); event Signed(uint256 indexed _epoch, uint256 indexed _tokenId, uint256 indexed _blockNumber); constructor() ERC721(NAME, SYMBOL) {} // Withdraw functions ************************************************* /// @notice Allow Pboy to modify ADDRESS_PBOY /// This function is dedicated to the represented shareholder according to require(). function setPboy(address PBOY) public { require(msg.sender == ADDRESS_PBOY, "error msg.sender"); ADDRESS_PBOY = PBOY; emit Shareholder(SHARE_PBOY, ADDRESS_PBOY); } /// @notice Allow Jolan to modify ADDRESS_JOLAN /// This function is dedicated to the represented shareholder according to require(). function setJolan(address JOLAN) public { require(msg.sender == ADDRESS_JOLAN, "error msg.sender"); ADDRESS_JOLAN = JOLAN; emit Shareholder(SHARE_JOLAN, ADDRESS_JOLAN); } /// @notice Used to withdraw ETH balance of the contract, this function is dedicated /// to contract owner according to { onlyOwner } modifier. function withdrawEquity() public onlyOwner nonReentrant { uint256 balance = address(this).balance; address[2] memory shareholders = [ ADDRESS_PBOY, ADDRESS_JOLAN ]; uint256[2] memory _shares = [ SHARE_PBOY * balance / 100, SHARE_JOLAN * balance / 100 ]; uint i = 0; while (i < 2) { require(payable(shareholders[i]).send(_shares[i])); emit Withdraw(_shares[i], shareholders[i]); i++; } } // Epoch functions **************************************************** /// @notice Used to manage authorization and reentrancy of the genesis NFT mint /// @param _genesisId Used to increment { genesisId } and write { epochMintingRegistry } function genesisController(uint256 _genesisId) private { require(epoch == 0, "error epoch"); require(genesisId <= maxGenesisSupply, "error genesisId"); require(!epochMintingRegistry[epoch][_genesisId], "error epochMintingRegistry"); /// @dev Set { _genesisId } for { epoch } as true epochMintingRegistry[epoch][_genesisId] = true; /// @dev When { genesisId } reaches { maxGenesisSupply } the function /// will compute the data to increment the epoch according /// /// { blockGenesis } is set only once, at this time /// { blockMeta } is set to { blockGenesis } because epoch=0 /// Then it is computed into the function epochRegulator() /// /// Once the epoch is regulated, the new generation start /// straight away, { generationMintAllowed } is set to true if (genesisId == maxGenesisSupply) { blockGenesis = block.number; blockMeta = blockGenesis; emit Genesis(epoch, blockGenesis); epochRegulator(); } } /// @notice Used to manage authorization and reentrancy of the Generation NFT mint /// @param _genesisId Used to write { epochMintingRegistry } and verify minting allowance function generationController(uint256 _genesisId) private { require(blockGenesis > 0, "error blockGenesis"); require(blockMeta > 0, "error blockMeta"); require(blockOmega > 0, "error blockOmega"); /// @dev If { block.number } >= { blockMeta } the function /// will compute the data to increment the epoch according /// /// Once the epoch is regulated, the new generation start /// straight away, { generationMintAllowed } is set to true /// /// { generationId } is reset to 1 if (block.number >= blockMeta) { epochRegulator(); generationId = 1; } /// @dev Be sure the mint is open if condition are favorable if (block.number < blockMeta && generationId <= maxGenerationSupply) { generationMintAllowed = true; } require(maxTokenSupply >= tokenId, "error maxTokenSupply"); require(epoch > 0 && epoch < epochMax, "error epoch"); require(ownerOf(_genesisId) == msg.sender, "error ownerOf"); require(generationMintAllowed, "error generationMintAllowed"); require(generationId <= maxGenerationSupply, "error generationId"); require(epochMintingRegistry[0][_genesisId], "error epochMintingRegistry"); require(!epochMintingRegistry[epoch][_genesisId], "error epochMintingRegistry"); /// @dev Set { _genesisId } for { epoch } as true epochMintingRegistry[epoch][_genesisId] = true; /// @dev If { generationId } reaches { maxGenerationSupply } the modifier /// will set { generationMintAllowed } to false to stop the mint /// on this generation /// /// { generationId } is reset to 0 /// /// This condition will not block the function because as long as /// { block.number } >= { blockMeta } minting will reopen /// according and this condition will become obsolete until /// the condition is reached again if (generationId == maxGenerationSupply) { generationMintAllowed = false; generationId = 0; } } /// @notice Used to protect epoch block length from difficulty bomb of the /// Ethereum network. A difficulty bomb heavily increases the difficulty /// on the network, likely also causing an increase in block time. /// If the block time increases too much, the epoch generation could become /// exponentially higher than what is desired, ending with an undesired Ice-Age. /// To protect against this, the emergencySecure() function is allowed to /// manually reconfigure the epoch block length and the block Meta /// to match the network conditions if necessary. /// /// It can also be useful if the block time decreases for some reason with consensus change. /// /// This function is dedicated to contract owner according to { onlyOwner } modifier function emergencySecure(uint256 _epoch, uint256 _epochLen, uint256 _blockMeta, uint256 _inflateRatio) public onlyOwner { require(epoch > 0, "error epoch"); require(_epoch > 0, "error _epoch"); require(maxTokenSupply >= tokenId, "error maxTokenSupply"); epoch = _epoch; epochLen = _epochLen; blockMeta = _blockMeta; inflateRatio = _inflateRatio; computeBlockOmega(); emit Securized(epoch, epochLen, blockMeta, inflateRatio); } /// @notice Used to compute blockOmega() function, { blockOmega } represents /// the block when it won't ever be possible to mint another Dollars Nakamoto NFT. /// It is possible to be computed because of the deterministic state of the current protocol /// The following algorithm simulate the 10 epochs of the protocol block computation to result blockOmega function computeBlockOmega() private { uint256 i = 0; uint256 _blockMeta = 0; uint256 _epochLen = epochLen; while (i < epochMax) { if (i > 0) _epochLen *= inflateRatio; if (i == 9) { blockOmega = blockGenesis + _blockMeta; emit Omega(blockOmega); break; } _blockMeta += _epochLen; i++; } } /// @notice Used to regulate the epoch incrementation and block computation, known as Metas /// @dev When epoch=0, the { blockOmega } will be computed /// When epoch!=0 the block length { epochLen } will be multiplied /// by { inflateRatio } thus making the block length required for each /// epoch longer according /// /// { blockMeta } += { epochLen } result the exact block of the next Meta /// Allow generation mint after incrementing the epoch function epochRegulator() private { if (epoch == 0) computeBlockOmega(); if (epoch > 0) epochLen *= inflateRatio; blockMeta += epochLen; emit Meta(epoch, blockMeta); epoch++; if (block.number >= blockMeta && epoch < epochMax) { epochRegulator(); } generationMintAllowed = true; } // Mint functions ***************************************************** /// @notice Used to add/remove address from { _allowList } function setBatchGenesisAllowance(address[] memory batch) public onlyOwner { uint len = batch.length; require(len > 0, "error len"); uint i = 0; while (i < len) { _allowList[batch[i]] = _allowList[batch[i]] ? false : true; i++; } } /// @notice Used to transfer { _allowList } slot to another address function transferListSlot(address to) public { require(epoch == 0, "error epoch"); require(_allowList[msg.sender], "error msg.sender"); require(!_allowList[to], "error to"); _allowList[msg.sender] = false; _allowList[to] = true; } /// @notice Used to open the mint of Genesis NFT function setGenesisMint() public onlyOwner { genesisMintAllowed = true; } /// @notice Used to gift Genesis NFT, this function is dedicated /// to contract owner according to { onlyOwner } modifier function giftGenesis(address to) public onlyOwner { uint256 _genesisId = ++genesisId; setMetadata(tokenId, _genesisId, epoch); genesisController(_genesisId); mintUSDSat(to, tokenId++); } /// @notice Used to mint Genesis NFT, this function is payable /// the price of this function is equal to { genesisPrice }, /// require to be present on { _allowList } to call function mintGenesis() public payable { uint256 _genesisId = ++genesisId; setMetadata(tokenId, _genesisId, epoch); genesisController(_genesisId); require(genesisMintAllowed, "error genesisMintAllowed"); require(_allowList[msg.sender], "error allowList"); require(genesisPrice == msg.value, "error genesisPrice"); _allowList[msg.sender] = false; mintUSDSat(msg.sender, tokenId++); } /// @notice Used to gift Generation NFT, you need a Genesis NFT to call this function function giftGenerations(uint256 _genesisId, address to) public { ++generationId; generationController(_genesisId); setMetadata(tokenId, _genesisId, epoch); mintUSDSat(to, tokenId++); } /// @notice Used to mint Generation NFT, you need a Genesis NFT to call this function function mintGenerations(uint256 _genesisId) public { ++generationId; generationController(_genesisId); setMetadata(tokenId, _genesisId, epoch); mintUSDSat(msg.sender, tokenId++); } /// @notice Token is minted on { ADDRESS_SIGN } and instantly transferred to { msg.sender } as { to }, /// this is to ensure the token creation is signed with { ADDRESS_SIGN } /// This function is private and can be only called by the contract function mintUSDSat(address to, uint256 _tokenId) private { emit PermanentURI(_compileMetadata(_tokenId), _tokenId); _safeMint(ADDRESS_SIGN, _tokenId); emit Signed(epoch, _tokenId, block.number); _safeTransfer(ADDRESS_SIGN, to, _tokenId, ""); emit Minted(epoch, _tokenId, to); } // Contract URI functions ********************************************* /// @notice Used to set the { ContractCID } metadata from ipfs, /// this function is dedicated to contract owner according /// to { onlyOwner } modifier function setContractCID(string memory CID) public onlyOwner { ContractCID = string(abi.encodePacked("ipfs://", CID)); } /// @notice Used to render { ContractCID } as { contractURI } according to /// Opensea contract metadata standard function contractURI() public view virtual returns (string memory) { return ContractCID; } // Utilitaries functions ********************************************** /// @notice Used to fetch all entry for { epoch } into { epochMintingRegistry } function getMapRegisteryForEpoch(uint256 _epoch) public view returns (bool[210] memory result) { uint i = 1; while (i <= maxGenesisSupply) { result[i] = epochMintingRegistry[_epoch][i]; i++; } } /// @notice Used to fetch all { tokenIds } from { owner } function exposeHeldIds(address owner) public view returns(uint[] memory) { uint tokenCount = balanceOf(owner); uint[] memory tokenIds = new uint[](tokenCount); uint i = 0; while (i < tokenCount) { tokenIds[i] = tokenOfOwnerByIndex(owner, i); i++; } return tokenIds; } // ERC721 Spec functions ********************************************** /// @notice Used to render metadata as { tokenURI } according to ERC721 standard function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token"); return _compileMetadata(_tokenId); } /// @dev ERC721 required override function _beforeTokenTransfer(address from, address to, uint256 _tokenId) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, _tokenId); } /// @dev ERC721 required override function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } }
/// ``.. /// `.` `````.``.-````-`` `.` /// ` ``````.`..///.-..----. --..--`.-....`..-.```` ``` /// `` `.`..--...`:::/::-``..``..:-.://///---..-....----- /// ``-:::/+++:::/-.-///://oso+::++/--:--../+:/:..:-....-://:/:-`` /// `-+/++/+o+://+::-:soo+oosss+s+//o:/:--`--:://://:ooso/-.--.-:-.` /// ``.+ooso++o+:+:+sosyhsyshhddyo+:/sds/yoo++/+:--/--.--:..--..``.```` /// ``:++/---:+/::::///oyhhyy+++:hddhhNNho///ohosyhs+/-:/+/---.....-.. ` /// ``-:-...-/+///++///+o+:-:o+o/oydmNmNNdddhsoyo/oyyyho///:-.--.-.``. `` /// ```--`..-:+/:--:::-.-///++++ydsdNNMNdmMNMmNysddyoooosso+//-.-`....````` ..` /// .```:-:::/-.-+o++/+:/+/o/hNNNNhmdNMMNNMMdyydNNmdyys+++oo++-`--.:.-.`````... /// ..--.`-..`.-`-hh++-/:+shho+hsysyyhhhmNNmmNMMmNNNdmmy+:+sh/o+y/+-`+./::.```` ` /// -/` ``.-``.//o++y+//ssyh+hhdmmdmmddmhdmNdmdsh+oNNMmmddoodh/s:yss.--+.//+`.` `. /// `.`-.` -`..+h+yo++ooyyyyyoyhy+shmNNmmdhhdhyyhymdyyhdmshoohs+y:oy+/+o/:/++.`- .` /// ``.`.``-.-++syyyhhhhhhhhmhysosyyoooosssdhhhdmmdhdmdsy+ss+/+ho/hody-s+-:+::--`` ` /// .`` ``-//s+:ohmdmddNmNmhhshhddNNNhyyhhhdNNhmNNmNNmmyso+yhhso++hhdy.:/ ::-:--``.` /// .```.-`.//shdmNNmddyysohmMmdmNNmmNshdmNhso+-/ohNoyhmmsysosd++hy/osss/.:-o/-.:/--. /// ``..:++-+hhy/syhhhdhdNNddNMmNsNMNyyso+//:-.`-/..+hmdsmdy+ossos:+o/h/+..//-s.`.:::o/ /// `.-.oy//hm+o:-..-+/shdNNNNNNhsNdo/oyoyyhoh+/so//+/mNmyhh+/s+dy/+s::+:`-`-:s--:-.::+`-` /// .`:h-`+y+./oyhhdddhyohMMNmmNmdhoo/oyyhddhmNNNmhsoodmdhs+///++:+-:.:/--/-/o/--+//...:` /// ``+o``yoodNNNNNMhdyyo+ymhsymyshhyys+sssssNmdmmdmy+oso/++:://+/-`::-:--:/::+.//o:-.--: /// `:-:-`oNhyhdNNNmyys+/:://oohy++/+hmmmmNNNNhohydmmyhy++////ooy./----.-:---/::-o+:...-/ /// ``-.-` yms+mmNmMMmNho/:o++++hhh++:mMmNmmmNMNdhdms+ysyy//:-+o:.-.`.``.-:/::-:-+/y/.- -` /// ..:` hh+oNNmMNNNmss/:-+oyhs+o+.-yhdNmdhmmydmms+o///:///+/+--/`-``.o::/:-o//-/y::/.- /// `.-``hh+yNdmdohdy:++/./myhds/./shNhhyy++o:oyos/s+:s//+////.:- ...`--`..`-.:--o:+::` /// `-/+yyho.`.-+oso///+/Nmddh//y+:s:.../soy+:o+.:sdyo++++o:.-. `.:.:-```:.`:``/o:`:` /// ./.`..sMN+:::yh+s+ysyhhddh+ymdsd/:/+o+ysydhohoh/o+/so++o+/o.--..`-:::``:-`+-`:+--.` /// ``:``..-NNy++/yyysohmo+NNmy/+:+hMNmy+yydmNMNddhs:yyydmmmso:o///..-.-+-:o:/.o/-/+-`` /// ``+.`..-mMhsyo+++oo+yoshyyo+/`+hNmhyy+sdmdssssho-MMMNMNh//+/oo+/+:-....`.s+/`..-` /// .+ `oNMmdhhsohhmmydmNms/yy.oNmmdy+++/+ss+odNm+mNmdddo-s+:+/++/-:--//`/o+s/.-`` /// `/` dNNNhooddNmNymMNNdsoo+y+shhhmyymhss+hddms+hdhmdo+/+-/oo+/.///+sh:-/-s/` /// `::`hdNmh+ooNmdohNNMMmsooohh+oysydhdooo/syysodmNmys+/o+//+y/:.+/hmso.-//s- /// -+ohdmmhyhdysysyyhmysoyddhhoo+shdhdyddmddmNmmhssds/::/oo/..:/+Nmo+`-:so /// .oyhdmmNNdm+s:/:os/+/ssyyds+/ssdNNyhdmmhdmmdymymy///o:/``/+-dmdoo++:o` /// `ysyMNhhmoo+h-:/+o/+:.:/:/+doo+dNdhddmhmmmy++yhds/+-+::..o/+Nmosyhs+- /// s+dNNyNhsdhNhsy:+:oo/soo+dNmmooyosohMhsymmhyy+++:+:/+/-/o+yNh+hMNs. /// +yhNNMd+dmydmdy/+/sshydmhdNNmNooyhhhhshohmNh+:+oso++ssy+/odyhhNmh` /// `yyhdms+dMh+oyshhyhysdmNd+ohyNN+++mNddmNy+yo//+o/hddddymmyhosNmms` /// oydos:oMmhoyyhysssysdmMmNmhNmNNh/+mmNmddh+/+o+::+s+hmhmdyNNNNy: /// `/dNm/+Ndhy+oshdhhdyo::ohmdyhhNysy:smshmdo/o:so//:s++ymhyohdy-` /// `sNNN/hNm/:do+o:+/++++s:/+shyymmddy/ydmmh/s/+oss//oysy++o+o+` /// oNNMNmm:/hyy/:/o/+hhsosysoo-ohhhss/hmmhd/dyh++/soyooy++o+:. /// :/dMNh/smhh+//+s+--:+/so+ohhy/:sydmmmmm+/mdddhy++/ohs//-o/` /// `/odmhyhsyh++/-:+:::/:/o/:ooddy/+yodNNh+ydhmmmy++/hhyo+://` /// `:os/+o//oshss/yhs+//:+/-/:soooo/+sso+dddydss+:+sy///+:++ /// ./o/s//hhNho+shyyyoyyso+/ys+/+-:y+:/soooyyh++sNyo++/:/+ /// -/:osmmhyo:++++/+/osshdssooo/:/h//://++oyhsshmdo+//s/- /// .osmhydh::/+++/o+ohhysddyoo++os+-+++///yhhhmNs+o/:// /// -.++yss//////+/+/+soo++shyhsyy+::/:+y+yhdmdoo//:/:- /// ``.oss/:////++://+o//:://+oo-:o++/shhhmmh+o+++///-` /// ..:+++oo/+///ys:///://+::-sy+osh+osdyo+o/::/s:/y-` /// `odoyhds+/yysyydss+///+/:+oshdmNo+:+/oo/+++++:hy//` /// `://hyoyy/o/++shhy:+y:/:o/+omNmhsoohhsso+++:+o+sy:/++ /// -/---oddooss+oosy+ohNdo+++oyNhsdo/++shhhoo:s+oydmyo//o+ /// :y.`.``yyd++shoyydhhyymdhyyhyhhs+////+/+s/+:odmmyso.:ohy. /// .yy/o-..+h/+o/+//++ssoohhhssso+++:/:/yy+//sydmNddo+/./ohy+. /// .dmmhs+osdoos///o//++/+shdsoshoys+ssss++shmNNNyyds+:-s-//:+. /// -shmNmyhddsyss++/+ysddhyyydhdmyssNddyydyhNmdNmddso/::s:--`.-.` /// `+dmNhhdmddsooyyooossysshdhmoss+/+mNdyymydMdyMdyoo+/--/:/:`...-.` /// .:smNNMmsMNNmdhyyo/yymmdmdyo+ooooshysyysNNNmmmNyss/+o-`-:-/:```.`` ``` /// `.-+o/sdNNNmhdddNmmdsso/sdshyyyyhsdddyohymdmNdmmmmmyoo+/.... -os.`.``-.`` /// `/-:-/+.hymmmmdhmyNdMNmmhhs+sosoyhddyddmmho/ooymhddhdhyos-.oy..-:o+:..`` ```` ` /// ..::``--.-hoymmdNNNNNNMmhyNh+oo+soyNdmNmmmysooooymhy+so++yo..:+.--`..:.`.` `-- ``.` ` /// ```-.-.``..`:ddymmmNNdmNNNNmhN: -/oys/sdmmNdydsydmhhsmdso+/yo:/-..`.``.` ``:.`.````-. ` /// ````-:/.```:::syyydmddNhNNdsdMMs`./oddmd./odNdy+yssss++ooo/o+//-`:/:..:`-.```/-:.`.```..`` ` /// ```..-`` --.`.--o+sNhoyMmho+omhmo+Ns::dhdmmdy:.oNoyhhs+/o+o++s+hhoo+.`-:....``.-:-`..-````.-``.`` /// @title Dollars Nakamoto by Pascal Boyart /// @author jolan.eth /// @notice This contract will allow you to yield farm Dollars Nakamoto NFT. /// During epoch 0 you will be able to mint a Genesis NFT, /// Over time, epoch will increment allowing you to mint more editions. /// Minting generations editions is allowed only 1 time per epoch and per Genesis NFT. /// Generations editions do not allow you to mint other generations.
NatSpecSingleLine
computeBlockOmega
function computeBlockOmega() private { uint256 i = 0; uint256 _blockMeta = 0; uint256 _epochLen = epochLen; while (i < epochMax) { if (i > 0) _epochLen *= inflateRatio; if (i == 9) { blockOmega = blockGenesis + _blockMeta; emit Omega(blockOmega); break; } _blockMeta += _epochLen; i++; } }
/// @notice Used to compute blockOmega() function, { blockOmega } represents /// the block when it won't ever be possible to mint another Dollars Nakamoto NFT. /// It is possible to be computed because of the deterministic state of the current protocol /// The following algorithm simulate the 10 epochs of the protocol block computation to result blockOmega
NatSpecSingleLine
v0.8.10+commit.fc410830
MIT
ipfs://627efb7c58e0f1a820013031c32ab417b2b86eb0e16948f99bf7e29ad6e50407
{ "func_code_index": [ 10573, 11040 ] }
2,673
USDSat
USDSat.sol
0xbeda58401038c864c9fc9145f28e47b7b00a0e86
Solidity
USDSat
contract USDSat is USDSatMetadata, ERC721, ERC721Enumerable, Ownable, ReentrancyGuard { string SYMBOL = "USDSat"; string NAME = "Dollars Nakamoto"; string ContractCID; /// @notice Address used to sign NFT on mint address public ADDRESS_SIGN = 0x1Af70e564847bE46e4bA286c0b0066Da8372F902; /// @notice Ether shareholder address address public ADDRESS_PBOY = 0x709e17B3Ec505F80eAb064d0F2A71c743cE225B3; /// @notice Ether shareholder address address public ADDRESS_JOLAN = 0x51BdFa2Cbb25591AF58b202aCdcdB33325a325c2; /// @notice Equity per shareholder in % uint256 public SHARE_PBOY = 90; /// @notice Equity per shareholder in % uint256 public SHARE_JOLAN = 10; /// @notice Mapping used to represent allowed addresses to call { mintGenesis } mapping (address => bool) public _allowList; /// @notice Represent the current epoch uint256 public epoch = 0; /// @notice Represent the maximum epoch possible uint256 public epochMax = 10; /// @notice Represent the block length of an epoch uint256 public epochLen = 41016; /// @notice Index of the NFT /// @dev Start at 1 because var++ uint256 public tokenId = 1; /// @notice Index of the Genesis NFT /// @dev Start at 0 because ++var uint256 public genesisId = 0; /// @notice Index of the Generation NFT /// @dev Start at 0 because ++var uint256 public generationId = 0; /// @notice Maximum total supply uint256 public maxTokenSupply = 2100; /// @notice Maximum Genesis supply uint256 public maxGenesisSupply = 210; /// @notice Maximum supply per generation uint256 public maxGenerationSupply = 210; /// @notice Price of the Genesis NFT (Generations NFT are free) uint256 public genesisPrice = 0.5 ether; /// @notice Define the ending block uint256 public blockOmega; /// @notice Define the starting block uint256 public blockGenesis; /// @notice Define in which block the Meta must occur uint256 public blockMeta; /// @notice Used to inflate blockMeta each epoch incrementation uint256 public inflateRatio = 2; /// @notice Open Genesis mint when true bool public genesisMintAllowed = false; /// @notice Open Generation mint when true bool public generationMintAllowed = false; /// @notice Multi dimensionnal mapping to keep a track of the minting reentrancy over epoch mapping(uint256 => mapping(uint256 => bool)) public epochMintingRegistry; event Omega(uint256 _blockNumber); event Genesis(uint256 indexed _epoch, uint256 _blockNumber); event Meta(uint256 indexed _epoch, uint256 _blockNumber); event Withdraw(uint256 indexed _share, address _shareholder); event Shareholder(uint256 indexed _sharePercent, address _shareholder); event Securized(uint256 indexed _epoch, uint256 _epochLen, uint256 _blockMeta, uint256 _inflateRatio); event PermanentURI(string _value, uint256 indexed _id); event Minted(uint256 indexed _epoch, uint256 indexed _tokenId, address indexed _owner); event Signed(uint256 indexed _epoch, uint256 indexed _tokenId, uint256 indexed _blockNumber); constructor() ERC721(NAME, SYMBOL) {} // Withdraw functions ************************************************* /// @notice Allow Pboy to modify ADDRESS_PBOY /// This function is dedicated to the represented shareholder according to require(). function setPboy(address PBOY) public { require(msg.sender == ADDRESS_PBOY, "error msg.sender"); ADDRESS_PBOY = PBOY; emit Shareholder(SHARE_PBOY, ADDRESS_PBOY); } /// @notice Allow Jolan to modify ADDRESS_JOLAN /// This function is dedicated to the represented shareholder according to require(). function setJolan(address JOLAN) public { require(msg.sender == ADDRESS_JOLAN, "error msg.sender"); ADDRESS_JOLAN = JOLAN; emit Shareholder(SHARE_JOLAN, ADDRESS_JOLAN); } /// @notice Used to withdraw ETH balance of the contract, this function is dedicated /// to contract owner according to { onlyOwner } modifier. function withdrawEquity() public onlyOwner nonReentrant { uint256 balance = address(this).balance; address[2] memory shareholders = [ ADDRESS_PBOY, ADDRESS_JOLAN ]; uint256[2] memory _shares = [ SHARE_PBOY * balance / 100, SHARE_JOLAN * balance / 100 ]; uint i = 0; while (i < 2) { require(payable(shareholders[i]).send(_shares[i])); emit Withdraw(_shares[i], shareholders[i]); i++; } } // Epoch functions **************************************************** /// @notice Used to manage authorization and reentrancy of the genesis NFT mint /// @param _genesisId Used to increment { genesisId } and write { epochMintingRegistry } function genesisController(uint256 _genesisId) private { require(epoch == 0, "error epoch"); require(genesisId <= maxGenesisSupply, "error genesisId"); require(!epochMintingRegistry[epoch][_genesisId], "error epochMintingRegistry"); /// @dev Set { _genesisId } for { epoch } as true epochMintingRegistry[epoch][_genesisId] = true; /// @dev When { genesisId } reaches { maxGenesisSupply } the function /// will compute the data to increment the epoch according /// /// { blockGenesis } is set only once, at this time /// { blockMeta } is set to { blockGenesis } because epoch=0 /// Then it is computed into the function epochRegulator() /// /// Once the epoch is regulated, the new generation start /// straight away, { generationMintAllowed } is set to true if (genesisId == maxGenesisSupply) { blockGenesis = block.number; blockMeta = blockGenesis; emit Genesis(epoch, blockGenesis); epochRegulator(); } } /// @notice Used to manage authorization and reentrancy of the Generation NFT mint /// @param _genesisId Used to write { epochMintingRegistry } and verify minting allowance function generationController(uint256 _genesisId) private { require(blockGenesis > 0, "error blockGenesis"); require(blockMeta > 0, "error blockMeta"); require(blockOmega > 0, "error blockOmega"); /// @dev If { block.number } >= { blockMeta } the function /// will compute the data to increment the epoch according /// /// Once the epoch is regulated, the new generation start /// straight away, { generationMintAllowed } is set to true /// /// { generationId } is reset to 1 if (block.number >= blockMeta) { epochRegulator(); generationId = 1; } /// @dev Be sure the mint is open if condition are favorable if (block.number < blockMeta && generationId <= maxGenerationSupply) { generationMintAllowed = true; } require(maxTokenSupply >= tokenId, "error maxTokenSupply"); require(epoch > 0 && epoch < epochMax, "error epoch"); require(ownerOf(_genesisId) == msg.sender, "error ownerOf"); require(generationMintAllowed, "error generationMintAllowed"); require(generationId <= maxGenerationSupply, "error generationId"); require(epochMintingRegistry[0][_genesisId], "error epochMintingRegistry"); require(!epochMintingRegistry[epoch][_genesisId], "error epochMintingRegistry"); /// @dev Set { _genesisId } for { epoch } as true epochMintingRegistry[epoch][_genesisId] = true; /// @dev If { generationId } reaches { maxGenerationSupply } the modifier /// will set { generationMintAllowed } to false to stop the mint /// on this generation /// /// { generationId } is reset to 0 /// /// This condition will not block the function because as long as /// { block.number } >= { blockMeta } minting will reopen /// according and this condition will become obsolete until /// the condition is reached again if (generationId == maxGenerationSupply) { generationMintAllowed = false; generationId = 0; } } /// @notice Used to protect epoch block length from difficulty bomb of the /// Ethereum network. A difficulty bomb heavily increases the difficulty /// on the network, likely also causing an increase in block time. /// If the block time increases too much, the epoch generation could become /// exponentially higher than what is desired, ending with an undesired Ice-Age. /// To protect against this, the emergencySecure() function is allowed to /// manually reconfigure the epoch block length and the block Meta /// to match the network conditions if necessary. /// /// It can also be useful if the block time decreases for some reason with consensus change. /// /// This function is dedicated to contract owner according to { onlyOwner } modifier function emergencySecure(uint256 _epoch, uint256 _epochLen, uint256 _blockMeta, uint256 _inflateRatio) public onlyOwner { require(epoch > 0, "error epoch"); require(_epoch > 0, "error _epoch"); require(maxTokenSupply >= tokenId, "error maxTokenSupply"); epoch = _epoch; epochLen = _epochLen; blockMeta = _blockMeta; inflateRatio = _inflateRatio; computeBlockOmega(); emit Securized(epoch, epochLen, blockMeta, inflateRatio); } /// @notice Used to compute blockOmega() function, { blockOmega } represents /// the block when it won't ever be possible to mint another Dollars Nakamoto NFT. /// It is possible to be computed because of the deterministic state of the current protocol /// The following algorithm simulate the 10 epochs of the protocol block computation to result blockOmega function computeBlockOmega() private { uint256 i = 0; uint256 _blockMeta = 0; uint256 _epochLen = epochLen; while (i < epochMax) { if (i > 0) _epochLen *= inflateRatio; if (i == 9) { blockOmega = blockGenesis + _blockMeta; emit Omega(blockOmega); break; } _blockMeta += _epochLen; i++; } } /// @notice Used to regulate the epoch incrementation and block computation, known as Metas /// @dev When epoch=0, the { blockOmega } will be computed /// When epoch!=0 the block length { epochLen } will be multiplied /// by { inflateRatio } thus making the block length required for each /// epoch longer according /// /// { blockMeta } += { epochLen } result the exact block of the next Meta /// Allow generation mint after incrementing the epoch function epochRegulator() private { if (epoch == 0) computeBlockOmega(); if (epoch > 0) epochLen *= inflateRatio; blockMeta += epochLen; emit Meta(epoch, blockMeta); epoch++; if (block.number >= blockMeta && epoch < epochMax) { epochRegulator(); } generationMintAllowed = true; } // Mint functions ***************************************************** /// @notice Used to add/remove address from { _allowList } function setBatchGenesisAllowance(address[] memory batch) public onlyOwner { uint len = batch.length; require(len > 0, "error len"); uint i = 0; while (i < len) { _allowList[batch[i]] = _allowList[batch[i]] ? false : true; i++; } } /// @notice Used to transfer { _allowList } slot to another address function transferListSlot(address to) public { require(epoch == 0, "error epoch"); require(_allowList[msg.sender], "error msg.sender"); require(!_allowList[to], "error to"); _allowList[msg.sender] = false; _allowList[to] = true; } /// @notice Used to open the mint of Genesis NFT function setGenesisMint() public onlyOwner { genesisMintAllowed = true; } /// @notice Used to gift Genesis NFT, this function is dedicated /// to contract owner according to { onlyOwner } modifier function giftGenesis(address to) public onlyOwner { uint256 _genesisId = ++genesisId; setMetadata(tokenId, _genesisId, epoch); genesisController(_genesisId); mintUSDSat(to, tokenId++); } /// @notice Used to mint Genesis NFT, this function is payable /// the price of this function is equal to { genesisPrice }, /// require to be present on { _allowList } to call function mintGenesis() public payable { uint256 _genesisId = ++genesisId; setMetadata(tokenId, _genesisId, epoch); genesisController(_genesisId); require(genesisMintAllowed, "error genesisMintAllowed"); require(_allowList[msg.sender], "error allowList"); require(genesisPrice == msg.value, "error genesisPrice"); _allowList[msg.sender] = false; mintUSDSat(msg.sender, tokenId++); } /// @notice Used to gift Generation NFT, you need a Genesis NFT to call this function function giftGenerations(uint256 _genesisId, address to) public { ++generationId; generationController(_genesisId); setMetadata(tokenId, _genesisId, epoch); mintUSDSat(to, tokenId++); } /// @notice Used to mint Generation NFT, you need a Genesis NFT to call this function function mintGenerations(uint256 _genesisId) public { ++generationId; generationController(_genesisId); setMetadata(tokenId, _genesisId, epoch); mintUSDSat(msg.sender, tokenId++); } /// @notice Token is minted on { ADDRESS_SIGN } and instantly transferred to { msg.sender } as { to }, /// this is to ensure the token creation is signed with { ADDRESS_SIGN } /// This function is private and can be only called by the contract function mintUSDSat(address to, uint256 _tokenId) private { emit PermanentURI(_compileMetadata(_tokenId), _tokenId); _safeMint(ADDRESS_SIGN, _tokenId); emit Signed(epoch, _tokenId, block.number); _safeTransfer(ADDRESS_SIGN, to, _tokenId, ""); emit Minted(epoch, _tokenId, to); } // Contract URI functions ********************************************* /// @notice Used to set the { ContractCID } metadata from ipfs, /// this function is dedicated to contract owner according /// to { onlyOwner } modifier function setContractCID(string memory CID) public onlyOwner { ContractCID = string(abi.encodePacked("ipfs://", CID)); } /// @notice Used to render { ContractCID } as { contractURI } according to /// Opensea contract metadata standard function contractURI() public view virtual returns (string memory) { return ContractCID; } // Utilitaries functions ********************************************** /// @notice Used to fetch all entry for { epoch } into { epochMintingRegistry } function getMapRegisteryForEpoch(uint256 _epoch) public view returns (bool[210] memory result) { uint i = 1; while (i <= maxGenesisSupply) { result[i] = epochMintingRegistry[_epoch][i]; i++; } } /// @notice Used to fetch all { tokenIds } from { owner } function exposeHeldIds(address owner) public view returns(uint[] memory) { uint tokenCount = balanceOf(owner); uint[] memory tokenIds = new uint[](tokenCount); uint i = 0; while (i < tokenCount) { tokenIds[i] = tokenOfOwnerByIndex(owner, i); i++; } return tokenIds; } // ERC721 Spec functions ********************************************** /// @notice Used to render metadata as { tokenURI } according to ERC721 standard function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token"); return _compileMetadata(_tokenId); } /// @dev ERC721 required override function _beforeTokenTransfer(address from, address to, uint256 _tokenId) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, _tokenId); } /// @dev ERC721 required override function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } }
/// ``.. /// `.` `````.``.-````-`` `.` /// ` ``````.`..///.-..----. --..--`.-....`..-.```` ``` /// `` `.`..--...`:::/::-``..``..:-.://///---..-....----- /// ``-:::/+++:::/-.-///://oso+::++/--:--../+:/:..:-....-://:/:-`` /// `-+/++/+o+://+::-:soo+oosss+s+//o:/:--`--:://://:ooso/-.--.-:-.` /// ``.+ooso++o+:+:+sosyhsyshhddyo+:/sds/yoo++/+:--/--.--:..--..``.```` /// ``:++/---:+/::::///oyhhyy+++:hddhhNNho///ohosyhs+/-:/+/---.....-.. ` /// ``-:-...-/+///++///+o+:-:o+o/oydmNmNNdddhsoyo/oyyyho///:-.--.-.``. `` /// ```--`..-:+/:--:::-.-///++++ydsdNNMNdmMNMmNysddyoooosso+//-.-`....````` ..` /// .```:-:::/-.-+o++/+:/+/o/hNNNNhmdNMMNNMMdyydNNmdyys+++oo++-`--.:.-.`````... /// ..--.`-..`.-`-hh++-/:+shho+hsysyyhhhmNNmmNMMmNNNdmmy+:+sh/o+y/+-`+./::.```` ` /// -/` ``.-``.//o++y+//ssyh+hhdmmdmmddmhdmNdmdsh+oNNMmmddoodh/s:yss.--+.//+`.` `. /// `.`-.` -`..+h+yo++ooyyyyyoyhy+shmNNmmdhhdhyyhymdyyhdmshoohs+y:oy+/+o/:/++.`- .` /// ``.`.``-.-++syyyhhhhhhhhmhysosyyoooosssdhhhdmmdhdmdsy+ss+/+ho/hody-s+-:+::--`` ` /// .`` ``-//s+:ohmdmddNmNmhhshhddNNNhyyhhhdNNhmNNmNNmmyso+yhhso++hhdy.:/ ::-:--``.` /// .```.-`.//shdmNNmddyysohmMmdmNNmmNshdmNhso+-/ohNoyhmmsysosd++hy/osss/.:-o/-.:/--. /// ``..:++-+hhy/syhhhdhdNNddNMmNsNMNyyso+//:-.`-/..+hmdsmdy+ossos:+o/h/+..//-s.`.:::o/ /// `.-.oy//hm+o:-..-+/shdNNNNNNhsNdo/oyoyyhoh+/so//+/mNmyhh+/s+dy/+s::+:`-`-:s--:-.::+`-` /// .`:h-`+y+./oyhhdddhyohMMNmmNmdhoo/oyyhddhmNNNmhsoodmdhs+///++:+-:.:/--/-/o/--+//...:` /// ``+o``yoodNNNNNMhdyyo+ymhsymyshhyys+sssssNmdmmdmy+oso/++:://+/-`::-:--:/::+.//o:-.--: /// `:-:-`oNhyhdNNNmyys+/:://oohy++/+hmmmmNNNNhohydmmyhy++////ooy./----.-:---/::-o+:...-/ /// ``-.-` yms+mmNmMMmNho/:o++++hhh++:mMmNmmmNMNdhdms+ysyy//:-+o:.-.`.``.-:/::-:-+/y/.- -` /// ..:` hh+oNNmMNNNmss/:-+oyhs+o+.-yhdNmdhmmydmms+o///:///+/+--/`-``.o::/:-o//-/y::/.- /// `.-``hh+yNdmdohdy:++/./myhds/./shNhhyy++o:oyos/s+:s//+////.:- ...`--`..`-.:--o:+::` /// `-/+yyho.`.-+oso///+/Nmddh//y+:s:.../soy+:o+.:sdyo++++o:.-. `.:.:-```:.`:``/o:`:` /// ./.`..sMN+:::yh+s+ysyhhddh+ymdsd/:/+o+ysydhohoh/o+/so++o+/o.--..`-:::``:-`+-`:+--.` /// ``:``..-NNy++/yyysohmo+NNmy/+:+hMNmy+yydmNMNddhs:yyydmmmso:o///..-.-+-:o:/.o/-/+-`` /// ``+.`..-mMhsyo+++oo+yoshyyo+/`+hNmhyy+sdmdssssho-MMMNMNh//+/oo+/+:-....`.s+/`..-` /// .+ `oNMmdhhsohhmmydmNms/yy.oNmmdy+++/+ss+odNm+mNmdddo-s+:+/++/-:--//`/o+s/.-`` /// `/` dNNNhooddNmNymMNNdsoo+y+shhhmyymhss+hddms+hdhmdo+/+-/oo+/.///+sh:-/-s/` /// `::`hdNmh+ooNmdohNNMMmsooohh+oysydhdooo/syysodmNmys+/o+//+y/:.+/hmso.-//s- /// -+ohdmmhyhdysysyyhmysoyddhhoo+shdhdyddmddmNmmhssds/::/oo/..:/+Nmo+`-:so /// .oyhdmmNNdm+s:/:os/+/ssyyds+/ssdNNyhdmmhdmmdymymy///o:/``/+-dmdoo++:o` /// `ysyMNhhmoo+h-:/+o/+:.:/:/+doo+dNdhddmhmmmy++yhds/+-+::..o/+Nmosyhs+- /// s+dNNyNhsdhNhsy:+:oo/soo+dNmmooyosohMhsymmhyy+++:+:/+/-/o+yNh+hMNs. /// +yhNNMd+dmydmdy/+/sshydmhdNNmNooyhhhhshohmNh+:+oso++ssy+/odyhhNmh` /// `yyhdms+dMh+oyshhyhysdmNd+ohyNN+++mNddmNy+yo//+o/hddddymmyhosNmms` /// oydos:oMmhoyyhysssysdmMmNmhNmNNh/+mmNmddh+/+o+::+s+hmhmdyNNNNy: /// `/dNm/+Ndhy+oshdhhdyo::ohmdyhhNysy:smshmdo/o:so//:s++ymhyohdy-` /// `sNNN/hNm/:do+o:+/++++s:/+shyymmddy/ydmmh/s/+oss//oysy++o+o+` /// oNNMNmm:/hyy/:/o/+hhsosysoo-ohhhss/hmmhd/dyh++/soyooy++o+:. /// :/dMNh/smhh+//+s+--:+/so+ohhy/:sydmmmmm+/mdddhy++/ohs//-o/` /// `/odmhyhsyh++/-:+:::/:/o/:ooddy/+yodNNh+ydhmmmy++/hhyo+://` /// `:os/+o//oshss/yhs+//:+/-/:soooo/+sso+dddydss+:+sy///+:++ /// ./o/s//hhNho+shyyyoyyso+/ys+/+-:y+:/soooyyh++sNyo++/:/+ /// -/:osmmhyo:++++/+/osshdssooo/:/h//://++oyhsshmdo+//s/- /// .osmhydh::/+++/o+ohhysddyoo++os+-+++///yhhhmNs+o/:// /// -.++yss//////+/+/+soo++shyhsyy+::/:+y+yhdmdoo//:/:- /// ``.oss/:////++://+o//:://+oo-:o++/shhhmmh+o+++///-` /// ..:+++oo/+///ys:///://+::-sy+osh+osdyo+o/::/s:/y-` /// `odoyhds+/yysyydss+///+/:+oshdmNo+:+/oo/+++++:hy//` /// `://hyoyy/o/++shhy:+y:/:o/+omNmhsoohhsso+++:+o+sy:/++ /// -/---oddooss+oosy+ohNdo+++oyNhsdo/++shhhoo:s+oydmyo//o+ /// :y.`.``yyd++shoyydhhyymdhyyhyhhs+////+/+s/+:odmmyso.:ohy. /// .yy/o-..+h/+o/+//++ssoohhhssso+++:/:/yy+//sydmNddo+/./ohy+. /// .dmmhs+osdoos///o//++/+shdsoshoys+ssss++shmNNNyyds+:-s-//:+. /// -shmNmyhddsyss++/+ysddhyyydhdmyssNddyydyhNmdNmddso/::s:--`.-.` /// `+dmNhhdmddsooyyooossysshdhmoss+/+mNdyymydMdyMdyoo+/--/:/:`...-.` /// .:smNNMmsMNNmdhyyo/yymmdmdyo+ooooshysyysNNNmmmNyss/+o-`-:-/:```.`` ``` /// `.-+o/sdNNNmhdddNmmdsso/sdshyyyyhsdddyohymdmNdmmmmmyoo+/.... -os.`.``-.`` /// `/-:-/+.hymmmmdhmyNdMNmmhhs+sosoyhddyddmmho/ooymhddhdhyos-.oy..-:o+:..`` ```` ` /// ..::``--.-hoymmdNNNNNNMmhyNh+oo+soyNdmNmmmysooooymhy+so++yo..:+.--`..:.`.` `-- ``.` ` /// ```-.-.``..`:ddymmmNNdmNNNNmhN: -/oys/sdmmNdydsydmhhsmdso+/yo:/-..`.``.` ``:.`.````-. ` /// ````-:/.```:::syyydmddNhNNdsdMMs`./oddmd./odNdy+yssss++ooo/o+//-`:/:..:`-.```/-:.`.```..`` ` /// ```..-`` --.`.--o+sNhoyMmho+omhmo+Ns::dhdmmdy:.oNoyhhs+/o+o++s+hhoo+.`-:....``.-:-`..-````.-``.`` /// @title Dollars Nakamoto by Pascal Boyart /// @author jolan.eth /// @notice This contract will allow you to yield farm Dollars Nakamoto NFT. /// During epoch 0 you will be able to mint a Genesis NFT, /// Over time, epoch will increment allowing you to mint more editions. /// Minting generations editions is allowed only 1 time per epoch and per Genesis NFT. /// Generations editions do not allow you to mint other generations.
NatSpecSingleLine
epochRegulator
function epochRegulator() private { if (epoch == 0) computeBlockOmega(); if (epoch > 0) epochLen *= inflateRatio; blockMeta += epochLen; emit Meta(epoch, blockMeta); epoch++; if (block.number >= blockMeta && epoch < epochMax) { epochRegulator(); } generationMintAllowed = true; }
/// @notice Used to regulate the epoch incrementation and block computation, known as Metas /// @dev When epoch=0, the { blockOmega } will be computed /// When epoch!=0 the block length { epochLen } will be multiplied /// by { inflateRatio } thus making the block length required for each /// epoch longer according /// /// { blockMeta } += { epochLen } result the exact block of the next Meta /// Allow generation mint after incrementing the epoch
NatSpecSingleLine
v0.8.10+commit.fc410830
MIT
ipfs://627efb7c58e0f1a820013031c32ab417b2b86eb0e16948f99bf7e29ad6e50407
{ "func_code_index": [ 11557, 11960 ] }
2,674
USDSat
USDSat.sol
0xbeda58401038c864c9fc9145f28e47b7b00a0e86
Solidity
USDSat
contract USDSat is USDSatMetadata, ERC721, ERC721Enumerable, Ownable, ReentrancyGuard { string SYMBOL = "USDSat"; string NAME = "Dollars Nakamoto"; string ContractCID; /// @notice Address used to sign NFT on mint address public ADDRESS_SIGN = 0x1Af70e564847bE46e4bA286c0b0066Da8372F902; /// @notice Ether shareholder address address public ADDRESS_PBOY = 0x709e17B3Ec505F80eAb064d0F2A71c743cE225B3; /// @notice Ether shareholder address address public ADDRESS_JOLAN = 0x51BdFa2Cbb25591AF58b202aCdcdB33325a325c2; /// @notice Equity per shareholder in % uint256 public SHARE_PBOY = 90; /// @notice Equity per shareholder in % uint256 public SHARE_JOLAN = 10; /// @notice Mapping used to represent allowed addresses to call { mintGenesis } mapping (address => bool) public _allowList; /// @notice Represent the current epoch uint256 public epoch = 0; /// @notice Represent the maximum epoch possible uint256 public epochMax = 10; /// @notice Represent the block length of an epoch uint256 public epochLen = 41016; /// @notice Index of the NFT /// @dev Start at 1 because var++ uint256 public tokenId = 1; /// @notice Index of the Genesis NFT /// @dev Start at 0 because ++var uint256 public genesisId = 0; /// @notice Index of the Generation NFT /// @dev Start at 0 because ++var uint256 public generationId = 0; /// @notice Maximum total supply uint256 public maxTokenSupply = 2100; /// @notice Maximum Genesis supply uint256 public maxGenesisSupply = 210; /// @notice Maximum supply per generation uint256 public maxGenerationSupply = 210; /// @notice Price of the Genesis NFT (Generations NFT are free) uint256 public genesisPrice = 0.5 ether; /// @notice Define the ending block uint256 public blockOmega; /// @notice Define the starting block uint256 public blockGenesis; /// @notice Define in which block the Meta must occur uint256 public blockMeta; /// @notice Used to inflate blockMeta each epoch incrementation uint256 public inflateRatio = 2; /// @notice Open Genesis mint when true bool public genesisMintAllowed = false; /// @notice Open Generation mint when true bool public generationMintAllowed = false; /// @notice Multi dimensionnal mapping to keep a track of the minting reentrancy over epoch mapping(uint256 => mapping(uint256 => bool)) public epochMintingRegistry; event Omega(uint256 _blockNumber); event Genesis(uint256 indexed _epoch, uint256 _blockNumber); event Meta(uint256 indexed _epoch, uint256 _blockNumber); event Withdraw(uint256 indexed _share, address _shareholder); event Shareholder(uint256 indexed _sharePercent, address _shareholder); event Securized(uint256 indexed _epoch, uint256 _epochLen, uint256 _blockMeta, uint256 _inflateRatio); event PermanentURI(string _value, uint256 indexed _id); event Minted(uint256 indexed _epoch, uint256 indexed _tokenId, address indexed _owner); event Signed(uint256 indexed _epoch, uint256 indexed _tokenId, uint256 indexed _blockNumber); constructor() ERC721(NAME, SYMBOL) {} // Withdraw functions ************************************************* /// @notice Allow Pboy to modify ADDRESS_PBOY /// This function is dedicated to the represented shareholder according to require(). function setPboy(address PBOY) public { require(msg.sender == ADDRESS_PBOY, "error msg.sender"); ADDRESS_PBOY = PBOY; emit Shareholder(SHARE_PBOY, ADDRESS_PBOY); } /// @notice Allow Jolan to modify ADDRESS_JOLAN /// This function is dedicated to the represented shareholder according to require(). function setJolan(address JOLAN) public { require(msg.sender == ADDRESS_JOLAN, "error msg.sender"); ADDRESS_JOLAN = JOLAN; emit Shareholder(SHARE_JOLAN, ADDRESS_JOLAN); } /// @notice Used to withdraw ETH balance of the contract, this function is dedicated /// to contract owner according to { onlyOwner } modifier. function withdrawEquity() public onlyOwner nonReentrant { uint256 balance = address(this).balance; address[2] memory shareholders = [ ADDRESS_PBOY, ADDRESS_JOLAN ]; uint256[2] memory _shares = [ SHARE_PBOY * balance / 100, SHARE_JOLAN * balance / 100 ]; uint i = 0; while (i < 2) { require(payable(shareholders[i]).send(_shares[i])); emit Withdraw(_shares[i], shareholders[i]); i++; } } // Epoch functions **************************************************** /// @notice Used to manage authorization and reentrancy of the genesis NFT mint /// @param _genesisId Used to increment { genesisId } and write { epochMintingRegistry } function genesisController(uint256 _genesisId) private { require(epoch == 0, "error epoch"); require(genesisId <= maxGenesisSupply, "error genesisId"); require(!epochMintingRegistry[epoch][_genesisId], "error epochMintingRegistry"); /// @dev Set { _genesisId } for { epoch } as true epochMintingRegistry[epoch][_genesisId] = true; /// @dev When { genesisId } reaches { maxGenesisSupply } the function /// will compute the data to increment the epoch according /// /// { blockGenesis } is set only once, at this time /// { blockMeta } is set to { blockGenesis } because epoch=0 /// Then it is computed into the function epochRegulator() /// /// Once the epoch is regulated, the new generation start /// straight away, { generationMintAllowed } is set to true if (genesisId == maxGenesisSupply) { blockGenesis = block.number; blockMeta = blockGenesis; emit Genesis(epoch, blockGenesis); epochRegulator(); } } /// @notice Used to manage authorization and reentrancy of the Generation NFT mint /// @param _genesisId Used to write { epochMintingRegistry } and verify minting allowance function generationController(uint256 _genesisId) private { require(blockGenesis > 0, "error blockGenesis"); require(blockMeta > 0, "error blockMeta"); require(blockOmega > 0, "error blockOmega"); /// @dev If { block.number } >= { blockMeta } the function /// will compute the data to increment the epoch according /// /// Once the epoch is regulated, the new generation start /// straight away, { generationMintAllowed } is set to true /// /// { generationId } is reset to 1 if (block.number >= blockMeta) { epochRegulator(); generationId = 1; } /// @dev Be sure the mint is open if condition are favorable if (block.number < blockMeta && generationId <= maxGenerationSupply) { generationMintAllowed = true; } require(maxTokenSupply >= tokenId, "error maxTokenSupply"); require(epoch > 0 && epoch < epochMax, "error epoch"); require(ownerOf(_genesisId) == msg.sender, "error ownerOf"); require(generationMintAllowed, "error generationMintAllowed"); require(generationId <= maxGenerationSupply, "error generationId"); require(epochMintingRegistry[0][_genesisId], "error epochMintingRegistry"); require(!epochMintingRegistry[epoch][_genesisId], "error epochMintingRegistry"); /// @dev Set { _genesisId } for { epoch } as true epochMintingRegistry[epoch][_genesisId] = true; /// @dev If { generationId } reaches { maxGenerationSupply } the modifier /// will set { generationMintAllowed } to false to stop the mint /// on this generation /// /// { generationId } is reset to 0 /// /// This condition will not block the function because as long as /// { block.number } >= { blockMeta } minting will reopen /// according and this condition will become obsolete until /// the condition is reached again if (generationId == maxGenerationSupply) { generationMintAllowed = false; generationId = 0; } } /// @notice Used to protect epoch block length from difficulty bomb of the /// Ethereum network. A difficulty bomb heavily increases the difficulty /// on the network, likely also causing an increase in block time. /// If the block time increases too much, the epoch generation could become /// exponentially higher than what is desired, ending with an undesired Ice-Age. /// To protect against this, the emergencySecure() function is allowed to /// manually reconfigure the epoch block length and the block Meta /// to match the network conditions if necessary. /// /// It can also be useful if the block time decreases for some reason with consensus change. /// /// This function is dedicated to contract owner according to { onlyOwner } modifier function emergencySecure(uint256 _epoch, uint256 _epochLen, uint256 _blockMeta, uint256 _inflateRatio) public onlyOwner { require(epoch > 0, "error epoch"); require(_epoch > 0, "error _epoch"); require(maxTokenSupply >= tokenId, "error maxTokenSupply"); epoch = _epoch; epochLen = _epochLen; blockMeta = _blockMeta; inflateRatio = _inflateRatio; computeBlockOmega(); emit Securized(epoch, epochLen, blockMeta, inflateRatio); } /// @notice Used to compute blockOmega() function, { blockOmega } represents /// the block when it won't ever be possible to mint another Dollars Nakamoto NFT. /// It is possible to be computed because of the deterministic state of the current protocol /// The following algorithm simulate the 10 epochs of the protocol block computation to result blockOmega function computeBlockOmega() private { uint256 i = 0; uint256 _blockMeta = 0; uint256 _epochLen = epochLen; while (i < epochMax) { if (i > 0) _epochLen *= inflateRatio; if (i == 9) { blockOmega = blockGenesis + _blockMeta; emit Omega(blockOmega); break; } _blockMeta += _epochLen; i++; } } /// @notice Used to regulate the epoch incrementation and block computation, known as Metas /// @dev When epoch=0, the { blockOmega } will be computed /// When epoch!=0 the block length { epochLen } will be multiplied /// by { inflateRatio } thus making the block length required for each /// epoch longer according /// /// { blockMeta } += { epochLen } result the exact block of the next Meta /// Allow generation mint after incrementing the epoch function epochRegulator() private { if (epoch == 0) computeBlockOmega(); if (epoch > 0) epochLen *= inflateRatio; blockMeta += epochLen; emit Meta(epoch, blockMeta); epoch++; if (block.number >= blockMeta && epoch < epochMax) { epochRegulator(); } generationMintAllowed = true; } // Mint functions ***************************************************** /// @notice Used to add/remove address from { _allowList } function setBatchGenesisAllowance(address[] memory batch) public onlyOwner { uint len = batch.length; require(len > 0, "error len"); uint i = 0; while (i < len) { _allowList[batch[i]] = _allowList[batch[i]] ? false : true; i++; } } /// @notice Used to transfer { _allowList } slot to another address function transferListSlot(address to) public { require(epoch == 0, "error epoch"); require(_allowList[msg.sender], "error msg.sender"); require(!_allowList[to], "error to"); _allowList[msg.sender] = false; _allowList[to] = true; } /// @notice Used to open the mint of Genesis NFT function setGenesisMint() public onlyOwner { genesisMintAllowed = true; } /// @notice Used to gift Genesis NFT, this function is dedicated /// to contract owner according to { onlyOwner } modifier function giftGenesis(address to) public onlyOwner { uint256 _genesisId = ++genesisId; setMetadata(tokenId, _genesisId, epoch); genesisController(_genesisId); mintUSDSat(to, tokenId++); } /// @notice Used to mint Genesis NFT, this function is payable /// the price of this function is equal to { genesisPrice }, /// require to be present on { _allowList } to call function mintGenesis() public payable { uint256 _genesisId = ++genesisId; setMetadata(tokenId, _genesisId, epoch); genesisController(_genesisId); require(genesisMintAllowed, "error genesisMintAllowed"); require(_allowList[msg.sender], "error allowList"); require(genesisPrice == msg.value, "error genesisPrice"); _allowList[msg.sender] = false; mintUSDSat(msg.sender, tokenId++); } /// @notice Used to gift Generation NFT, you need a Genesis NFT to call this function function giftGenerations(uint256 _genesisId, address to) public { ++generationId; generationController(_genesisId); setMetadata(tokenId, _genesisId, epoch); mintUSDSat(to, tokenId++); } /// @notice Used to mint Generation NFT, you need a Genesis NFT to call this function function mintGenerations(uint256 _genesisId) public { ++generationId; generationController(_genesisId); setMetadata(tokenId, _genesisId, epoch); mintUSDSat(msg.sender, tokenId++); } /// @notice Token is minted on { ADDRESS_SIGN } and instantly transferred to { msg.sender } as { to }, /// this is to ensure the token creation is signed with { ADDRESS_SIGN } /// This function is private and can be only called by the contract function mintUSDSat(address to, uint256 _tokenId) private { emit PermanentURI(_compileMetadata(_tokenId), _tokenId); _safeMint(ADDRESS_SIGN, _tokenId); emit Signed(epoch, _tokenId, block.number); _safeTransfer(ADDRESS_SIGN, to, _tokenId, ""); emit Minted(epoch, _tokenId, to); } // Contract URI functions ********************************************* /// @notice Used to set the { ContractCID } metadata from ipfs, /// this function is dedicated to contract owner according /// to { onlyOwner } modifier function setContractCID(string memory CID) public onlyOwner { ContractCID = string(abi.encodePacked("ipfs://", CID)); } /// @notice Used to render { ContractCID } as { contractURI } according to /// Opensea contract metadata standard function contractURI() public view virtual returns (string memory) { return ContractCID; } // Utilitaries functions ********************************************** /// @notice Used to fetch all entry for { epoch } into { epochMintingRegistry } function getMapRegisteryForEpoch(uint256 _epoch) public view returns (bool[210] memory result) { uint i = 1; while (i <= maxGenesisSupply) { result[i] = epochMintingRegistry[_epoch][i]; i++; } } /// @notice Used to fetch all { tokenIds } from { owner } function exposeHeldIds(address owner) public view returns(uint[] memory) { uint tokenCount = balanceOf(owner); uint[] memory tokenIds = new uint[](tokenCount); uint i = 0; while (i < tokenCount) { tokenIds[i] = tokenOfOwnerByIndex(owner, i); i++; } return tokenIds; } // ERC721 Spec functions ********************************************** /// @notice Used to render metadata as { tokenURI } according to ERC721 standard function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token"); return _compileMetadata(_tokenId); } /// @dev ERC721 required override function _beforeTokenTransfer(address from, address to, uint256 _tokenId) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, _tokenId); } /// @dev ERC721 required override function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } }
/// ``.. /// `.` `````.``.-````-`` `.` /// ` ``````.`..///.-..----. --..--`.-....`..-.```` ``` /// `` `.`..--...`:::/::-``..``..:-.://///---..-....----- /// ``-:::/+++:::/-.-///://oso+::++/--:--../+:/:..:-....-://:/:-`` /// `-+/++/+o+://+::-:soo+oosss+s+//o:/:--`--:://://:ooso/-.--.-:-.` /// ``.+ooso++o+:+:+sosyhsyshhddyo+:/sds/yoo++/+:--/--.--:..--..``.```` /// ``:++/---:+/::::///oyhhyy+++:hddhhNNho///ohosyhs+/-:/+/---.....-.. ` /// ``-:-...-/+///++///+o+:-:o+o/oydmNmNNdddhsoyo/oyyyho///:-.--.-.``. `` /// ```--`..-:+/:--:::-.-///++++ydsdNNMNdmMNMmNysddyoooosso+//-.-`....````` ..` /// .```:-:::/-.-+o++/+:/+/o/hNNNNhmdNMMNNMMdyydNNmdyys+++oo++-`--.:.-.`````... /// ..--.`-..`.-`-hh++-/:+shho+hsysyyhhhmNNmmNMMmNNNdmmy+:+sh/o+y/+-`+./::.```` ` /// -/` ``.-``.//o++y+//ssyh+hhdmmdmmddmhdmNdmdsh+oNNMmmddoodh/s:yss.--+.//+`.` `. /// `.`-.` -`..+h+yo++ooyyyyyoyhy+shmNNmmdhhdhyyhymdyyhdmshoohs+y:oy+/+o/:/++.`- .` /// ``.`.``-.-++syyyhhhhhhhhmhysosyyoooosssdhhhdmmdhdmdsy+ss+/+ho/hody-s+-:+::--`` ` /// .`` ``-//s+:ohmdmddNmNmhhshhddNNNhyyhhhdNNhmNNmNNmmyso+yhhso++hhdy.:/ ::-:--``.` /// .```.-`.//shdmNNmddyysohmMmdmNNmmNshdmNhso+-/ohNoyhmmsysosd++hy/osss/.:-o/-.:/--. /// ``..:++-+hhy/syhhhdhdNNddNMmNsNMNyyso+//:-.`-/..+hmdsmdy+ossos:+o/h/+..//-s.`.:::o/ /// `.-.oy//hm+o:-..-+/shdNNNNNNhsNdo/oyoyyhoh+/so//+/mNmyhh+/s+dy/+s::+:`-`-:s--:-.::+`-` /// .`:h-`+y+./oyhhdddhyohMMNmmNmdhoo/oyyhddhmNNNmhsoodmdhs+///++:+-:.:/--/-/o/--+//...:` /// ``+o``yoodNNNNNMhdyyo+ymhsymyshhyys+sssssNmdmmdmy+oso/++:://+/-`::-:--:/::+.//o:-.--: /// `:-:-`oNhyhdNNNmyys+/:://oohy++/+hmmmmNNNNhohydmmyhy++////ooy./----.-:---/::-o+:...-/ /// ``-.-` yms+mmNmMMmNho/:o++++hhh++:mMmNmmmNMNdhdms+ysyy//:-+o:.-.`.``.-:/::-:-+/y/.- -` /// ..:` hh+oNNmMNNNmss/:-+oyhs+o+.-yhdNmdhmmydmms+o///:///+/+--/`-``.o::/:-o//-/y::/.- /// `.-``hh+yNdmdohdy:++/./myhds/./shNhhyy++o:oyos/s+:s//+////.:- ...`--`..`-.:--o:+::` /// `-/+yyho.`.-+oso///+/Nmddh//y+:s:.../soy+:o+.:sdyo++++o:.-. `.:.:-```:.`:``/o:`:` /// ./.`..sMN+:::yh+s+ysyhhddh+ymdsd/:/+o+ysydhohoh/o+/so++o+/o.--..`-:::``:-`+-`:+--.` /// ``:``..-NNy++/yyysohmo+NNmy/+:+hMNmy+yydmNMNddhs:yyydmmmso:o///..-.-+-:o:/.o/-/+-`` /// ``+.`..-mMhsyo+++oo+yoshyyo+/`+hNmhyy+sdmdssssho-MMMNMNh//+/oo+/+:-....`.s+/`..-` /// .+ `oNMmdhhsohhmmydmNms/yy.oNmmdy+++/+ss+odNm+mNmdddo-s+:+/++/-:--//`/o+s/.-`` /// `/` dNNNhooddNmNymMNNdsoo+y+shhhmyymhss+hddms+hdhmdo+/+-/oo+/.///+sh:-/-s/` /// `::`hdNmh+ooNmdohNNMMmsooohh+oysydhdooo/syysodmNmys+/o+//+y/:.+/hmso.-//s- /// -+ohdmmhyhdysysyyhmysoyddhhoo+shdhdyddmddmNmmhssds/::/oo/..:/+Nmo+`-:so /// .oyhdmmNNdm+s:/:os/+/ssyyds+/ssdNNyhdmmhdmmdymymy///o:/``/+-dmdoo++:o` /// `ysyMNhhmoo+h-:/+o/+:.:/:/+doo+dNdhddmhmmmy++yhds/+-+::..o/+Nmosyhs+- /// s+dNNyNhsdhNhsy:+:oo/soo+dNmmooyosohMhsymmhyy+++:+:/+/-/o+yNh+hMNs. /// +yhNNMd+dmydmdy/+/sshydmhdNNmNooyhhhhshohmNh+:+oso++ssy+/odyhhNmh` /// `yyhdms+dMh+oyshhyhysdmNd+ohyNN+++mNddmNy+yo//+o/hddddymmyhosNmms` /// oydos:oMmhoyyhysssysdmMmNmhNmNNh/+mmNmddh+/+o+::+s+hmhmdyNNNNy: /// `/dNm/+Ndhy+oshdhhdyo::ohmdyhhNysy:smshmdo/o:so//:s++ymhyohdy-` /// `sNNN/hNm/:do+o:+/++++s:/+shyymmddy/ydmmh/s/+oss//oysy++o+o+` /// oNNMNmm:/hyy/:/o/+hhsosysoo-ohhhss/hmmhd/dyh++/soyooy++o+:. /// :/dMNh/smhh+//+s+--:+/so+ohhy/:sydmmmmm+/mdddhy++/ohs//-o/` /// `/odmhyhsyh++/-:+:::/:/o/:ooddy/+yodNNh+ydhmmmy++/hhyo+://` /// `:os/+o//oshss/yhs+//:+/-/:soooo/+sso+dddydss+:+sy///+:++ /// ./o/s//hhNho+shyyyoyyso+/ys+/+-:y+:/soooyyh++sNyo++/:/+ /// -/:osmmhyo:++++/+/osshdssooo/:/h//://++oyhsshmdo+//s/- /// .osmhydh::/+++/o+ohhysddyoo++os+-+++///yhhhmNs+o/:// /// -.++yss//////+/+/+soo++shyhsyy+::/:+y+yhdmdoo//:/:- /// ``.oss/:////++://+o//:://+oo-:o++/shhhmmh+o+++///-` /// ..:+++oo/+///ys:///://+::-sy+osh+osdyo+o/::/s:/y-` /// `odoyhds+/yysyydss+///+/:+oshdmNo+:+/oo/+++++:hy//` /// `://hyoyy/o/++shhy:+y:/:o/+omNmhsoohhsso+++:+o+sy:/++ /// -/---oddooss+oosy+ohNdo+++oyNhsdo/++shhhoo:s+oydmyo//o+ /// :y.`.``yyd++shoyydhhyymdhyyhyhhs+////+/+s/+:odmmyso.:ohy. /// .yy/o-..+h/+o/+//++ssoohhhssso+++:/:/yy+//sydmNddo+/./ohy+. /// .dmmhs+osdoos///o//++/+shdsoshoys+ssss++shmNNNyyds+:-s-//:+. /// -shmNmyhddsyss++/+ysddhyyydhdmyssNddyydyhNmdNmddso/::s:--`.-.` /// `+dmNhhdmddsooyyooossysshdhmoss+/+mNdyymydMdyMdyoo+/--/:/:`...-.` /// .:smNNMmsMNNmdhyyo/yymmdmdyo+ooooshysyysNNNmmmNyss/+o-`-:-/:```.`` ``` /// `.-+o/sdNNNmhdddNmmdsso/sdshyyyyhsdddyohymdmNdmmmmmyoo+/.... -os.`.``-.`` /// `/-:-/+.hymmmmdhmyNdMNmmhhs+sosoyhddyddmmho/ooymhddhdhyos-.oy..-:o+:..`` ```` ` /// ..::``--.-hoymmdNNNNNNMmhyNh+oo+soyNdmNmmmysooooymhy+so++yo..:+.--`..:.`.` `-- ``.` ` /// ```-.-.``..`:ddymmmNNdmNNNNmhN: -/oys/sdmmNdydsydmhhsmdso+/yo:/-..`.``.` ``:.`.````-. ` /// ````-:/.```:::syyydmddNhNNdsdMMs`./oddmd./odNdy+yssss++ooo/o+//-`:/:..:`-.```/-:.`.```..`` ` /// ```..-`` --.`.--o+sNhoyMmho+omhmo+Ns::dhdmmdy:.oNoyhhs+/o+o++s+hhoo+.`-:....``.-:-`..-````.-``.`` /// @title Dollars Nakamoto by Pascal Boyart /// @author jolan.eth /// @notice This contract will allow you to yield farm Dollars Nakamoto NFT. /// During epoch 0 you will be able to mint a Genesis NFT, /// Over time, epoch will increment allowing you to mint more editions. /// Minting generations editions is allowed only 1 time per epoch and per Genesis NFT. /// Generations editions do not allow you to mint other generations.
NatSpecSingleLine
setBatchGenesisAllowance
function setBatchGenesisAllowance(address[] memory batch) public onlyOwner { uint len = batch.length; require(len > 0, "error len"); uint i = 0; while (i < len) { _allowList[batch[i]] = _allowList[batch[i]] ? false : true; i++; } }
/// @notice Used to add/remove address from { _allowList }
NatSpecSingleLine
v0.8.10+commit.fc410830
MIT
ipfs://627efb7c58e0f1a820013031c32ab417b2b86eb0e16948f99bf7e29ad6e50407
{ "func_code_index": [ 12106, 12446 ] }
2,675
USDSat
USDSat.sol
0xbeda58401038c864c9fc9145f28e47b7b00a0e86
Solidity
USDSat
contract USDSat is USDSatMetadata, ERC721, ERC721Enumerable, Ownable, ReentrancyGuard { string SYMBOL = "USDSat"; string NAME = "Dollars Nakamoto"; string ContractCID; /// @notice Address used to sign NFT on mint address public ADDRESS_SIGN = 0x1Af70e564847bE46e4bA286c0b0066Da8372F902; /// @notice Ether shareholder address address public ADDRESS_PBOY = 0x709e17B3Ec505F80eAb064d0F2A71c743cE225B3; /// @notice Ether shareholder address address public ADDRESS_JOLAN = 0x51BdFa2Cbb25591AF58b202aCdcdB33325a325c2; /// @notice Equity per shareholder in % uint256 public SHARE_PBOY = 90; /// @notice Equity per shareholder in % uint256 public SHARE_JOLAN = 10; /// @notice Mapping used to represent allowed addresses to call { mintGenesis } mapping (address => bool) public _allowList; /// @notice Represent the current epoch uint256 public epoch = 0; /// @notice Represent the maximum epoch possible uint256 public epochMax = 10; /// @notice Represent the block length of an epoch uint256 public epochLen = 41016; /// @notice Index of the NFT /// @dev Start at 1 because var++ uint256 public tokenId = 1; /// @notice Index of the Genesis NFT /// @dev Start at 0 because ++var uint256 public genesisId = 0; /// @notice Index of the Generation NFT /// @dev Start at 0 because ++var uint256 public generationId = 0; /// @notice Maximum total supply uint256 public maxTokenSupply = 2100; /// @notice Maximum Genesis supply uint256 public maxGenesisSupply = 210; /// @notice Maximum supply per generation uint256 public maxGenerationSupply = 210; /// @notice Price of the Genesis NFT (Generations NFT are free) uint256 public genesisPrice = 0.5 ether; /// @notice Define the ending block uint256 public blockOmega; /// @notice Define the starting block uint256 public blockGenesis; /// @notice Define in which block the Meta must occur uint256 public blockMeta; /// @notice Used to inflate blockMeta each epoch incrementation uint256 public inflateRatio = 2; /// @notice Open Genesis mint when true bool public genesisMintAllowed = false; /// @notice Open Generation mint when true bool public generationMintAllowed = false; /// @notice Multi dimensionnal mapping to keep a track of the minting reentrancy over epoch mapping(uint256 => mapping(uint256 => bool)) public epochMintingRegistry; event Omega(uint256 _blockNumber); event Genesis(uint256 indexed _epoch, uint256 _blockNumber); event Meta(uint256 indexed _epoch, uint256 _blockNumber); event Withdraw(uint256 indexed _share, address _shareholder); event Shareholder(uint256 indexed _sharePercent, address _shareholder); event Securized(uint256 indexed _epoch, uint256 _epochLen, uint256 _blockMeta, uint256 _inflateRatio); event PermanentURI(string _value, uint256 indexed _id); event Minted(uint256 indexed _epoch, uint256 indexed _tokenId, address indexed _owner); event Signed(uint256 indexed _epoch, uint256 indexed _tokenId, uint256 indexed _blockNumber); constructor() ERC721(NAME, SYMBOL) {} // Withdraw functions ************************************************* /// @notice Allow Pboy to modify ADDRESS_PBOY /// This function is dedicated to the represented shareholder according to require(). function setPboy(address PBOY) public { require(msg.sender == ADDRESS_PBOY, "error msg.sender"); ADDRESS_PBOY = PBOY; emit Shareholder(SHARE_PBOY, ADDRESS_PBOY); } /// @notice Allow Jolan to modify ADDRESS_JOLAN /// This function is dedicated to the represented shareholder according to require(). function setJolan(address JOLAN) public { require(msg.sender == ADDRESS_JOLAN, "error msg.sender"); ADDRESS_JOLAN = JOLAN; emit Shareholder(SHARE_JOLAN, ADDRESS_JOLAN); } /// @notice Used to withdraw ETH balance of the contract, this function is dedicated /// to contract owner according to { onlyOwner } modifier. function withdrawEquity() public onlyOwner nonReentrant { uint256 balance = address(this).balance; address[2] memory shareholders = [ ADDRESS_PBOY, ADDRESS_JOLAN ]; uint256[2] memory _shares = [ SHARE_PBOY * balance / 100, SHARE_JOLAN * balance / 100 ]; uint i = 0; while (i < 2) { require(payable(shareholders[i]).send(_shares[i])); emit Withdraw(_shares[i], shareholders[i]); i++; } } // Epoch functions **************************************************** /// @notice Used to manage authorization and reentrancy of the genesis NFT mint /// @param _genesisId Used to increment { genesisId } and write { epochMintingRegistry } function genesisController(uint256 _genesisId) private { require(epoch == 0, "error epoch"); require(genesisId <= maxGenesisSupply, "error genesisId"); require(!epochMintingRegistry[epoch][_genesisId], "error epochMintingRegistry"); /// @dev Set { _genesisId } for { epoch } as true epochMintingRegistry[epoch][_genesisId] = true; /// @dev When { genesisId } reaches { maxGenesisSupply } the function /// will compute the data to increment the epoch according /// /// { blockGenesis } is set only once, at this time /// { blockMeta } is set to { blockGenesis } because epoch=0 /// Then it is computed into the function epochRegulator() /// /// Once the epoch is regulated, the new generation start /// straight away, { generationMintAllowed } is set to true if (genesisId == maxGenesisSupply) { blockGenesis = block.number; blockMeta = blockGenesis; emit Genesis(epoch, blockGenesis); epochRegulator(); } } /// @notice Used to manage authorization and reentrancy of the Generation NFT mint /// @param _genesisId Used to write { epochMintingRegistry } and verify minting allowance function generationController(uint256 _genesisId) private { require(blockGenesis > 0, "error blockGenesis"); require(blockMeta > 0, "error blockMeta"); require(blockOmega > 0, "error blockOmega"); /// @dev If { block.number } >= { blockMeta } the function /// will compute the data to increment the epoch according /// /// Once the epoch is regulated, the new generation start /// straight away, { generationMintAllowed } is set to true /// /// { generationId } is reset to 1 if (block.number >= blockMeta) { epochRegulator(); generationId = 1; } /// @dev Be sure the mint is open if condition are favorable if (block.number < blockMeta && generationId <= maxGenerationSupply) { generationMintAllowed = true; } require(maxTokenSupply >= tokenId, "error maxTokenSupply"); require(epoch > 0 && epoch < epochMax, "error epoch"); require(ownerOf(_genesisId) == msg.sender, "error ownerOf"); require(generationMintAllowed, "error generationMintAllowed"); require(generationId <= maxGenerationSupply, "error generationId"); require(epochMintingRegistry[0][_genesisId], "error epochMintingRegistry"); require(!epochMintingRegistry[epoch][_genesisId], "error epochMintingRegistry"); /// @dev Set { _genesisId } for { epoch } as true epochMintingRegistry[epoch][_genesisId] = true; /// @dev If { generationId } reaches { maxGenerationSupply } the modifier /// will set { generationMintAllowed } to false to stop the mint /// on this generation /// /// { generationId } is reset to 0 /// /// This condition will not block the function because as long as /// { block.number } >= { blockMeta } minting will reopen /// according and this condition will become obsolete until /// the condition is reached again if (generationId == maxGenerationSupply) { generationMintAllowed = false; generationId = 0; } } /// @notice Used to protect epoch block length from difficulty bomb of the /// Ethereum network. A difficulty bomb heavily increases the difficulty /// on the network, likely also causing an increase in block time. /// If the block time increases too much, the epoch generation could become /// exponentially higher than what is desired, ending with an undesired Ice-Age. /// To protect against this, the emergencySecure() function is allowed to /// manually reconfigure the epoch block length and the block Meta /// to match the network conditions if necessary. /// /// It can also be useful if the block time decreases for some reason with consensus change. /// /// This function is dedicated to contract owner according to { onlyOwner } modifier function emergencySecure(uint256 _epoch, uint256 _epochLen, uint256 _blockMeta, uint256 _inflateRatio) public onlyOwner { require(epoch > 0, "error epoch"); require(_epoch > 0, "error _epoch"); require(maxTokenSupply >= tokenId, "error maxTokenSupply"); epoch = _epoch; epochLen = _epochLen; blockMeta = _blockMeta; inflateRatio = _inflateRatio; computeBlockOmega(); emit Securized(epoch, epochLen, blockMeta, inflateRatio); } /// @notice Used to compute blockOmega() function, { blockOmega } represents /// the block when it won't ever be possible to mint another Dollars Nakamoto NFT. /// It is possible to be computed because of the deterministic state of the current protocol /// The following algorithm simulate the 10 epochs of the protocol block computation to result blockOmega function computeBlockOmega() private { uint256 i = 0; uint256 _blockMeta = 0; uint256 _epochLen = epochLen; while (i < epochMax) { if (i > 0) _epochLen *= inflateRatio; if (i == 9) { blockOmega = blockGenesis + _blockMeta; emit Omega(blockOmega); break; } _blockMeta += _epochLen; i++; } } /// @notice Used to regulate the epoch incrementation and block computation, known as Metas /// @dev When epoch=0, the { blockOmega } will be computed /// When epoch!=0 the block length { epochLen } will be multiplied /// by { inflateRatio } thus making the block length required for each /// epoch longer according /// /// { blockMeta } += { epochLen } result the exact block of the next Meta /// Allow generation mint after incrementing the epoch function epochRegulator() private { if (epoch == 0) computeBlockOmega(); if (epoch > 0) epochLen *= inflateRatio; blockMeta += epochLen; emit Meta(epoch, blockMeta); epoch++; if (block.number >= blockMeta && epoch < epochMax) { epochRegulator(); } generationMintAllowed = true; } // Mint functions ***************************************************** /// @notice Used to add/remove address from { _allowList } function setBatchGenesisAllowance(address[] memory batch) public onlyOwner { uint len = batch.length; require(len > 0, "error len"); uint i = 0; while (i < len) { _allowList[batch[i]] = _allowList[batch[i]] ? false : true; i++; } } /// @notice Used to transfer { _allowList } slot to another address function transferListSlot(address to) public { require(epoch == 0, "error epoch"); require(_allowList[msg.sender], "error msg.sender"); require(!_allowList[to], "error to"); _allowList[msg.sender] = false; _allowList[to] = true; } /// @notice Used to open the mint of Genesis NFT function setGenesisMint() public onlyOwner { genesisMintAllowed = true; } /// @notice Used to gift Genesis NFT, this function is dedicated /// to contract owner according to { onlyOwner } modifier function giftGenesis(address to) public onlyOwner { uint256 _genesisId = ++genesisId; setMetadata(tokenId, _genesisId, epoch); genesisController(_genesisId); mintUSDSat(to, tokenId++); } /// @notice Used to mint Genesis NFT, this function is payable /// the price of this function is equal to { genesisPrice }, /// require to be present on { _allowList } to call function mintGenesis() public payable { uint256 _genesisId = ++genesisId; setMetadata(tokenId, _genesisId, epoch); genesisController(_genesisId); require(genesisMintAllowed, "error genesisMintAllowed"); require(_allowList[msg.sender], "error allowList"); require(genesisPrice == msg.value, "error genesisPrice"); _allowList[msg.sender] = false; mintUSDSat(msg.sender, tokenId++); } /// @notice Used to gift Generation NFT, you need a Genesis NFT to call this function function giftGenerations(uint256 _genesisId, address to) public { ++generationId; generationController(_genesisId); setMetadata(tokenId, _genesisId, epoch); mintUSDSat(to, tokenId++); } /// @notice Used to mint Generation NFT, you need a Genesis NFT to call this function function mintGenerations(uint256 _genesisId) public { ++generationId; generationController(_genesisId); setMetadata(tokenId, _genesisId, epoch); mintUSDSat(msg.sender, tokenId++); } /// @notice Token is minted on { ADDRESS_SIGN } and instantly transferred to { msg.sender } as { to }, /// this is to ensure the token creation is signed with { ADDRESS_SIGN } /// This function is private and can be only called by the contract function mintUSDSat(address to, uint256 _tokenId) private { emit PermanentURI(_compileMetadata(_tokenId), _tokenId); _safeMint(ADDRESS_SIGN, _tokenId); emit Signed(epoch, _tokenId, block.number); _safeTransfer(ADDRESS_SIGN, to, _tokenId, ""); emit Minted(epoch, _tokenId, to); } // Contract URI functions ********************************************* /// @notice Used to set the { ContractCID } metadata from ipfs, /// this function is dedicated to contract owner according /// to { onlyOwner } modifier function setContractCID(string memory CID) public onlyOwner { ContractCID = string(abi.encodePacked("ipfs://", CID)); } /// @notice Used to render { ContractCID } as { contractURI } according to /// Opensea contract metadata standard function contractURI() public view virtual returns (string memory) { return ContractCID; } // Utilitaries functions ********************************************** /// @notice Used to fetch all entry for { epoch } into { epochMintingRegistry } function getMapRegisteryForEpoch(uint256 _epoch) public view returns (bool[210] memory result) { uint i = 1; while (i <= maxGenesisSupply) { result[i] = epochMintingRegistry[_epoch][i]; i++; } } /// @notice Used to fetch all { tokenIds } from { owner } function exposeHeldIds(address owner) public view returns(uint[] memory) { uint tokenCount = balanceOf(owner); uint[] memory tokenIds = new uint[](tokenCount); uint i = 0; while (i < tokenCount) { tokenIds[i] = tokenOfOwnerByIndex(owner, i); i++; } return tokenIds; } // ERC721 Spec functions ********************************************** /// @notice Used to render metadata as { tokenURI } according to ERC721 standard function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token"); return _compileMetadata(_tokenId); } /// @dev ERC721 required override function _beforeTokenTransfer(address from, address to, uint256 _tokenId) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, _tokenId); } /// @dev ERC721 required override function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } }
/// ``.. /// `.` `````.``.-````-`` `.` /// ` ``````.`..///.-..----. --..--`.-....`..-.```` ``` /// `` `.`..--...`:::/::-``..``..:-.://///---..-....----- /// ``-:::/+++:::/-.-///://oso+::++/--:--../+:/:..:-....-://:/:-`` /// `-+/++/+o+://+::-:soo+oosss+s+//o:/:--`--:://://:ooso/-.--.-:-.` /// ``.+ooso++o+:+:+sosyhsyshhddyo+:/sds/yoo++/+:--/--.--:..--..``.```` /// ``:++/---:+/::::///oyhhyy+++:hddhhNNho///ohosyhs+/-:/+/---.....-.. ` /// ``-:-...-/+///++///+o+:-:o+o/oydmNmNNdddhsoyo/oyyyho///:-.--.-.``. `` /// ```--`..-:+/:--:::-.-///++++ydsdNNMNdmMNMmNysddyoooosso+//-.-`....````` ..` /// .```:-:::/-.-+o++/+:/+/o/hNNNNhmdNMMNNMMdyydNNmdyys+++oo++-`--.:.-.`````... /// ..--.`-..`.-`-hh++-/:+shho+hsysyyhhhmNNmmNMMmNNNdmmy+:+sh/o+y/+-`+./::.```` ` /// -/` ``.-``.//o++y+//ssyh+hhdmmdmmddmhdmNdmdsh+oNNMmmddoodh/s:yss.--+.//+`.` `. /// `.`-.` -`..+h+yo++ooyyyyyoyhy+shmNNmmdhhdhyyhymdyyhdmshoohs+y:oy+/+o/:/++.`- .` /// ``.`.``-.-++syyyhhhhhhhhmhysosyyoooosssdhhhdmmdhdmdsy+ss+/+ho/hody-s+-:+::--`` ` /// .`` ``-//s+:ohmdmddNmNmhhshhddNNNhyyhhhdNNhmNNmNNmmyso+yhhso++hhdy.:/ ::-:--``.` /// .```.-`.//shdmNNmddyysohmMmdmNNmmNshdmNhso+-/ohNoyhmmsysosd++hy/osss/.:-o/-.:/--. /// ``..:++-+hhy/syhhhdhdNNddNMmNsNMNyyso+//:-.`-/..+hmdsmdy+ossos:+o/h/+..//-s.`.:::o/ /// `.-.oy//hm+o:-..-+/shdNNNNNNhsNdo/oyoyyhoh+/so//+/mNmyhh+/s+dy/+s::+:`-`-:s--:-.::+`-` /// .`:h-`+y+./oyhhdddhyohMMNmmNmdhoo/oyyhddhmNNNmhsoodmdhs+///++:+-:.:/--/-/o/--+//...:` /// ``+o``yoodNNNNNMhdyyo+ymhsymyshhyys+sssssNmdmmdmy+oso/++:://+/-`::-:--:/::+.//o:-.--: /// `:-:-`oNhyhdNNNmyys+/:://oohy++/+hmmmmNNNNhohydmmyhy++////ooy./----.-:---/::-o+:...-/ /// ``-.-` yms+mmNmMMmNho/:o++++hhh++:mMmNmmmNMNdhdms+ysyy//:-+o:.-.`.``.-:/::-:-+/y/.- -` /// ..:` hh+oNNmMNNNmss/:-+oyhs+o+.-yhdNmdhmmydmms+o///:///+/+--/`-``.o::/:-o//-/y::/.- /// `.-``hh+yNdmdohdy:++/./myhds/./shNhhyy++o:oyos/s+:s//+////.:- ...`--`..`-.:--o:+::` /// `-/+yyho.`.-+oso///+/Nmddh//y+:s:.../soy+:o+.:sdyo++++o:.-. `.:.:-```:.`:``/o:`:` /// ./.`..sMN+:::yh+s+ysyhhddh+ymdsd/:/+o+ysydhohoh/o+/so++o+/o.--..`-:::``:-`+-`:+--.` /// ``:``..-NNy++/yyysohmo+NNmy/+:+hMNmy+yydmNMNddhs:yyydmmmso:o///..-.-+-:o:/.o/-/+-`` /// ``+.`..-mMhsyo+++oo+yoshyyo+/`+hNmhyy+sdmdssssho-MMMNMNh//+/oo+/+:-....`.s+/`..-` /// .+ `oNMmdhhsohhmmydmNms/yy.oNmmdy+++/+ss+odNm+mNmdddo-s+:+/++/-:--//`/o+s/.-`` /// `/` dNNNhooddNmNymMNNdsoo+y+shhhmyymhss+hddms+hdhmdo+/+-/oo+/.///+sh:-/-s/` /// `::`hdNmh+ooNmdohNNMMmsooohh+oysydhdooo/syysodmNmys+/o+//+y/:.+/hmso.-//s- /// -+ohdmmhyhdysysyyhmysoyddhhoo+shdhdyddmddmNmmhssds/::/oo/..:/+Nmo+`-:so /// .oyhdmmNNdm+s:/:os/+/ssyyds+/ssdNNyhdmmhdmmdymymy///o:/``/+-dmdoo++:o` /// `ysyMNhhmoo+h-:/+o/+:.:/:/+doo+dNdhddmhmmmy++yhds/+-+::..o/+Nmosyhs+- /// s+dNNyNhsdhNhsy:+:oo/soo+dNmmooyosohMhsymmhyy+++:+:/+/-/o+yNh+hMNs. /// +yhNNMd+dmydmdy/+/sshydmhdNNmNooyhhhhshohmNh+:+oso++ssy+/odyhhNmh` /// `yyhdms+dMh+oyshhyhysdmNd+ohyNN+++mNddmNy+yo//+o/hddddymmyhosNmms` /// oydos:oMmhoyyhysssysdmMmNmhNmNNh/+mmNmddh+/+o+::+s+hmhmdyNNNNy: /// `/dNm/+Ndhy+oshdhhdyo::ohmdyhhNysy:smshmdo/o:so//:s++ymhyohdy-` /// `sNNN/hNm/:do+o:+/++++s:/+shyymmddy/ydmmh/s/+oss//oysy++o+o+` /// oNNMNmm:/hyy/:/o/+hhsosysoo-ohhhss/hmmhd/dyh++/soyooy++o+:. /// :/dMNh/smhh+//+s+--:+/so+ohhy/:sydmmmmm+/mdddhy++/ohs//-o/` /// `/odmhyhsyh++/-:+:::/:/o/:ooddy/+yodNNh+ydhmmmy++/hhyo+://` /// `:os/+o//oshss/yhs+//:+/-/:soooo/+sso+dddydss+:+sy///+:++ /// ./o/s//hhNho+shyyyoyyso+/ys+/+-:y+:/soooyyh++sNyo++/:/+ /// -/:osmmhyo:++++/+/osshdssooo/:/h//://++oyhsshmdo+//s/- /// .osmhydh::/+++/o+ohhysddyoo++os+-+++///yhhhmNs+o/:// /// -.++yss//////+/+/+soo++shyhsyy+::/:+y+yhdmdoo//:/:- /// ``.oss/:////++://+o//:://+oo-:o++/shhhmmh+o+++///-` /// ..:+++oo/+///ys:///://+::-sy+osh+osdyo+o/::/s:/y-` /// `odoyhds+/yysyydss+///+/:+oshdmNo+:+/oo/+++++:hy//` /// `://hyoyy/o/++shhy:+y:/:o/+omNmhsoohhsso+++:+o+sy:/++ /// -/---oddooss+oosy+ohNdo+++oyNhsdo/++shhhoo:s+oydmyo//o+ /// :y.`.``yyd++shoyydhhyymdhyyhyhhs+////+/+s/+:odmmyso.:ohy. /// .yy/o-..+h/+o/+//++ssoohhhssso+++:/:/yy+//sydmNddo+/./ohy+. /// .dmmhs+osdoos///o//++/+shdsoshoys+ssss++shmNNNyyds+:-s-//:+. /// -shmNmyhddsyss++/+ysddhyyydhdmyssNddyydyhNmdNmddso/::s:--`.-.` /// `+dmNhhdmddsooyyooossysshdhmoss+/+mNdyymydMdyMdyoo+/--/:/:`...-.` /// .:smNNMmsMNNmdhyyo/yymmdmdyo+ooooshysyysNNNmmmNyss/+o-`-:-/:```.`` ``` /// `.-+o/sdNNNmhdddNmmdsso/sdshyyyyhsdddyohymdmNdmmmmmyoo+/.... -os.`.``-.`` /// `/-:-/+.hymmmmdhmyNdMNmmhhs+sosoyhddyddmmho/ooymhddhdhyos-.oy..-:o+:..`` ```` ` /// ..::``--.-hoymmdNNNNNNMmhyNh+oo+soyNdmNmmmysooooymhy+so++yo..:+.--`..:.`.` `-- ``.` ` /// ```-.-.``..`:ddymmmNNdmNNNNmhN: -/oys/sdmmNdydsydmhhsmdso+/yo:/-..`.``.` ``:.`.````-. ` /// ````-:/.```:::syyydmddNhNNdsdMMs`./oddmd./odNdy+yssss++ooo/o+//-`:/:..:`-.```/-:.`.```..`` ` /// ```..-`` --.`.--o+sNhoyMmho+omhmo+Ns::dhdmmdy:.oNoyhhs+/o+o++s+hhoo+.`-:....``.-:-`..-````.-``.`` /// @title Dollars Nakamoto by Pascal Boyart /// @author jolan.eth /// @notice This contract will allow you to yield farm Dollars Nakamoto NFT. /// During epoch 0 you will be able to mint a Genesis NFT, /// Over time, epoch will increment allowing you to mint more editions. /// Minting generations editions is allowed only 1 time per epoch and per Genesis NFT. /// Generations editions do not allow you to mint other generations.
NatSpecSingleLine
transferListSlot
function transferListSlot(address to) public { require(epoch == 0, "error epoch"); require(_allowList[msg.sender], "error msg.sender"); require(!_allowList[to], "error to"); _allowList[msg.sender] = false; _allowList[to] = true; }
/// @notice Used to transfer { _allowList } slot to another address
NatSpecSingleLine
v0.8.10+commit.fc410830
MIT
ipfs://627efb7c58e0f1a820013031c32ab417b2b86eb0e16948f99bf7e29ad6e50407
{ "func_code_index": [ 12522, 12812 ] }
2,676
USDSat
USDSat.sol
0xbeda58401038c864c9fc9145f28e47b7b00a0e86
Solidity
USDSat
contract USDSat is USDSatMetadata, ERC721, ERC721Enumerable, Ownable, ReentrancyGuard { string SYMBOL = "USDSat"; string NAME = "Dollars Nakamoto"; string ContractCID; /// @notice Address used to sign NFT on mint address public ADDRESS_SIGN = 0x1Af70e564847bE46e4bA286c0b0066Da8372F902; /// @notice Ether shareholder address address public ADDRESS_PBOY = 0x709e17B3Ec505F80eAb064d0F2A71c743cE225B3; /// @notice Ether shareholder address address public ADDRESS_JOLAN = 0x51BdFa2Cbb25591AF58b202aCdcdB33325a325c2; /// @notice Equity per shareholder in % uint256 public SHARE_PBOY = 90; /// @notice Equity per shareholder in % uint256 public SHARE_JOLAN = 10; /// @notice Mapping used to represent allowed addresses to call { mintGenesis } mapping (address => bool) public _allowList; /// @notice Represent the current epoch uint256 public epoch = 0; /// @notice Represent the maximum epoch possible uint256 public epochMax = 10; /// @notice Represent the block length of an epoch uint256 public epochLen = 41016; /// @notice Index of the NFT /// @dev Start at 1 because var++ uint256 public tokenId = 1; /// @notice Index of the Genesis NFT /// @dev Start at 0 because ++var uint256 public genesisId = 0; /// @notice Index of the Generation NFT /// @dev Start at 0 because ++var uint256 public generationId = 0; /// @notice Maximum total supply uint256 public maxTokenSupply = 2100; /// @notice Maximum Genesis supply uint256 public maxGenesisSupply = 210; /// @notice Maximum supply per generation uint256 public maxGenerationSupply = 210; /// @notice Price of the Genesis NFT (Generations NFT are free) uint256 public genesisPrice = 0.5 ether; /// @notice Define the ending block uint256 public blockOmega; /// @notice Define the starting block uint256 public blockGenesis; /// @notice Define in which block the Meta must occur uint256 public blockMeta; /// @notice Used to inflate blockMeta each epoch incrementation uint256 public inflateRatio = 2; /// @notice Open Genesis mint when true bool public genesisMintAllowed = false; /// @notice Open Generation mint when true bool public generationMintAllowed = false; /// @notice Multi dimensionnal mapping to keep a track of the minting reentrancy over epoch mapping(uint256 => mapping(uint256 => bool)) public epochMintingRegistry; event Omega(uint256 _blockNumber); event Genesis(uint256 indexed _epoch, uint256 _blockNumber); event Meta(uint256 indexed _epoch, uint256 _blockNumber); event Withdraw(uint256 indexed _share, address _shareholder); event Shareholder(uint256 indexed _sharePercent, address _shareholder); event Securized(uint256 indexed _epoch, uint256 _epochLen, uint256 _blockMeta, uint256 _inflateRatio); event PermanentURI(string _value, uint256 indexed _id); event Minted(uint256 indexed _epoch, uint256 indexed _tokenId, address indexed _owner); event Signed(uint256 indexed _epoch, uint256 indexed _tokenId, uint256 indexed _blockNumber); constructor() ERC721(NAME, SYMBOL) {} // Withdraw functions ************************************************* /// @notice Allow Pboy to modify ADDRESS_PBOY /// This function is dedicated to the represented shareholder according to require(). function setPboy(address PBOY) public { require(msg.sender == ADDRESS_PBOY, "error msg.sender"); ADDRESS_PBOY = PBOY; emit Shareholder(SHARE_PBOY, ADDRESS_PBOY); } /// @notice Allow Jolan to modify ADDRESS_JOLAN /// This function is dedicated to the represented shareholder according to require(). function setJolan(address JOLAN) public { require(msg.sender == ADDRESS_JOLAN, "error msg.sender"); ADDRESS_JOLAN = JOLAN; emit Shareholder(SHARE_JOLAN, ADDRESS_JOLAN); } /// @notice Used to withdraw ETH balance of the contract, this function is dedicated /// to contract owner according to { onlyOwner } modifier. function withdrawEquity() public onlyOwner nonReentrant { uint256 balance = address(this).balance; address[2] memory shareholders = [ ADDRESS_PBOY, ADDRESS_JOLAN ]; uint256[2] memory _shares = [ SHARE_PBOY * balance / 100, SHARE_JOLAN * balance / 100 ]; uint i = 0; while (i < 2) { require(payable(shareholders[i]).send(_shares[i])); emit Withdraw(_shares[i], shareholders[i]); i++; } } // Epoch functions **************************************************** /// @notice Used to manage authorization and reentrancy of the genesis NFT mint /// @param _genesisId Used to increment { genesisId } and write { epochMintingRegistry } function genesisController(uint256 _genesisId) private { require(epoch == 0, "error epoch"); require(genesisId <= maxGenesisSupply, "error genesisId"); require(!epochMintingRegistry[epoch][_genesisId], "error epochMintingRegistry"); /// @dev Set { _genesisId } for { epoch } as true epochMintingRegistry[epoch][_genesisId] = true; /// @dev When { genesisId } reaches { maxGenesisSupply } the function /// will compute the data to increment the epoch according /// /// { blockGenesis } is set only once, at this time /// { blockMeta } is set to { blockGenesis } because epoch=0 /// Then it is computed into the function epochRegulator() /// /// Once the epoch is regulated, the new generation start /// straight away, { generationMintAllowed } is set to true if (genesisId == maxGenesisSupply) { blockGenesis = block.number; blockMeta = blockGenesis; emit Genesis(epoch, blockGenesis); epochRegulator(); } } /// @notice Used to manage authorization and reentrancy of the Generation NFT mint /// @param _genesisId Used to write { epochMintingRegistry } and verify minting allowance function generationController(uint256 _genesisId) private { require(blockGenesis > 0, "error blockGenesis"); require(blockMeta > 0, "error blockMeta"); require(blockOmega > 0, "error blockOmega"); /// @dev If { block.number } >= { blockMeta } the function /// will compute the data to increment the epoch according /// /// Once the epoch is regulated, the new generation start /// straight away, { generationMintAllowed } is set to true /// /// { generationId } is reset to 1 if (block.number >= blockMeta) { epochRegulator(); generationId = 1; } /// @dev Be sure the mint is open if condition are favorable if (block.number < blockMeta && generationId <= maxGenerationSupply) { generationMintAllowed = true; } require(maxTokenSupply >= tokenId, "error maxTokenSupply"); require(epoch > 0 && epoch < epochMax, "error epoch"); require(ownerOf(_genesisId) == msg.sender, "error ownerOf"); require(generationMintAllowed, "error generationMintAllowed"); require(generationId <= maxGenerationSupply, "error generationId"); require(epochMintingRegistry[0][_genesisId], "error epochMintingRegistry"); require(!epochMintingRegistry[epoch][_genesisId], "error epochMintingRegistry"); /// @dev Set { _genesisId } for { epoch } as true epochMintingRegistry[epoch][_genesisId] = true; /// @dev If { generationId } reaches { maxGenerationSupply } the modifier /// will set { generationMintAllowed } to false to stop the mint /// on this generation /// /// { generationId } is reset to 0 /// /// This condition will not block the function because as long as /// { block.number } >= { blockMeta } minting will reopen /// according and this condition will become obsolete until /// the condition is reached again if (generationId == maxGenerationSupply) { generationMintAllowed = false; generationId = 0; } } /// @notice Used to protect epoch block length from difficulty bomb of the /// Ethereum network. A difficulty bomb heavily increases the difficulty /// on the network, likely also causing an increase in block time. /// If the block time increases too much, the epoch generation could become /// exponentially higher than what is desired, ending with an undesired Ice-Age. /// To protect against this, the emergencySecure() function is allowed to /// manually reconfigure the epoch block length and the block Meta /// to match the network conditions if necessary. /// /// It can also be useful if the block time decreases for some reason with consensus change. /// /// This function is dedicated to contract owner according to { onlyOwner } modifier function emergencySecure(uint256 _epoch, uint256 _epochLen, uint256 _blockMeta, uint256 _inflateRatio) public onlyOwner { require(epoch > 0, "error epoch"); require(_epoch > 0, "error _epoch"); require(maxTokenSupply >= tokenId, "error maxTokenSupply"); epoch = _epoch; epochLen = _epochLen; blockMeta = _blockMeta; inflateRatio = _inflateRatio; computeBlockOmega(); emit Securized(epoch, epochLen, blockMeta, inflateRatio); } /// @notice Used to compute blockOmega() function, { blockOmega } represents /// the block when it won't ever be possible to mint another Dollars Nakamoto NFT. /// It is possible to be computed because of the deterministic state of the current protocol /// The following algorithm simulate the 10 epochs of the protocol block computation to result blockOmega function computeBlockOmega() private { uint256 i = 0; uint256 _blockMeta = 0; uint256 _epochLen = epochLen; while (i < epochMax) { if (i > 0) _epochLen *= inflateRatio; if (i == 9) { blockOmega = blockGenesis + _blockMeta; emit Omega(blockOmega); break; } _blockMeta += _epochLen; i++; } } /// @notice Used to regulate the epoch incrementation and block computation, known as Metas /// @dev When epoch=0, the { blockOmega } will be computed /// When epoch!=0 the block length { epochLen } will be multiplied /// by { inflateRatio } thus making the block length required for each /// epoch longer according /// /// { blockMeta } += { epochLen } result the exact block of the next Meta /// Allow generation mint after incrementing the epoch function epochRegulator() private { if (epoch == 0) computeBlockOmega(); if (epoch > 0) epochLen *= inflateRatio; blockMeta += epochLen; emit Meta(epoch, blockMeta); epoch++; if (block.number >= blockMeta && epoch < epochMax) { epochRegulator(); } generationMintAllowed = true; } // Mint functions ***************************************************** /// @notice Used to add/remove address from { _allowList } function setBatchGenesisAllowance(address[] memory batch) public onlyOwner { uint len = batch.length; require(len > 0, "error len"); uint i = 0; while (i < len) { _allowList[batch[i]] = _allowList[batch[i]] ? false : true; i++; } } /// @notice Used to transfer { _allowList } slot to another address function transferListSlot(address to) public { require(epoch == 0, "error epoch"); require(_allowList[msg.sender], "error msg.sender"); require(!_allowList[to], "error to"); _allowList[msg.sender] = false; _allowList[to] = true; } /// @notice Used to open the mint of Genesis NFT function setGenesisMint() public onlyOwner { genesisMintAllowed = true; } /// @notice Used to gift Genesis NFT, this function is dedicated /// to contract owner according to { onlyOwner } modifier function giftGenesis(address to) public onlyOwner { uint256 _genesisId = ++genesisId; setMetadata(tokenId, _genesisId, epoch); genesisController(_genesisId); mintUSDSat(to, tokenId++); } /// @notice Used to mint Genesis NFT, this function is payable /// the price of this function is equal to { genesisPrice }, /// require to be present on { _allowList } to call function mintGenesis() public payable { uint256 _genesisId = ++genesisId; setMetadata(tokenId, _genesisId, epoch); genesisController(_genesisId); require(genesisMintAllowed, "error genesisMintAllowed"); require(_allowList[msg.sender], "error allowList"); require(genesisPrice == msg.value, "error genesisPrice"); _allowList[msg.sender] = false; mintUSDSat(msg.sender, tokenId++); } /// @notice Used to gift Generation NFT, you need a Genesis NFT to call this function function giftGenerations(uint256 _genesisId, address to) public { ++generationId; generationController(_genesisId); setMetadata(tokenId, _genesisId, epoch); mintUSDSat(to, tokenId++); } /// @notice Used to mint Generation NFT, you need a Genesis NFT to call this function function mintGenerations(uint256 _genesisId) public { ++generationId; generationController(_genesisId); setMetadata(tokenId, _genesisId, epoch); mintUSDSat(msg.sender, tokenId++); } /// @notice Token is minted on { ADDRESS_SIGN } and instantly transferred to { msg.sender } as { to }, /// this is to ensure the token creation is signed with { ADDRESS_SIGN } /// This function is private and can be only called by the contract function mintUSDSat(address to, uint256 _tokenId) private { emit PermanentURI(_compileMetadata(_tokenId), _tokenId); _safeMint(ADDRESS_SIGN, _tokenId); emit Signed(epoch, _tokenId, block.number); _safeTransfer(ADDRESS_SIGN, to, _tokenId, ""); emit Minted(epoch, _tokenId, to); } // Contract URI functions ********************************************* /// @notice Used to set the { ContractCID } metadata from ipfs, /// this function is dedicated to contract owner according /// to { onlyOwner } modifier function setContractCID(string memory CID) public onlyOwner { ContractCID = string(abi.encodePacked("ipfs://", CID)); } /// @notice Used to render { ContractCID } as { contractURI } according to /// Opensea contract metadata standard function contractURI() public view virtual returns (string memory) { return ContractCID; } // Utilitaries functions ********************************************** /// @notice Used to fetch all entry for { epoch } into { epochMintingRegistry } function getMapRegisteryForEpoch(uint256 _epoch) public view returns (bool[210] memory result) { uint i = 1; while (i <= maxGenesisSupply) { result[i] = epochMintingRegistry[_epoch][i]; i++; } } /// @notice Used to fetch all { tokenIds } from { owner } function exposeHeldIds(address owner) public view returns(uint[] memory) { uint tokenCount = balanceOf(owner); uint[] memory tokenIds = new uint[](tokenCount); uint i = 0; while (i < tokenCount) { tokenIds[i] = tokenOfOwnerByIndex(owner, i); i++; } return tokenIds; } // ERC721 Spec functions ********************************************** /// @notice Used to render metadata as { tokenURI } according to ERC721 standard function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token"); return _compileMetadata(_tokenId); } /// @dev ERC721 required override function _beforeTokenTransfer(address from, address to, uint256 _tokenId) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, _tokenId); } /// @dev ERC721 required override function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } }
/// ``.. /// `.` `````.``.-````-`` `.` /// ` ``````.`..///.-..----. --..--`.-....`..-.```` ``` /// `` `.`..--...`:::/::-``..``..:-.://///---..-....----- /// ``-:::/+++:::/-.-///://oso+::++/--:--../+:/:..:-....-://:/:-`` /// `-+/++/+o+://+::-:soo+oosss+s+//o:/:--`--:://://:ooso/-.--.-:-.` /// ``.+ooso++o+:+:+sosyhsyshhddyo+:/sds/yoo++/+:--/--.--:..--..``.```` /// ``:++/---:+/::::///oyhhyy+++:hddhhNNho///ohosyhs+/-:/+/---.....-.. ` /// ``-:-...-/+///++///+o+:-:o+o/oydmNmNNdddhsoyo/oyyyho///:-.--.-.``. `` /// ```--`..-:+/:--:::-.-///++++ydsdNNMNdmMNMmNysddyoooosso+//-.-`....````` ..` /// .```:-:::/-.-+o++/+:/+/o/hNNNNhmdNMMNNMMdyydNNmdyys+++oo++-`--.:.-.`````... /// ..--.`-..`.-`-hh++-/:+shho+hsysyyhhhmNNmmNMMmNNNdmmy+:+sh/o+y/+-`+./::.```` ` /// -/` ``.-``.//o++y+//ssyh+hhdmmdmmddmhdmNdmdsh+oNNMmmddoodh/s:yss.--+.//+`.` `. /// `.`-.` -`..+h+yo++ooyyyyyoyhy+shmNNmmdhhdhyyhymdyyhdmshoohs+y:oy+/+o/:/++.`- .` /// ``.`.``-.-++syyyhhhhhhhhmhysosyyoooosssdhhhdmmdhdmdsy+ss+/+ho/hody-s+-:+::--`` ` /// .`` ``-//s+:ohmdmddNmNmhhshhddNNNhyyhhhdNNhmNNmNNmmyso+yhhso++hhdy.:/ ::-:--``.` /// .```.-`.//shdmNNmddyysohmMmdmNNmmNshdmNhso+-/ohNoyhmmsysosd++hy/osss/.:-o/-.:/--. /// ``..:++-+hhy/syhhhdhdNNddNMmNsNMNyyso+//:-.`-/..+hmdsmdy+ossos:+o/h/+..//-s.`.:::o/ /// `.-.oy//hm+o:-..-+/shdNNNNNNhsNdo/oyoyyhoh+/so//+/mNmyhh+/s+dy/+s::+:`-`-:s--:-.::+`-` /// .`:h-`+y+./oyhhdddhyohMMNmmNmdhoo/oyyhddhmNNNmhsoodmdhs+///++:+-:.:/--/-/o/--+//...:` /// ``+o``yoodNNNNNMhdyyo+ymhsymyshhyys+sssssNmdmmdmy+oso/++:://+/-`::-:--:/::+.//o:-.--: /// `:-:-`oNhyhdNNNmyys+/:://oohy++/+hmmmmNNNNhohydmmyhy++////ooy./----.-:---/::-o+:...-/ /// ``-.-` yms+mmNmMMmNho/:o++++hhh++:mMmNmmmNMNdhdms+ysyy//:-+o:.-.`.``.-:/::-:-+/y/.- -` /// ..:` hh+oNNmMNNNmss/:-+oyhs+o+.-yhdNmdhmmydmms+o///:///+/+--/`-``.o::/:-o//-/y::/.- /// `.-``hh+yNdmdohdy:++/./myhds/./shNhhyy++o:oyos/s+:s//+////.:- ...`--`..`-.:--o:+::` /// `-/+yyho.`.-+oso///+/Nmddh//y+:s:.../soy+:o+.:sdyo++++o:.-. `.:.:-```:.`:``/o:`:` /// ./.`..sMN+:::yh+s+ysyhhddh+ymdsd/:/+o+ysydhohoh/o+/so++o+/o.--..`-:::``:-`+-`:+--.` /// ``:``..-NNy++/yyysohmo+NNmy/+:+hMNmy+yydmNMNddhs:yyydmmmso:o///..-.-+-:o:/.o/-/+-`` /// ``+.`..-mMhsyo+++oo+yoshyyo+/`+hNmhyy+sdmdssssho-MMMNMNh//+/oo+/+:-....`.s+/`..-` /// .+ `oNMmdhhsohhmmydmNms/yy.oNmmdy+++/+ss+odNm+mNmdddo-s+:+/++/-:--//`/o+s/.-`` /// `/` dNNNhooddNmNymMNNdsoo+y+shhhmyymhss+hddms+hdhmdo+/+-/oo+/.///+sh:-/-s/` /// `::`hdNmh+ooNmdohNNMMmsooohh+oysydhdooo/syysodmNmys+/o+//+y/:.+/hmso.-//s- /// -+ohdmmhyhdysysyyhmysoyddhhoo+shdhdyddmddmNmmhssds/::/oo/..:/+Nmo+`-:so /// .oyhdmmNNdm+s:/:os/+/ssyyds+/ssdNNyhdmmhdmmdymymy///o:/``/+-dmdoo++:o` /// `ysyMNhhmoo+h-:/+o/+:.:/:/+doo+dNdhddmhmmmy++yhds/+-+::..o/+Nmosyhs+- /// s+dNNyNhsdhNhsy:+:oo/soo+dNmmooyosohMhsymmhyy+++:+:/+/-/o+yNh+hMNs. /// +yhNNMd+dmydmdy/+/sshydmhdNNmNooyhhhhshohmNh+:+oso++ssy+/odyhhNmh` /// `yyhdms+dMh+oyshhyhysdmNd+ohyNN+++mNddmNy+yo//+o/hddddymmyhosNmms` /// oydos:oMmhoyyhysssysdmMmNmhNmNNh/+mmNmddh+/+o+::+s+hmhmdyNNNNy: /// `/dNm/+Ndhy+oshdhhdyo::ohmdyhhNysy:smshmdo/o:so//:s++ymhyohdy-` /// `sNNN/hNm/:do+o:+/++++s:/+shyymmddy/ydmmh/s/+oss//oysy++o+o+` /// oNNMNmm:/hyy/:/o/+hhsosysoo-ohhhss/hmmhd/dyh++/soyooy++o+:. /// :/dMNh/smhh+//+s+--:+/so+ohhy/:sydmmmmm+/mdddhy++/ohs//-o/` /// `/odmhyhsyh++/-:+:::/:/o/:ooddy/+yodNNh+ydhmmmy++/hhyo+://` /// `:os/+o//oshss/yhs+//:+/-/:soooo/+sso+dddydss+:+sy///+:++ /// ./o/s//hhNho+shyyyoyyso+/ys+/+-:y+:/soooyyh++sNyo++/:/+ /// -/:osmmhyo:++++/+/osshdssooo/:/h//://++oyhsshmdo+//s/- /// .osmhydh::/+++/o+ohhysddyoo++os+-+++///yhhhmNs+o/:// /// -.++yss//////+/+/+soo++shyhsyy+::/:+y+yhdmdoo//:/:- /// ``.oss/:////++://+o//:://+oo-:o++/shhhmmh+o+++///-` /// ..:+++oo/+///ys:///://+::-sy+osh+osdyo+o/::/s:/y-` /// `odoyhds+/yysyydss+///+/:+oshdmNo+:+/oo/+++++:hy//` /// `://hyoyy/o/++shhy:+y:/:o/+omNmhsoohhsso+++:+o+sy:/++ /// -/---oddooss+oosy+ohNdo+++oyNhsdo/++shhhoo:s+oydmyo//o+ /// :y.`.``yyd++shoyydhhyymdhyyhyhhs+////+/+s/+:odmmyso.:ohy. /// .yy/o-..+h/+o/+//++ssoohhhssso+++:/:/yy+//sydmNddo+/./ohy+. /// .dmmhs+osdoos///o//++/+shdsoshoys+ssss++shmNNNyyds+:-s-//:+. /// -shmNmyhddsyss++/+ysddhyyydhdmyssNddyydyhNmdNmddso/::s:--`.-.` /// `+dmNhhdmddsooyyooossysshdhmoss+/+mNdyymydMdyMdyoo+/--/:/:`...-.` /// .:smNNMmsMNNmdhyyo/yymmdmdyo+ooooshysyysNNNmmmNyss/+o-`-:-/:```.`` ``` /// `.-+o/sdNNNmhdddNmmdsso/sdshyyyyhsdddyohymdmNdmmmmmyoo+/.... -os.`.``-.`` /// `/-:-/+.hymmmmdhmyNdMNmmhhs+sosoyhddyddmmho/ooymhddhdhyos-.oy..-:o+:..`` ```` ` /// ..::``--.-hoymmdNNNNNNMmhyNh+oo+soyNdmNmmmysooooymhy+so++yo..:+.--`..:.`.` `-- ``.` ` /// ```-.-.``..`:ddymmmNNdmNNNNmhN: -/oys/sdmmNdydsydmhhsmdso+/yo:/-..`.``.` ``:.`.````-. ` /// ````-:/.```:::syyydmddNhNNdsdMMs`./oddmd./odNdy+yssss++ooo/o+//-`:/:..:`-.```/-:.`.```..`` ` /// ```..-`` --.`.--o+sNhoyMmho+omhmo+Ns::dhdmmdy:.oNoyhhs+/o+o++s+hhoo+.`-:....``.-:-`..-````.-``.`` /// @title Dollars Nakamoto by Pascal Boyart /// @author jolan.eth /// @notice This contract will allow you to yield farm Dollars Nakamoto NFT. /// During epoch 0 you will be able to mint a Genesis NFT, /// Over time, epoch will increment allowing you to mint more editions. /// Minting generations editions is allowed only 1 time per epoch and per Genesis NFT. /// Generations editions do not allow you to mint other generations.
NatSpecSingleLine
setGenesisMint
function setGenesisMint() public onlyOwner { genesisMintAllowed = true; }
/// @notice Used to open the mint of Genesis NFT
NatSpecSingleLine
v0.8.10+commit.fc410830
MIT
ipfs://627efb7c58e0f1a820013031c32ab417b2b86eb0e16948f99bf7e29ad6e50407
{ "func_code_index": [ 12869, 12966 ] }
2,677
USDSat
USDSat.sol
0xbeda58401038c864c9fc9145f28e47b7b00a0e86
Solidity
USDSat
contract USDSat is USDSatMetadata, ERC721, ERC721Enumerable, Ownable, ReentrancyGuard { string SYMBOL = "USDSat"; string NAME = "Dollars Nakamoto"; string ContractCID; /// @notice Address used to sign NFT on mint address public ADDRESS_SIGN = 0x1Af70e564847bE46e4bA286c0b0066Da8372F902; /// @notice Ether shareholder address address public ADDRESS_PBOY = 0x709e17B3Ec505F80eAb064d0F2A71c743cE225B3; /// @notice Ether shareholder address address public ADDRESS_JOLAN = 0x51BdFa2Cbb25591AF58b202aCdcdB33325a325c2; /// @notice Equity per shareholder in % uint256 public SHARE_PBOY = 90; /// @notice Equity per shareholder in % uint256 public SHARE_JOLAN = 10; /// @notice Mapping used to represent allowed addresses to call { mintGenesis } mapping (address => bool) public _allowList; /// @notice Represent the current epoch uint256 public epoch = 0; /// @notice Represent the maximum epoch possible uint256 public epochMax = 10; /// @notice Represent the block length of an epoch uint256 public epochLen = 41016; /// @notice Index of the NFT /// @dev Start at 1 because var++ uint256 public tokenId = 1; /// @notice Index of the Genesis NFT /// @dev Start at 0 because ++var uint256 public genesisId = 0; /// @notice Index of the Generation NFT /// @dev Start at 0 because ++var uint256 public generationId = 0; /// @notice Maximum total supply uint256 public maxTokenSupply = 2100; /// @notice Maximum Genesis supply uint256 public maxGenesisSupply = 210; /// @notice Maximum supply per generation uint256 public maxGenerationSupply = 210; /// @notice Price of the Genesis NFT (Generations NFT are free) uint256 public genesisPrice = 0.5 ether; /// @notice Define the ending block uint256 public blockOmega; /// @notice Define the starting block uint256 public blockGenesis; /// @notice Define in which block the Meta must occur uint256 public blockMeta; /// @notice Used to inflate blockMeta each epoch incrementation uint256 public inflateRatio = 2; /// @notice Open Genesis mint when true bool public genesisMintAllowed = false; /// @notice Open Generation mint when true bool public generationMintAllowed = false; /// @notice Multi dimensionnal mapping to keep a track of the minting reentrancy over epoch mapping(uint256 => mapping(uint256 => bool)) public epochMintingRegistry; event Omega(uint256 _blockNumber); event Genesis(uint256 indexed _epoch, uint256 _blockNumber); event Meta(uint256 indexed _epoch, uint256 _blockNumber); event Withdraw(uint256 indexed _share, address _shareholder); event Shareholder(uint256 indexed _sharePercent, address _shareholder); event Securized(uint256 indexed _epoch, uint256 _epochLen, uint256 _blockMeta, uint256 _inflateRatio); event PermanentURI(string _value, uint256 indexed _id); event Minted(uint256 indexed _epoch, uint256 indexed _tokenId, address indexed _owner); event Signed(uint256 indexed _epoch, uint256 indexed _tokenId, uint256 indexed _blockNumber); constructor() ERC721(NAME, SYMBOL) {} // Withdraw functions ************************************************* /// @notice Allow Pboy to modify ADDRESS_PBOY /// This function is dedicated to the represented shareholder according to require(). function setPboy(address PBOY) public { require(msg.sender == ADDRESS_PBOY, "error msg.sender"); ADDRESS_PBOY = PBOY; emit Shareholder(SHARE_PBOY, ADDRESS_PBOY); } /// @notice Allow Jolan to modify ADDRESS_JOLAN /// This function is dedicated to the represented shareholder according to require(). function setJolan(address JOLAN) public { require(msg.sender == ADDRESS_JOLAN, "error msg.sender"); ADDRESS_JOLAN = JOLAN; emit Shareholder(SHARE_JOLAN, ADDRESS_JOLAN); } /// @notice Used to withdraw ETH balance of the contract, this function is dedicated /// to contract owner according to { onlyOwner } modifier. function withdrawEquity() public onlyOwner nonReentrant { uint256 balance = address(this).balance; address[2] memory shareholders = [ ADDRESS_PBOY, ADDRESS_JOLAN ]; uint256[2] memory _shares = [ SHARE_PBOY * balance / 100, SHARE_JOLAN * balance / 100 ]; uint i = 0; while (i < 2) { require(payable(shareholders[i]).send(_shares[i])); emit Withdraw(_shares[i], shareholders[i]); i++; } } // Epoch functions **************************************************** /// @notice Used to manage authorization and reentrancy of the genesis NFT mint /// @param _genesisId Used to increment { genesisId } and write { epochMintingRegistry } function genesisController(uint256 _genesisId) private { require(epoch == 0, "error epoch"); require(genesisId <= maxGenesisSupply, "error genesisId"); require(!epochMintingRegistry[epoch][_genesisId], "error epochMintingRegistry"); /// @dev Set { _genesisId } for { epoch } as true epochMintingRegistry[epoch][_genesisId] = true; /// @dev When { genesisId } reaches { maxGenesisSupply } the function /// will compute the data to increment the epoch according /// /// { blockGenesis } is set only once, at this time /// { blockMeta } is set to { blockGenesis } because epoch=0 /// Then it is computed into the function epochRegulator() /// /// Once the epoch is regulated, the new generation start /// straight away, { generationMintAllowed } is set to true if (genesisId == maxGenesisSupply) { blockGenesis = block.number; blockMeta = blockGenesis; emit Genesis(epoch, blockGenesis); epochRegulator(); } } /// @notice Used to manage authorization and reentrancy of the Generation NFT mint /// @param _genesisId Used to write { epochMintingRegistry } and verify minting allowance function generationController(uint256 _genesisId) private { require(blockGenesis > 0, "error blockGenesis"); require(blockMeta > 0, "error blockMeta"); require(blockOmega > 0, "error blockOmega"); /// @dev If { block.number } >= { blockMeta } the function /// will compute the data to increment the epoch according /// /// Once the epoch is regulated, the new generation start /// straight away, { generationMintAllowed } is set to true /// /// { generationId } is reset to 1 if (block.number >= blockMeta) { epochRegulator(); generationId = 1; } /// @dev Be sure the mint is open if condition are favorable if (block.number < blockMeta && generationId <= maxGenerationSupply) { generationMintAllowed = true; } require(maxTokenSupply >= tokenId, "error maxTokenSupply"); require(epoch > 0 && epoch < epochMax, "error epoch"); require(ownerOf(_genesisId) == msg.sender, "error ownerOf"); require(generationMintAllowed, "error generationMintAllowed"); require(generationId <= maxGenerationSupply, "error generationId"); require(epochMintingRegistry[0][_genesisId], "error epochMintingRegistry"); require(!epochMintingRegistry[epoch][_genesisId], "error epochMintingRegistry"); /// @dev Set { _genesisId } for { epoch } as true epochMintingRegistry[epoch][_genesisId] = true; /// @dev If { generationId } reaches { maxGenerationSupply } the modifier /// will set { generationMintAllowed } to false to stop the mint /// on this generation /// /// { generationId } is reset to 0 /// /// This condition will not block the function because as long as /// { block.number } >= { blockMeta } minting will reopen /// according and this condition will become obsolete until /// the condition is reached again if (generationId == maxGenerationSupply) { generationMintAllowed = false; generationId = 0; } } /// @notice Used to protect epoch block length from difficulty bomb of the /// Ethereum network. A difficulty bomb heavily increases the difficulty /// on the network, likely also causing an increase in block time. /// If the block time increases too much, the epoch generation could become /// exponentially higher than what is desired, ending with an undesired Ice-Age. /// To protect against this, the emergencySecure() function is allowed to /// manually reconfigure the epoch block length and the block Meta /// to match the network conditions if necessary. /// /// It can also be useful if the block time decreases for some reason with consensus change. /// /// This function is dedicated to contract owner according to { onlyOwner } modifier function emergencySecure(uint256 _epoch, uint256 _epochLen, uint256 _blockMeta, uint256 _inflateRatio) public onlyOwner { require(epoch > 0, "error epoch"); require(_epoch > 0, "error _epoch"); require(maxTokenSupply >= tokenId, "error maxTokenSupply"); epoch = _epoch; epochLen = _epochLen; blockMeta = _blockMeta; inflateRatio = _inflateRatio; computeBlockOmega(); emit Securized(epoch, epochLen, blockMeta, inflateRatio); } /// @notice Used to compute blockOmega() function, { blockOmega } represents /// the block when it won't ever be possible to mint another Dollars Nakamoto NFT. /// It is possible to be computed because of the deterministic state of the current protocol /// The following algorithm simulate the 10 epochs of the protocol block computation to result blockOmega function computeBlockOmega() private { uint256 i = 0; uint256 _blockMeta = 0; uint256 _epochLen = epochLen; while (i < epochMax) { if (i > 0) _epochLen *= inflateRatio; if (i == 9) { blockOmega = blockGenesis + _blockMeta; emit Omega(blockOmega); break; } _blockMeta += _epochLen; i++; } } /// @notice Used to regulate the epoch incrementation and block computation, known as Metas /// @dev When epoch=0, the { blockOmega } will be computed /// When epoch!=0 the block length { epochLen } will be multiplied /// by { inflateRatio } thus making the block length required for each /// epoch longer according /// /// { blockMeta } += { epochLen } result the exact block of the next Meta /// Allow generation mint after incrementing the epoch function epochRegulator() private { if (epoch == 0) computeBlockOmega(); if (epoch > 0) epochLen *= inflateRatio; blockMeta += epochLen; emit Meta(epoch, blockMeta); epoch++; if (block.number >= blockMeta && epoch < epochMax) { epochRegulator(); } generationMintAllowed = true; } // Mint functions ***************************************************** /// @notice Used to add/remove address from { _allowList } function setBatchGenesisAllowance(address[] memory batch) public onlyOwner { uint len = batch.length; require(len > 0, "error len"); uint i = 0; while (i < len) { _allowList[batch[i]] = _allowList[batch[i]] ? false : true; i++; } } /// @notice Used to transfer { _allowList } slot to another address function transferListSlot(address to) public { require(epoch == 0, "error epoch"); require(_allowList[msg.sender], "error msg.sender"); require(!_allowList[to], "error to"); _allowList[msg.sender] = false; _allowList[to] = true; } /// @notice Used to open the mint of Genesis NFT function setGenesisMint() public onlyOwner { genesisMintAllowed = true; } /// @notice Used to gift Genesis NFT, this function is dedicated /// to contract owner according to { onlyOwner } modifier function giftGenesis(address to) public onlyOwner { uint256 _genesisId = ++genesisId; setMetadata(tokenId, _genesisId, epoch); genesisController(_genesisId); mintUSDSat(to, tokenId++); } /// @notice Used to mint Genesis NFT, this function is payable /// the price of this function is equal to { genesisPrice }, /// require to be present on { _allowList } to call function mintGenesis() public payable { uint256 _genesisId = ++genesisId; setMetadata(tokenId, _genesisId, epoch); genesisController(_genesisId); require(genesisMintAllowed, "error genesisMintAllowed"); require(_allowList[msg.sender], "error allowList"); require(genesisPrice == msg.value, "error genesisPrice"); _allowList[msg.sender] = false; mintUSDSat(msg.sender, tokenId++); } /// @notice Used to gift Generation NFT, you need a Genesis NFT to call this function function giftGenerations(uint256 _genesisId, address to) public { ++generationId; generationController(_genesisId); setMetadata(tokenId, _genesisId, epoch); mintUSDSat(to, tokenId++); } /// @notice Used to mint Generation NFT, you need a Genesis NFT to call this function function mintGenerations(uint256 _genesisId) public { ++generationId; generationController(_genesisId); setMetadata(tokenId, _genesisId, epoch); mintUSDSat(msg.sender, tokenId++); } /// @notice Token is minted on { ADDRESS_SIGN } and instantly transferred to { msg.sender } as { to }, /// this is to ensure the token creation is signed with { ADDRESS_SIGN } /// This function is private and can be only called by the contract function mintUSDSat(address to, uint256 _tokenId) private { emit PermanentURI(_compileMetadata(_tokenId), _tokenId); _safeMint(ADDRESS_SIGN, _tokenId); emit Signed(epoch, _tokenId, block.number); _safeTransfer(ADDRESS_SIGN, to, _tokenId, ""); emit Minted(epoch, _tokenId, to); } // Contract URI functions ********************************************* /// @notice Used to set the { ContractCID } metadata from ipfs, /// this function is dedicated to contract owner according /// to { onlyOwner } modifier function setContractCID(string memory CID) public onlyOwner { ContractCID = string(abi.encodePacked("ipfs://", CID)); } /// @notice Used to render { ContractCID } as { contractURI } according to /// Opensea contract metadata standard function contractURI() public view virtual returns (string memory) { return ContractCID; } // Utilitaries functions ********************************************** /// @notice Used to fetch all entry for { epoch } into { epochMintingRegistry } function getMapRegisteryForEpoch(uint256 _epoch) public view returns (bool[210] memory result) { uint i = 1; while (i <= maxGenesisSupply) { result[i] = epochMintingRegistry[_epoch][i]; i++; } } /// @notice Used to fetch all { tokenIds } from { owner } function exposeHeldIds(address owner) public view returns(uint[] memory) { uint tokenCount = balanceOf(owner); uint[] memory tokenIds = new uint[](tokenCount); uint i = 0; while (i < tokenCount) { tokenIds[i] = tokenOfOwnerByIndex(owner, i); i++; } return tokenIds; } // ERC721 Spec functions ********************************************** /// @notice Used to render metadata as { tokenURI } according to ERC721 standard function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token"); return _compileMetadata(_tokenId); } /// @dev ERC721 required override function _beforeTokenTransfer(address from, address to, uint256 _tokenId) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, _tokenId); } /// @dev ERC721 required override function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } }
/// ``.. /// `.` `````.``.-````-`` `.` /// ` ``````.`..///.-..----. --..--`.-....`..-.```` ``` /// `` `.`..--...`:::/::-``..``..:-.://///---..-....----- /// ``-:::/+++:::/-.-///://oso+::++/--:--../+:/:..:-....-://:/:-`` /// `-+/++/+o+://+::-:soo+oosss+s+//o:/:--`--:://://:ooso/-.--.-:-.` /// ``.+ooso++o+:+:+sosyhsyshhddyo+:/sds/yoo++/+:--/--.--:..--..``.```` /// ``:++/---:+/::::///oyhhyy+++:hddhhNNho///ohosyhs+/-:/+/---.....-.. ` /// ``-:-...-/+///++///+o+:-:o+o/oydmNmNNdddhsoyo/oyyyho///:-.--.-.``. `` /// ```--`..-:+/:--:::-.-///++++ydsdNNMNdmMNMmNysddyoooosso+//-.-`....````` ..` /// .```:-:::/-.-+o++/+:/+/o/hNNNNhmdNMMNNMMdyydNNmdyys+++oo++-`--.:.-.`````... /// ..--.`-..`.-`-hh++-/:+shho+hsysyyhhhmNNmmNMMmNNNdmmy+:+sh/o+y/+-`+./::.```` ` /// -/` ``.-``.//o++y+//ssyh+hhdmmdmmddmhdmNdmdsh+oNNMmmddoodh/s:yss.--+.//+`.` `. /// `.`-.` -`..+h+yo++ooyyyyyoyhy+shmNNmmdhhdhyyhymdyyhdmshoohs+y:oy+/+o/:/++.`- .` /// ``.`.``-.-++syyyhhhhhhhhmhysosyyoooosssdhhhdmmdhdmdsy+ss+/+ho/hody-s+-:+::--`` ` /// .`` ``-//s+:ohmdmddNmNmhhshhddNNNhyyhhhdNNhmNNmNNmmyso+yhhso++hhdy.:/ ::-:--``.` /// .```.-`.//shdmNNmddyysohmMmdmNNmmNshdmNhso+-/ohNoyhmmsysosd++hy/osss/.:-o/-.:/--. /// ``..:++-+hhy/syhhhdhdNNddNMmNsNMNyyso+//:-.`-/..+hmdsmdy+ossos:+o/h/+..//-s.`.:::o/ /// `.-.oy//hm+o:-..-+/shdNNNNNNhsNdo/oyoyyhoh+/so//+/mNmyhh+/s+dy/+s::+:`-`-:s--:-.::+`-` /// .`:h-`+y+./oyhhdddhyohMMNmmNmdhoo/oyyhddhmNNNmhsoodmdhs+///++:+-:.:/--/-/o/--+//...:` /// ``+o``yoodNNNNNMhdyyo+ymhsymyshhyys+sssssNmdmmdmy+oso/++:://+/-`::-:--:/::+.//o:-.--: /// `:-:-`oNhyhdNNNmyys+/:://oohy++/+hmmmmNNNNhohydmmyhy++////ooy./----.-:---/::-o+:...-/ /// ``-.-` yms+mmNmMMmNho/:o++++hhh++:mMmNmmmNMNdhdms+ysyy//:-+o:.-.`.``.-:/::-:-+/y/.- -` /// ..:` hh+oNNmMNNNmss/:-+oyhs+o+.-yhdNmdhmmydmms+o///:///+/+--/`-``.o::/:-o//-/y::/.- /// `.-``hh+yNdmdohdy:++/./myhds/./shNhhyy++o:oyos/s+:s//+////.:- ...`--`..`-.:--o:+::` /// `-/+yyho.`.-+oso///+/Nmddh//y+:s:.../soy+:o+.:sdyo++++o:.-. `.:.:-```:.`:``/o:`:` /// ./.`..sMN+:::yh+s+ysyhhddh+ymdsd/:/+o+ysydhohoh/o+/so++o+/o.--..`-:::``:-`+-`:+--.` /// ``:``..-NNy++/yyysohmo+NNmy/+:+hMNmy+yydmNMNddhs:yyydmmmso:o///..-.-+-:o:/.o/-/+-`` /// ``+.`..-mMhsyo+++oo+yoshyyo+/`+hNmhyy+sdmdssssho-MMMNMNh//+/oo+/+:-....`.s+/`..-` /// .+ `oNMmdhhsohhmmydmNms/yy.oNmmdy+++/+ss+odNm+mNmdddo-s+:+/++/-:--//`/o+s/.-`` /// `/` dNNNhooddNmNymMNNdsoo+y+shhhmyymhss+hddms+hdhmdo+/+-/oo+/.///+sh:-/-s/` /// `::`hdNmh+ooNmdohNNMMmsooohh+oysydhdooo/syysodmNmys+/o+//+y/:.+/hmso.-//s- /// -+ohdmmhyhdysysyyhmysoyddhhoo+shdhdyddmddmNmmhssds/::/oo/..:/+Nmo+`-:so /// .oyhdmmNNdm+s:/:os/+/ssyyds+/ssdNNyhdmmhdmmdymymy///o:/``/+-dmdoo++:o` /// `ysyMNhhmoo+h-:/+o/+:.:/:/+doo+dNdhddmhmmmy++yhds/+-+::..o/+Nmosyhs+- /// s+dNNyNhsdhNhsy:+:oo/soo+dNmmooyosohMhsymmhyy+++:+:/+/-/o+yNh+hMNs. /// +yhNNMd+dmydmdy/+/sshydmhdNNmNooyhhhhshohmNh+:+oso++ssy+/odyhhNmh` /// `yyhdms+dMh+oyshhyhysdmNd+ohyNN+++mNddmNy+yo//+o/hddddymmyhosNmms` /// oydos:oMmhoyyhysssysdmMmNmhNmNNh/+mmNmddh+/+o+::+s+hmhmdyNNNNy: /// `/dNm/+Ndhy+oshdhhdyo::ohmdyhhNysy:smshmdo/o:so//:s++ymhyohdy-` /// `sNNN/hNm/:do+o:+/++++s:/+shyymmddy/ydmmh/s/+oss//oysy++o+o+` /// oNNMNmm:/hyy/:/o/+hhsosysoo-ohhhss/hmmhd/dyh++/soyooy++o+:. /// :/dMNh/smhh+//+s+--:+/so+ohhy/:sydmmmmm+/mdddhy++/ohs//-o/` /// `/odmhyhsyh++/-:+:::/:/o/:ooddy/+yodNNh+ydhmmmy++/hhyo+://` /// `:os/+o//oshss/yhs+//:+/-/:soooo/+sso+dddydss+:+sy///+:++ /// ./o/s//hhNho+shyyyoyyso+/ys+/+-:y+:/soooyyh++sNyo++/:/+ /// -/:osmmhyo:++++/+/osshdssooo/:/h//://++oyhsshmdo+//s/- /// .osmhydh::/+++/o+ohhysddyoo++os+-+++///yhhhmNs+o/:// /// -.++yss//////+/+/+soo++shyhsyy+::/:+y+yhdmdoo//:/:- /// ``.oss/:////++://+o//:://+oo-:o++/shhhmmh+o+++///-` /// ..:+++oo/+///ys:///://+::-sy+osh+osdyo+o/::/s:/y-` /// `odoyhds+/yysyydss+///+/:+oshdmNo+:+/oo/+++++:hy//` /// `://hyoyy/o/++shhy:+y:/:o/+omNmhsoohhsso+++:+o+sy:/++ /// -/---oddooss+oosy+ohNdo+++oyNhsdo/++shhhoo:s+oydmyo//o+ /// :y.`.``yyd++shoyydhhyymdhyyhyhhs+////+/+s/+:odmmyso.:ohy. /// .yy/o-..+h/+o/+//++ssoohhhssso+++:/:/yy+//sydmNddo+/./ohy+. /// .dmmhs+osdoos///o//++/+shdsoshoys+ssss++shmNNNyyds+:-s-//:+. /// -shmNmyhddsyss++/+ysddhyyydhdmyssNddyydyhNmdNmddso/::s:--`.-.` /// `+dmNhhdmddsooyyooossysshdhmoss+/+mNdyymydMdyMdyoo+/--/:/:`...-.` /// .:smNNMmsMNNmdhyyo/yymmdmdyo+ooooshysyysNNNmmmNyss/+o-`-:-/:```.`` ``` /// `.-+o/sdNNNmhdddNmmdsso/sdshyyyyhsdddyohymdmNdmmmmmyoo+/.... -os.`.``-.`` /// `/-:-/+.hymmmmdhmyNdMNmmhhs+sosoyhddyddmmho/ooymhddhdhyos-.oy..-:o+:..`` ```` ` /// ..::``--.-hoymmdNNNNNNMmhyNh+oo+soyNdmNmmmysooooymhy+so++yo..:+.--`..:.`.` `-- ``.` ` /// ```-.-.``..`:ddymmmNNdmNNNNmhN: -/oys/sdmmNdydsydmhhsmdso+/yo:/-..`.``.` ``:.`.````-. ` /// ````-:/.```:::syyydmddNhNNdsdMMs`./oddmd./odNdy+yssss++ooo/o+//-`:/:..:`-.```/-:.`.```..`` ` /// ```..-`` --.`.--o+sNhoyMmho+omhmo+Ns::dhdmmdy:.oNoyhhs+/o+o++s+hhoo+.`-:....``.-:-`..-````.-``.`` /// @title Dollars Nakamoto by Pascal Boyart /// @author jolan.eth /// @notice This contract will allow you to yield farm Dollars Nakamoto NFT. /// During epoch 0 you will be able to mint a Genesis NFT, /// Over time, epoch will increment allowing you to mint more editions. /// Minting generations editions is allowed only 1 time per epoch and per Genesis NFT. /// Generations editions do not allow you to mint other generations.
NatSpecSingleLine
giftGenesis
function giftGenesis(address to) public onlyOwner { uint256 _genesisId = ++genesisId; setMetadata(tokenId, _genesisId, epoch); genesisController(_genesisId); mintUSDSat(to, tokenId++); }
/// @notice Used to gift Genesis NFT, this function is dedicated /// to contract owner according to { onlyOwner } modifier
NatSpecSingleLine
v0.8.10+commit.fc410830
MIT
ipfs://627efb7c58e0f1a820013031c32ab417b2b86eb0e16948f99bf7e29ad6e50407
{ "func_code_index": [ 13110, 13347 ] }
2,678
USDSat
USDSat.sol
0xbeda58401038c864c9fc9145f28e47b7b00a0e86
Solidity
USDSat
contract USDSat is USDSatMetadata, ERC721, ERC721Enumerable, Ownable, ReentrancyGuard { string SYMBOL = "USDSat"; string NAME = "Dollars Nakamoto"; string ContractCID; /// @notice Address used to sign NFT on mint address public ADDRESS_SIGN = 0x1Af70e564847bE46e4bA286c0b0066Da8372F902; /// @notice Ether shareholder address address public ADDRESS_PBOY = 0x709e17B3Ec505F80eAb064d0F2A71c743cE225B3; /// @notice Ether shareholder address address public ADDRESS_JOLAN = 0x51BdFa2Cbb25591AF58b202aCdcdB33325a325c2; /// @notice Equity per shareholder in % uint256 public SHARE_PBOY = 90; /// @notice Equity per shareholder in % uint256 public SHARE_JOLAN = 10; /// @notice Mapping used to represent allowed addresses to call { mintGenesis } mapping (address => bool) public _allowList; /// @notice Represent the current epoch uint256 public epoch = 0; /// @notice Represent the maximum epoch possible uint256 public epochMax = 10; /// @notice Represent the block length of an epoch uint256 public epochLen = 41016; /// @notice Index of the NFT /// @dev Start at 1 because var++ uint256 public tokenId = 1; /// @notice Index of the Genesis NFT /// @dev Start at 0 because ++var uint256 public genesisId = 0; /// @notice Index of the Generation NFT /// @dev Start at 0 because ++var uint256 public generationId = 0; /// @notice Maximum total supply uint256 public maxTokenSupply = 2100; /// @notice Maximum Genesis supply uint256 public maxGenesisSupply = 210; /// @notice Maximum supply per generation uint256 public maxGenerationSupply = 210; /// @notice Price of the Genesis NFT (Generations NFT are free) uint256 public genesisPrice = 0.5 ether; /// @notice Define the ending block uint256 public blockOmega; /// @notice Define the starting block uint256 public blockGenesis; /// @notice Define in which block the Meta must occur uint256 public blockMeta; /// @notice Used to inflate blockMeta each epoch incrementation uint256 public inflateRatio = 2; /// @notice Open Genesis mint when true bool public genesisMintAllowed = false; /// @notice Open Generation mint when true bool public generationMintAllowed = false; /// @notice Multi dimensionnal mapping to keep a track of the minting reentrancy over epoch mapping(uint256 => mapping(uint256 => bool)) public epochMintingRegistry; event Omega(uint256 _blockNumber); event Genesis(uint256 indexed _epoch, uint256 _blockNumber); event Meta(uint256 indexed _epoch, uint256 _blockNumber); event Withdraw(uint256 indexed _share, address _shareholder); event Shareholder(uint256 indexed _sharePercent, address _shareholder); event Securized(uint256 indexed _epoch, uint256 _epochLen, uint256 _blockMeta, uint256 _inflateRatio); event PermanentURI(string _value, uint256 indexed _id); event Minted(uint256 indexed _epoch, uint256 indexed _tokenId, address indexed _owner); event Signed(uint256 indexed _epoch, uint256 indexed _tokenId, uint256 indexed _blockNumber); constructor() ERC721(NAME, SYMBOL) {} // Withdraw functions ************************************************* /// @notice Allow Pboy to modify ADDRESS_PBOY /// This function is dedicated to the represented shareholder according to require(). function setPboy(address PBOY) public { require(msg.sender == ADDRESS_PBOY, "error msg.sender"); ADDRESS_PBOY = PBOY; emit Shareholder(SHARE_PBOY, ADDRESS_PBOY); } /// @notice Allow Jolan to modify ADDRESS_JOLAN /// This function is dedicated to the represented shareholder according to require(). function setJolan(address JOLAN) public { require(msg.sender == ADDRESS_JOLAN, "error msg.sender"); ADDRESS_JOLAN = JOLAN; emit Shareholder(SHARE_JOLAN, ADDRESS_JOLAN); } /// @notice Used to withdraw ETH balance of the contract, this function is dedicated /// to contract owner according to { onlyOwner } modifier. function withdrawEquity() public onlyOwner nonReentrant { uint256 balance = address(this).balance; address[2] memory shareholders = [ ADDRESS_PBOY, ADDRESS_JOLAN ]; uint256[2] memory _shares = [ SHARE_PBOY * balance / 100, SHARE_JOLAN * balance / 100 ]; uint i = 0; while (i < 2) { require(payable(shareholders[i]).send(_shares[i])); emit Withdraw(_shares[i], shareholders[i]); i++; } } // Epoch functions **************************************************** /// @notice Used to manage authorization and reentrancy of the genesis NFT mint /// @param _genesisId Used to increment { genesisId } and write { epochMintingRegistry } function genesisController(uint256 _genesisId) private { require(epoch == 0, "error epoch"); require(genesisId <= maxGenesisSupply, "error genesisId"); require(!epochMintingRegistry[epoch][_genesisId], "error epochMintingRegistry"); /// @dev Set { _genesisId } for { epoch } as true epochMintingRegistry[epoch][_genesisId] = true; /// @dev When { genesisId } reaches { maxGenesisSupply } the function /// will compute the data to increment the epoch according /// /// { blockGenesis } is set only once, at this time /// { blockMeta } is set to { blockGenesis } because epoch=0 /// Then it is computed into the function epochRegulator() /// /// Once the epoch is regulated, the new generation start /// straight away, { generationMintAllowed } is set to true if (genesisId == maxGenesisSupply) { blockGenesis = block.number; blockMeta = blockGenesis; emit Genesis(epoch, blockGenesis); epochRegulator(); } } /// @notice Used to manage authorization and reentrancy of the Generation NFT mint /// @param _genesisId Used to write { epochMintingRegistry } and verify minting allowance function generationController(uint256 _genesisId) private { require(blockGenesis > 0, "error blockGenesis"); require(blockMeta > 0, "error blockMeta"); require(blockOmega > 0, "error blockOmega"); /// @dev If { block.number } >= { blockMeta } the function /// will compute the data to increment the epoch according /// /// Once the epoch is regulated, the new generation start /// straight away, { generationMintAllowed } is set to true /// /// { generationId } is reset to 1 if (block.number >= blockMeta) { epochRegulator(); generationId = 1; } /// @dev Be sure the mint is open if condition are favorable if (block.number < blockMeta && generationId <= maxGenerationSupply) { generationMintAllowed = true; } require(maxTokenSupply >= tokenId, "error maxTokenSupply"); require(epoch > 0 && epoch < epochMax, "error epoch"); require(ownerOf(_genesisId) == msg.sender, "error ownerOf"); require(generationMintAllowed, "error generationMintAllowed"); require(generationId <= maxGenerationSupply, "error generationId"); require(epochMintingRegistry[0][_genesisId], "error epochMintingRegistry"); require(!epochMintingRegistry[epoch][_genesisId], "error epochMintingRegistry"); /// @dev Set { _genesisId } for { epoch } as true epochMintingRegistry[epoch][_genesisId] = true; /// @dev If { generationId } reaches { maxGenerationSupply } the modifier /// will set { generationMintAllowed } to false to stop the mint /// on this generation /// /// { generationId } is reset to 0 /// /// This condition will not block the function because as long as /// { block.number } >= { blockMeta } minting will reopen /// according and this condition will become obsolete until /// the condition is reached again if (generationId == maxGenerationSupply) { generationMintAllowed = false; generationId = 0; } } /// @notice Used to protect epoch block length from difficulty bomb of the /// Ethereum network. A difficulty bomb heavily increases the difficulty /// on the network, likely also causing an increase in block time. /// If the block time increases too much, the epoch generation could become /// exponentially higher than what is desired, ending with an undesired Ice-Age. /// To protect against this, the emergencySecure() function is allowed to /// manually reconfigure the epoch block length and the block Meta /// to match the network conditions if necessary. /// /// It can also be useful if the block time decreases for some reason with consensus change. /// /// This function is dedicated to contract owner according to { onlyOwner } modifier function emergencySecure(uint256 _epoch, uint256 _epochLen, uint256 _blockMeta, uint256 _inflateRatio) public onlyOwner { require(epoch > 0, "error epoch"); require(_epoch > 0, "error _epoch"); require(maxTokenSupply >= tokenId, "error maxTokenSupply"); epoch = _epoch; epochLen = _epochLen; blockMeta = _blockMeta; inflateRatio = _inflateRatio; computeBlockOmega(); emit Securized(epoch, epochLen, blockMeta, inflateRatio); } /// @notice Used to compute blockOmega() function, { blockOmega } represents /// the block when it won't ever be possible to mint another Dollars Nakamoto NFT. /// It is possible to be computed because of the deterministic state of the current protocol /// The following algorithm simulate the 10 epochs of the protocol block computation to result blockOmega function computeBlockOmega() private { uint256 i = 0; uint256 _blockMeta = 0; uint256 _epochLen = epochLen; while (i < epochMax) { if (i > 0) _epochLen *= inflateRatio; if (i == 9) { blockOmega = blockGenesis + _blockMeta; emit Omega(blockOmega); break; } _blockMeta += _epochLen; i++; } } /// @notice Used to regulate the epoch incrementation and block computation, known as Metas /// @dev When epoch=0, the { blockOmega } will be computed /// When epoch!=0 the block length { epochLen } will be multiplied /// by { inflateRatio } thus making the block length required for each /// epoch longer according /// /// { blockMeta } += { epochLen } result the exact block of the next Meta /// Allow generation mint after incrementing the epoch function epochRegulator() private { if (epoch == 0) computeBlockOmega(); if (epoch > 0) epochLen *= inflateRatio; blockMeta += epochLen; emit Meta(epoch, blockMeta); epoch++; if (block.number >= blockMeta && epoch < epochMax) { epochRegulator(); } generationMintAllowed = true; } // Mint functions ***************************************************** /// @notice Used to add/remove address from { _allowList } function setBatchGenesisAllowance(address[] memory batch) public onlyOwner { uint len = batch.length; require(len > 0, "error len"); uint i = 0; while (i < len) { _allowList[batch[i]] = _allowList[batch[i]] ? false : true; i++; } } /// @notice Used to transfer { _allowList } slot to another address function transferListSlot(address to) public { require(epoch == 0, "error epoch"); require(_allowList[msg.sender], "error msg.sender"); require(!_allowList[to], "error to"); _allowList[msg.sender] = false; _allowList[to] = true; } /// @notice Used to open the mint of Genesis NFT function setGenesisMint() public onlyOwner { genesisMintAllowed = true; } /// @notice Used to gift Genesis NFT, this function is dedicated /// to contract owner according to { onlyOwner } modifier function giftGenesis(address to) public onlyOwner { uint256 _genesisId = ++genesisId; setMetadata(tokenId, _genesisId, epoch); genesisController(_genesisId); mintUSDSat(to, tokenId++); } /// @notice Used to mint Genesis NFT, this function is payable /// the price of this function is equal to { genesisPrice }, /// require to be present on { _allowList } to call function mintGenesis() public payable { uint256 _genesisId = ++genesisId; setMetadata(tokenId, _genesisId, epoch); genesisController(_genesisId); require(genesisMintAllowed, "error genesisMintAllowed"); require(_allowList[msg.sender], "error allowList"); require(genesisPrice == msg.value, "error genesisPrice"); _allowList[msg.sender] = false; mintUSDSat(msg.sender, tokenId++); } /// @notice Used to gift Generation NFT, you need a Genesis NFT to call this function function giftGenerations(uint256 _genesisId, address to) public { ++generationId; generationController(_genesisId); setMetadata(tokenId, _genesisId, epoch); mintUSDSat(to, tokenId++); } /// @notice Used to mint Generation NFT, you need a Genesis NFT to call this function function mintGenerations(uint256 _genesisId) public { ++generationId; generationController(_genesisId); setMetadata(tokenId, _genesisId, epoch); mintUSDSat(msg.sender, tokenId++); } /// @notice Token is minted on { ADDRESS_SIGN } and instantly transferred to { msg.sender } as { to }, /// this is to ensure the token creation is signed with { ADDRESS_SIGN } /// This function is private and can be only called by the contract function mintUSDSat(address to, uint256 _tokenId) private { emit PermanentURI(_compileMetadata(_tokenId), _tokenId); _safeMint(ADDRESS_SIGN, _tokenId); emit Signed(epoch, _tokenId, block.number); _safeTransfer(ADDRESS_SIGN, to, _tokenId, ""); emit Minted(epoch, _tokenId, to); } // Contract URI functions ********************************************* /// @notice Used to set the { ContractCID } metadata from ipfs, /// this function is dedicated to contract owner according /// to { onlyOwner } modifier function setContractCID(string memory CID) public onlyOwner { ContractCID = string(abi.encodePacked("ipfs://", CID)); } /// @notice Used to render { ContractCID } as { contractURI } according to /// Opensea contract metadata standard function contractURI() public view virtual returns (string memory) { return ContractCID; } // Utilitaries functions ********************************************** /// @notice Used to fetch all entry for { epoch } into { epochMintingRegistry } function getMapRegisteryForEpoch(uint256 _epoch) public view returns (bool[210] memory result) { uint i = 1; while (i <= maxGenesisSupply) { result[i] = epochMintingRegistry[_epoch][i]; i++; } } /// @notice Used to fetch all { tokenIds } from { owner } function exposeHeldIds(address owner) public view returns(uint[] memory) { uint tokenCount = balanceOf(owner); uint[] memory tokenIds = new uint[](tokenCount); uint i = 0; while (i < tokenCount) { tokenIds[i] = tokenOfOwnerByIndex(owner, i); i++; } return tokenIds; } // ERC721 Spec functions ********************************************** /// @notice Used to render metadata as { tokenURI } according to ERC721 standard function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token"); return _compileMetadata(_tokenId); } /// @dev ERC721 required override function _beforeTokenTransfer(address from, address to, uint256 _tokenId) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, _tokenId); } /// @dev ERC721 required override function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } }
/// ``.. /// `.` `````.``.-````-`` `.` /// ` ``````.`..///.-..----. --..--`.-....`..-.```` ``` /// `` `.`..--...`:::/::-``..``..:-.://///---..-....----- /// ``-:::/+++:::/-.-///://oso+::++/--:--../+:/:..:-....-://:/:-`` /// `-+/++/+o+://+::-:soo+oosss+s+//o:/:--`--:://://:ooso/-.--.-:-.` /// ``.+ooso++o+:+:+sosyhsyshhddyo+:/sds/yoo++/+:--/--.--:..--..``.```` /// ``:++/---:+/::::///oyhhyy+++:hddhhNNho///ohosyhs+/-:/+/---.....-.. ` /// ``-:-...-/+///++///+o+:-:o+o/oydmNmNNdddhsoyo/oyyyho///:-.--.-.``. `` /// ```--`..-:+/:--:::-.-///++++ydsdNNMNdmMNMmNysddyoooosso+//-.-`....````` ..` /// .```:-:::/-.-+o++/+:/+/o/hNNNNhmdNMMNNMMdyydNNmdyys+++oo++-`--.:.-.`````... /// ..--.`-..`.-`-hh++-/:+shho+hsysyyhhhmNNmmNMMmNNNdmmy+:+sh/o+y/+-`+./::.```` ` /// -/` ``.-``.//o++y+//ssyh+hhdmmdmmddmhdmNdmdsh+oNNMmmddoodh/s:yss.--+.//+`.` `. /// `.`-.` -`..+h+yo++ooyyyyyoyhy+shmNNmmdhhdhyyhymdyyhdmshoohs+y:oy+/+o/:/++.`- .` /// ``.`.``-.-++syyyhhhhhhhhmhysosyyoooosssdhhhdmmdhdmdsy+ss+/+ho/hody-s+-:+::--`` ` /// .`` ``-//s+:ohmdmddNmNmhhshhddNNNhyyhhhdNNhmNNmNNmmyso+yhhso++hhdy.:/ ::-:--``.` /// .```.-`.//shdmNNmddyysohmMmdmNNmmNshdmNhso+-/ohNoyhmmsysosd++hy/osss/.:-o/-.:/--. /// ``..:++-+hhy/syhhhdhdNNddNMmNsNMNyyso+//:-.`-/..+hmdsmdy+ossos:+o/h/+..//-s.`.:::o/ /// `.-.oy//hm+o:-..-+/shdNNNNNNhsNdo/oyoyyhoh+/so//+/mNmyhh+/s+dy/+s::+:`-`-:s--:-.::+`-` /// .`:h-`+y+./oyhhdddhyohMMNmmNmdhoo/oyyhddhmNNNmhsoodmdhs+///++:+-:.:/--/-/o/--+//...:` /// ``+o``yoodNNNNNMhdyyo+ymhsymyshhyys+sssssNmdmmdmy+oso/++:://+/-`::-:--:/::+.//o:-.--: /// `:-:-`oNhyhdNNNmyys+/:://oohy++/+hmmmmNNNNhohydmmyhy++////ooy./----.-:---/::-o+:...-/ /// ``-.-` yms+mmNmMMmNho/:o++++hhh++:mMmNmmmNMNdhdms+ysyy//:-+o:.-.`.``.-:/::-:-+/y/.- -` /// ..:` hh+oNNmMNNNmss/:-+oyhs+o+.-yhdNmdhmmydmms+o///:///+/+--/`-``.o::/:-o//-/y::/.- /// `.-``hh+yNdmdohdy:++/./myhds/./shNhhyy++o:oyos/s+:s//+////.:- ...`--`..`-.:--o:+::` /// `-/+yyho.`.-+oso///+/Nmddh//y+:s:.../soy+:o+.:sdyo++++o:.-. `.:.:-```:.`:``/o:`:` /// ./.`..sMN+:::yh+s+ysyhhddh+ymdsd/:/+o+ysydhohoh/o+/so++o+/o.--..`-:::``:-`+-`:+--.` /// ``:``..-NNy++/yyysohmo+NNmy/+:+hMNmy+yydmNMNddhs:yyydmmmso:o///..-.-+-:o:/.o/-/+-`` /// ``+.`..-mMhsyo+++oo+yoshyyo+/`+hNmhyy+sdmdssssho-MMMNMNh//+/oo+/+:-....`.s+/`..-` /// .+ `oNMmdhhsohhmmydmNms/yy.oNmmdy+++/+ss+odNm+mNmdddo-s+:+/++/-:--//`/o+s/.-`` /// `/` dNNNhooddNmNymMNNdsoo+y+shhhmyymhss+hddms+hdhmdo+/+-/oo+/.///+sh:-/-s/` /// `::`hdNmh+ooNmdohNNMMmsooohh+oysydhdooo/syysodmNmys+/o+//+y/:.+/hmso.-//s- /// -+ohdmmhyhdysysyyhmysoyddhhoo+shdhdyddmddmNmmhssds/::/oo/..:/+Nmo+`-:so /// .oyhdmmNNdm+s:/:os/+/ssyyds+/ssdNNyhdmmhdmmdymymy///o:/``/+-dmdoo++:o` /// `ysyMNhhmoo+h-:/+o/+:.:/:/+doo+dNdhddmhmmmy++yhds/+-+::..o/+Nmosyhs+- /// s+dNNyNhsdhNhsy:+:oo/soo+dNmmooyosohMhsymmhyy+++:+:/+/-/o+yNh+hMNs. /// +yhNNMd+dmydmdy/+/sshydmhdNNmNooyhhhhshohmNh+:+oso++ssy+/odyhhNmh` /// `yyhdms+dMh+oyshhyhysdmNd+ohyNN+++mNddmNy+yo//+o/hddddymmyhosNmms` /// oydos:oMmhoyyhysssysdmMmNmhNmNNh/+mmNmddh+/+o+::+s+hmhmdyNNNNy: /// `/dNm/+Ndhy+oshdhhdyo::ohmdyhhNysy:smshmdo/o:so//:s++ymhyohdy-` /// `sNNN/hNm/:do+o:+/++++s:/+shyymmddy/ydmmh/s/+oss//oysy++o+o+` /// oNNMNmm:/hyy/:/o/+hhsosysoo-ohhhss/hmmhd/dyh++/soyooy++o+:. /// :/dMNh/smhh+//+s+--:+/so+ohhy/:sydmmmmm+/mdddhy++/ohs//-o/` /// `/odmhyhsyh++/-:+:::/:/o/:ooddy/+yodNNh+ydhmmmy++/hhyo+://` /// `:os/+o//oshss/yhs+//:+/-/:soooo/+sso+dddydss+:+sy///+:++ /// ./o/s//hhNho+shyyyoyyso+/ys+/+-:y+:/soooyyh++sNyo++/:/+ /// -/:osmmhyo:++++/+/osshdssooo/:/h//://++oyhsshmdo+//s/- /// .osmhydh::/+++/o+ohhysddyoo++os+-+++///yhhhmNs+o/:// /// -.++yss//////+/+/+soo++shyhsyy+::/:+y+yhdmdoo//:/:- /// ``.oss/:////++://+o//:://+oo-:o++/shhhmmh+o+++///-` /// ..:+++oo/+///ys:///://+::-sy+osh+osdyo+o/::/s:/y-` /// `odoyhds+/yysyydss+///+/:+oshdmNo+:+/oo/+++++:hy//` /// `://hyoyy/o/++shhy:+y:/:o/+omNmhsoohhsso+++:+o+sy:/++ /// -/---oddooss+oosy+ohNdo+++oyNhsdo/++shhhoo:s+oydmyo//o+ /// :y.`.``yyd++shoyydhhyymdhyyhyhhs+////+/+s/+:odmmyso.:ohy. /// .yy/o-..+h/+o/+//++ssoohhhssso+++:/:/yy+//sydmNddo+/./ohy+. /// .dmmhs+osdoos///o//++/+shdsoshoys+ssss++shmNNNyyds+:-s-//:+. /// -shmNmyhddsyss++/+ysddhyyydhdmyssNddyydyhNmdNmddso/::s:--`.-.` /// `+dmNhhdmddsooyyooossysshdhmoss+/+mNdyymydMdyMdyoo+/--/:/:`...-.` /// .:smNNMmsMNNmdhyyo/yymmdmdyo+ooooshysyysNNNmmmNyss/+o-`-:-/:```.`` ``` /// `.-+o/sdNNNmhdddNmmdsso/sdshyyyyhsdddyohymdmNdmmmmmyoo+/.... -os.`.``-.`` /// `/-:-/+.hymmmmdhmyNdMNmmhhs+sosoyhddyddmmho/ooymhddhdhyos-.oy..-:o+:..`` ```` ` /// ..::``--.-hoymmdNNNNNNMmhyNh+oo+soyNdmNmmmysooooymhy+so++yo..:+.--`..:.`.` `-- ``.` ` /// ```-.-.``..`:ddymmmNNdmNNNNmhN: -/oys/sdmmNdydsydmhhsmdso+/yo:/-..`.``.` ``:.`.````-. ` /// ````-:/.```:::syyydmddNhNNdsdMMs`./oddmd./odNdy+yssss++ooo/o+//-`:/:..:`-.```/-:.`.```..`` ` /// ```..-`` --.`.--o+sNhoyMmho+omhmo+Ns::dhdmmdy:.oNoyhhs+/o+o++s+hhoo+.`-:....``.-:-`..-````.-``.`` /// @title Dollars Nakamoto by Pascal Boyart /// @author jolan.eth /// @notice This contract will allow you to yield farm Dollars Nakamoto NFT. /// During epoch 0 you will be able to mint a Genesis NFT, /// Over time, epoch will increment allowing you to mint more editions. /// Minting generations editions is allowed only 1 time per epoch and per Genesis NFT. /// Generations editions do not allow you to mint other generations.
NatSpecSingleLine
mintGenesis
function mintGenesis() public payable { uint256 _genesisId = ++genesisId; setMetadata(tokenId, _genesisId, epoch); genesisController(_genesisId); require(genesisMintAllowed, "error genesisMintAllowed"); require(_allowList[msg.sender], "error allowList"); require(genesisPrice == msg.value, "error genesisPrice"); _allowList[msg.sender] = false; mintUSDSat(msg.sender, tokenId++); }
/// @notice Used to mint Genesis NFT, this function is payable /// the price of this function is equal to { genesisPrice }, /// require to be present on { _allowList } to call
NatSpecSingleLine
v0.8.10+commit.fc410830
MIT
ipfs://627efb7c58e0f1a820013031c32ab417b2b86eb0e16948f99bf7e29ad6e50407
{ "func_code_index": [ 13557, 14028 ] }
2,679
USDSat
USDSat.sol
0xbeda58401038c864c9fc9145f28e47b7b00a0e86
Solidity
USDSat
contract USDSat is USDSatMetadata, ERC721, ERC721Enumerable, Ownable, ReentrancyGuard { string SYMBOL = "USDSat"; string NAME = "Dollars Nakamoto"; string ContractCID; /// @notice Address used to sign NFT on mint address public ADDRESS_SIGN = 0x1Af70e564847bE46e4bA286c0b0066Da8372F902; /// @notice Ether shareholder address address public ADDRESS_PBOY = 0x709e17B3Ec505F80eAb064d0F2A71c743cE225B3; /// @notice Ether shareholder address address public ADDRESS_JOLAN = 0x51BdFa2Cbb25591AF58b202aCdcdB33325a325c2; /// @notice Equity per shareholder in % uint256 public SHARE_PBOY = 90; /// @notice Equity per shareholder in % uint256 public SHARE_JOLAN = 10; /// @notice Mapping used to represent allowed addresses to call { mintGenesis } mapping (address => bool) public _allowList; /// @notice Represent the current epoch uint256 public epoch = 0; /// @notice Represent the maximum epoch possible uint256 public epochMax = 10; /// @notice Represent the block length of an epoch uint256 public epochLen = 41016; /// @notice Index of the NFT /// @dev Start at 1 because var++ uint256 public tokenId = 1; /// @notice Index of the Genesis NFT /// @dev Start at 0 because ++var uint256 public genesisId = 0; /// @notice Index of the Generation NFT /// @dev Start at 0 because ++var uint256 public generationId = 0; /// @notice Maximum total supply uint256 public maxTokenSupply = 2100; /// @notice Maximum Genesis supply uint256 public maxGenesisSupply = 210; /// @notice Maximum supply per generation uint256 public maxGenerationSupply = 210; /// @notice Price of the Genesis NFT (Generations NFT are free) uint256 public genesisPrice = 0.5 ether; /// @notice Define the ending block uint256 public blockOmega; /// @notice Define the starting block uint256 public blockGenesis; /// @notice Define in which block the Meta must occur uint256 public blockMeta; /// @notice Used to inflate blockMeta each epoch incrementation uint256 public inflateRatio = 2; /// @notice Open Genesis mint when true bool public genesisMintAllowed = false; /// @notice Open Generation mint when true bool public generationMintAllowed = false; /// @notice Multi dimensionnal mapping to keep a track of the minting reentrancy over epoch mapping(uint256 => mapping(uint256 => bool)) public epochMintingRegistry; event Omega(uint256 _blockNumber); event Genesis(uint256 indexed _epoch, uint256 _blockNumber); event Meta(uint256 indexed _epoch, uint256 _blockNumber); event Withdraw(uint256 indexed _share, address _shareholder); event Shareholder(uint256 indexed _sharePercent, address _shareholder); event Securized(uint256 indexed _epoch, uint256 _epochLen, uint256 _blockMeta, uint256 _inflateRatio); event PermanentURI(string _value, uint256 indexed _id); event Minted(uint256 indexed _epoch, uint256 indexed _tokenId, address indexed _owner); event Signed(uint256 indexed _epoch, uint256 indexed _tokenId, uint256 indexed _blockNumber); constructor() ERC721(NAME, SYMBOL) {} // Withdraw functions ************************************************* /// @notice Allow Pboy to modify ADDRESS_PBOY /// This function is dedicated to the represented shareholder according to require(). function setPboy(address PBOY) public { require(msg.sender == ADDRESS_PBOY, "error msg.sender"); ADDRESS_PBOY = PBOY; emit Shareholder(SHARE_PBOY, ADDRESS_PBOY); } /// @notice Allow Jolan to modify ADDRESS_JOLAN /// This function is dedicated to the represented shareholder according to require(). function setJolan(address JOLAN) public { require(msg.sender == ADDRESS_JOLAN, "error msg.sender"); ADDRESS_JOLAN = JOLAN; emit Shareholder(SHARE_JOLAN, ADDRESS_JOLAN); } /// @notice Used to withdraw ETH balance of the contract, this function is dedicated /// to contract owner according to { onlyOwner } modifier. function withdrawEquity() public onlyOwner nonReentrant { uint256 balance = address(this).balance; address[2] memory shareholders = [ ADDRESS_PBOY, ADDRESS_JOLAN ]; uint256[2] memory _shares = [ SHARE_PBOY * balance / 100, SHARE_JOLAN * balance / 100 ]; uint i = 0; while (i < 2) { require(payable(shareholders[i]).send(_shares[i])); emit Withdraw(_shares[i], shareholders[i]); i++; } } // Epoch functions **************************************************** /// @notice Used to manage authorization and reentrancy of the genesis NFT mint /// @param _genesisId Used to increment { genesisId } and write { epochMintingRegistry } function genesisController(uint256 _genesisId) private { require(epoch == 0, "error epoch"); require(genesisId <= maxGenesisSupply, "error genesisId"); require(!epochMintingRegistry[epoch][_genesisId], "error epochMintingRegistry"); /// @dev Set { _genesisId } for { epoch } as true epochMintingRegistry[epoch][_genesisId] = true; /// @dev When { genesisId } reaches { maxGenesisSupply } the function /// will compute the data to increment the epoch according /// /// { blockGenesis } is set only once, at this time /// { blockMeta } is set to { blockGenesis } because epoch=0 /// Then it is computed into the function epochRegulator() /// /// Once the epoch is regulated, the new generation start /// straight away, { generationMintAllowed } is set to true if (genesisId == maxGenesisSupply) { blockGenesis = block.number; blockMeta = blockGenesis; emit Genesis(epoch, blockGenesis); epochRegulator(); } } /// @notice Used to manage authorization and reentrancy of the Generation NFT mint /// @param _genesisId Used to write { epochMintingRegistry } and verify minting allowance function generationController(uint256 _genesisId) private { require(blockGenesis > 0, "error blockGenesis"); require(blockMeta > 0, "error blockMeta"); require(blockOmega > 0, "error blockOmega"); /// @dev If { block.number } >= { blockMeta } the function /// will compute the data to increment the epoch according /// /// Once the epoch is regulated, the new generation start /// straight away, { generationMintAllowed } is set to true /// /// { generationId } is reset to 1 if (block.number >= blockMeta) { epochRegulator(); generationId = 1; } /// @dev Be sure the mint is open if condition are favorable if (block.number < blockMeta && generationId <= maxGenerationSupply) { generationMintAllowed = true; } require(maxTokenSupply >= tokenId, "error maxTokenSupply"); require(epoch > 0 && epoch < epochMax, "error epoch"); require(ownerOf(_genesisId) == msg.sender, "error ownerOf"); require(generationMintAllowed, "error generationMintAllowed"); require(generationId <= maxGenerationSupply, "error generationId"); require(epochMintingRegistry[0][_genesisId], "error epochMintingRegistry"); require(!epochMintingRegistry[epoch][_genesisId], "error epochMintingRegistry"); /// @dev Set { _genesisId } for { epoch } as true epochMintingRegistry[epoch][_genesisId] = true; /// @dev If { generationId } reaches { maxGenerationSupply } the modifier /// will set { generationMintAllowed } to false to stop the mint /// on this generation /// /// { generationId } is reset to 0 /// /// This condition will not block the function because as long as /// { block.number } >= { blockMeta } minting will reopen /// according and this condition will become obsolete until /// the condition is reached again if (generationId == maxGenerationSupply) { generationMintAllowed = false; generationId = 0; } } /// @notice Used to protect epoch block length from difficulty bomb of the /// Ethereum network. A difficulty bomb heavily increases the difficulty /// on the network, likely also causing an increase in block time. /// If the block time increases too much, the epoch generation could become /// exponentially higher than what is desired, ending with an undesired Ice-Age. /// To protect against this, the emergencySecure() function is allowed to /// manually reconfigure the epoch block length and the block Meta /// to match the network conditions if necessary. /// /// It can also be useful if the block time decreases for some reason with consensus change. /// /// This function is dedicated to contract owner according to { onlyOwner } modifier function emergencySecure(uint256 _epoch, uint256 _epochLen, uint256 _blockMeta, uint256 _inflateRatio) public onlyOwner { require(epoch > 0, "error epoch"); require(_epoch > 0, "error _epoch"); require(maxTokenSupply >= tokenId, "error maxTokenSupply"); epoch = _epoch; epochLen = _epochLen; blockMeta = _blockMeta; inflateRatio = _inflateRatio; computeBlockOmega(); emit Securized(epoch, epochLen, blockMeta, inflateRatio); } /// @notice Used to compute blockOmega() function, { blockOmega } represents /// the block when it won't ever be possible to mint another Dollars Nakamoto NFT. /// It is possible to be computed because of the deterministic state of the current protocol /// The following algorithm simulate the 10 epochs of the protocol block computation to result blockOmega function computeBlockOmega() private { uint256 i = 0; uint256 _blockMeta = 0; uint256 _epochLen = epochLen; while (i < epochMax) { if (i > 0) _epochLen *= inflateRatio; if (i == 9) { blockOmega = blockGenesis + _blockMeta; emit Omega(blockOmega); break; } _blockMeta += _epochLen; i++; } } /// @notice Used to regulate the epoch incrementation and block computation, known as Metas /// @dev When epoch=0, the { blockOmega } will be computed /// When epoch!=0 the block length { epochLen } will be multiplied /// by { inflateRatio } thus making the block length required for each /// epoch longer according /// /// { blockMeta } += { epochLen } result the exact block of the next Meta /// Allow generation mint after incrementing the epoch function epochRegulator() private { if (epoch == 0) computeBlockOmega(); if (epoch > 0) epochLen *= inflateRatio; blockMeta += epochLen; emit Meta(epoch, blockMeta); epoch++; if (block.number >= blockMeta && epoch < epochMax) { epochRegulator(); } generationMintAllowed = true; } // Mint functions ***************************************************** /// @notice Used to add/remove address from { _allowList } function setBatchGenesisAllowance(address[] memory batch) public onlyOwner { uint len = batch.length; require(len > 0, "error len"); uint i = 0; while (i < len) { _allowList[batch[i]] = _allowList[batch[i]] ? false : true; i++; } } /// @notice Used to transfer { _allowList } slot to another address function transferListSlot(address to) public { require(epoch == 0, "error epoch"); require(_allowList[msg.sender], "error msg.sender"); require(!_allowList[to], "error to"); _allowList[msg.sender] = false; _allowList[to] = true; } /// @notice Used to open the mint of Genesis NFT function setGenesisMint() public onlyOwner { genesisMintAllowed = true; } /// @notice Used to gift Genesis NFT, this function is dedicated /// to contract owner according to { onlyOwner } modifier function giftGenesis(address to) public onlyOwner { uint256 _genesisId = ++genesisId; setMetadata(tokenId, _genesisId, epoch); genesisController(_genesisId); mintUSDSat(to, tokenId++); } /// @notice Used to mint Genesis NFT, this function is payable /// the price of this function is equal to { genesisPrice }, /// require to be present on { _allowList } to call function mintGenesis() public payable { uint256 _genesisId = ++genesisId; setMetadata(tokenId, _genesisId, epoch); genesisController(_genesisId); require(genesisMintAllowed, "error genesisMintAllowed"); require(_allowList[msg.sender], "error allowList"); require(genesisPrice == msg.value, "error genesisPrice"); _allowList[msg.sender] = false; mintUSDSat(msg.sender, tokenId++); } /// @notice Used to gift Generation NFT, you need a Genesis NFT to call this function function giftGenerations(uint256 _genesisId, address to) public { ++generationId; generationController(_genesisId); setMetadata(tokenId, _genesisId, epoch); mintUSDSat(to, tokenId++); } /// @notice Used to mint Generation NFT, you need a Genesis NFT to call this function function mintGenerations(uint256 _genesisId) public { ++generationId; generationController(_genesisId); setMetadata(tokenId, _genesisId, epoch); mintUSDSat(msg.sender, tokenId++); } /// @notice Token is minted on { ADDRESS_SIGN } and instantly transferred to { msg.sender } as { to }, /// this is to ensure the token creation is signed with { ADDRESS_SIGN } /// This function is private and can be only called by the contract function mintUSDSat(address to, uint256 _tokenId) private { emit PermanentURI(_compileMetadata(_tokenId), _tokenId); _safeMint(ADDRESS_SIGN, _tokenId); emit Signed(epoch, _tokenId, block.number); _safeTransfer(ADDRESS_SIGN, to, _tokenId, ""); emit Minted(epoch, _tokenId, to); } // Contract URI functions ********************************************* /// @notice Used to set the { ContractCID } metadata from ipfs, /// this function is dedicated to contract owner according /// to { onlyOwner } modifier function setContractCID(string memory CID) public onlyOwner { ContractCID = string(abi.encodePacked("ipfs://", CID)); } /// @notice Used to render { ContractCID } as { contractURI } according to /// Opensea contract metadata standard function contractURI() public view virtual returns (string memory) { return ContractCID; } // Utilitaries functions ********************************************** /// @notice Used to fetch all entry for { epoch } into { epochMintingRegistry } function getMapRegisteryForEpoch(uint256 _epoch) public view returns (bool[210] memory result) { uint i = 1; while (i <= maxGenesisSupply) { result[i] = epochMintingRegistry[_epoch][i]; i++; } } /// @notice Used to fetch all { tokenIds } from { owner } function exposeHeldIds(address owner) public view returns(uint[] memory) { uint tokenCount = balanceOf(owner); uint[] memory tokenIds = new uint[](tokenCount); uint i = 0; while (i < tokenCount) { tokenIds[i] = tokenOfOwnerByIndex(owner, i); i++; } return tokenIds; } // ERC721 Spec functions ********************************************** /// @notice Used to render metadata as { tokenURI } according to ERC721 standard function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token"); return _compileMetadata(_tokenId); } /// @dev ERC721 required override function _beforeTokenTransfer(address from, address to, uint256 _tokenId) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, _tokenId); } /// @dev ERC721 required override function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } }
/// ``.. /// `.` `````.``.-````-`` `.` /// ` ``````.`..///.-..----. --..--`.-....`..-.```` ``` /// `` `.`..--...`:::/::-``..``..:-.://///---..-....----- /// ``-:::/+++:::/-.-///://oso+::++/--:--../+:/:..:-....-://:/:-`` /// `-+/++/+o+://+::-:soo+oosss+s+//o:/:--`--:://://:ooso/-.--.-:-.` /// ``.+ooso++o+:+:+sosyhsyshhddyo+:/sds/yoo++/+:--/--.--:..--..``.```` /// ``:++/---:+/::::///oyhhyy+++:hddhhNNho///ohosyhs+/-:/+/---.....-.. ` /// ``-:-...-/+///++///+o+:-:o+o/oydmNmNNdddhsoyo/oyyyho///:-.--.-.``. `` /// ```--`..-:+/:--:::-.-///++++ydsdNNMNdmMNMmNysddyoooosso+//-.-`....````` ..` /// .```:-:::/-.-+o++/+:/+/o/hNNNNhmdNMMNNMMdyydNNmdyys+++oo++-`--.:.-.`````... /// ..--.`-..`.-`-hh++-/:+shho+hsysyyhhhmNNmmNMMmNNNdmmy+:+sh/o+y/+-`+./::.```` ` /// -/` ``.-``.//o++y+//ssyh+hhdmmdmmddmhdmNdmdsh+oNNMmmddoodh/s:yss.--+.//+`.` `. /// `.`-.` -`..+h+yo++ooyyyyyoyhy+shmNNmmdhhdhyyhymdyyhdmshoohs+y:oy+/+o/:/++.`- .` /// ``.`.``-.-++syyyhhhhhhhhmhysosyyoooosssdhhhdmmdhdmdsy+ss+/+ho/hody-s+-:+::--`` ` /// .`` ``-//s+:ohmdmddNmNmhhshhddNNNhyyhhhdNNhmNNmNNmmyso+yhhso++hhdy.:/ ::-:--``.` /// .```.-`.//shdmNNmddyysohmMmdmNNmmNshdmNhso+-/ohNoyhmmsysosd++hy/osss/.:-o/-.:/--. /// ``..:++-+hhy/syhhhdhdNNddNMmNsNMNyyso+//:-.`-/..+hmdsmdy+ossos:+o/h/+..//-s.`.:::o/ /// `.-.oy//hm+o:-..-+/shdNNNNNNhsNdo/oyoyyhoh+/so//+/mNmyhh+/s+dy/+s::+:`-`-:s--:-.::+`-` /// .`:h-`+y+./oyhhdddhyohMMNmmNmdhoo/oyyhddhmNNNmhsoodmdhs+///++:+-:.:/--/-/o/--+//...:` /// ``+o``yoodNNNNNMhdyyo+ymhsymyshhyys+sssssNmdmmdmy+oso/++:://+/-`::-:--:/::+.//o:-.--: /// `:-:-`oNhyhdNNNmyys+/:://oohy++/+hmmmmNNNNhohydmmyhy++////ooy./----.-:---/::-o+:...-/ /// ``-.-` yms+mmNmMMmNho/:o++++hhh++:mMmNmmmNMNdhdms+ysyy//:-+o:.-.`.``.-:/::-:-+/y/.- -` /// ..:` hh+oNNmMNNNmss/:-+oyhs+o+.-yhdNmdhmmydmms+o///:///+/+--/`-``.o::/:-o//-/y::/.- /// `.-``hh+yNdmdohdy:++/./myhds/./shNhhyy++o:oyos/s+:s//+////.:- ...`--`..`-.:--o:+::` /// `-/+yyho.`.-+oso///+/Nmddh//y+:s:.../soy+:o+.:sdyo++++o:.-. `.:.:-```:.`:``/o:`:` /// ./.`..sMN+:::yh+s+ysyhhddh+ymdsd/:/+o+ysydhohoh/o+/so++o+/o.--..`-:::``:-`+-`:+--.` /// ``:``..-NNy++/yyysohmo+NNmy/+:+hMNmy+yydmNMNddhs:yyydmmmso:o///..-.-+-:o:/.o/-/+-`` /// ``+.`..-mMhsyo+++oo+yoshyyo+/`+hNmhyy+sdmdssssho-MMMNMNh//+/oo+/+:-....`.s+/`..-` /// .+ `oNMmdhhsohhmmydmNms/yy.oNmmdy+++/+ss+odNm+mNmdddo-s+:+/++/-:--//`/o+s/.-`` /// `/` dNNNhooddNmNymMNNdsoo+y+shhhmyymhss+hddms+hdhmdo+/+-/oo+/.///+sh:-/-s/` /// `::`hdNmh+ooNmdohNNMMmsooohh+oysydhdooo/syysodmNmys+/o+//+y/:.+/hmso.-//s- /// -+ohdmmhyhdysysyyhmysoyddhhoo+shdhdyddmddmNmmhssds/::/oo/..:/+Nmo+`-:so /// .oyhdmmNNdm+s:/:os/+/ssyyds+/ssdNNyhdmmhdmmdymymy///o:/``/+-dmdoo++:o` /// `ysyMNhhmoo+h-:/+o/+:.:/:/+doo+dNdhddmhmmmy++yhds/+-+::..o/+Nmosyhs+- /// s+dNNyNhsdhNhsy:+:oo/soo+dNmmooyosohMhsymmhyy+++:+:/+/-/o+yNh+hMNs. /// +yhNNMd+dmydmdy/+/sshydmhdNNmNooyhhhhshohmNh+:+oso++ssy+/odyhhNmh` /// `yyhdms+dMh+oyshhyhysdmNd+ohyNN+++mNddmNy+yo//+o/hddddymmyhosNmms` /// oydos:oMmhoyyhysssysdmMmNmhNmNNh/+mmNmddh+/+o+::+s+hmhmdyNNNNy: /// `/dNm/+Ndhy+oshdhhdyo::ohmdyhhNysy:smshmdo/o:so//:s++ymhyohdy-` /// `sNNN/hNm/:do+o:+/++++s:/+shyymmddy/ydmmh/s/+oss//oysy++o+o+` /// oNNMNmm:/hyy/:/o/+hhsosysoo-ohhhss/hmmhd/dyh++/soyooy++o+:. /// :/dMNh/smhh+//+s+--:+/so+ohhy/:sydmmmmm+/mdddhy++/ohs//-o/` /// `/odmhyhsyh++/-:+:::/:/o/:ooddy/+yodNNh+ydhmmmy++/hhyo+://` /// `:os/+o//oshss/yhs+//:+/-/:soooo/+sso+dddydss+:+sy///+:++ /// ./o/s//hhNho+shyyyoyyso+/ys+/+-:y+:/soooyyh++sNyo++/:/+ /// -/:osmmhyo:++++/+/osshdssooo/:/h//://++oyhsshmdo+//s/- /// .osmhydh::/+++/o+ohhysddyoo++os+-+++///yhhhmNs+o/:// /// -.++yss//////+/+/+soo++shyhsyy+::/:+y+yhdmdoo//:/:- /// ``.oss/:////++://+o//:://+oo-:o++/shhhmmh+o+++///-` /// ..:+++oo/+///ys:///://+::-sy+osh+osdyo+o/::/s:/y-` /// `odoyhds+/yysyydss+///+/:+oshdmNo+:+/oo/+++++:hy//` /// `://hyoyy/o/++shhy:+y:/:o/+omNmhsoohhsso+++:+o+sy:/++ /// -/---oddooss+oosy+ohNdo+++oyNhsdo/++shhhoo:s+oydmyo//o+ /// :y.`.``yyd++shoyydhhyymdhyyhyhhs+////+/+s/+:odmmyso.:ohy. /// .yy/o-..+h/+o/+//++ssoohhhssso+++:/:/yy+//sydmNddo+/./ohy+. /// .dmmhs+osdoos///o//++/+shdsoshoys+ssss++shmNNNyyds+:-s-//:+. /// -shmNmyhddsyss++/+ysddhyyydhdmyssNddyydyhNmdNmddso/::s:--`.-.` /// `+dmNhhdmddsooyyooossysshdhmoss+/+mNdyymydMdyMdyoo+/--/:/:`...-.` /// .:smNNMmsMNNmdhyyo/yymmdmdyo+ooooshysyysNNNmmmNyss/+o-`-:-/:```.`` ``` /// `.-+o/sdNNNmhdddNmmdsso/sdshyyyyhsdddyohymdmNdmmmmmyoo+/.... -os.`.``-.`` /// `/-:-/+.hymmmmdhmyNdMNmmhhs+sosoyhddyddmmho/ooymhddhdhyos-.oy..-:o+:..`` ```` ` /// ..::``--.-hoymmdNNNNNNMmhyNh+oo+soyNdmNmmmysooooymhy+so++yo..:+.--`..:.`.` `-- ``.` ` /// ```-.-.``..`:ddymmmNNdmNNNNmhN: -/oys/sdmmNdydsydmhhsmdso+/yo:/-..`.``.` ``:.`.````-. ` /// ````-:/.```:::syyydmddNhNNdsdMMs`./oddmd./odNdy+yssss++ooo/o+//-`:/:..:`-.```/-:.`.```..`` ` /// ```..-`` --.`.--o+sNhoyMmho+omhmo+Ns::dhdmmdy:.oNoyhhs+/o+o++s+hhoo+.`-:....``.-:-`..-````.-``.`` /// @title Dollars Nakamoto by Pascal Boyart /// @author jolan.eth /// @notice This contract will allow you to yield farm Dollars Nakamoto NFT. /// During epoch 0 you will be able to mint a Genesis NFT, /// Over time, epoch will increment allowing you to mint more editions. /// Minting generations editions is allowed only 1 time per epoch and per Genesis NFT. /// Generations editions do not allow you to mint other generations.
NatSpecSingleLine
giftGenerations
function giftGenerations(uint256 _genesisId, address to) public { ++generationId; generationController(_genesisId); setMetadata(tokenId, _genesisId, epoch); mintUSDSat(to, tokenId++); }
/// @notice Used to gift Generation NFT, you need a Genesis NFT to call this function
NatSpecSingleLine
v0.8.10+commit.fc410830
MIT
ipfs://627efb7c58e0f1a820013031c32ab417b2b86eb0e16948f99bf7e29ad6e50407
{ "func_code_index": [ 14122, 14359 ] }
2,680
USDSat
USDSat.sol
0xbeda58401038c864c9fc9145f28e47b7b00a0e86
Solidity
USDSat
contract USDSat is USDSatMetadata, ERC721, ERC721Enumerable, Ownable, ReentrancyGuard { string SYMBOL = "USDSat"; string NAME = "Dollars Nakamoto"; string ContractCID; /// @notice Address used to sign NFT on mint address public ADDRESS_SIGN = 0x1Af70e564847bE46e4bA286c0b0066Da8372F902; /// @notice Ether shareholder address address public ADDRESS_PBOY = 0x709e17B3Ec505F80eAb064d0F2A71c743cE225B3; /// @notice Ether shareholder address address public ADDRESS_JOLAN = 0x51BdFa2Cbb25591AF58b202aCdcdB33325a325c2; /// @notice Equity per shareholder in % uint256 public SHARE_PBOY = 90; /// @notice Equity per shareholder in % uint256 public SHARE_JOLAN = 10; /// @notice Mapping used to represent allowed addresses to call { mintGenesis } mapping (address => bool) public _allowList; /// @notice Represent the current epoch uint256 public epoch = 0; /// @notice Represent the maximum epoch possible uint256 public epochMax = 10; /// @notice Represent the block length of an epoch uint256 public epochLen = 41016; /// @notice Index of the NFT /// @dev Start at 1 because var++ uint256 public tokenId = 1; /// @notice Index of the Genesis NFT /// @dev Start at 0 because ++var uint256 public genesisId = 0; /// @notice Index of the Generation NFT /// @dev Start at 0 because ++var uint256 public generationId = 0; /// @notice Maximum total supply uint256 public maxTokenSupply = 2100; /// @notice Maximum Genesis supply uint256 public maxGenesisSupply = 210; /// @notice Maximum supply per generation uint256 public maxGenerationSupply = 210; /// @notice Price of the Genesis NFT (Generations NFT are free) uint256 public genesisPrice = 0.5 ether; /// @notice Define the ending block uint256 public blockOmega; /// @notice Define the starting block uint256 public blockGenesis; /// @notice Define in which block the Meta must occur uint256 public blockMeta; /// @notice Used to inflate blockMeta each epoch incrementation uint256 public inflateRatio = 2; /// @notice Open Genesis mint when true bool public genesisMintAllowed = false; /// @notice Open Generation mint when true bool public generationMintAllowed = false; /// @notice Multi dimensionnal mapping to keep a track of the minting reentrancy over epoch mapping(uint256 => mapping(uint256 => bool)) public epochMintingRegistry; event Omega(uint256 _blockNumber); event Genesis(uint256 indexed _epoch, uint256 _blockNumber); event Meta(uint256 indexed _epoch, uint256 _blockNumber); event Withdraw(uint256 indexed _share, address _shareholder); event Shareholder(uint256 indexed _sharePercent, address _shareholder); event Securized(uint256 indexed _epoch, uint256 _epochLen, uint256 _blockMeta, uint256 _inflateRatio); event PermanentURI(string _value, uint256 indexed _id); event Minted(uint256 indexed _epoch, uint256 indexed _tokenId, address indexed _owner); event Signed(uint256 indexed _epoch, uint256 indexed _tokenId, uint256 indexed _blockNumber); constructor() ERC721(NAME, SYMBOL) {} // Withdraw functions ************************************************* /// @notice Allow Pboy to modify ADDRESS_PBOY /// This function is dedicated to the represented shareholder according to require(). function setPboy(address PBOY) public { require(msg.sender == ADDRESS_PBOY, "error msg.sender"); ADDRESS_PBOY = PBOY; emit Shareholder(SHARE_PBOY, ADDRESS_PBOY); } /// @notice Allow Jolan to modify ADDRESS_JOLAN /// This function is dedicated to the represented shareholder according to require(). function setJolan(address JOLAN) public { require(msg.sender == ADDRESS_JOLAN, "error msg.sender"); ADDRESS_JOLAN = JOLAN; emit Shareholder(SHARE_JOLAN, ADDRESS_JOLAN); } /// @notice Used to withdraw ETH balance of the contract, this function is dedicated /// to contract owner according to { onlyOwner } modifier. function withdrawEquity() public onlyOwner nonReentrant { uint256 balance = address(this).balance; address[2] memory shareholders = [ ADDRESS_PBOY, ADDRESS_JOLAN ]; uint256[2] memory _shares = [ SHARE_PBOY * balance / 100, SHARE_JOLAN * balance / 100 ]; uint i = 0; while (i < 2) { require(payable(shareholders[i]).send(_shares[i])); emit Withdraw(_shares[i], shareholders[i]); i++; } } // Epoch functions **************************************************** /// @notice Used to manage authorization and reentrancy of the genesis NFT mint /// @param _genesisId Used to increment { genesisId } and write { epochMintingRegistry } function genesisController(uint256 _genesisId) private { require(epoch == 0, "error epoch"); require(genesisId <= maxGenesisSupply, "error genesisId"); require(!epochMintingRegistry[epoch][_genesisId], "error epochMintingRegistry"); /// @dev Set { _genesisId } for { epoch } as true epochMintingRegistry[epoch][_genesisId] = true; /// @dev When { genesisId } reaches { maxGenesisSupply } the function /// will compute the data to increment the epoch according /// /// { blockGenesis } is set only once, at this time /// { blockMeta } is set to { blockGenesis } because epoch=0 /// Then it is computed into the function epochRegulator() /// /// Once the epoch is regulated, the new generation start /// straight away, { generationMintAllowed } is set to true if (genesisId == maxGenesisSupply) { blockGenesis = block.number; blockMeta = blockGenesis; emit Genesis(epoch, blockGenesis); epochRegulator(); } } /// @notice Used to manage authorization and reentrancy of the Generation NFT mint /// @param _genesisId Used to write { epochMintingRegistry } and verify minting allowance function generationController(uint256 _genesisId) private { require(blockGenesis > 0, "error blockGenesis"); require(blockMeta > 0, "error blockMeta"); require(blockOmega > 0, "error blockOmega"); /// @dev If { block.number } >= { blockMeta } the function /// will compute the data to increment the epoch according /// /// Once the epoch is regulated, the new generation start /// straight away, { generationMintAllowed } is set to true /// /// { generationId } is reset to 1 if (block.number >= blockMeta) { epochRegulator(); generationId = 1; } /// @dev Be sure the mint is open if condition are favorable if (block.number < blockMeta && generationId <= maxGenerationSupply) { generationMintAllowed = true; } require(maxTokenSupply >= tokenId, "error maxTokenSupply"); require(epoch > 0 && epoch < epochMax, "error epoch"); require(ownerOf(_genesisId) == msg.sender, "error ownerOf"); require(generationMintAllowed, "error generationMintAllowed"); require(generationId <= maxGenerationSupply, "error generationId"); require(epochMintingRegistry[0][_genesisId], "error epochMintingRegistry"); require(!epochMintingRegistry[epoch][_genesisId], "error epochMintingRegistry"); /// @dev Set { _genesisId } for { epoch } as true epochMintingRegistry[epoch][_genesisId] = true; /// @dev If { generationId } reaches { maxGenerationSupply } the modifier /// will set { generationMintAllowed } to false to stop the mint /// on this generation /// /// { generationId } is reset to 0 /// /// This condition will not block the function because as long as /// { block.number } >= { blockMeta } minting will reopen /// according and this condition will become obsolete until /// the condition is reached again if (generationId == maxGenerationSupply) { generationMintAllowed = false; generationId = 0; } } /// @notice Used to protect epoch block length from difficulty bomb of the /// Ethereum network. A difficulty bomb heavily increases the difficulty /// on the network, likely also causing an increase in block time. /// If the block time increases too much, the epoch generation could become /// exponentially higher than what is desired, ending with an undesired Ice-Age. /// To protect against this, the emergencySecure() function is allowed to /// manually reconfigure the epoch block length and the block Meta /// to match the network conditions if necessary. /// /// It can also be useful if the block time decreases for some reason with consensus change. /// /// This function is dedicated to contract owner according to { onlyOwner } modifier function emergencySecure(uint256 _epoch, uint256 _epochLen, uint256 _blockMeta, uint256 _inflateRatio) public onlyOwner { require(epoch > 0, "error epoch"); require(_epoch > 0, "error _epoch"); require(maxTokenSupply >= tokenId, "error maxTokenSupply"); epoch = _epoch; epochLen = _epochLen; blockMeta = _blockMeta; inflateRatio = _inflateRatio; computeBlockOmega(); emit Securized(epoch, epochLen, blockMeta, inflateRatio); } /// @notice Used to compute blockOmega() function, { blockOmega } represents /// the block when it won't ever be possible to mint another Dollars Nakamoto NFT. /// It is possible to be computed because of the deterministic state of the current protocol /// The following algorithm simulate the 10 epochs of the protocol block computation to result blockOmega function computeBlockOmega() private { uint256 i = 0; uint256 _blockMeta = 0; uint256 _epochLen = epochLen; while (i < epochMax) { if (i > 0) _epochLen *= inflateRatio; if (i == 9) { blockOmega = blockGenesis + _blockMeta; emit Omega(blockOmega); break; } _blockMeta += _epochLen; i++; } } /// @notice Used to regulate the epoch incrementation and block computation, known as Metas /// @dev When epoch=0, the { blockOmega } will be computed /// When epoch!=0 the block length { epochLen } will be multiplied /// by { inflateRatio } thus making the block length required for each /// epoch longer according /// /// { blockMeta } += { epochLen } result the exact block of the next Meta /// Allow generation mint after incrementing the epoch function epochRegulator() private { if (epoch == 0) computeBlockOmega(); if (epoch > 0) epochLen *= inflateRatio; blockMeta += epochLen; emit Meta(epoch, blockMeta); epoch++; if (block.number >= blockMeta && epoch < epochMax) { epochRegulator(); } generationMintAllowed = true; } // Mint functions ***************************************************** /// @notice Used to add/remove address from { _allowList } function setBatchGenesisAllowance(address[] memory batch) public onlyOwner { uint len = batch.length; require(len > 0, "error len"); uint i = 0; while (i < len) { _allowList[batch[i]] = _allowList[batch[i]] ? false : true; i++; } } /// @notice Used to transfer { _allowList } slot to another address function transferListSlot(address to) public { require(epoch == 0, "error epoch"); require(_allowList[msg.sender], "error msg.sender"); require(!_allowList[to], "error to"); _allowList[msg.sender] = false; _allowList[to] = true; } /// @notice Used to open the mint of Genesis NFT function setGenesisMint() public onlyOwner { genesisMintAllowed = true; } /// @notice Used to gift Genesis NFT, this function is dedicated /// to contract owner according to { onlyOwner } modifier function giftGenesis(address to) public onlyOwner { uint256 _genesisId = ++genesisId; setMetadata(tokenId, _genesisId, epoch); genesisController(_genesisId); mintUSDSat(to, tokenId++); } /// @notice Used to mint Genesis NFT, this function is payable /// the price of this function is equal to { genesisPrice }, /// require to be present on { _allowList } to call function mintGenesis() public payable { uint256 _genesisId = ++genesisId; setMetadata(tokenId, _genesisId, epoch); genesisController(_genesisId); require(genesisMintAllowed, "error genesisMintAllowed"); require(_allowList[msg.sender], "error allowList"); require(genesisPrice == msg.value, "error genesisPrice"); _allowList[msg.sender] = false; mintUSDSat(msg.sender, tokenId++); } /// @notice Used to gift Generation NFT, you need a Genesis NFT to call this function function giftGenerations(uint256 _genesisId, address to) public { ++generationId; generationController(_genesisId); setMetadata(tokenId, _genesisId, epoch); mintUSDSat(to, tokenId++); } /// @notice Used to mint Generation NFT, you need a Genesis NFT to call this function function mintGenerations(uint256 _genesisId) public { ++generationId; generationController(_genesisId); setMetadata(tokenId, _genesisId, epoch); mintUSDSat(msg.sender, tokenId++); } /// @notice Token is minted on { ADDRESS_SIGN } and instantly transferred to { msg.sender } as { to }, /// this is to ensure the token creation is signed with { ADDRESS_SIGN } /// This function is private and can be only called by the contract function mintUSDSat(address to, uint256 _tokenId) private { emit PermanentURI(_compileMetadata(_tokenId), _tokenId); _safeMint(ADDRESS_SIGN, _tokenId); emit Signed(epoch, _tokenId, block.number); _safeTransfer(ADDRESS_SIGN, to, _tokenId, ""); emit Minted(epoch, _tokenId, to); } // Contract URI functions ********************************************* /// @notice Used to set the { ContractCID } metadata from ipfs, /// this function is dedicated to contract owner according /// to { onlyOwner } modifier function setContractCID(string memory CID) public onlyOwner { ContractCID = string(abi.encodePacked("ipfs://", CID)); } /// @notice Used to render { ContractCID } as { contractURI } according to /// Opensea contract metadata standard function contractURI() public view virtual returns (string memory) { return ContractCID; } // Utilitaries functions ********************************************** /// @notice Used to fetch all entry for { epoch } into { epochMintingRegistry } function getMapRegisteryForEpoch(uint256 _epoch) public view returns (bool[210] memory result) { uint i = 1; while (i <= maxGenesisSupply) { result[i] = epochMintingRegistry[_epoch][i]; i++; } } /// @notice Used to fetch all { tokenIds } from { owner } function exposeHeldIds(address owner) public view returns(uint[] memory) { uint tokenCount = balanceOf(owner); uint[] memory tokenIds = new uint[](tokenCount); uint i = 0; while (i < tokenCount) { tokenIds[i] = tokenOfOwnerByIndex(owner, i); i++; } return tokenIds; } // ERC721 Spec functions ********************************************** /// @notice Used to render metadata as { tokenURI } according to ERC721 standard function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token"); return _compileMetadata(_tokenId); } /// @dev ERC721 required override function _beforeTokenTransfer(address from, address to, uint256 _tokenId) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, _tokenId); } /// @dev ERC721 required override function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } }
/// ``.. /// `.` `````.``.-````-`` `.` /// ` ``````.`..///.-..----. --..--`.-....`..-.```` ``` /// `` `.`..--...`:::/::-``..``..:-.://///---..-....----- /// ``-:::/+++:::/-.-///://oso+::++/--:--../+:/:..:-....-://:/:-`` /// `-+/++/+o+://+::-:soo+oosss+s+//o:/:--`--:://://:ooso/-.--.-:-.` /// ``.+ooso++o+:+:+sosyhsyshhddyo+:/sds/yoo++/+:--/--.--:..--..``.```` /// ``:++/---:+/::::///oyhhyy+++:hddhhNNho///ohosyhs+/-:/+/---.....-.. ` /// ``-:-...-/+///++///+o+:-:o+o/oydmNmNNdddhsoyo/oyyyho///:-.--.-.``. `` /// ```--`..-:+/:--:::-.-///++++ydsdNNMNdmMNMmNysddyoooosso+//-.-`....````` ..` /// .```:-:::/-.-+o++/+:/+/o/hNNNNhmdNMMNNMMdyydNNmdyys+++oo++-`--.:.-.`````... /// ..--.`-..`.-`-hh++-/:+shho+hsysyyhhhmNNmmNMMmNNNdmmy+:+sh/o+y/+-`+./::.```` ` /// -/` ``.-``.//o++y+//ssyh+hhdmmdmmddmhdmNdmdsh+oNNMmmddoodh/s:yss.--+.//+`.` `. /// `.`-.` -`..+h+yo++ooyyyyyoyhy+shmNNmmdhhdhyyhymdyyhdmshoohs+y:oy+/+o/:/++.`- .` /// ``.`.``-.-++syyyhhhhhhhhmhysosyyoooosssdhhhdmmdhdmdsy+ss+/+ho/hody-s+-:+::--`` ` /// .`` ``-//s+:ohmdmddNmNmhhshhddNNNhyyhhhdNNhmNNmNNmmyso+yhhso++hhdy.:/ ::-:--``.` /// .```.-`.//shdmNNmddyysohmMmdmNNmmNshdmNhso+-/ohNoyhmmsysosd++hy/osss/.:-o/-.:/--. /// ``..:++-+hhy/syhhhdhdNNddNMmNsNMNyyso+//:-.`-/..+hmdsmdy+ossos:+o/h/+..//-s.`.:::o/ /// `.-.oy//hm+o:-..-+/shdNNNNNNhsNdo/oyoyyhoh+/so//+/mNmyhh+/s+dy/+s::+:`-`-:s--:-.::+`-` /// .`:h-`+y+./oyhhdddhyohMMNmmNmdhoo/oyyhddhmNNNmhsoodmdhs+///++:+-:.:/--/-/o/--+//...:` /// ``+o``yoodNNNNNMhdyyo+ymhsymyshhyys+sssssNmdmmdmy+oso/++:://+/-`::-:--:/::+.//o:-.--: /// `:-:-`oNhyhdNNNmyys+/:://oohy++/+hmmmmNNNNhohydmmyhy++////ooy./----.-:---/::-o+:...-/ /// ``-.-` yms+mmNmMMmNho/:o++++hhh++:mMmNmmmNMNdhdms+ysyy//:-+o:.-.`.``.-:/::-:-+/y/.- -` /// ..:` hh+oNNmMNNNmss/:-+oyhs+o+.-yhdNmdhmmydmms+o///:///+/+--/`-``.o::/:-o//-/y::/.- /// `.-``hh+yNdmdohdy:++/./myhds/./shNhhyy++o:oyos/s+:s//+////.:- ...`--`..`-.:--o:+::` /// `-/+yyho.`.-+oso///+/Nmddh//y+:s:.../soy+:o+.:sdyo++++o:.-. `.:.:-```:.`:``/o:`:` /// ./.`..sMN+:::yh+s+ysyhhddh+ymdsd/:/+o+ysydhohoh/o+/so++o+/o.--..`-:::``:-`+-`:+--.` /// ``:``..-NNy++/yyysohmo+NNmy/+:+hMNmy+yydmNMNddhs:yyydmmmso:o///..-.-+-:o:/.o/-/+-`` /// ``+.`..-mMhsyo+++oo+yoshyyo+/`+hNmhyy+sdmdssssho-MMMNMNh//+/oo+/+:-....`.s+/`..-` /// .+ `oNMmdhhsohhmmydmNms/yy.oNmmdy+++/+ss+odNm+mNmdddo-s+:+/++/-:--//`/o+s/.-`` /// `/` dNNNhooddNmNymMNNdsoo+y+shhhmyymhss+hddms+hdhmdo+/+-/oo+/.///+sh:-/-s/` /// `::`hdNmh+ooNmdohNNMMmsooohh+oysydhdooo/syysodmNmys+/o+//+y/:.+/hmso.-//s- /// -+ohdmmhyhdysysyyhmysoyddhhoo+shdhdyddmddmNmmhssds/::/oo/..:/+Nmo+`-:so /// .oyhdmmNNdm+s:/:os/+/ssyyds+/ssdNNyhdmmhdmmdymymy///o:/``/+-dmdoo++:o` /// `ysyMNhhmoo+h-:/+o/+:.:/:/+doo+dNdhddmhmmmy++yhds/+-+::..o/+Nmosyhs+- /// s+dNNyNhsdhNhsy:+:oo/soo+dNmmooyosohMhsymmhyy+++:+:/+/-/o+yNh+hMNs. /// +yhNNMd+dmydmdy/+/sshydmhdNNmNooyhhhhshohmNh+:+oso++ssy+/odyhhNmh` /// `yyhdms+dMh+oyshhyhysdmNd+ohyNN+++mNddmNy+yo//+o/hddddymmyhosNmms` /// oydos:oMmhoyyhysssysdmMmNmhNmNNh/+mmNmddh+/+o+::+s+hmhmdyNNNNy: /// `/dNm/+Ndhy+oshdhhdyo::ohmdyhhNysy:smshmdo/o:so//:s++ymhyohdy-` /// `sNNN/hNm/:do+o:+/++++s:/+shyymmddy/ydmmh/s/+oss//oysy++o+o+` /// oNNMNmm:/hyy/:/o/+hhsosysoo-ohhhss/hmmhd/dyh++/soyooy++o+:. /// :/dMNh/smhh+//+s+--:+/so+ohhy/:sydmmmmm+/mdddhy++/ohs//-o/` /// `/odmhyhsyh++/-:+:::/:/o/:ooddy/+yodNNh+ydhmmmy++/hhyo+://` /// `:os/+o//oshss/yhs+//:+/-/:soooo/+sso+dddydss+:+sy///+:++ /// ./o/s//hhNho+shyyyoyyso+/ys+/+-:y+:/soooyyh++sNyo++/:/+ /// -/:osmmhyo:++++/+/osshdssooo/:/h//://++oyhsshmdo+//s/- /// .osmhydh::/+++/o+ohhysddyoo++os+-+++///yhhhmNs+o/:// /// -.++yss//////+/+/+soo++shyhsyy+::/:+y+yhdmdoo//:/:- /// ``.oss/:////++://+o//:://+oo-:o++/shhhmmh+o+++///-` /// ..:+++oo/+///ys:///://+::-sy+osh+osdyo+o/::/s:/y-` /// `odoyhds+/yysyydss+///+/:+oshdmNo+:+/oo/+++++:hy//` /// `://hyoyy/o/++shhy:+y:/:o/+omNmhsoohhsso+++:+o+sy:/++ /// -/---oddooss+oosy+ohNdo+++oyNhsdo/++shhhoo:s+oydmyo//o+ /// :y.`.``yyd++shoyydhhyymdhyyhyhhs+////+/+s/+:odmmyso.:ohy. /// .yy/o-..+h/+o/+//++ssoohhhssso+++:/:/yy+//sydmNddo+/./ohy+. /// .dmmhs+osdoos///o//++/+shdsoshoys+ssss++shmNNNyyds+:-s-//:+. /// -shmNmyhddsyss++/+ysddhyyydhdmyssNddyydyhNmdNmddso/::s:--`.-.` /// `+dmNhhdmddsooyyooossysshdhmoss+/+mNdyymydMdyMdyoo+/--/:/:`...-.` /// .:smNNMmsMNNmdhyyo/yymmdmdyo+ooooshysyysNNNmmmNyss/+o-`-:-/:```.`` ``` /// `.-+o/sdNNNmhdddNmmdsso/sdshyyyyhsdddyohymdmNdmmmmmyoo+/.... -os.`.``-.`` /// `/-:-/+.hymmmmdhmyNdMNmmhhs+sosoyhddyddmmho/ooymhddhdhyos-.oy..-:o+:..`` ```` ` /// ..::``--.-hoymmdNNNNNNMmhyNh+oo+soyNdmNmmmysooooymhy+so++yo..:+.--`..:.`.` `-- ``.` ` /// ```-.-.``..`:ddymmmNNdmNNNNmhN: -/oys/sdmmNdydsydmhhsmdso+/yo:/-..`.``.` ``:.`.````-. ` /// ````-:/.```:::syyydmddNhNNdsdMMs`./oddmd./odNdy+yssss++ooo/o+//-`:/:..:`-.```/-:.`.```..`` ` /// ```..-`` --.`.--o+sNhoyMmho+omhmo+Ns::dhdmmdy:.oNoyhhs+/o+o++s+hhoo+.`-:....``.-:-`..-````.-``.`` /// @title Dollars Nakamoto by Pascal Boyart /// @author jolan.eth /// @notice This contract will allow you to yield farm Dollars Nakamoto NFT. /// During epoch 0 you will be able to mint a Genesis NFT, /// Over time, epoch will increment allowing you to mint more editions. /// Minting generations editions is allowed only 1 time per epoch and per Genesis NFT. /// Generations editions do not allow you to mint other generations.
NatSpecSingleLine
mintGenerations
function mintGenerations(uint256 _genesisId) public { ++generationId; generationController(_genesisId); setMetadata(tokenId, _genesisId, epoch); mintUSDSat(msg.sender, tokenId++); }
/// @notice Used to mint Generation NFT, you need a Genesis NFT to call this function
NatSpecSingleLine
v0.8.10+commit.fc410830
MIT
ipfs://627efb7c58e0f1a820013031c32ab417b2b86eb0e16948f99bf7e29ad6e50407
{ "func_code_index": [ 14453, 14685 ] }
2,681
USDSat
USDSat.sol
0xbeda58401038c864c9fc9145f28e47b7b00a0e86
Solidity
USDSat
contract USDSat is USDSatMetadata, ERC721, ERC721Enumerable, Ownable, ReentrancyGuard { string SYMBOL = "USDSat"; string NAME = "Dollars Nakamoto"; string ContractCID; /// @notice Address used to sign NFT on mint address public ADDRESS_SIGN = 0x1Af70e564847bE46e4bA286c0b0066Da8372F902; /// @notice Ether shareholder address address public ADDRESS_PBOY = 0x709e17B3Ec505F80eAb064d0F2A71c743cE225B3; /// @notice Ether shareholder address address public ADDRESS_JOLAN = 0x51BdFa2Cbb25591AF58b202aCdcdB33325a325c2; /// @notice Equity per shareholder in % uint256 public SHARE_PBOY = 90; /// @notice Equity per shareholder in % uint256 public SHARE_JOLAN = 10; /// @notice Mapping used to represent allowed addresses to call { mintGenesis } mapping (address => bool) public _allowList; /// @notice Represent the current epoch uint256 public epoch = 0; /// @notice Represent the maximum epoch possible uint256 public epochMax = 10; /// @notice Represent the block length of an epoch uint256 public epochLen = 41016; /// @notice Index of the NFT /// @dev Start at 1 because var++ uint256 public tokenId = 1; /// @notice Index of the Genesis NFT /// @dev Start at 0 because ++var uint256 public genesisId = 0; /// @notice Index of the Generation NFT /// @dev Start at 0 because ++var uint256 public generationId = 0; /// @notice Maximum total supply uint256 public maxTokenSupply = 2100; /// @notice Maximum Genesis supply uint256 public maxGenesisSupply = 210; /// @notice Maximum supply per generation uint256 public maxGenerationSupply = 210; /// @notice Price of the Genesis NFT (Generations NFT are free) uint256 public genesisPrice = 0.5 ether; /// @notice Define the ending block uint256 public blockOmega; /// @notice Define the starting block uint256 public blockGenesis; /// @notice Define in which block the Meta must occur uint256 public blockMeta; /// @notice Used to inflate blockMeta each epoch incrementation uint256 public inflateRatio = 2; /// @notice Open Genesis mint when true bool public genesisMintAllowed = false; /// @notice Open Generation mint when true bool public generationMintAllowed = false; /// @notice Multi dimensionnal mapping to keep a track of the minting reentrancy over epoch mapping(uint256 => mapping(uint256 => bool)) public epochMintingRegistry; event Omega(uint256 _blockNumber); event Genesis(uint256 indexed _epoch, uint256 _blockNumber); event Meta(uint256 indexed _epoch, uint256 _blockNumber); event Withdraw(uint256 indexed _share, address _shareholder); event Shareholder(uint256 indexed _sharePercent, address _shareholder); event Securized(uint256 indexed _epoch, uint256 _epochLen, uint256 _blockMeta, uint256 _inflateRatio); event PermanentURI(string _value, uint256 indexed _id); event Minted(uint256 indexed _epoch, uint256 indexed _tokenId, address indexed _owner); event Signed(uint256 indexed _epoch, uint256 indexed _tokenId, uint256 indexed _blockNumber); constructor() ERC721(NAME, SYMBOL) {} // Withdraw functions ************************************************* /// @notice Allow Pboy to modify ADDRESS_PBOY /// This function is dedicated to the represented shareholder according to require(). function setPboy(address PBOY) public { require(msg.sender == ADDRESS_PBOY, "error msg.sender"); ADDRESS_PBOY = PBOY; emit Shareholder(SHARE_PBOY, ADDRESS_PBOY); } /// @notice Allow Jolan to modify ADDRESS_JOLAN /// This function is dedicated to the represented shareholder according to require(). function setJolan(address JOLAN) public { require(msg.sender == ADDRESS_JOLAN, "error msg.sender"); ADDRESS_JOLAN = JOLAN; emit Shareholder(SHARE_JOLAN, ADDRESS_JOLAN); } /// @notice Used to withdraw ETH balance of the contract, this function is dedicated /// to contract owner according to { onlyOwner } modifier. function withdrawEquity() public onlyOwner nonReentrant { uint256 balance = address(this).balance; address[2] memory shareholders = [ ADDRESS_PBOY, ADDRESS_JOLAN ]; uint256[2] memory _shares = [ SHARE_PBOY * balance / 100, SHARE_JOLAN * balance / 100 ]; uint i = 0; while (i < 2) { require(payable(shareholders[i]).send(_shares[i])); emit Withdraw(_shares[i], shareholders[i]); i++; } } // Epoch functions **************************************************** /// @notice Used to manage authorization and reentrancy of the genesis NFT mint /// @param _genesisId Used to increment { genesisId } and write { epochMintingRegistry } function genesisController(uint256 _genesisId) private { require(epoch == 0, "error epoch"); require(genesisId <= maxGenesisSupply, "error genesisId"); require(!epochMintingRegistry[epoch][_genesisId], "error epochMintingRegistry"); /// @dev Set { _genesisId } for { epoch } as true epochMintingRegistry[epoch][_genesisId] = true; /// @dev When { genesisId } reaches { maxGenesisSupply } the function /// will compute the data to increment the epoch according /// /// { blockGenesis } is set only once, at this time /// { blockMeta } is set to { blockGenesis } because epoch=0 /// Then it is computed into the function epochRegulator() /// /// Once the epoch is regulated, the new generation start /// straight away, { generationMintAllowed } is set to true if (genesisId == maxGenesisSupply) { blockGenesis = block.number; blockMeta = blockGenesis; emit Genesis(epoch, blockGenesis); epochRegulator(); } } /// @notice Used to manage authorization and reentrancy of the Generation NFT mint /// @param _genesisId Used to write { epochMintingRegistry } and verify minting allowance function generationController(uint256 _genesisId) private { require(blockGenesis > 0, "error blockGenesis"); require(blockMeta > 0, "error blockMeta"); require(blockOmega > 0, "error blockOmega"); /// @dev If { block.number } >= { blockMeta } the function /// will compute the data to increment the epoch according /// /// Once the epoch is regulated, the new generation start /// straight away, { generationMintAllowed } is set to true /// /// { generationId } is reset to 1 if (block.number >= blockMeta) { epochRegulator(); generationId = 1; } /// @dev Be sure the mint is open if condition are favorable if (block.number < blockMeta && generationId <= maxGenerationSupply) { generationMintAllowed = true; } require(maxTokenSupply >= tokenId, "error maxTokenSupply"); require(epoch > 0 && epoch < epochMax, "error epoch"); require(ownerOf(_genesisId) == msg.sender, "error ownerOf"); require(generationMintAllowed, "error generationMintAllowed"); require(generationId <= maxGenerationSupply, "error generationId"); require(epochMintingRegistry[0][_genesisId], "error epochMintingRegistry"); require(!epochMintingRegistry[epoch][_genesisId], "error epochMintingRegistry"); /// @dev Set { _genesisId } for { epoch } as true epochMintingRegistry[epoch][_genesisId] = true; /// @dev If { generationId } reaches { maxGenerationSupply } the modifier /// will set { generationMintAllowed } to false to stop the mint /// on this generation /// /// { generationId } is reset to 0 /// /// This condition will not block the function because as long as /// { block.number } >= { blockMeta } minting will reopen /// according and this condition will become obsolete until /// the condition is reached again if (generationId == maxGenerationSupply) { generationMintAllowed = false; generationId = 0; } } /// @notice Used to protect epoch block length from difficulty bomb of the /// Ethereum network. A difficulty bomb heavily increases the difficulty /// on the network, likely also causing an increase in block time. /// If the block time increases too much, the epoch generation could become /// exponentially higher than what is desired, ending with an undesired Ice-Age. /// To protect against this, the emergencySecure() function is allowed to /// manually reconfigure the epoch block length and the block Meta /// to match the network conditions if necessary. /// /// It can also be useful if the block time decreases for some reason with consensus change. /// /// This function is dedicated to contract owner according to { onlyOwner } modifier function emergencySecure(uint256 _epoch, uint256 _epochLen, uint256 _blockMeta, uint256 _inflateRatio) public onlyOwner { require(epoch > 0, "error epoch"); require(_epoch > 0, "error _epoch"); require(maxTokenSupply >= tokenId, "error maxTokenSupply"); epoch = _epoch; epochLen = _epochLen; blockMeta = _blockMeta; inflateRatio = _inflateRatio; computeBlockOmega(); emit Securized(epoch, epochLen, blockMeta, inflateRatio); } /// @notice Used to compute blockOmega() function, { blockOmega } represents /// the block when it won't ever be possible to mint another Dollars Nakamoto NFT. /// It is possible to be computed because of the deterministic state of the current protocol /// The following algorithm simulate the 10 epochs of the protocol block computation to result blockOmega function computeBlockOmega() private { uint256 i = 0; uint256 _blockMeta = 0; uint256 _epochLen = epochLen; while (i < epochMax) { if (i > 0) _epochLen *= inflateRatio; if (i == 9) { blockOmega = blockGenesis + _blockMeta; emit Omega(blockOmega); break; } _blockMeta += _epochLen; i++; } } /// @notice Used to regulate the epoch incrementation and block computation, known as Metas /// @dev When epoch=0, the { blockOmega } will be computed /// When epoch!=0 the block length { epochLen } will be multiplied /// by { inflateRatio } thus making the block length required for each /// epoch longer according /// /// { blockMeta } += { epochLen } result the exact block of the next Meta /// Allow generation mint after incrementing the epoch function epochRegulator() private { if (epoch == 0) computeBlockOmega(); if (epoch > 0) epochLen *= inflateRatio; blockMeta += epochLen; emit Meta(epoch, blockMeta); epoch++; if (block.number >= blockMeta && epoch < epochMax) { epochRegulator(); } generationMintAllowed = true; } // Mint functions ***************************************************** /// @notice Used to add/remove address from { _allowList } function setBatchGenesisAllowance(address[] memory batch) public onlyOwner { uint len = batch.length; require(len > 0, "error len"); uint i = 0; while (i < len) { _allowList[batch[i]] = _allowList[batch[i]] ? false : true; i++; } } /// @notice Used to transfer { _allowList } slot to another address function transferListSlot(address to) public { require(epoch == 0, "error epoch"); require(_allowList[msg.sender], "error msg.sender"); require(!_allowList[to], "error to"); _allowList[msg.sender] = false; _allowList[to] = true; } /// @notice Used to open the mint of Genesis NFT function setGenesisMint() public onlyOwner { genesisMintAllowed = true; } /// @notice Used to gift Genesis NFT, this function is dedicated /// to contract owner according to { onlyOwner } modifier function giftGenesis(address to) public onlyOwner { uint256 _genesisId = ++genesisId; setMetadata(tokenId, _genesisId, epoch); genesisController(_genesisId); mintUSDSat(to, tokenId++); } /// @notice Used to mint Genesis NFT, this function is payable /// the price of this function is equal to { genesisPrice }, /// require to be present on { _allowList } to call function mintGenesis() public payable { uint256 _genesisId = ++genesisId; setMetadata(tokenId, _genesisId, epoch); genesisController(_genesisId); require(genesisMintAllowed, "error genesisMintAllowed"); require(_allowList[msg.sender], "error allowList"); require(genesisPrice == msg.value, "error genesisPrice"); _allowList[msg.sender] = false; mintUSDSat(msg.sender, tokenId++); } /// @notice Used to gift Generation NFT, you need a Genesis NFT to call this function function giftGenerations(uint256 _genesisId, address to) public { ++generationId; generationController(_genesisId); setMetadata(tokenId, _genesisId, epoch); mintUSDSat(to, tokenId++); } /// @notice Used to mint Generation NFT, you need a Genesis NFT to call this function function mintGenerations(uint256 _genesisId) public { ++generationId; generationController(_genesisId); setMetadata(tokenId, _genesisId, epoch); mintUSDSat(msg.sender, tokenId++); } /// @notice Token is minted on { ADDRESS_SIGN } and instantly transferred to { msg.sender } as { to }, /// this is to ensure the token creation is signed with { ADDRESS_SIGN } /// This function is private and can be only called by the contract function mintUSDSat(address to, uint256 _tokenId) private { emit PermanentURI(_compileMetadata(_tokenId), _tokenId); _safeMint(ADDRESS_SIGN, _tokenId); emit Signed(epoch, _tokenId, block.number); _safeTransfer(ADDRESS_SIGN, to, _tokenId, ""); emit Minted(epoch, _tokenId, to); } // Contract URI functions ********************************************* /// @notice Used to set the { ContractCID } metadata from ipfs, /// this function is dedicated to contract owner according /// to { onlyOwner } modifier function setContractCID(string memory CID) public onlyOwner { ContractCID = string(abi.encodePacked("ipfs://", CID)); } /// @notice Used to render { ContractCID } as { contractURI } according to /// Opensea contract metadata standard function contractURI() public view virtual returns (string memory) { return ContractCID; } // Utilitaries functions ********************************************** /// @notice Used to fetch all entry for { epoch } into { epochMintingRegistry } function getMapRegisteryForEpoch(uint256 _epoch) public view returns (bool[210] memory result) { uint i = 1; while (i <= maxGenesisSupply) { result[i] = epochMintingRegistry[_epoch][i]; i++; } } /// @notice Used to fetch all { tokenIds } from { owner } function exposeHeldIds(address owner) public view returns(uint[] memory) { uint tokenCount = balanceOf(owner); uint[] memory tokenIds = new uint[](tokenCount); uint i = 0; while (i < tokenCount) { tokenIds[i] = tokenOfOwnerByIndex(owner, i); i++; } return tokenIds; } // ERC721 Spec functions ********************************************** /// @notice Used to render metadata as { tokenURI } according to ERC721 standard function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token"); return _compileMetadata(_tokenId); } /// @dev ERC721 required override function _beforeTokenTransfer(address from, address to, uint256 _tokenId) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, _tokenId); } /// @dev ERC721 required override function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } }
/// ``.. /// `.` `````.``.-````-`` `.` /// ` ``````.`..///.-..----. --..--`.-....`..-.```` ``` /// `` `.`..--...`:::/::-``..``..:-.://///---..-....----- /// ``-:::/+++:::/-.-///://oso+::++/--:--../+:/:..:-....-://:/:-`` /// `-+/++/+o+://+::-:soo+oosss+s+//o:/:--`--:://://:ooso/-.--.-:-.` /// ``.+ooso++o+:+:+sosyhsyshhddyo+:/sds/yoo++/+:--/--.--:..--..``.```` /// ``:++/---:+/::::///oyhhyy+++:hddhhNNho///ohosyhs+/-:/+/---.....-.. ` /// ``-:-...-/+///++///+o+:-:o+o/oydmNmNNdddhsoyo/oyyyho///:-.--.-.``. `` /// ```--`..-:+/:--:::-.-///++++ydsdNNMNdmMNMmNysddyoooosso+//-.-`....````` ..` /// .```:-:::/-.-+o++/+:/+/o/hNNNNhmdNMMNNMMdyydNNmdyys+++oo++-`--.:.-.`````... /// ..--.`-..`.-`-hh++-/:+shho+hsysyyhhhmNNmmNMMmNNNdmmy+:+sh/o+y/+-`+./::.```` ` /// -/` ``.-``.//o++y+//ssyh+hhdmmdmmddmhdmNdmdsh+oNNMmmddoodh/s:yss.--+.//+`.` `. /// `.`-.` -`..+h+yo++ooyyyyyoyhy+shmNNmmdhhdhyyhymdyyhdmshoohs+y:oy+/+o/:/++.`- .` /// ``.`.``-.-++syyyhhhhhhhhmhysosyyoooosssdhhhdmmdhdmdsy+ss+/+ho/hody-s+-:+::--`` ` /// .`` ``-//s+:ohmdmddNmNmhhshhddNNNhyyhhhdNNhmNNmNNmmyso+yhhso++hhdy.:/ ::-:--``.` /// .```.-`.//shdmNNmddyysohmMmdmNNmmNshdmNhso+-/ohNoyhmmsysosd++hy/osss/.:-o/-.:/--. /// ``..:++-+hhy/syhhhdhdNNddNMmNsNMNyyso+//:-.`-/..+hmdsmdy+ossos:+o/h/+..//-s.`.:::o/ /// `.-.oy//hm+o:-..-+/shdNNNNNNhsNdo/oyoyyhoh+/so//+/mNmyhh+/s+dy/+s::+:`-`-:s--:-.::+`-` /// .`:h-`+y+./oyhhdddhyohMMNmmNmdhoo/oyyhddhmNNNmhsoodmdhs+///++:+-:.:/--/-/o/--+//...:` /// ``+o``yoodNNNNNMhdyyo+ymhsymyshhyys+sssssNmdmmdmy+oso/++:://+/-`::-:--:/::+.//o:-.--: /// `:-:-`oNhyhdNNNmyys+/:://oohy++/+hmmmmNNNNhohydmmyhy++////ooy./----.-:---/::-o+:...-/ /// ``-.-` yms+mmNmMMmNho/:o++++hhh++:mMmNmmmNMNdhdms+ysyy//:-+o:.-.`.``.-:/::-:-+/y/.- -` /// ..:` hh+oNNmMNNNmss/:-+oyhs+o+.-yhdNmdhmmydmms+o///:///+/+--/`-``.o::/:-o//-/y::/.- /// `.-``hh+yNdmdohdy:++/./myhds/./shNhhyy++o:oyos/s+:s//+////.:- ...`--`..`-.:--o:+::` /// `-/+yyho.`.-+oso///+/Nmddh//y+:s:.../soy+:o+.:sdyo++++o:.-. `.:.:-```:.`:``/o:`:` /// ./.`..sMN+:::yh+s+ysyhhddh+ymdsd/:/+o+ysydhohoh/o+/so++o+/o.--..`-:::``:-`+-`:+--.` /// ``:``..-NNy++/yyysohmo+NNmy/+:+hMNmy+yydmNMNddhs:yyydmmmso:o///..-.-+-:o:/.o/-/+-`` /// ``+.`..-mMhsyo+++oo+yoshyyo+/`+hNmhyy+sdmdssssho-MMMNMNh//+/oo+/+:-....`.s+/`..-` /// .+ `oNMmdhhsohhmmydmNms/yy.oNmmdy+++/+ss+odNm+mNmdddo-s+:+/++/-:--//`/o+s/.-`` /// `/` dNNNhooddNmNymMNNdsoo+y+shhhmyymhss+hddms+hdhmdo+/+-/oo+/.///+sh:-/-s/` /// `::`hdNmh+ooNmdohNNMMmsooohh+oysydhdooo/syysodmNmys+/o+//+y/:.+/hmso.-//s- /// -+ohdmmhyhdysysyyhmysoyddhhoo+shdhdyddmddmNmmhssds/::/oo/..:/+Nmo+`-:so /// .oyhdmmNNdm+s:/:os/+/ssyyds+/ssdNNyhdmmhdmmdymymy///o:/``/+-dmdoo++:o` /// `ysyMNhhmoo+h-:/+o/+:.:/:/+doo+dNdhddmhmmmy++yhds/+-+::..o/+Nmosyhs+- /// s+dNNyNhsdhNhsy:+:oo/soo+dNmmooyosohMhsymmhyy+++:+:/+/-/o+yNh+hMNs. /// +yhNNMd+dmydmdy/+/sshydmhdNNmNooyhhhhshohmNh+:+oso++ssy+/odyhhNmh` /// `yyhdms+dMh+oyshhyhysdmNd+ohyNN+++mNddmNy+yo//+o/hddddymmyhosNmms` /// oydos:oMmhoyyhysssysdmMmNmhNmNNh/+mmNmddh+/+o+::+s+hmhmdyNNNNy: /// `/dNm/+Ndhy+oshdhhdyo::ohmdyhhNysy:smshmdo/o:so//:s++ymhyohdy-` /// `sNNN/hNm/:do+o:+/++++s:/+shyymmddy/ydmmh/s/+oss//oysy++o+o+` /// oNNMNmm:/hyy/:/o/+hhsosysoo-ohhhss/hmmhd/dyh++/soyooy++o+:. /// :/dMNh/smhh+//+s+--:+/so+ohhy/:sydmmmmm+/mdddhy++/ohs//-o/` /// `/odmhyhsyh++/-:+:::/:/o/:ooddy/+yodNNh+ydhmmmy++/hhyo+://` /// `:os/+o//oshss/yhs+//:+/-/:soooo/+sso+dddydss+:+sy///+:++ /// ./o/s//hhNho+shyyyoyyso+/ys+/+-:y+:/soooyyh++sNyo++/:/+ /// -/:osmmhyo:++++/+/osshdssooo/:/h//://++oyhsshmdo+//s/- /// .osmhydh::/+++/o+ohhysddyoo++os+-+++///yhhhmNs+o/:// /// -.++yss//////+/+/+soo++shyhsyy+::/:+y+yhdmdoo//:/:- /// ``.oss/:////++://+o//:://+oo-:o++/shhhmmh+o+++///-` /// ..:+++oo/+///ys:///://+::-sy+osh+osdyo+o/::/s:/y-` /// `odoyhds+/yysyydss+///+/:+oshdmNo+:+/oo/+++++:hy//` /// `://hyoyy/o/++shhy:+y:/:o/+omNmhsoohhsso+++:+o+sy:/++ /// -/---oddooss+oosy+ohNdo+++oyNhsdo/++shhhoo:s+oydmyo//o+ /// :y.`.``yyd++shoyydhhyymdhyyhyhhs+////+/+s/+:odmmyso.:ohy. /// .yy/o-..+h/+o/+//++ssoohhhssso+++:/:/yy+//sydmNddo+/./ohy+. /// .dmmhs+osdoos///o//++/+shdsoshoys+ssss++shmNNNyyds+:-s-//:+. /// -shmNmyhddsyss++/+ysddhyyydhdmyssNddyydyhNmdNmddso/::s:--`.-.` /// `+dmNhhdmddsooyyooossysshdhmoss+/+mNdyymydMdyMdyoo+/--/:/:`...-.` /// .:smNNMmsMNNmdhyyo/yymmdmdyo+ooooshysyysNNNmmmNyss/+o-`-:-/:```.`` ``` /// `.-+o/sdNNNmhdddNmmdsso/sdshyyyyhsdddyohymdmNdmmmmmyoo+/.... -os.`.``-.`` /// `/-:-/+.hymmmmdhmyNdMNmmhhs+sosoyhddyddmmho/ooymhddhdhyos-.oy..-:o+:..`` ```` ` /// ..::``--.-hoymmdNNNNNNMmhyNh+oo+soyNdmNmmmysooooymhy+so++yo..:+.--`..:.`.` `-- ``.` ` /// ```-.-.``..`:ddymmmNNdmNNNNmhN: -/oys/sdmmNdydsydmhhsmdso+/yo:/-..`.``.` ``:.`.````-. ` /// ````-:/.```:::syyydmddNhNNdsdMMs`./oddmd./odNdy+yssss++ooo/o+//-`:/:..:`-.```/-:.`.```..`` ` /// ```..-`` --.`.--o+sNhoyMmho+omhmo+Ns::dhdmmdy:.oNoyhhs+/o+o++s+hhoo+.`-:....``.-:-`..-````.-``.`` /// @title Dollars Nakamoto by Pascal Boyart /// @author jolan.eth /// @notice This contract will allow you to yield farm Dollars Nakamoto NFT. /// During epoch 0 you will be able to mint a Genesis NFT, /// Over time, epoch will increment allowing you to mint more editions. /// Minting generations editions is allowed only 1 time per epoch and per Genesis NFT. /// Generations editions do not allow you to mint other generations.
NatSpecSingleLine
mintUSDSat
function mintUSDSat(address to, uint256 _tokenId) private { emit PermanentURI(_compileMetadata(_tokenId), _tokenId); _safeMint(ADDRESS_SIGN, _tokenId); emit Signed(epoch, _tokenId, block.number); _safeTransfer(ADDRESS_SIGN, to, _tokenId, ""); emit Minted(epoch, _tokenId, to); }
/// @notice Token is minted on { ADDRESS_SIGN } and instantly transferred to { msg.sender } as { to }, /// this is to ensure the token creation is signed with { ADDRESS_SIGN } /// This function is private and can be only called by the contract
NatSpecSingleLine
v0.8.10+commit.fc410830
MIT
ipfs://627efb7c58e0f1a820013031c32ab417b2b86eb0e16948f99bf7e29ad6e50407
{ "func_code_index": [ 14963, 15301 ] }
2,682
USDSat
USDSat.sol
0xbeda58401038c864c9fc9145f28e47b7b00a0e86
Solidity
USDSat
contract USDSat is USDSatMetadata, ERC721, ERC721Enumerable, Ownable, ReentrancyGuard { string SYMBOL = "USDSat"; string NAME = "Dollars Nakamoto"; string ContractCID; /// @notice Address used to sign NFT on mint address public ADDRESS_SIGN = 0x1Af70e564847bE46e4bA286c0b0066Da8372F902; /// @notice Ether shareholder address address public ADDRESS_PBOY = 0x709e17B3Ec505F80eAb064d0F2A71c743cE225B3; /// @notice Ether shareholder address address public ADDRESS_JOLAN = 0x51BdFa2Cbb25591AF58b202aCdcdB33325a325c2; /// @notice Equity per shareholder in % uint256 public SHARE_PBOY = 90; /// @notice Equity per shareholder in % uint256 public SHARE_JOLAN = 10; /// @notice Mapping used to represent allowed addresses to call { mintGenesis } mapping (address => bool) public _allowList; /// @notice Represent the current epoch uint256 public epoch = 0; /// @notice Represent the maximum epoch possible uint256 public epochMax = 10; /// @notice Represent the block length of an epoch uint256 public epochLen = 41016; /// @notice Index of the NFT /// @dev Start at 1 because var++ uint256 public tokenId = 1; /// @notice Index of the Genesis NFT /// @dev Start at 0 because ++var uint256 public genesisId = 0; /// @notice Index of the Generation NFT /// @dev Start at 0 because ++var uint256 public generationId = 0; /// @notice Maximum total supply uint256 public maxTokenSupply = 2100; /// @notice Maximum Genesis supply uint256 public maxGenesisSupply = 210; /// @notice Maximum supply per generation uint256 public maxGenerationSupply = 210; /// @notice Price of the Genesis NFT (Generations NFT are free) uint256 public genesisPrice = 0.5 ether; /// @notice Define the ending block uint256 public blockOmega; /// @notice Define the starting block uint256 public blockGenesis; /// @notice Define in which block the Meta must occur uint256 public blockMeta; /// @notice Used to inflate blockMeta each epoch incrementation uint256 public inflateRatio = 2; /// @notice Open Genesis mint when true bool public genesisMintAllowed = false; /// @notice Open Generation mint when true bool public generationMintAllowed = false; /// @notice Multi dimensionnal mapping to keep a track of the minting reentrancy over epoch mapping(uint256 => mapping(uint256 => bool)) public epochMintingRegistry; event Omega(uint256 _blockNumber); event Genesis(uint256 indexed _epoch, uint256 _blockNumber); event Meta(uint256 indexed _epoch, uint256 _blockNumber); event Withdraw(uint256 indexed _share, address _shareholder); event Shareholder(uint256 indexed _sharePercent, address _shareholder); event Securized(uint256 indexed _epoch, uint256 _epochLen, uint256 _blockMeta, uint256 _inflateRatio); event PermanentURI(string _value, uint256 indexed _id); event Minted(uint256 indexed _epoch, uint256 indexed _tokenId, address indexed _owner); event Signed(uint256 indexed _epoch, uint256 indexed _tokenId, uint256 indexed _blockNumber); constructor() ERC721(NAME, SYMBOL) {} // Withdraw functions ************************************************* /// @notice Allow Pboy to modify ADDRESS_PBOY /// This function is dedicated to the represented shareholder according to require(). function setPboy(address PBOY) public { require(msg.sender == ADDRESS_PBOY, "error msg.sender"); ADDRESS_PBOY = PBOY; emit Shareholder(SHARE_PBOY, ADDRESS_PBOY); } /// @notice Allow Jolan to modify ADDRESS_JOLAN /// This function is dedicated to the represented shareholder according to require(). function setJolan(address JOLAN) public { require(msg.sender == ADDRESS_JOLAN, "error msg.sender"); ADDRESS_JOLAN = JOLAN; emit Shareholder(SHARE_JOLAN, ADDRESS_JOLAN); } /// @notice Used to withdraw ETH balance of the contract, this function is dedicated /// to contract owner according to { onlyOwner } modifier. function withdrawEquity() public onlyOwner nonReentrant { uint256 balance = address(this).balance; address[2] memory shareholders = [ ADDRESS_PBOY, ADDRESS_JOLAN ]; uint256[2] memory _shares = [ SHARE_PBOY * balance / 100, SHARE_JOLAN * balance / 100 ]; uint i = 0; while (i < 2) { require(payable(shareholders[i]).send(_shares[i])); emit Withdraw(_shares[i], shareholders[i]); i++; } } // Epoch functions **************************************************** /// @notice Used to manage authorization and reentrancy of the genesis NFT mint /// @param _genesisId Used to increment { genesisId } and write { epochMintingRegistry } function genesisController(uint256 _genesisId) private { require(epoch == 0, "error epoch"); require(genesisId <= maxGenesisSupply, "error genesisId"); require(!epochMintingRegistry[epoch][_genesisId], "error epochMintingRegistry"); /// @dev Set { _genesisId } for { epoch } as true epochMintingRegistry[epoch][_genesisId] = true; /// @dev When { genesisId } reaches { maxGenesisSupply } the function /// will compute the data to increment the epoch according /// /// { blockGenesis } is set only once, at this time /// { blockMeta } is set to { blockGenesis } because epoch=0 /// Then it is computed into the function epochRegulator() /// /// Once the epoch is regulated, the new generation start /// straight away, { generationMintAllowed } is set to true if (genesisId == maxGenesisSupply) { blockGenesis = block.number; blockMeta = blockGenesis; emit Genesis(epoch, blockGenesis); epochRegulator(); } } /// @notice Used to manage authorization and reentrancy of the Generation NFT mint /// @param _genesisId Used to write { epochMintingRegistry } and verify minting allowance function generationController(uint256 _genesisId) private { require(blockGenesis > 0, "error blockGenesis"); require(blockMeta > 0, "error blockMeta"); require(blockOmega > 0, "error blockOmega"); /// @dev If { block.number } >= { blockMeta } the function /// will compute the data to increment the epoch according /// /// Once the epoch is regulated, the new generation start /// straight away, { generationMintAllowed } is set to true /// /// { generationId } is reset to 1 if (block.number >= blockMeta) { epochRegulator(); generationId = 1; } /// @dev Be sure the mint is open if condition are favorable if (block.number < blockMeta && generationId <= maxGenerationSupply) { generationMintAllowed = true; } require(maxTokenSupply >= tokenId, "error maxTokenSupply"); require(epoch > 0 && epoch < epochMax, "error epoch"); require(ownerOf(_genesisId) == msg.sender, "error ownerOf"); require(generationMintAllowed, "error generationMintAllowed"); require(generationId <= maxGenerationSupply, "error generationId"); require(epochMintingRegistry[0][_genesisId], "error epochMintingRegistry"); require(!epochMintingRegistry[epoch][_genesisId], "error epochMintingRegistry"); /// @dev Set { _genesisId } for { epoch } as true epochMintingRegistry[epoch][_genesisId] = true; /// @dev If { generationId } reaches { maxGenerationSupply } the modifier /// will set { generationMintAllowed } to false to stop the mint /// on this generation /// /// { generationId } is reset to 0 /// /// This condition will not block the function because as long as /// { block.number } >= { blockMeta } minting will reopen /// according and this condition will become obsolete until /// the condition is reached again if (generationId == maxGenerationSupply) { generationMintAllowed = false; generationId = 0; } } /// @notice Used to protect epoch block length from difficulty bomb of the /// Ethereum network. A difficulty bomb heavily increases the difficulty /// on the network, likely also causing an increase in block time. /// If the block time increases too much, the epoch generation could become /// exponentially higher than what is desired, ending with an undesired Ice-Age. /// To protect against this, the emergencySecure() function is allowed to /// manually reconfigure the epoch block length and the block Meta /// to match the network conditions if necessary. /// /// It can also be useful if the block time decreases for some reason with consensus change. /// /// This function is dedicated to contract owner according to { onlyOwner } modifier function emergencySecure(uint256 _epoch, uint256 _epochLen, uint256 _blockMeta, uint256 _inflateRatio) public onlyOwner { require(epoch > 0, "error epoch"); require(_epoch > 0, "error _epoch"); require(maxTokenSupply >= tokenId, "error maxTokenSupply"); epoch = _epoch; epochLen = _epochLen; blockMeta = _blockMeta; inflateRatio = _inflateRatio; computeBlockOmega(); emit Securized(epoch, epochLen, blockMeta, inflateRatio); } /// @notice Used to compute blockOmega() function, { blockOmega } represents /// the block when it won't ever be possible to mint another Dollars Nakamoto NFT. /// It is possible to be computed because of the deterministic state of the current protocol /// The following algorithm simulate the 10 epochs of the protocol block computation to result blockOmega function computeBlockOmega() private { uint256 i = 0; uint256 _blockMeta = 0; uint256 _epochLen = epochLen; while (i < epochMax) { if (i > 0) _epochLen *= inflateRatio; if (i == 9) { blockOmega = blockGenesis + _blockMeta; emit Omega(blockOmega); break; } _blockMeta += _epochLen; i++; } } /// @notice Used to regulate the epoch incrementation and block computation, known as Metas /// @dev When epoch=0, the { blockOmega } will be computed /// When epoch!=0 the block length { epochLen } will be multiplied /// by { inflateRatio } thus making the block length required for each /// epoch longer according /// /// { blockMeta } += { epochLen } result the exact block of the next Meta /// Allow generation mint after incrementing the epoch function epochRegulator() private { if (epoch == 0) computeBlockOmega(); if (epoch > 0) epochLen *= inflateRatio; blockMeta += epochLen; emit Meta(epoch, blockMeta); epoch++; if (block.number >= blockMeta && epoch < epochMax) { epochRegulator(); } generationMintAllowed = true; } // Mint functions ***************************************************** /// @notice Used to add/remove address from { _allowList } function setBatchGenesisAllowance(address[] memory batch) public onlyOwner { uint len = batch.length; require(len > 0, "error len"); uint i = 0; while (i < len) { _allowList[batch[i]] = _allowList[batch[i]] ? false : true; i++; } } /// @notice Used to transfer { _allowList } slot to another address function transferListSlot(address to) public { require(epoch == 0, "error epoch"); require(_allowList[msg.sender], "error msg.sender"); require(!_allowList[to], "error to"); _allowList[msg.sender] = false; _allowList[to] = true; } /// @notice Used to open the mint of Genesis NFT function setGenesisMint() public onlyOwner { genesisMintAllowed = true; } /// @notice Used to gift Genesis NFT, this function is dedicated /// to contract owner according to { onlyOwner } modifier function giftGenesis(address to) public onlyOwner { uint256 _genesisId = ++genesisId; setMetadata(tokenId, _genesisId, epoch); genesisController(_genesisId); mintUSDSat(to, tokenId++); } /// @notice Used to mint Genesis NFT, this function is payable /// the price of this function is equal to { genesisPrice }, /// require to be present on { _allowList } to call function mintGenesis() public payable { uint256 _genesisId = ++genesisId; setMetadata(tokenId, _genesisId, epoch); genesisController(_genesisId); require(genesisMintAllowed, "error genesisMintAllowed"); require(_allowList[msg.sender], "error allowList"); require(genesisPrice == msg.value, "error genesisPrice"); _allowList[msg.sender] = false; mintUSDSat(msg.sender, tokenId++); } /// @notice Used to gift Generation NFT, you need a Genesis NFT to call this function function giftGenerations(uint256 _genesisId, address to) public { ++generationId; generationController(_genesisId); setMetadata(tokenId, _genesisId, epoch); mintUSDSat(to, tokenId++); } /// @notice Used to mint Generation NFT, you need a Genesis NFT to call this function function mintGenerations(uint256 _genesisId) public { ++generationId; generationController(_genesisId); setMetadata(tokenId, _genesisId, epoch); mintUSDSat(msg.sender, tokenId++); } /// @notice Token is minted on { ADDRESS_SIGN } and instantly transferred to { msg.sender } as { to }, /// this is to ensure the token creation is signed with { ADDRESS_SIGN } /// This function is private and can be only called by the contract function mintUSDSat(address to, uint256 _tokenId) private { emit PermanentURI(_compileMetadata(_tokenId), _tokenId); _safeMint(ADDRESS_SIGN, _tokenId); emit Signed(epoch, _tokenId, block.number); _safeTransfer(ADDRESS_SIGN, to, _tokenId, ""); emit Minted(epoch, _tokenId, to); } // Contract URI functions ********************************************* /// @notice Used to set the { ContractCID } metadata from ipfs, /// this function is dedicated to contract owner according /// to { onlyOwner } modifier function setContractCID(string memory CID) public onlyOwner { ContractCID = string(abi.encodePacked("ipfs://", CID)); } /// @notice Used to render { ContractCID } as { contractURI } according to /// Opensea contract metadata standard function contractURI() public view virtual returns (string memory) { return ContractCID; } // Utilitaries functions ********************************************** /// @notice Used to fetch all entry for { epoch } into { epochMintingRegistry } function getMapRegisteryForEpoch(uint256 _epoch) public view returns (bool[210] memory result) { uint i = 1; while (i <= maxGenesisSupply) { result[i] = epochMintingRegistry[_epoch][i]; i++; } } /// @notice Used to fetch all { tokenIds } from { owner } function exposeHeldIds(address owner) public view returns(uint[] memory) { uint tokenCount = balanceOf(owner); uint[] memory tokenIds = new uint[](tokenCount); uint i = 0; while (i < tokenCount) { tokenIds[i] = tokenOfOwnerByIndex(owner, i); i++; } return tokenIds; } // ERC721 Spec functions ********************************************** /// @notice Used to render metadata as { tokenURI } according to ERC721 standard function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token"); return _compileMetadata(_tokenId); } /// @dev ERC721 required override function _beforeTokenTransfer(address from, address to, uint256 _tokenId) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, _tokenId); } /// @dev ERC721 required override function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } }
/// ``.. /// `.` `````.``.-````-`` `.` /// ` ``````.`..///.-..----. --..--`.-....`..-.```` ``` /// `` `.`..--...`:::/::-``..``..:-.://///---..-....----- /// ``-:::/+++:::/-.-///://oso+::++/--:--../+:/:..:-....-://:/:-`` /// `-+/++/+o+://+::-:soo+oosss+s+//o:/:--`--:://://:ooso/-.--.-:-.` /// ``.+ooso++o+:+:+sosyhsyshhddyo+:/sds/yoo++/+:--/--.--:..--..``.```` /// ``:++/---:+/::::///oyhhyy+++:hddhhNNho///ohosyhs+/-:/+/---.....-.. ` /// ``-:-...-/+///++///+o+:-:o+o/oydmNmNNdddhsoyo/oyyyho///:-.--.-.``. `` /// ```--`..-:+/:--:::-.-///++++ydsdNNMNdmMNMmNysddyoooosso+//-.-`....````` ..` /// .```:-:::/-.-+o++/+:/+/o/hNNNNhmdNMMNNMMdyydNNmdyys+++oo++-`--.:.-.`````... /// ..--.`-..`.-`-hh++-/:+shho+hsysyyhhhmNNmmNMMmNNNdmmy+:+sh/o+y/+-`+./::.```` ` /// -/` ``.-``.//o++y+//ssyh+hhdmmdmmddmhdmNdmdsh+oNNMmmddoodh/s:yss.--+.//+`.` `. /// `.`-.` -`..+h+yo++ooyyyyyoyhy+shmNNmmdhhdhyyhymdyyhdmshoohs+y:oy+/+o/:/++.`- .` /// ``.`.``-.-++syyyhhhhhhhhmhysosyyoooosssdhhhdmmdhdmdsy+ss+/+ho/hody-s+-:+::--`` ` /// .`` ``-//s+:ohmdmddNmNmhhshhddNNNhyyhhhdNNhmNNmNNmmyso+yhhso++hhdy.:/ ::-:--``.` /// .```.-`.//shdmNNmddyysohmMmdmNNmmNshdmNhso+-/ohNoyhmmsysosd++hy/osss/.:-o/-.:/--. /// ``..:++-+hhy/syhhhdhdNNddNMmNsNMNyyso+//:-.`-/..+hmdsmdy+ossos:+o/h/+..//-s.`.:::o/ /// `.-.oy//hm+o:-..-+/shdNNNNNNhsNdo/oyoyyhoh+/so//+/mNmyhh+/s+dy/+s::+:`-`-:s--:-.::+`-` /// .`:h-`+y+./oyhhdddhyohMMNmmNmdhoo/oyyhddhmNNNmhsoodmdhs+///++:+-:.:/--/-/o/--+//...:` /// ``+o``yoodNNNNNMhdyyo+ymhsymyshhyys+sssssNmdmmdmy+oso/++:://+/-`::-:--:/::+.//o:-.--: /// `:-:-`oNhyhdNNNmyys+/:://oohy++/+hmmmmNNNNhohydmmyhy++////ooy./----.-:---/::-o+:...-/ /// ``-.-` yms+mmNmMMmNho/:o++++hhh++:mMmNmmmNMNdhdms+ysyy//:-+o:.-.`.``.-:/::-:-+/y/.- -` /// ..:` hh+oNNmMNNNmss/:-+oyhs+o+.-yhdNmdhmmydmms+o///:///+/+--/`-``.o::/:-o//-/y::/.- /// `.-``hh+yNdmdohdy:++/./myhds/./shNhhyy++o:oyos/s+:s//+////.:- ...`--`..`-.:--o:+::` /// `-/+yyho.`.-+oso///+/Nmddh//y+:s:.../soy+:o+.:sdyo++++o:.-. `.:.:-```:.`:``/o:`:` /// ./.`..sMN+:::yh+s+ysyhhddh+ymdsd/:/+o+ysydhohoh/o+/so++o+/o.--..`-:::``:-`+-`:+--.` /// ``:``..-NNy++/yyysohmo+NNmy/+:+hMNmy+yydmNMNddhs:yyydmmmso:o///..-.-+-:o:/.o/-/+-`` /// ``+.`..-mMhsyo+++oo+yoshyyo+/`+hNmhyy+sdmdssssho-MMMNMNh//+/oo+/+:-....`.s+/`..-` /// .+ `oNMmdhhsohhmmydmNms/yy.oNmmdy+++/+ss+odNm+mNmdddo-s+:+/++/-:--//`/o+s/.-`` /// `/` dNNNhooddNmNymMNNdsoo+y+shhhmyymhss+hddms+hdhmdo+/+-/oo+/.///+sh:-/-s/` /// `::`hdNmh+ooNmdohNNMMmsooohh+oysydhdooo/syysodmNmys+/o+//+y/:.+/hmso.-//s- /// -+ohdmmhyhdysysyyhmysoyddhhoo+shdhdyddmddmNmmhssds/::/oo/..:/+Nmo+`-:so /// .oyhdmmNNdm+s:/:os/+/ssyyds+/ssdNNyhdmmhdmmdymymy///o:/``/+-dmdoo++:o` /// `ysyMNhhmoo+h-:/+o/+:.:/:/+doo+dNdhddmhmmmy++yhds/+-+::..o/+Nmosyhs+- /// s+dNNyNhsdhNhsy:+:oo/soo+dNmmooyosohMhsymmhyy+++:+:/+/-/o+yNh+hMNs. /// +yhNNMd+dmydmdy/+/sshydmhdNNmNooyhhhhshohmNh+:+oso++ssy+/odyhhNmh` /// `yyhdms+dMh+oyshhyhysdmNd+ohyNN+++mNddmNy+yo//+o/hddddymmyhosNmms` /// oydos:oMmhoyyhysssysdmMmNmhNmNNh/+mmNmddh+/+o+::+s+hmhmdyNNNNy: /// `/dNm/+Ndhy+oshdhhdyo::ohmdyhhNysy:smshmdo/o:so//:s++ymhyohdy-` /// `sNNN/hNm/:do+o:+/++++s:/+shyymmddy/ydmmh/s/+oss//oysy++o+o+` /// oNNMNmm:/hyy/:/o/+hhsosysoo-ohhhss/hmmhd/dyh++/soyooy++o+:. /// :/dMNh/smhh+//+s+--:+/so+ohhy/:sydmmmmm+/mdddhy++/ohs//-o/` /// `/odmhyhsyh++/-:+:::/:/o/:ooddy/+yodNNh+ydhmmmy++/hhyo+://` /// `:os/+o//oshss/yhs+//:+/-/:soooo/+sso+dddydss+:+sy///+:++ /// ./o/s//hhNho+shyyyoyyso+/ys+/+-:y+:/soooyyh++sNyo++/:/+ /// -/:osmmhyo:++++/+/osshdssooo/:/h//://++oyhsshmdo+//s/- /// .osmhydh::/+++/o+ohhysddyoo++os+-+++///yhhhmNs+o/:// /// -.++yss//////+/+/+soo++shyhsyy+::/:+y+yhdmdoo//:/:- /// ``.oss/:////++://+o//:://+oo-:o++/shhhmmh+o+++///-` /// ..:+++oo/+///ys:///://+::-sy+osh+osdyo+o/::/s:/y-` /// `odoyhds+/yysyydss+///+/:+oshdmNo+:+/oo/+++++:hy//` /// `://hyoyy/o/++shhy:+y:/:o/+omNmhsoohhsso+++:+o+sy:/++ /// -/---oddooss+oosy+ohNdo+++oyNhsdo/++shhhoo:s+oydmyo//o+ /// :y.`.``yyd++shoyydhhyymdhyyhyhhs+////+/+s/+:odmmyso.:ohy. /// .yy/o-..+h/+o/+//++ssoohhhssso+++:/:/yy+//sydmNddo+/./ohy+. /// .dmmhs+osdoos///o//++/+shdsoshoys+ssss++shmNNNyyds+:-s-//:+. /// -shmNmyhddsyss++/+ysddhyyydhdmyssNddyydyhNmdNmddso/::s:--`.-.` /// `+dmNhhdmddsooyyooossysshdhmoss+/+mNdyymydMdyMdyoo+/--/:/:`...-.` /// .:smNNMmsMNNmdhyyo/yymmdmdyo+ooooshysyysNNNmmmNyss/+o-`-:-/:```.`` ``` /// `.-+o/sdNNNmhdddNmmdsso/sdshyyyyhsdddyohymdmNdmmmmmyoo+/.... -os.`.``-.`` /// `/-:-/+.hymmmmdhmyNdMNmmhhs+sosoyhddyddmmho/ooymhddhdhyos-.oy..-:o+:..`` ```` ` /// ..::``--.-hoymmdNNNNNNMmhyNh+oo+soyNdmNmmmysooooymhy+so++yo..:+.--`..:.`.` `-- ``.` ` /// ```-.-.``..`:ddymmmNNdmNNNNmhN: -/oys/sdmmNdydsydmhhsmdso+/yo:/-..`.``.` ``:.`.````-. ` /// ````-:/.```:::syyydmddNhNNdsdMMs`./oddmd./odNdy+yssss++ooo/o+//-`:/:..:`-.```/-:.`.```..`` ` /// ```..-`` --.`.--o+sNhoyMmho+omhmo+Ns::dhdmmdy:.oNoyhhs+/o+o++s+hhoo+.`-:....``.-:-`..-````.-``.`` /// @title Dollars Nakamoto by Pascal Boyart /// @author jolan.eth /// @notice This contract will allow you to yield farm Dollars Nakamoto NFT. /// During epoch 0 you will be able to mint a Genesis NFT, /// Over time, epoch will increment allowing you to mint more editions. /// Minting generations editions is allowed only 1 time per epoch and per Genesis NFT. /// Generations editions do not allow you to mint other generations.
NatSpecSingleLine
setContractCID
function setContractCID(string memory CID) public onlyOwner { ContractCID = string(abi.encodePacked("ipfs://", CID)); }
/// @notice Used to set the { ContractCID } metadata from ipfs, /// this function is dedicated to contract owner according /// to { onlyOwner } modifier
NatSpecSingleLine
v0.8.10+commit.fc410830
MIT
ipfs://627efb7c58e0f1a820013031c32ab417b2b86eb0e16948f99bf7e29ad6e50407
{ "func_code_index": [ 15567, 15710 ] }
2,683
USDSat
USDSat.sol
0xbeda58401038c864c9fc9145f28e47b7b00a0e86
Solidity
USDSat
contract USDSat is USDSatMetadata, ERC721, ERC721Enumerable, Ownable, ReentrancyGuard { string SYMBOL = "USDSat"; string NAME = "Dollars Nakamoto"; string ContractCID; /// @notice Address used to sign NFT on mint address public ADDRESS_SIGN = 0x1Af70e564847bE46e4bA286c0b0066Da8372F902; /// @notice Ether shareholder address address public ADDRESS_PBOY = 0x709e17B3Ec505F80eAb064d0F2A71c743cE225B3; /// @notice Ether shareholder address address public ADDRESS_JOLAN = 0x51BdFa2Cbb25591AF58b202aCdcdB33325a325c2; /// @notice Equity per shareholder in % uint256 public SHARE_PBOY = 90; /// @notice Equity per shareholder in % uint256 public SHARE_JOLAN = 10; /// @notice Mapping used to represent allowed addresses to call { mintGenesis } mapping (address => bool) public _allowList; /// @notice Represent the current epoch uint256 public epoch = 0; /// @notice Represent the maximum epoch possible uint256 public epochMax = 10; /// @notice Represent the block length of an epoch uint256 public epochLen = 41016; /// @notice Index of the NFT /// @dev Start at 1 because var++ uint256 public tokenId = 1; /// @notice Index of the Genesis NFT /// @dev Start at 0 because ++var uint256 public genesisId = 0; /// @notice Index of the Generation NFT /// @dev Start at 0 because ++var uint256 public generationId = 0; /// @notice Maximum total supply uint256 public maxTokenSupply = 2100; /// @notice Maximum Genesis supply uint256 public maxGenesisSupply = 210; /// @notice Maximum supply per generation uint256 public maxGenerationSupply = 210; /// @notice Price of the Genesis NFT (Generations NFT are free) uint256 public genesisPrice = 0.5 ether; /// @notice Define the ending block uint256 public blockOmega; /// @notice Define the starting block uint256 public blockGenesis; /// @notice Define in which block the Meta must occur uint256 public blockMeta; /// @notice Used to inflate blockMeta each epoch incrementation uint256 public inflateRatio = 2; /// @notice Open Genesis mint when true bool public genesisMintAllowed = false; /// @notice Open Generation mint when true bool public generationMintAllowed = false; /// @notice Multi dimensionnal mapping to keep a track of the minting reentrancy over epoch mapping(uint256 => mapping(uint256 => bool)) public epochMintingRegistry; event Omega(uint256 _blockNumber); event Genesis(uint256 indexed _epoch, uint256 _blockNumber); event Meta(uint256 indexed _epoch, uint256 _blockNumber); event Withdraw(uint256 indexed _share, address _shareholder); event Shareholder(uint256 indexed _sharePercent, address _shareholder); event Securized(uint256 indexed _epoch, uint256 _epochLen, uint256 _blockMeta, uint256 _inflateRatio); event PermanentURI(string _value, uint256 indexed _id); event Minted(uint256 indexed _epoch, uint256 indexed _tokenId, address indexed _owner); event Signed(uint256 indexed _epoch, uint256 indexed _tokenId, uint256 indexed _blockNumber); constructor() ERC721(NAME, SYMBOL) {} // Withdraw functions ************************************************* /// @notice Allow Pboy to modify ADDRESS_PBOY /// This function is dedicated to the represented shareholder according to require(). function setPboy(address PBOY) public { require(msg.sender == ADDRESS_PBOY, "error msg.sender"); ADDRESS_PBOY = PBOY; emit Shareholder(SHARE_PBOY, ADDRESS_PBOY); } /// @notice Allow Jolan to modify ADDRESS_JOLAN /// This function is dedicated to the represented shareholder according to require(). function setJolan(address JOLAN) public { require(msg.sender == ADDRESS_JOLAN, "error msg.sender"); ADDRESS_JOLAN = JOLAN; emit Shareholder(SHARE_JOLAN, ADDRESS_JOLAN); } /// @notice Used to withdraw ETH balance of the contract, this function is dedicated /// to contract owner according to { onlyOwner } modifier. function withdrawEquity() public onlyOwner nonReentrant { uint256 balance = address(this).balance; address[2] memory shareholders = [ ADDRESS_PBOY, ADDRESS_JOLAN ]; uint256[2] memory _shares = [ SHARE_PBOY * balance / 100, SHARE_JOLAN * balance / 100 ]; uint i = 0; while (i < 2) { require(payable(shareholders[i]).send(_shares[i])); emit Withdraw(_shares[i], shareholders[i]); i++; } } // Epoch functions **************************************************** /// @notice Used to manage authorization and reentrancy of the genesis NFT mint /// @param _genesisId Used to increment { genesisId } and write { epochMintingRegistry } function genesisController(uint256 _genesisId) private { require(epoch == 0, "error epoch"); require(genesisId <= maxGenesisSupply, "error genesisId"); require(!epochMintingRegistry[epoch][_genesisId], "error epochMintingRegistry"); /// @dev Set { _genesisId } for { epoch } as true epochMintingRegistry[epoch][_genesisId] = true; /// @dev When { genesisId } reaches { maxGenesisSupply } the function /// will compute the data to increment the epoch according /// /// { blockGenesis } is set only once, at this time /// { blockMeta } is set to { blockGenesis } because epoch=0 /// Then it is computed into the function epochRegulator() /// /// Once the epoch is regulated, the new generation start /// straight away, { generationMintAllowed } is set to true if (genesisId == maxGenesisSupply) { blockGenesis = block.number; blockMeta = blockGenesis; emit Genesis(epoch, blockGenesis); epochRegulator(); } } /// @notice Used to manage authorization and reentrancy of the Generation NFT mint /// @param _genesisId Used to write { epochMintingRegistry } and verify minting allowance function generationController(uint256 _genesisId) private { require(blockGenesis > 0, "error blockGenesis"); require(blockMeta > 0, "error blockMeta"); require(blockOmega > 0, "error blockOmega"); /// @dev If { block.number } >= { blockMeta } the function /// will compute the data to increment the epoch according /// /// Once the epoch is regulated, the new generation start /// straight away, { generationMintAllowed } is set to true /// /// { generationId } is reset to 1 if (block.number >= blockMeta) { epochRegulator(); generationId = 1; } /// @dev Be sure the mint is open if condition are favorable if (block.number < blockMeta && generationId <= maxGenerationSupply) { generationMintAllowed = true; } require(maxTokenSupply >= tokenId, "error maxTokenSupply"); require(epoch > 0 && epoch < epochMax, "error epoch"); require(ownerOf(_genesisId) == msg.sender, "error ownerOf"); require(generationMintAllowed, "error generationMintAllowed"); require(generationId <= maxGenerationSupply, "error generationId"); require(epochMintingRegistry[0][_genesisId], "error epochMintingRegistry"); require(!epochMintingRegistry[epoch][_genesisId], "error epochMintingRegistry"); /// @dev Set { _genesisId } for { epoch } as true epochMintingRegistry[epoch][_genesisId] = true; /// @dev If { generationId } reaches { maxGenerationSupply } the modifier /// will set { generationMintAllowed } to false to stop the mint /// on this generation /// /// { generationId } is reset to 0 /// /// This condition will not block the function because as long as /// { block.number } >= { blockMeta } minting will reopen /// according and this condition will become obsolete until /// the condition is reached again if (generationId == maxGenerationSupply) { generationMintAllowed = false; generationId = 0; } } /// @notice Used to protect epoch block length from difficulty bomb of the /// Ethereum network. A difficulty bomb heavily increases the difficulty /// on the network, likely also causing an increase in block time. /// If the block time increases too much, the epoch generation could become /// exponentially higher than what is desired, ending with an undesired Ice-Age. /// To protect against this, the emergencySecure() function is allowed to /// manually reconfigure the epoch block length and the block Meta /// to match the network conditions if necessary. /// /// It can also be useful if the block time decreases for some reason with consensus change. /// /// This function is dedicated to contract owner according to { onlyOwner } modifier function emergencySecure(uint256 _epoch, uint256 _epochLen, uint256 _blockMeta, uint256 _inflateRatio) public onlyOwner { require(epoch > 0, "error epoch"); require(_epoch > 0, "error _epoch"); require(maxTokenSupply >= tokenId, "error maxTokenSupply"); epoch = _epoch; epochLen = _epochLen; blockMeta = _blockMeta; inflateRatio = _inflateRatio; computeBlockOmega(); emit Securized(epoch, epochLen, blockMeta, inflateRatio); } /// @notice Used to compute blockOmega() function, { blockOmega } represents /// the block when it won't ever be possible to mint another Dollars Nakamoto NFT. /// It is possible to be computed because of the deterministic state of the current protocol /// The following algorithm simulate the 10 epochs of the protocol block computation to result blockOmega function computeBlockOmega() private { uint256 i = 0; uint256 _blockMeta = 0; uint256 _epochLen = epochLen; while (i < epochMax) { if (i > 0) _epochLen *= inflateRatio; if (i == 9) { blockOmega = blockGenesis + _blockMeta; emit Omega(blockOmega); break; } _blockMeta += _epochLen; i++; } } /// @notice Used to regulate the epoch incrementation and block computation, known as Metas /// @dev When epoch=0, the { blockOmega } will be computed /// When epoch!=0 the block length { epochLen } will be multiplied /// by { inflateRatio } thus making the block length required for each /// epoch longer according /// /// { blockMeta } += { epochLen } result the exact block of the next Meta /// Allow generation mint after incrementing the epoch function epochRegulator() private { if (epoch == 0) computeBlockOmega(); if (epoch > 0) epochLen *= inflateRatio; blockMeta += epochLen; emit Meta(epoch, blockMeta); epoch++; if (block.number >= blockMeta && epoch < epochMax) { epochRegulator(); } generationMintAllowed = true; } // Mint functions ***************************************************** /// @notice Used to add/remove address from { _allowList } function setBatchGenesisAllowance(address[] memory batch) public onlyOwner { uint len = batch.length; require(len > 0, "error len"); uint i = 0; while (i < len) { _allowList[batch[i]] = _allowList[batch[i]] ? false : true; i++; } } /// @notice Used to transfer { _allowList } slot to another address function transferListSlot(address to) public { require(epoch == 0, "error epoch"); require(_allowList[msg.sender], "error msg.sender"); require(!_allowList[to], "error to"); _allowList[msg.sender] = false; _allowList[to] = true; } /// @notice Used to open the mint of Genesis NFT function setGenesisMint() public onlyOwner { genesisMintAllowed = true; } /// @notice Used to gift Genesis NFT, this function is dedicated /// to contract owner according to { onlyOwner } modifier function giftGenesis(address to) public onlyOwner { uint256 _genesisId = ++genesisId; setMetadata(tokenId, _genesisId, epoch); genesisController(_genesisId); mintUSDSat(to, tokenId++); } /// @notice Used to mint Genesis NFT, this function is payable /// the price of this function is equal to { genesisPrice }, /// require to be present on { _allowList } to call function mintGenesis() public payable { uint256 _genesisId = ++genesisId; setMetadata(tokenId, _genesisId, epoch); genesisController(_genesisId); require(genesisMintAllowed, "error genesisMintAllowed"); require(_allowList[msg.sender], "error allowList"); require(genesisPrice == msg.value, "error genesisPrice"); _allowList[msg.sender] = false; mintUSDSat(msg.sender, tokenId++); } /// @notice Used to gift Generation NFT, you need a Genesis NFT to call this function function giftGenerations(uint256 _genesisId, address to) public { ++generationId; generationController(_genesisId); setMetadata(tokenId, _genesisId, epoch); mintUSDSat(to, tokenId++); } /// @notice Used to mint Generation NFT, you need a Genesis NFT to call this function function mintGenerations(uint256 _genesisId) public { ++generationId; generationController(_genesisId); setMetadata(tokenId, _genesisId, epoch); mintUSDSat(msg.sender, tokenId++); } /// @notice Token is minted on { ADDRESS_SIGN } and instantly transferred to { msg.sender } as { to }, /// this is to ensure the token creation is signed with { ADDRESS_SIGN } /// This function is private and can be only called by the contract function mintUSDSat(address to, uint256 _tokenId) private { emit PermanentURI(_compileMetadata(_tokenId), _tokenId); _safeMint(ADDRESS_SIGN, _tokenId); emit Signed(epoch, _tokenId, block.number); _safeTransfer(ADDRESS_SIGN, to, _tokenId, ""); emit Minted(epoch, _tokenId, to); } // Contract URI functions ********************************************* /// @notice Used to set the { ContractCID } metadata from ipfs, /// this function is dedicated to contract owner according /// to { onlyOwner } modifier function setContractCID(string memory CID) public onlyOwner { ContractCID = string(abi.encodePacked("ipfs://", CID)); } /// @notice Used to render { ContractCID } as { contractURI } according to /// Opensea contract metadata standard function contractURI() public view virtual returns (string memory) { return ContractCID; } // Utilitaries functions ********************************************** /// @notice Used to fetch all entry for { epoch } into { epochMintingRegistry } function getMapRegisteryForEpoch(uint256 _epoch) public view returns (bool[210] memory result) { uint i = 1; while (i <= maxGenesisSupply) { result[i] = epochMintingRegistry[_epoch][i]; i++; } } /// @notice Used to fetch all { tokenIds } from { owner } function exposeHeldIds(address owner) public view returns(uint[] memory) { uint tokenCount = balanceOf(owner); uint[] memory tokenIds = new uint[](tokenCount); uint i = 0; while (i < tokenCount) { tokenIds[i] = tokenOfOwnerByIndex(owner, i); i++; } return tokenIds; } // ERC721 Spec functions ********************************************** /// @notice Used to render metadata as { tokenURI } according to ERC721 standard function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token"); return _compileMetadata(_tokenId); } /// @dev ERC721 required override function _beforeTokenTransfer(address from, address to, uint256 _tokenId) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, _tokenId); } /// @dev ERC721 required override function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } }
/// ``.. /// `.` `````.``.-````-`` `.` /// ` ``````.`..///.-..----. --..--`.-....`..-.```` ``` /// `` `.`..--...`:::/::-``..``..:-.://///---..-....----- /// ``-:::/+++:::/-.-///://oso+::++/--:--../+:/:..:-....-://:/:-`` /// `-+/++/+o+://+::-:soo+oosss+s+//o:/:--`--:://://:ooso/-.--.-:-.` /// ``.+ooso++o+:+:+sosyhsyshhddyo+:/sds/yoo++/+:--/--.--:..--..``.```` /// ``:++/---:+/::::///oyhhyy+++:hddhhNNho///ohosyhs+/-:/+/---.....-.. ` /// ``-:-...-/+///++///+o+:-:o+o/oydmNmNNdddhsoyo/oyyyho///:-.--.-.``. `` /// ```--`..-:+/:--:::-.-///++++ydsdNNMNdmMNMmNysddyoooosso+//-.-`....````` ..` /// .```:-:::/-.-+o++/+:/+/o/hNNNNhmdNMMNNMMdyydNNmdyys+++oo++-`--.:.-.`````... /// ..--.`-..`.-`-hh++-/:+shho+hsysyyhhhmNNmmNMMmNNNdmmy+:+sh/o+y/+-`+./::.```` ` /// -/` ``.-``.//o++y+//ssyh+hhdmmdmmddmhdmNdmdsh+oNNMmmddoodh/s:yss.--+.//+`.` `. /// `.`-.` -`..+h+yo++ooyyyyyoyhy+shmNNmmdhhdhyyhymdyyhdmshoohs+y:oy+/+o/:/++.`- .` /// ``.`.``-.-++syyyhhhhhhhhmhysosyyoooosssdhhhdmmdhdmdsy+ss+/+ho/hody-s+-:+::--`` ` /// .`` ``-//s+:ohmdmddNmNmhhshhddNNNhyyhhhdNNhmNNmNNmmyso+yhhso++hhdy.:/ ::-:--``.` /// .```.-`.//shdmNNmddyysohmMmdmNNmmNshdmNhso+-/ohNoyhmmsysosd++hy/osss/.:-o/-.:/--. /// ``..:++-+hhy/syhhhdhdNNddNMmNsNMNyyso+//:-.`-/..+hmdsmdy+ossos:+o/h/+..//-s.`.:::o/ /// `.-.oy//hm+o:-..-+/shdNNNNNNhsNdo/oyoyyhoh+/so//+/mNmyhh+/s+dy/+s::+:`-`-:s--:-.::+`-` /// .`:h-`+y+./oyhhdddhyohMMNmmNmdhoo/oyyhddhmNNNmhsoodmdhs+///++:+-:.:/--/-/o/--+//...:` /// ``+o``yoodNNNNNMhdyyo+ymhsymyshhyys+sssssNmdmmdmy+oso/++:://+/-`::-:--:/::+.//o:-.--: /// `:-:-`oNhyhdNNNmyys+/:://oohy++/+hmmmmNNNNhohydmmyhy++////ooy./----.-:---/::-o+:...-/ /// ``-.-` yms+mmNmMMmNho/:o++++hhh++:mMmNmmmNMNdhdms+ysyy//:-+o:.-.`.``.-:/::-:-+/y/.- -` /// ..:` hh+oNNmMNNNmss/:-+oyhs+o+.-yhdNmdhmmydmms+o///:///+/+--/`-``.o::/:-o//-/y::/.- /// `.-``hh+yNdmdohdy:++/./myhds/./shNhhyy++o:oyos/s+:s//+////.:- ...`--`..`-.:--o:+::` /// `-/+yyho.`.-+oso///+/Nmddh//y+:s:.../soy+:o+.:sdyo++++o:.-. `.:.:-```:.`:``/o:`:` /// ./.`..sMN+:::yh+s+ysyhhddh+ymdsd/:/+o+ysydhohoh/o+/so++o+/o.--..`-:::``:-`+-`:+--.` /// ``:``..-NNy++/yyysohmo+NNmy/+:+hMNmy+yydmNMNddhs:yyydmmmso:o///..-.-+-:o:/.o/-/+-`` /// ``+.`..-mMhsyo+++oo+yoshyyo+/`+hNmhyy+sdmdssssho-MMMNMNh//+/oo+/+:-....`.s+/`..-` /// .+ `oNMmdhhsohhmmydmNms/yy.oNmmdy+++/+ss+odNm+mNmdddo-s+:+/++/-:--//`/o+s/.-`` /// `/` dNNNhooddNmNymMNNdsoo+y+shhhmyymhss+hddms+hdhmdo+/+-/oo+/.///+sh:-/-s/` /// `::`hdNmh+ooNmdohNNMMmsooohh+oysydhdooo/syysodmNmys+/o+//+y/:.+/hmso.-//s- /// -+ohdmmhyhdysysyyhmysoyddhhoo+shdhdyddmddmNmmhssds/::/oo/..:/+Nmo+`-:so /// .oyhdmmNNdm+s:/:os/+/ssyyds+/ssdNNyhdmmhdmmdymymy///o:/``/+-dmdoo++:o` /// `ysyMNhhmoo+h-:/+o/+:.:/:/+doo+dNdhddmhmmmy++yhds/+-+::..o/+Nmosyhs+- /// s+dNNyNhsdhNhsy:+:oo/soo+dNmmooyosohMhsymmhyy+++:+:/+/-/o+yNh+hMNs. /// +yhNNMd+dmydmdy/+/sshydmhdNNmNooyhhhhshohmNh+:+oso++ssy+/odyhhNmh` /// `yyhdms+dMh+oyshhyhysdmNd+ohyNN+++mNddmNy+yo//+o/hddddymmyhosNmms` /// oydos:oMmhoyyhysssysdmMmNmhNmNNh/+mmNmddh+/+o+::+s+hmhmdyNNNNy: /// `/dNm/+Ndhy+oshdhhdyo::ohmdyhhNysy:smshmdo/o:so//:s++ymhyohdy-` /// `sNNN/hNm/:do+o:+/++++s:/+shyymmddy/ydmmh/s/+oss//oysy++o+o+` /// oNNMNmm:/hyy/:/o/+hhsosysoo-ohhhss/hmmhd/dyh++/soyooy++o+:. /// :/dMNh/smhh+//+s+--:+/so+ohhy/:sydmmmmm+/mdddhy++/ohs//-o/` /// `/odmhyhsyh++/-:+:::/:/o/:ooddy/+yodNNh+ydhmmmy++/hhyo+://` /// `:os/+o//oshss/yhs+//:+/-/:soooo/+sso+dddydss+:+sy///+:++ /// ./o/s//hhNho+shyyyoyyso+/ys+/+-:y+:/soooyyh++sNyo++/:/+ /// -/:osmmhyo:++++/+/osshdssooo/:/h//://++oyhsshmdo+//s/- /// .osmhydh::/+++/o+ohhysddyoo++os+-+++///yhhhmNs+o/:// /// -.++yss//////+/+/+soo++shyhsyy+::/:+y+yhdmdoo//:/:- /// ``.oss/:////++://+o//:://+oo-:o++/shhhmmh+o+++///-` /// ..:+++oo/+///ys:///://+::-sy+osh+osdyo+o/::/s:/y-` /// `odoyhds+/yysyydss+///+/:+oshdmNo+:+/oo/+++++:hy//` /// `://hyoyy/o/++shhy:+y:/:o/+omNmhsoohhsso+++:+o+sy:/++ /// -/---oddooss+oosy+ohNdo+++oyNhsdo/++shhhoo:s+oydmyo//o+ /// :y.`.``yyd++shoyydhhyymdhyyhyhhs+////+/+s/+:odmmyso.:ohy. /// .yy/o-..+h/+o/+//++ssoohhhssso+++:/:/yy+//sydmNddo+/./ohy+. /// .dmmhs+osdoos///o//++/+shdsoshoys+ssss++shmNNNyyds+:-s-//:+. /// -shmNmyhddsyss++/+ysddhyyydhdmyssNddyydyhNmdNmddso/::s:--`.-.` /// `+dmNhhdmddsooyyooossysshdhmoss+/+mNdyymydMdyMdyoo+/--/:/:`...-.` /// .:smNNMmsMNNmdhyyo/yymmdmdyo+ooooshysyysNNNmmmNyss/+o-`-:-/:```.`` ``` /// `.-+o/sdNNNmhdddNmmdsso/sdshyyyyhsdddyohymdmNdmmmmmyoo+/.... -os.`.``-.`` /// `/-:-/+.hymmmmdhmyNdMNmmhhs+sosoyhddyddmmho/ooymhddhdhyos-.oy..-:o+:..`` ```` ` /// ..::``--.-hoymmdNNNNNNMmhyNh+oo+soyNdmNmmmysooooymhy+so++yo..:+.--`..:.`.` `-- ``.` ` /// ```-.-.``..`:ddymmmNNdmNNNNmhN: -/oys/sdmmNdydsydmhhsmdso+/yo:/-..`.``.` ``:.`.````-. ` /// ````-:/.```:::syyydmddNhNNdsdMMs`./oddmd./odNdy+yssss++ooo/o+//-`:/:..:`-.```/-:.`.```..`` ` /// ```..-`` --.`.--o+sNhoyMmho+omhmo+Ns::dhdmmdy:.oNoyhhs+/o+o++s+hhoo+.`-:....``.-:-`..-````.-``.`` /// @title Dollars Nakamoto by Pascal Boyart /// @author jolan.eth /// @notice This contract will allow you to yield farm Dollars Nakamoto NFT. /// During epoch 0 you will be able to mint a Genesis NFT, /// Over time, epoch will increment allowing you to mint more editions. /// Minting generations editions is allowed only 1 time per epoch and per Genesis NFT. /// Generations editions do not allow you to mint other generations.
NatSpecSingleLine
contractURI
function contractURI() public view virtual returns (string memory) { return ContractCID; }
/// @notice Used to render { ContractCID } as { contractURI } according to /// Opensea contract metadata standard
NatSpecSingleLine
v0.8.10+commit.fc410830
MIT
ipfs://627efb7c58e0f1a820013031c32ab417b2b86eb0e16948f99bf7e29ad6e50407
{ "func_code_index": [ 15845, 15959 ] }
2,684
USDSat
USDSat.sol
0xbeda58401038c864c9fc9145f28e47b7b00a0e86
Solidity
USDSat
contract USDSat is USDSatMetadata, ERC721, ERC721Enumerable, Ownable, ReentrancyGuard { string SYMBOL = "USDSat"; string NAME = "Dollars Nakamoto"; string ContractCID; /// @notice Address used to sign NFT on mint address public ADDRESS_SIGN = 0x1Af70e564847bE46e4bA286c0b0066Da8372F902; /// @notice Ether shareholder address address public ADDRESS_PBOY = 0x709e17B3Ec505F80eAb064d0F2A71c743cE225B3; /// @notice Ether shareholder address address public ADDRESS_JOLAN = 0x51BdFa2Cbb25591AF58b202aCdcdB33325a325c2; /// @notice Equity per shareholder in % uint256 public SHARE_PBOY = 90; /// @notice Equity per shareholder in % uint256 public SHARE_JOLAN = 10; /// @notice Mapping used to represent allowed addresses to call { mintGenesis } mapping (address => bool) public _allowList; /// @notice Represent the current epoch uint256 public epoch = 0; /// @notice Represent the maximum epoch possible uint256 public epochMax = 10; /// @notice Represent the block length of an epoch uint256 public epochLen = 41016; /// @notice Index of the NFT /// @dev Start at 1 because var++ uint256 public tokenId = 1; /// @notice Index of the Genesis NFT /// @dev Start at 0 because ++var uint256 public genesisId = 0; /// @notice Index of the Generation NFT /// @dev Start at 0 because ++var uint256 public generationId = 0; /// @notice Maximum total supply uint256 public maxTokenSupply = 2100; /// @notice Maximum Genesis supply uint256 public maxGenesisSupply = 210; /// @notice Maximum supply per generation uint256 public maxGenerationSupply = 210; /// @notice Price of the Genesis NFT (Generations NFT are free) uint256 public genesisPrice = 0.5 ether; /// @notice Define the ending block uint256 public blockOmega; /// @notice Define the starting block uint256 public blockGenesis; /// @notice Define in which block the Meta must occur uint256 public blockMeta; /// @notice Used to inflate blockMeta each epoch incrementation uint256 public inflateRatio = 2; /// @notice Open Genesis mint when true bool public genesisMintAllowed = false; /// @notice Open Generation mint when true bool public generationMintAllowed = false; /// @notice Multi dimensionnal mapping to keep a track of the minting reentrancy over epoch mapping(uint256 => mapping(uint256 => bool)) public epochMintingRegistry; event Omega(uint256 _blockNumber); event Genesis(uint256 indexed _epoch, uint256 _blockNumber); event Meta(uint256 indexed _epoch, uint256 _blockNumber); event Withdraw(uint256 indexed _share, address _shareholder); event Shareholder(uint256 indexed _sharePercent, address _shareholder); event Securized(uint256 indexed _epoch, uint256 _epochLen, uint256 _blockMeta, uint256 _inflateRatio); event PermanentURI(string _value, uint256 indexed _id); event Minted(uint256 indexed _epoch, uint256 indexed _tokenId, address indexed _owner); event Signed(uint256 indexed _epoch, uint256 indexed _tokenId, uint256 indexed _blockNumber); constructor() ERC721(NAME, SYMBOL) {} // Withdraw functions ************************************************* /// @notice Allow Pboy to modify ADDRESS_PBOY /// This function is dedicated to the represented shareholder according to require(). function setPboy(address PBOY) public { require(msg.sender == ADDRESS_PBOY, "error msg.sender"); ADDRESS_PBOY = PBOY; emit Shareholder(SHARE_PBOY, ADDRESS_PBOY); } /// @notice Allow Jolan to modify ADDRESS_JOLAN /// This function is dedicated to the represented shareholder according to require(). function setJolan(address JOLAN) public { require(msg.sender == ADDRESS_JOLAN, "error msg.sender"); ADDRESS_JOLAN = JOLAN; emit Shareholder(SHARE_JOLAN, ADDRESS_JOLAN); } /// @notice Used to withdraw ETH balance of the contract, this function is dedicated /// to contract owner according to { onlyOwner } modifier. function withdrawEquity() public onlyOwner nonReentrant { uint256 balance = address(this).balance; address[2] memory shareholders = [ ADDRESS_PBOY, ADDRESS_JOLAN ]; uint256[2] memory _shares = [ SHARE_PBOY * balance / 100, SHARE_JOLAN * balance / 100 ]; uint i = 0; while (i < 2) { require(payable(shareholders[i]).send(_shares[i])); emit Withdraw(_shares[i], shareholders[i]); i++; } } // Epoch functions **************************************************** /// @notice Used to manage authorization and reentrancy of the genesis NFT mint /// @param _genesisId Used to increment { genesisId } and write { epochMintingRegistry } function genesisController(uint256 _genesisId) private { require(epoch == 0, "error epoch"); require(genesisId <= maxGenesisSupply, "error genesisId"); require(!epochMintingRegistry[epoch][_genesisId], "error epochMintingRegistry"); /// @dev Set { _genesisId } for { epoch } as true epochMintingRegistry[epoch][_genesisId] = true; /// @dev When { genesisId } reaches { maxGenesisSupply } the function /// will compute the data to increment the epoch according /// /// { blockGenesis } is set only once, at this time /// { blockMeta } is set to { blockGenesis } because epoch=0 /// Then it is computed into the function epochRegulator() /// /// Once the epoch is regulated, the new generation start /// straight away, { generationMintAllowed } is set to true if (genesisId == maxGenesisSupply) { blockGenesis = block.number; blockMeta = blockGenesis; emit Genesis(epoch, blockGenesis); epochRegulator(); } } /// @notice Used to manage authorization and reentrancy of the Generation NFT mint /// @param _genesisId Used to write { epochMintingRegistry } and verify minting allowance function generationController(uint256 _genesisId) private { require(blockGenesis > 0, "error blockGenesis"); require(blockMeta > 0, "error blockMeta"); require(blockOmega > 0, "error blockOmega"); /// @dev If { block.number } >= { blockMeta } the function /// will compute the data to increment the epoch according /// /// Once the epoch is regulated, the new generation start /// straight away, { generationMintAllowed } is set to true /// /// { generationId } is reset to 1 if (block.number >= blockMeta) { epochRegulator(); generationId = 1; } /// @dev Be sure the mint is open if condition are favorable if (block.number < blockMeta && generationId <= maxGenerationSupply) { generationMintAllowed = true; } require(maxTokenSupply >= tokenId, "error maxTokenSupply"); require(epoch > 0 && epoch < epochMax, "error epoch"); require(ownerOf(_genesisId) == msg.sender, "error ownerOf"); require(generationMintAllowed, "error generationMintAllowed"); require(generationId <= maxGenerationSupply, "error generationId"); require(epochMintingRegistry[0][_genesisId], "error epochMintingRegistry"); require(!epochMintingRegistry[epoch][_genesisId], "error epochMintingRegistry"); /// @dev Set { _genesisId } for { epoch } as true epochMintingRegistry[epoch][_genesisId] = true; /// @dev If { generationId } reaches { maxGenerationSupply } the modifier /// will set { generationMintAllowed } to false to stop the mint /// on this generation /// /// { generationId } is reset to 0 /// /// This condition will not block the function because as long as /// { block.number } >= { blockMeta } minting will reopen /// according and this condition will become obsolete until /// the condition is reached again if (generationId == maxGenerationSupply) { generationMintAllowed = false; generationId = 0; } } /// @notice Used to protect epoch block length from difficulty bomb of the /// Ethereum network. A difficulty bomb heavily increases the difficulty /// on the network, likely also causing an increase in block time. /// If the block time increases too much, the epoch generation could become /// exponentially higher than what is desired, ending with an undesired Ice-Age. /// To protect against this, the emergencySecure() function is allowed to /// manually reconfigure the epoch block length and the block Meta /// to match the network conditions if necessary. /// /// It can also be useful if the block time decreases for some reason with consensus change. /// /// This function is dedicated to contract owner according to { onlyOwner } modifier function emergencySecure(uint256 _epoch, uint256 _epochLen, uint256 _blockMeta, uint256 _inflateRatio) public onlyOwner { require(epoch > 0, "error epoch"); require(_epoch > 0, "error _epoch"); require(maxTokenSupply >= tokenId, "error maxTokenSupply"); epoch = _epoch; epochLen = _epochLen; blockMeta = _blockMeta; inflateRatio = _inflateRatio; computeBlockOmega(); emit Securized(epoch, epochLen, blockMeta, inflateRatio); } /// @notice Used to compute blockOmega() function, { blockOmega } represents /// the block when it won't ever be possible to mint another Dollars Nakamoto NFT. /// It is possible to be computed because of the deterministic state of the current protocol /// The following algorithm simulate the 10 epochs of the protocol block computation to result blockOmega function computeBlockOmega() private { uint256 i = 0; uint256 _blockMeta = 0; uint256 _epochLen = epochLen; while (i < epochMax) { if (i > 0) _epochLen *= inflateRatio; if (i == 9) { blockOmega = blockGenesis + _blockMeta; emit Omega(blockOmega); break; } _blockMeta += _epochLen; i++; } } /// @notice Used to regulate the epoch incrementation and block computation, known as Metas /// @dev When epoch=0, the { blockOmega } will be computed /// When epoch!=0 the block length { epochLen } will be multiplied /// by { inflateRatio } thus making the block length required for each /// epoch longer according /// /// { blockMeta } += { epochLen } result the exact block of the next Meta /// Allow generation mint after incrementing the epoch function epochRegulator() private { if (epoch == 0) computeBlockOmega(); if (epoch > 0) epochLen *= inflateRatio; blockMeta += epochLen; emit Meta(epoch, blockMeta); epoch++; if (block.number >= blockMeta && epoch < epochMax) { epochRegulator(); } generationMintAllowed = true; } // Mint functions ***************************************************** /// @notice Used to add/remove address from { _allowList } function setBatchGenesisAllowance(address[] memory batch) public onlyOwner { uint len = batch.length; require(len > 0, "error len"); uint i = 0; while (i < len) { _allowList[batch[i]] = _allowList[batch[i]] ? false : true; i++; } } /// @notice Used to transfer { _allowList } slot to another address function transferListSlot(address to) public { require(epoch == 0, "error epoch"); require(_allowList[msg.sender], "error msg.sender"); require(!_allowList[to], "error to"); _allowList[msg.sender] = false; _allowList[to] = true; } /// @notice Used to open the mint of Genesis NFT function setGenesisMint() public onlyOwner { genesisMintAllowed = true; } /// @notice Used to gift Genesis NFT, this function is dedicated /// to contract owner according to { onlyOwner } modifier function giftGenesis(address to) public onlyOwner { uint256 _genesisId = ++genesisId; setMetadata(tokenId, _genesisId, epoch); genesisController(_genesisId); mintUSDSat(to, tokenId++); } /// @notice Used to mint Genesis NFT, this function is payable /// the price of this function is equal to { genesisPrice }, /// require to be present on { _allowList } to call function mintGenesis() public payable { uint256 _genesisId = ++genesisId; setMetadata(tokenId, _genesisId, epoch); genesisController(_genesisId); require(genesisMintAllowed, "error genesisMintAllowed"); require(_allowList[msg.sender], "error allowList"); require(genesisPrice == msg.value, "error genesisPrice"); _allowList[msg.sender] = false; mintUSDSat(msg.sender, tokenId++); } /// @notice Used to gift Generation NFT, you need a Genesis NFT to call this function function giftGenerations(uint256 _genesisId, address to) public { ++generationId; generationController(_genesisId); setMetadata(tokenId, _genesisId, epoch); mintUSDSat(to, tokenId++); } /// @notice Used to mint Generation NFT, you need a Genesis NFT to call this function function mintGenerations(uint256 _genesisId) public { ++generationId; generationController(_genesisId); setMetadata(tokenId, _genesisId, epoch); mintUSDSat(msg.sender, tokenId++); } /// @notice Token is minted on { ADDRESS_SIGN } and instantly transferred to { msg.sender } as { to }, /// this is to ensure the token creation is signed with { ADDRESS_SIGN } /// This function is private and can be only called by the contract function mintUSDSat(address to, uint256 _tokenId) private { emit PermanentURI(_compileMetadata(_tokenId), _tokenId); _safeMint(ADDRESS_SIGN, _tokenId); emit Signed(epoch, _tokenId, block.number); _safeTransfer(ADDRESS_SIGN, to, _tokenId, ""); emit Minted(epoch, _tokenId, to); } // Contract URI functions ********************************************* /// @notice Used to set the { ContractCID } metadata from ipfs, /// this function is dedicated to contract owner according /// to { onlyOwner } modifier function setContractCID(string memory CID) public onlyOwner { ContractCID = string(abi.encodePacked("ipfs://", CID)); } /// @notice Used to render { ContractCID } as { contractURI } according to /// Opensea contract metadata standard function contractURI() public view virtual returns (string memory) { return ContractCID; } // Utilitaries functions ********************************************** /// @notice Used to fetch all entry for { epoch } into { epochMintingRegistry } function getMapRegisteryForEpoch(uint256 _epoch) public view returns (bool[210] memory result) { uint i = 1; while (i <= maxGenesisSupply) { result[i] = epochMintingRegistry[_epoch][i]; i++; } } /// @notice Used to fetch all { tokenIds } from { owner } function exposeHeldIds(address owner) public view returns(uint[] memory) { uint tokenCount = balanceOf(owner); uint[] memory tokenIds = new uint[](tokenCount); uint i = 0; while (i < tokenCount) { tokenIds[i] = tokenOfOwnerByIndex(owner, i); i++; } return tokenIds; } // ERC721 Spec functions ********************************************** /// @notice Used to render metadata as { tokenURI } according to ERC721 standard function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token"); return _compileMetadata(_tokenId); } /// @dev ERC721 required override function _beforeTokenTransfer(address from, address to, uint256 _tokenId) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, _tokenId); } /// @dev ERC721 required override function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } }
/// ``.. /// `.` `````.``.-````-`` `.` /// ` ``````.`..///.-..----. --..--`.-....`..-.```` ``` /// `` `.`..--...`:::/::-``..``..:-.://///---..-....----- /// ``-:::/+++:::/-.-///://oso+::++/--:--../+:/:..:-....-://:/:-`` /// `-+/++/+o+://+::-:soo+oosss+s+//o:/:--`--:://://:ooso/-.--.-:-.` /// ``.+ooso++o+:+:+sosyhsyshhddyo+:/sds/yoo++/+:--/--.--:..--..``.```` /// ``:++/---:+/::::///oyhhyy+++:hddhhNNho///ohosyhs+/-:/+/---.....-.. ` /// ``-:-...-/+///++///+o+:-:o+o/oydmNmNNdddhsoyo/oyyyho///:-.--.-.``. `` /// ```--`..-:+/:--:::-.-///++++ydsdNNMNdmMNMmNysddyoooosso+//-.-`....````` ..` /// .```:-:::/-.-+o++/+:/+/o/hNNNNhmdNMMNNMMdyydNNmdyys+++oo++-`--.:.-.`````... /// ..--.`-..`.-`-hh++-/:+shho+hsysyyhhhmNNmmNMMmNNNdmmy+:+sh/o+y/+-`+./::.```` ` /// -/` ``.-``.//o++y+//ssyh+hhdmmdmmddmhdmNdmdsh+oNNMmmddoodh/s:yss.--+.//+`.` `. /// `.`-.` -`..+h+yo++ooyyyyyoyhy+shmNNmmdhhdhyyhymdyyhdmshoohs+y:oy+/+o/:/++.`- .` /// ``.`.``-.-++syyyhhhhhhhhmhysosyyoooosssdhhhdmmdhdmdsy+ss+/+ho/hody-s+-:+::--`` ` /// .`` ``-//s+:ohmdmddNmNmhhshhddNNNhyyhhhdNNhmNNmNNmmyso+yhhso++hhdy.:/ ::-:--``.` /// .```.-`.//shdmNNmddyysohmMmdmNNmmNshdmNhso+-/ohNoyhmmsysosd++hy/osss/.:-o/-.:/--. /// ``..:++-+hhy/syhhhdhdNNddNMmNsNMNyyso+//:-.`-/..+hmdsmdy+ossos:+o/h/+..//-s.`.:::o/ /// `.-.oy//hm+o:-..-+/shdNNNNNNhsNdo/oyoyyhoh+/so//+/mNmyhh+/s+dy/+s::+:`-`-:s--:-.::+`-` /// .`:h-`+y+./oyhhdddhyohMMNmmNmdhoo/oyyhddhmNNNmhsoodmdhs+///++:+-:.:/--/-/o/--+//...:` /// ``+o``yoodNNNNNMhdyyo+ymhsymyshhyys+sssssNmdmmdmy+oso/++:://+/-`::-:--:/::+.//o:-.--: /// `:-:-`oNhyhdNNNmyys+/:://oohy++/+hmmmmNNNNhohydmmyhy++////ooy./----.-:---/::-o+:...-/ /// ``-.-` yms+mmNmMMmNho/:o++++hhh++:mMmNmmmNMNdhdms+ysyy//:-+o:.-.`.``.-:/::-:-+/y/.- -` /// ..:` hh+oNNmMNNNmss/:-+oyhs+o+.-yhdNmdhmmydmms+o///:///+/+--/`-``.o::/:-o//-/y::/.- /// `.-``hh+yNdmdohdy:++/./myhds/./shNhhyy++o:oyos/s+:s//+////.:- ...`--`..`-.:--o:+::` /// `-/+yyho.`.-+oso///+/Nmddh//y+:s:.../soy+:o+.:sdyo++++o:.-. `.:.:-```:.`:``/o:`:` /// ./.`..sMN+:::yh+s+ysyhhddh+ymdsd/:/+o+ysydhohoh/o+/so++o+/o.--..`-:::``:-`+-`:+--.` /// ``:``..-NNy++/yyysohmo+NNmy/+:+hMNmy+yydmNMNddhs:yyydmmmso:o///..-.-+-:o:/.o/-/+-`` /// ``+.`..-mMhsyo+++oo+yoshyyo+/`+hNmhyy+sdmdssssho-MMMNMNh//+/oo+/+:-....`.s+/`..-` /// .+ `oNMmdhhsohhmmydmNms/yy.oNmmdy+++/+ss+odNm+mNmdddo-s+:+/++/-:--//`/o+s/.-`` /// `/` dNNNhooddNmNymMNNdsoo+y+shhhmyymhss+hddms+hdhmdo+/+-/oo+/.///+sh:-/-s/` /// `::`hdNmh+ooNmdohNNMMmsooohh+oysydhdooo/syysodmNmys+/o+//+y/:.+/hmso.-//s- /// -+ohdmmhyhdysysyyhmysoyddhhoo+shdhdyddmddmNmmhssds/::/oo/..:/+Nmo+`-:so /// .oyhdmmNNdm+s:/:os/+/ssyyds+/ssdNNyhdmmhdmmdymymy///o:/``/+-dmdoo++:o` /// `ysyMNhhmoo+h-:/+o/+:.:/:/+doo+dNdhddmhmmmy++yhds/+-+::..o/+Nmosyhs+- /// s+dNNyNhsdhNhsy:+:oo/soo+dNmmooyosohMhsymmhyy+++:+:/+/-/o+yNh+hMNs. /// +yhNNMd+dmydmdy/+/sshydmhdNNmNooyhhhhshohmNh+:+oso++ssy+/odyhhNmh` /// `yyhdms+dMh+oyshhyhysdmNd+ohyNN+++mNddmNy+yo//+o/hddddymmyhosNmms` /// oydos:oMmhoyyhysssysdmMmNmhNmNNh/+mmNmddh+/+o+::+s+hmhmdyNNNNy: /// `/dNm/+Ndhy+oshdhhdyo::ohmdyhhNysy:smshmdo/o:so//:s++ymhyohdy-` /// `sNNN/hNm/:do+o:+/++++s:/+shyymmddy/ydmmh/s/+oss//oysy++o+o+` /// oNNMNmm:/hyy/:/o/+hhsosysoo-ohhhss/hmmhd/dyh++/soyooy++o+:. /// :/dMNh/smhh+//+s+--:+/so+ohhy/:sydmmmmm+/mdddhy++/ohs//-o/` /// `/odmhyhsyh++/-:+:::/:/o/:ooddy/+yodNNh+ydhmmmy++/hhyo+://` /// `:os/+o//oshss/yhs+//:+/-/:soooo/+sso+dddydss+:+sy///+:++ /// ./o/s//hhNho+shyyyoyyso+/ys+/+-:y+:/soooyyh++sNyo++/:/+ /// -/:osmmhyo:++++/+/osshdssooo/:/h//://++oyhsshmdo+//s/- /// .osmhydh::/+++/o+ohhysddyoo++os+-+++///yhhhmNs+o/:// /// -.++yss//////+/+/+soo++shyhsyy+::/:+y+yhdmdoo//:/:- /// ``.oss/:////++://+o//:://+oo-:o++/shhhmmh+o+++///-` /// ..:+++oo/+///ys:///://+::-sy+osh+osdyo+o/::/s:/y-` /// `odoyhds+/yysyydss+///+/:+oshdmNo+:+/oo/+++++:hy//` /// `://hyoyy/o/++shhy:+y:/:o/+omNmhsoohhsso+++:+o+sy:/++ /// -/---oddooss+oosy+ohNdo+++oyNhsdo/++shhhoo:s+oydmyo//o+ /// :y.`.``yyd++shoyydhhyymdhyyhyhhs+////+/+s/+:odmmyso.:ohy. /// .yy/o-..+h/+o/+//++ssoohhhssso+++:/:/yy+//sydmNddo+/./ohy+. /// .dmmhs+osdoos///o//++/+shdsoshoys+ssss++shmNNNyyds+:-s-//:+. /// -shmNmyhddsyss++/+ysddhyyydhdmyssNddyydyhNmdNmddso/::s:--`.-.` /// `+dmNhhdmddsooyyooossysshdhmoss+/+mNdyymydMdyMdyoo+/--/:/:`...-.` /// .:smNNMmsMNNmdhyyo/yymmdmdyo+ooooshysyysNNNmmmNyss/+o-`-:-/:```.`` ``` /// `.-+o/sdNNNmhdddNmmdsso/sdshyyyyhsdddyohymdmNdmmmmmyoo+/.... -os.`.``-.`` /// `/-:-/+.hymmmmdhmyNdMNmmhhs+sosoyhddyddmmho/ooymhddhdhyos-.oy..-:o+:..`` ```` ` /// ..::``--.-hoymmdNNNNNNMmhyNh+oo+soyNdmNmmmysooooymhy+so++yo..:+.--`..:.`.` `-- ``.` ` /// ```-.-.``..`:ddymmmNNdmNNNNmhN: -/oys/sdmmNdydsydmhhsmdso+/yo:/-..`.``.` ``:.`.````-. ` /// ````-:/.```:::syyydmddNhNNdsdMMs`./oddmd./odNdy+yssss++ooo/o+//-`:/:..:`-.```/-:.`.```..`` ` /// ```..-`` --.`.--o+sNhoyMmho+omhmo+Ns::dhdmmdy:.oNoyhhs+/o+o++s+hhoo+.`-:....``.-:-`..-````.-``.`` /// @title Dollars Nakamoto by Pascal Boyart /// @author jolan.eth /// @notice This contract will allow you to yield farm Dollars Nakamoto NFT. /// During epoch 0 you will be able to mint a Genesis NFT, /// Over time, epoch will increment allowing you to mint more editions. /// Minting generations editions is allowed only 1 time per epoch and per Genesis NFT. /// Generations editions do not allow you to mint other generations.
NatSpecSingleLine
getMapRegisteryForEpoch
function getMapRegisteryForEpoch(uint256 _epoch) public view returns (bool[210] memory result) { uint i = 1; while (i <= maxGenesisSupply) { result[i] = epochMintingRegistry[_epoch][i]; i++; } }
/// @notice Used to fetch all entry for { epoch } into { epochMintingRegistry }
NatSpecSingleLine
v0.8.10+commit.fc410830
MIT
ipfs://627efb7c58e0f1a820013031c32ab417b2b86eb0e16948f99bf7e29ad6e50407
{ "func_code_index": [ 16127, 16389 ] }
2,685
USDSat
USDSat.sol
0xbeda58401038c864c9fc9145f28e47b7b00a0e86
Solidity
USDSat
contract USDSat is USDSatMetadata, ERC721, ERC721Enumerable, Ownable, ReentrancyGuard { string SYMBOL = "USDSat"; string NAME = "Dollars Nakamoto"; string ContractCID; /// @notice Address used to sign NFT on mint address public ADDRESS_SIGN = 0x1Af70e564847bE46e4bA286c0b0066Da8372F902; /// @notice Ether shareholder address address public ADDRESS_PBOY = 0x709e17B3Ec505F80eAb064d0F2A71c743cE225B3; /// @notice Ether shareholder address address public ADDRESS_JOLAN = 0x51BdFa2Cbb25591AF58b202aCdcdB33325a325c2; /// @notice Equity per shareholder in % uint256 public SHARE_PBOY = 90; /// @notice Equity per shareholder in % uint256 public SHARE_JOLAN = 10; /// @notice Mapping used to represent allowed addresses to call { mintGenesis } mapping (address => bool) public _allowList; /// @notice Represent the current epoch uint256 public epoch = 0; /// @notice Represent the maximum epoch possible uint256 public epochMax = 10; /// @notice Represent the block length of an epoch uint256 public epochLen = 41016; /// @notice Index of the NFT /// @dev Start at 1 because var++ uint256 public tokenId = 1; /// @notice Index of the Genesis NFT /// @dev Start at 0 because ++var uint256 public genesisId = 0; /// @notice Index of the Generation NFT /// @dev Start at 0 because ++var uint256 public generationId = 0; /// @notice Maximum total supply uint256 public maxTokenSupply = 2100; /// @notice Maximum Genesis supply uint256 public maxGenesisSupply = 210; /// @notice Maximum supply per generation uint256 public maxGenerationSupply = 210; /// @notice Price of the Genesis NFT (Generations NFT are free) uint256 public genesisPrice = 0.5 ether; /// @notice Define the ending block uint256 public blockOmega; /// @notice Define the starting block uint256 public blockGenesis; /// @notice Define in which block the Meta must occur uint256 public blockMeta; /// @notice Used to inflate blockMeta each epoch incrementation uint256 public inflateRatio = 2; /// @notice Open Genesis mint when true bool public genesisMintAllowed = false; /// @notice Open Generation mint when true bool public generationMintAllowed = false; /// @notice Multi dimensionnal mapping to keep a track of the minting reentrancy over epoch mapping(uint256 => mapping(uint256 => bool)) public epochMintingRegistry; event Omega(uint256 _blockNumber); event Genesis(uint256 indexed _epoch, uint256 _blockNumber); event Meta(uint256 indexed _epoch, uint256 _blockNumber); event Withdraw(uint256 indexed _share, address _shareholder); event Shareholder(uint256 indexed _sharePercent, address _shareholder); event Securized(uint256 indexed _epoch, uint256 _epochLen, uint256 _blockMeta, uint256 _inflateRatio); event PermanentURI(string _value, uint256 indexed _id); event Minted(uint256 indexed _epoch, uint256 indexed _tokenId, address indexed _owner); event Signed(uint256 indexed _epoch, uint256 indexed _tokenId, uint256 indexed _blockNumber); constructor() ERC721(NAME, SYMBOL) {} // Withdraw functions ************************************************* /// @notice Allow Pboy to modify ADDRESS_PBOY /// This function is dedicated to the represented shareholder according to require(). function setPboy(address PBOY) public { require(msg.sender == ADDRESS_PBOY, "error msg.sender"); ADDRESS_PBOY = PBOY; emit Shareholder(SHARE_PBOY, ADDRESS_PBOY); } /// @notice Allow Jolan to modify ADDRESS_JOLAN /// This function is dedicated to the represented shareholder according to require(). function setJolan(address JOLAN) public { require(msg.sender == ADDRESS_JOLAN, "error msg.sender"); ADDRESS_JOLAN = JOLAN; emit Shareholder(SHARE_JOLAN, ADDRESS_JOLAN); } /// @notice Used to withdraw ETH balance of the contract, this function is dedicated /// to contract owner according to { onlyOwner } modifier. function withdrawEquity() public onlyOwner nonReentrant { uint256 balance = address(this).balance; address[2] memory shareholders = [ ADDRESS_PBOY, ADDRESS_JOLAN ]; uint256[2] memory _shares = [ SHARE_PBOY * balance / 100, SHARE_JOLAN * balance / 100 ]; uint i = 0; while (i < 2) { require(payable(shareholders[i]).send(_shares[i])); emit Withdraw(_shares[i], shareholders[i]); i++; } } // Epoch functions **************************************************** /// @notice Used to manage authorization and reentrancy of the genesis NFT mint /// @param _genesisId Used to increment { genesisId } and write { epochMintingRegistry } function genesisController(uint256 _genesisId) private { require(epoch == 0, "error epoch"); require(genesisId <= maxGenesisSupply, "error genesisId"); require(!epochMintingRegistry[epoch][_genesisId], "error epochMintingRegistry"); /// @dev Set { _genesisId } for { epoch } as true epochMintingRegistry[epoch][_genesisId] = true; /// @dev When { genesisId } reaches { maxGenesisSupply } the function /// will compute the data to increment the epoch according /// /// { blockGenesis } is set only once, at this time /// { blockMeta } is set to { blockGenesis } because epoch=0 /// Then it is computed into the function epochRegulator() /// /// Once the epoch is regulated, the new generation start /// straight away, { generationMintAllowed } is set to true if (genesisId == maxGenesisSupply) { blockGenesis = block.number; blockMeta = blockGenesis; emit Genesis(epoch, blockGenesis); epochRegulator(); } } /// @notice Used to manage authorization and reentrancy of the Generation NFT mint /// @param _genesisId Used to write { epochMintingRegistry } and verify minting allowance function generationController(uint256 _genesisId) private { require(blockGenesis > 0, "error blockGenesis"); require(blockMeta > 0, "error blockMeta"); require(blockOmega > 0, "error blockOmega"); /// @dev If { block.number } >= { blockMeta } the function /// will compute the data to increment the epoch according /// /// Once the epoch is regulated, the new generation start /// straight away, { generationMintAllowed } is set to true /// /// { generationId } is reset to 1 if (block.number >= blockMeta) { epochRegulator(); generationId = 1; } /// @dev Be sure the mint is open if condition are favorable if (block.number < blockMeta && generationId <= maxGenerationSupply) { generationMintAllowed = true; } require(maxTokenSupply >= tokenId, "error maxTokenSupply"); require(epoch > 0 && epoch < epochMax, "error epoch"); require(ownerOf(_genesisId) == msg.sender, "error ownerOf"); require(generationMintAllowed, "error generationMintAllowed"); require(generationId <= maxGenerationSupply, "error generationId"); require(epochMintingRegistry[0][_genesisId], "error epochMintingRegistry"); require(!epochMintingRegistry[epoch][_genesisId], "error epochMintingRegistry"); /// @dev Set { _genesisId } for { epoch } as true epochMintingRegistry[epoch][_genesisId] = true; /// @dev If { generationId } reaches { maxGenerationSupply } the modifier /// will set { generationMintAllowed } to false to stop the mint /// on this generation /// /// { generationId } is reset to 0 /// /// This condition will not block the function because as long as /// { block.number } >= { blockMeta } minting will reopen /// according and this condition will become obsolete until /// the condition is reached again if (generationId == maxGenerationSupply) { generationMintAllowed = false; generationId = 0; } } /// @notice Used to protect epoch block length from difficulty bomb of the /// Ethereum network. A difficulty bomb heavily increases the difficulty /// on the network, likely also causing an increase in block time. /// If the block time increases too much, the epoch generation could become /// exponentially higher than what is desired, ending with an undesired Ice-Age. /// To protect against this, the emergencySecure() function is allowed to /// manually reconfigure the epoch block length and the block Meta /// to match the network conditions if necessary. /// /// It can also be useful if the block time decreases for some reason with consensus change. /// /// This function is dedicated to contract owner according to { onlyOwner } modifier function emergencySecure(uint256 _epoch, uint256 _epochLen, uint256 _blockMeta, uint256 _inflateRatio) public onlyOwner { require(epoch > 0, "error epoch"); require(_epoch > 0, "error _epoch"); require(maxTokenSupply >= tokenId, "error maxTokenSupply"); epoch = _epoch; epochLen = _epochLen; blockMeta = _blockMeta; inflateRatio = _inflateRatio; computeBlockOmega(); emit Securized(epoch, epochLen, blockMeta, inflateRatio); } /// @notice Used to compute blockOmega() function, { blockOmega } represents /// the block when it won't ever be possible to mint another Dollars Nakamoto NFT. /// It is possible to be computed because of the deterministic state of the current protocol /// The following algorithm simulate the 10 epochs of the protocol block computation to result blockOmega function computeBlockOmega() private { uint256 i = 0; uint256 _blockMeta = 0; uint256 _epochLen = epochLen; while (i < epochMax) { if (i > 0) _epochLen *= inflateRatio; if (i == 9) { blockOmega = blockGenesis + _blockMeta; emit Omega(blockOmega); break; } _blockMeta += _epochLen; i++; } } /// @notice Used to regulate the epoch incrementation and block computation, known as Metas /// @dev When epoch=0, the { blockOmega } will be computed /// When epoch!=0 the block length { epochLen } will be multiplied /// by { inflateRatio } thus making the block length required for each /// epoch longer according /// /// { blockMeta } += { epochLen } result the exact block of the next Meta /// Allow generation mint after incrementing the epoch function epochRegulator() private { if (epoch == 0) computeBlockOmega(); if (epoch > 0) epochLen *= inflateRatio; blockMeta += epochLen; emit Meta(epoch, blockMeta); epoch++; if (block.number >= blockMeta && epoch < epochMax) { epochRegulator(); } generationMintAllowed = true; } // Mint functions ***************************************************** /// @notice Used to add/remove address from { _allowList } function setBatchGenesisAllowance(address[] memory batch) public onlyOwner { uint len = batch.length; require(len > 0, "error len"); uint i = 0; while (i < len) { _allowList[batch[i]] = _allowList[batch[i]] ? false : true; i++; } } /// @notice Used to transfer { _allowList } slot to another address function transferListSlot(address to) public { require(epoch == 0, "error epoch"); require(_allowList[msg.sender], "error msg.sender"); require(!_allowList[to], "error to"); _allowList[msg.sender] = false; _allowList[to] = true; } /// @notice Used to open the mint of Genesis NFT function setGenesisMint() public onlyOwner { genesisMintAllowed = true; } /// @notice Used to gift Genesis NFT, this function is dedicated /// to contract owner according to { onlyOwner } modifier function giftGenesis(address to) public onlyOwner { uint256 _genesisId = ++genesisId; setMetadata(tokenId, _genesisId, epoch); genesisController(_genesisId); mintUSDSat(to, tokenId++); } /// @notice Used to mint Genesis NFT, this function is payable /// the price of this function is equal to { genesisPrice }, /// require to be present on { _allowList } to call function mintGenesis() public payable { uint256 _genesisId = ++genesisId; setMetadata(tokenId, _genesisId, epoch); genesisController(_genesisId); require(genesisMintAllowed, "error genesisMintAllowed"); require(_allowList[msg.sender], "error allowList"); require(genesisPrice == msg.value, "error genesisPrice"); _allowList[msg.sender] = false; mintUSDSat(msg.sender, tokenId++); } /// @notice Used to gift Generation NFT, you need a Genesis NFT to call this function function giftGenerations(uint256 _genesisId, address to) public { ++generationId; generationController(_genesisId); setMetadata(tokenId, _genesisId, epoch); mintUSDSat(to, tokenId++); } /// @notice Used to mint Generation NFT, you need a Genesis NFT to call this function function mintGenerations(uint256 _genesisId) public { ++generationId; generationController(_genesisId); setMetadata(tokenId, _genesisId, epoch); mintUSDSat(msg.sender, tokenId++); } /// @notice Token is minted on { ADDRESS_SIGN } and instantly transferred to { msg.sender } as { to }, /// this is to ensure the token creation is signed with { ADDRESS_SIGN } /// This function is private and can be only called by the contract function mintUSDSat(address to, uint256 _tokenId) private { emit PermanentURI(_compileMetadata(_tokenId), _tokenId); _safeMint(ADDRESS_SIGN, _tokenId); emit Signed(epoch, _tokenId, block.number); _safeTransfer(ADDRESS_SIGN, to, _tokenId, ""); emit Minted(epoch, _tokenId, to); } // Contract URI functions ********************************************* /// @notice Used to set the { ContractCID } metadata from ipfs, /// this function is dedicated to contract owner according /// to { onlyOwner } modifier function setContractCID(string memory CID) public onlyOwner { ContractCID = string(abi.encodePacked("ipfs://", CID)); } /// @notice Used to render { ContractCID } as { contractURI } according to /// Opensea contract metadata standard function contractURI() public view virtual returns (string memory) { return ContractCID; } // Utilitaries functions ********************************************** /// @notice Used to fetch all entry for { epoch } into { epochMintingRegistry } function getMapRegisteryForEpoch(uint256 _epoch) public view returns (bool[210] memory result) { uint i = 1; while (i <= maxGenesisSupply) { result[i] = epochMintingRegistry[_epoch][i]; i++; } } /// @notice Used to fetch all { tokenIds } from { owner } function exposeHeldIds(address owner) public view returns(uint[] memory) { uint tokenCount = balanceOf(owner); uint[] memory tokenIds = new uint[](tokenCount); uint i = 0; while (i < tokenCount) { tokenIds[i] = tokenOfOwnerByIndex(owner, i); i++; } return tokenIds; } // ERC721 Spec functions ********************************************** /// @notice Used to render metadata as { tokenURI } according to ERC721 standard function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token"); return _compileMetadata(_tokenId); } /// @dev ERC721 required override function _beforeTokenTransfer(address from, address to, uint256 _tokenId) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, _tokenId); } /// @dev ERC721 required override function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } }
/// ``.. /// `.` `````.``.-````-`` `.` /// ` ``````.`..///.-..----. --..--`.-....`..-.```` ``` /// `` `.`..--...`:::/::-``..``..:-.://///---..-....----- /// ``-:::/+++:::/-.-///://oso+::++/--:--../+:/:..:-....-://:/:-`` /// `-+/++/+o+://+::-:soo+oosss+s+//o:/:--`--:://://:ooso/-.--.-:-.` /// ``.+ooso++o+:+:+sosyhsyshhddyo+:/sds/yoo++/+:--/--.--:..--..``.```` /// ``:++/---:+/::::///oyhhyy+++:hddhhNNho///ohosyhs+/-:/+/---.....-.. ` /// ``-:-...-/+///++///+o+:-:o+o/oydmNmNNdddhsoyo/oyyyho///:-.--.-.``. `` /// ```--`..-:+/:--:::-.-///++++ydsdNNMNdmMNMmNysddyoooosso+//-.-`....````` ..` /// .```:-:::/-.-+o++/+:/+/o/hNNNNhmdNMMNNMMdyydNNmdyys+++oo++-`--.:.-.`````... /// ..--.`-..`.-`-hh++-/:+shho+hsysyyhhhmNNmmNMMmNNNdmmy+:+sh/o+y/+-`+./::.```` ` /// -/` ``.-``.//o++y+//ssyh+hhdmmdmmddmhdmNdmdsh+oNNMmmddoodh/s:yss.--+.//+`.` `. /// `.`-.` -`..+h+yo++ooyyyyyoyhy+shmNNmmdhhdhyyhymdyyhdmshoohs+y:oy+/+o/:/++.`- .` /// ``.`.``-.-++syyyhhhhhhhhmhysosyyoooosssdhhhdmmdhdmdsy+ss+/+ho/hody-s+-:+::--`` ` /// .`` ``-//s+:ohmdmddNmNmhhshhddNNNhyyhhhdNNhmNNmNNmmyso+yhhso++hhdy.:/ ::-:--``.` /// .```.-`.//shdmNNmddyysohmMmdmNNmmNshdmNhso+-/ohNoyhmmsysosd++hy/osss/.:-o/-.:/--. /// ``..:++-+hhy/syhhhdhdNNddNMmNsNMNyyso+//:-.`-/..+hmdsmdy+ossos:+o/h/+..//-s.`.:::o/ /// `.-.oy//hm+o:-..-+/shdNNNNNNhsNdo/oyoyyhoh+/so//+/mNmyhh+/s+dy/+s::+:`-`-:s--:-.::+`-` /// .`:h-`+y+./oyhhdddhyohMMNmmNmdhoo/oyyhddhmNNNmhsoodmdhs+///++:+-:.:/--/-/o/--+//...:` /// ``+o``yoodNNNNNMhdyyo+ymhsymyshhyys+sssssNmdmmdmy+oso/++:://+/-`::-:--:/::+.//o:-.--: /// `:-:-`oNhyhdNNNmyys+/:://oohy++/+hmmmmNNNNhohydmmyhy++////ooy./----.-:---/::-o+:...-/ /// ``-.-` yms+mmNmMMmNho/:o++++hhh++:mMmNmmmNMNdhdms+ysyy//:-+o:.-.`.``.-:/::-:-+/y/.- -` /// ..:` hh+oNNmMNNNmss/:-+oyhs+o+.-yhdNmdhmmydmms+o///:///+/+--/`-``.o::/:-o//-/y::/.- /// `.-``hh+yNdmdohdy:++/./myhds/./shNhhyy++o:oyos/s+:s//+////.:- ...`--`..`-.:--o:+::` /// `-/+yyho.`.-+oso///+/Nmddh//y+:s:.../soy+:o+.:sdyo++++o:.-. `.:.:-```:.`:``/o:`:` /// ./.`..sMN+:::yh+s+ysyhhddh+ymdsd/:/+o+ysydhohoh/o+/so++o+/o.--..`-:::``:-`+-`:+--.` /// ``:``..-NNy++/yyysohmo+NNmy/+:+hMNmy+yydmNMNddhs:yyydmmmso:o///..-.-+-:o:/.o/-/+-`` /// ``+.`..-mMhsyo+++oo+yoshyyo+/`+hNmhyy+sdmdssssho-MMMNMNh//+/oo+/+:-....`.s+/`..-` /// .+ `oNMmdhhsohhmmydmNms/yy.oNmmdy+++/+ss+odNm+mNmdddo-s+:+/++/-:--//`/o+s/.-`` /// `/` dNNNhooddNmNymMNNdsoo+y+shhhmyymhss+hddms+hdhmdo+/+-/oo+/.///+sh:-/-s/` /// `::`hdNmh+ooNmdohNNMMmsooohh+oysydhdooo/syysodmNmys+/o+//+y/:.+/hmso.-//s- /// -+ohdmmhyhdysysyyhmysoyddhhoo+shdhdyddmddmNmmhssds/::/oo/..:/+Nmo+`-:so /// .oyhdmmNNdm+s:/:os/+/ssyyds+/ssdNNyhdmmhdmmdymymy///o:/``/+-dmdoo++:o` /// `ysyMNhhmoo+h-:/+o/+:.:/:/+doo+dNdhddmhmmmy++yhds/+-+::..o/+Nmosyhs+- /// s+dNNyNhsdhNhsy:+:oo/soo+dNmmooyosohMhsymmhyy+++:+:/+/-/o+yNh+hMNs. /// +yhNNMd+dmydmdy/+/sshydmhdNNmNooyhhhhshohmNh+:+oso++ssy+/odyhhNmh` /// `yyhdms+dMh+oyshhyhysdmNd+ohyNN+++mNddmNy+yo//+o/hddddymmyhosNmms` /// oydos:oMmhoyyhysssysdmMmNmhNmNNh/+mmNmddh+/+o+::+s+hmhmdyNNNNy: /// `/dNm/+Ndhy+oshdhhdyo::ohmdyhhNysy:smshmdo/o:so//:s++ymhyohdy-` /// `sNNN/hNm/:do+o:+/++++s:/+shyymmddy/ydmmh/s/+oss//oysy++o+o+` /// oNNMNmm:/hyy/:/o/+hhsosysoo-ohhhss/hmmhd/dyh++/soyooy++o+:. /// :/dMNh/smhh+//+s+--:+/so+ohhy/:sydmmmmm+/mdddhy++/ohs//-o/` /// `/odmhyhsyh++/-:+:::/:/o/:ooddy/+yodNNh+ydhmmmy++/hhyo+://` /// `:os/+o//oshss/yhs+//:+/-/:soooo/+sso+dddydss+:+sy///+:++ /// ./o/s//hhNho+shyyyoyyso+/ys+/+-:y+:/soooyyh++sNyo++/:/+ /// -/:osmmhyo:++++/+/osshdssooo/:/h//://++oyhsshmdo+//s/- /// .osmhydh::/+++/o+ohhysddyoo++os+-+++///yhhhmNs+o/:// /// -.++yss//////+/+/+soo++shyhsyy+::/:+y+yhdmdoo//:/:- /// ``.oss/:////++://+o//:://+oo-:o++/shhhmmh+o+++///-` /// ..:+++oo/+///ys:///://+::-sy+osh+osdyo+o/::/s:/y-` /// `odoyhds+/yysyydss+///+/:+oshdmNo+:+/oo/+++++:hy//` /// `://hyoyy/o/++shhy:+y:/:o/+omNmhsoohhsso+++:+o+sy:/++ /// -/---oddooss+oosy+ohNdo+++oyNhsdo/++shhhoo:s+oydmyo//o+ /// :y.`.``yyd++shoyydhhyymdhyyhyhhs+////+/+s/+:odmmyso.:ohy. /// .yy/o-..+h/+o/+//++ssoohhhssso+++:/:/yy+//sydmNddo+/./ohy+. /// .dmmhs+osdoos///o//++/+shdsoshoys+ssss++shmNNNyyds+:-s-//:+. /// -shmNmyhddsyss++/+ysddhyyydhdmyssNddyydyhNmdNmddso/::s:--`.-.` /// `+dmNhhdmddsooyyooossysshdhmoss+/+mNdyymydMdyMdyoo+/--/:/:`...-.` /// .:smNNMmsMNNmdhyyo/yymmdmdyo+ooooshysyysNNNmmmNyss/+o-`-:-/:```.`` ``` /// `.-+o/sdNNNmhdddNmmdsso/sdshyyyyhsdddyohymdmNdmmmmmyoo+/.... -os.`.``-.`` /// `/-:-/+.hymmmmdhmyNdMNmmhhs+sosoyhddyddmmho/ooymhddhdhyos-.oy..-:o+:..`` ```` ` /// ..::``--.-hoymmdNNNNNNMmhyNh+oo+soyNdmNmmmysooooymhy+so++yo..:+.--`..:.`.` `-- ``.` ` /// ```-.-.``..`:ddymmmNNdmNNNNmhN: -/oys/sdmmNdydsydmhhsmdso+/yo:/-..`.``.` ``:.`.````-. ` /// ````-:/.```:::syyydmddNhNNdsdMMs`./oddmd./odNdy+yssss++ooo/o+//-`:/:..:`-.```/-:.`.```..`` ` /// ```..-`` --.`.--o+sNhoyMmho+omhmo+Ns::dhdmmdy:.oNoyhhs+/o+o++s+hhoo+.`-:....``.-:-`..-````.-``.`` /// @title Dollars Nakamoto by Pascal Boyart /// @author jolan.eth /// @notice This contract will allow you to yield farm Dollars Nakamoto NFT. /// During epoch 0 you will be able to mint a Genesis NFT, /// Over time, epoch will increment allowing you to mint more editions. /// Minting generations editions is allowed only 1 time per epoch and per Genesis NFT. /// Generations editions do not allow you to mint other generations.
NatSpecSingleLine
exposeHeldIds
function exposeHeldIds(address owner) public view returns(uint[] memory) { uint tokenCount = balanceOf(owner); uint[] memory tokenIds = new uint[](tokenCount); uint i = 0; while (i < tokenCount) { tokenIds[i] = tokenOfOwnerByIndex(owner, i); i++; } return tokenIds; }
/// @notice Used to fetch all { tokenIds } from { owner }
NatSpecSingleLine
v0.8.10+commit.fc410830
MIT
ipfs://627efb7c58e0f1a820013031c32ab417b2b86eb0e16948f99bf7e29ad6e50407
{ "func_code_index": [ 16459, 16824 ] }
2,686
USDSat
USDSat.sol
0xbeda58401038c864c9fc9145f28e47b7b00a0e86
Solidity
USDSat
contract USDSat is USDSatMetadata, ERC721, ERC721Enumerable, Ownable, ReentrancyGuard { string SYMBOL = "USDSat"; string NAME = "Dollars Nakamoto"; string ContractCID; /// @notice Address used to sign NFT on mint address public ADDRESS_SIGN = 0x1Af70e564847bE46e4bA286c0b0066Da8372F902; /// @notice Ether shareholder address address public ADDRESS_PBOY = 0x709e17B3Ec505F80eAb064d0F2A71c743cE225B3; /// @notice Ether shareholder address address public ADDRESS_JOLAN = 0x51BdFa2Cbb25591AF58b202aCdcdB33325a325c2; /// @notice Equity per shareholder in % uint256 public SHARE_PBOY = 90; /// @notice Equity per shareholder in % uint256 public SHARE_JOLAN = 10; /// @notice Mapping used to represent allowed addresses to call { mintGenesis } mapping (address => bool) public _allowList; /// @notice Represent the current epoch uint256 public epoch = 0; /// @notice Represent the maximum epoch possible uint256 public epochMax = 10; /// @notice Represent the block length of an epoch uint256 public epochLen = 41016; /// @notice Index of the NFT /// @dev Start at 1 because var++ uint256 public tokenId = 1; /// @notice Index of the Genesis NFT /// @dev Start at 0 because ++var uint256 public genesisId = 0; /// @notice Index of the Generation NFT /// @dev Start at 0 because ++var uint256 public generationId = 0; /// @notice Maximum total supply uint256 public maxTokenSupply = 2100; /// @notice Maximum Genesis supply uint256 public maxGenesisSupply = 210; /// @notice Maximum supply per generation uint256 public maxGenerationSupply = 210; /// @notice Price of the Genesis NFT (Generations NFT are free) uint256 public genesisPrice = 0.5 ether; /// @notice Define the ending block uint256 public blockOmega; /// @notice Define the starting block uint256 public blockGenesis; /// @notice Define in which block the Meta must occur uint256 public blockMeta; /// @notice Used to inflate blockMeta each epoch incrementation uint256 public inflateRatio = 2; /// @notice Open Genesis mint when true bool public genesisMintAllowed = false; /// @notice Open Generation mint when true bool public generationMintAllowed = false; /// @notice Multi dimensionnal mapping to keep a track of the minting reentrancy over epoch mapping(uint256 => mapping(uint256 => bool)) public epochMintingRegistry; event Omega(uint256 _blockNumber); event Genesis(uint256 indexed _epoch, uint256 _blockNumber); event Meta(uint256 indexed _epoch, uint256 _blockNumber); event Withdraw(uint256 indexed _share, address _shareholder); event Shareholder(uint256 indexed _sharePercent, address _shareholder); event Securized(uint256 indexed _epoch, uint256 _epochLen, uint256 _blockMeta, uint256 _inflateRatio); event PermanentURI(string _value, uint256 indexed _id); event Minted(uint256 indexed _epoch, uint256 indexed _tokenId, address indexed _owner); event Signed(uint256 indexed _epoch, uint256 indexed _tokenId, uint256 indexed _blockNumber); constructor() ERC721(NAME, SYMBOL) {} // Withdraw functions ************************************************* /// @notice Allow Pboy to modify ADDRESS_PBOY /// This function is dedicated to the represented shareholder according to require(). function setPboy(address PBOY) public { require(msg.sender == ADDRESS_PBOY, "error msg.sender"); ADDRESS_PBOY = PBOY; emit Shareholder(SHARE_PBOY, ADDRESS_PBOY); } /// @notice Allow Jolan to modify ADDRESS_JOLAN /// This function is dedicated to the represented shareholder according to require(). function setJolan(address JOLAN) public { require(msg.sender == ADDRESS_JOLAN, "error msg.sender"); ADDRESS_JOLAN = JOLAN; emit Shareholder(SHARE_JOLAN, ADDRESS_JOLAN); } /// @notice Used to withdraw ETH balance of the contract, this function is dedicated /// to contract owner according to { onlyOwner } modifier. function withdrawEquity() public onlyOwner nonReentrant { uint256 balance = address(this).balance; address[2] memory shareholders = [ ADDRESS_PBOY, ADDRESS_JOLAN ]; uint256[2] memory _shares = [ SHARE_PBOY * balance / 100, SHARE_JOLAN * balance / 100 ]; uint i = 0; while (i < 2) { require(payable(shareholders[i]).send(_shares[i])); emit Withdraw(_shares[i], shareholders[i]); i++; } } // Epoch functions **************************************************** /// @notice Used to manage authorization and reentrancy of the genesis NFT mint /// @param _genesisId Used to increment { genesisId } and write { epochMintingRegistry } function genesisController(uint256 _genesisId) private { require(epoch == 0, "error epoch"); require(genesisId <= maxGenesisSupply, "error genesisId"); require(!epochMintingRegistry[epoch][_genesisId], "error epochMintingRegistry"); /// @dev Set { _genesisId } for { epoch } as true epochMintingRegistry[epoch][_genesisId] = true; /// @dev When { genesisId } reaches { maxGenesisSupply } the function /// will compute the data to increment the epoch according /// /// { blockGenesis } is set only once, at this time /// { blockMeta } is set to { blockGenesis } because epoch=0 /// Then it is computed into the function epochRegulator() /// /// Once the epoch is regulated, the new generation start /// straight away, { generationMintAllowed } is set to true if (genesisId == maxGenesisSupply) { blockGenesis = block.number; blockMeta = blockGenesis; emit Genesis(epoch, blockGenesis); epochRegulator(); } } /// @notice Used to manage authorization and reentrancy of the Generation NFT mint /// @param _genesisId Used to write { epochMintingRegistry } and verify minting allowance function generationController(uint256 _genesisId) private { require(blockGenesis > 0, "error blockGenesis"); require(blockMeta > 0, "error blockMeta"); require(blockOmega > 0, "error blockOmega"); /// @dev If { block.number } >= { blockMeta } the function /// will compute the data to increment the epoch according /// /// Once the epoch is regulated, the new generation start /// straight away, { generationMintAllowed } is set to true /// /// { generationId } is reset to 1 if (block.number >= blockMeta) { epochRegulator(); generationId = 1; } /// @dev Be sure the mint is open if condition are favorable if (block.number < blockMeta && generationId <= maxGenerationSupply) { generationMintAllowed = true; } require(maxTokenSupply >= tokenId, "error maxTokenSupply"); require(epoch > 0 && epoch < epochMax, "error epoch"); require(ownerOf(_genesisId) == msg.sender, "error ownerOf"); require(generationMintAllowed, "error generationMintAllowed"); require(generationId <= maxGenerationSupply, "error generationId"); require(epochMintingRegistry[0][_genesisId], "error epochMintingRegistry"); require(!epochMintingRegistry[epoch][_genesisId], "error epochMintingRegistry"); /// @dev Set { _genesisId } for { epoch } as true epochMintingRegistry[epoch][_genesisId] = true; /// @dev If { generationId } reaches { maxGenerationSupply } the modifier /// will set { generationMintAllowed } to false to stop the mint /// on this generation /// /// { generationId } is reset to 0 /// /// This condition will not block the function because as long as /// { block.number } >= { blockMeta } minting will reopen /// according and this condition will become obsolete until /// the condition is reached again if (generationId == maxGenerationSupply) { generationMintAllowed = false; generationId = 0; } } /// @notice Used to protect epoch block length from difficulty bomb of the /// Ethereum network. A difficulty bomb heavily increases the difficulty /// on the network, likely also causing an increase in block time. /// If the block time increases too much, the epoch generation could become /// exponentially higher than what is desired, ending with an undesired Ice-Age. /// To protect against this, the emergencySecure() function is allowed to /// manually reconfigure the epoch block length and the block Meta /// to match the network conditions if necessary. /// /// It can also be useful if the block time decreases for some reason with consensus change. /// /// This function is dedicated to contract owner according to { onlyOwner } modifier function emergencySecure(uint256 _epoch, uint256 _epochLen, uint256 _blockMeta, uint256 _inflateRatio) public onlyOwner { require(epoch > 0, "error epoch"); require(_epoch > 0, "error _epoch"); require(maxTokenSupply >= tokenId, "error maxTokenSupply"); epoch = _epoch; epochLen = _epochLen; blockMeta = _blockMeta; inflateRatio = _inflateRatio; computeBlockOmega(); emit Securized(epoch, epochLen, blockMeta, inflateRatio); } /// @notice Used to compute blockOmega() function, { blockOmega } represents /// the block when it won't ever be possible to mint another Dollars Nakamoto NFT. /// It is possible to be computed because of the deterministic state of the current protocol /// The following algorithm simulate the 10 epochs of the protocol block computation to result blockOmega function computeBlockOmega() private { uint256 i = 0; uint256 _blockMeta = 0; uint256 _epochLen = epochLen; while (i < epochMax) { if (i > 0) _epochLen *= inflateRatio; if (i == 9) { blockOmega = blockGenesis + _blockMeta; emit Omega(blockOmega); break; } _blockMeta += _epochLen; i++; } } /// @notice Used to regulate the epoch incrementation and block computation, known as Metas /// @dev When epoch=0, the { blockOmega } will be computed /// When epoch!=0 the block length { epochLen } will be multiplied /// by { inflateRatio } thus making the block length required for each /// epoch longer according /// /// { blockMeta } += { epochLen } result the exact block of the next Meta /// Allow generation mint after incrementing the epoch function epochRegulator() private { if (epoch == 0) computeBlockOmega(); if (epoch > 0) epochLen *= inflateRatio; blockMeta += epochLen; emit Meta(epoch, blockMeta); epoch++; if (block.number >= blockMeta && epoch < epochMax) { epochRegulator(); } generationMintAllowed = true; } // Mint functions ***************************************************** /// @notice Used to add/remove address from { _allowList } function setBatchGenesisAllowance(address[] memory batch) public onlyOwner { uint len = batch.length; require(len > 0, "error len"); uint i = 0; while (i < len) { _allowList[batch[i]] = _allowList[batch[i]] ? false : true; i++; } } /// @notice Used to transfer { _allowList } slot to another address function transferListSlot(address to) public { require(epoch == 0, "error epoch"); require(_allowList[msg.sender], "error msg.sender"); require(!_allowList[to], "error to"); _allowList[msg.sender] = false; _allowList[to] = true; } /// @notice Used to open the mint of Genesis NFT function setGenesisMint() public onlyOwner { genesisMintAllowed = true; } /// @notice Used to gift Genesis NFT, this function is dedicated /// to contract owner according to { onlyOwner } modifier function giftGenesis(address to) public onlyOwner { uint256 _genesisId = ++genesisId; setMetadata(tokenId, _genesisId, epoch); genesisController(_genesisId); mintUSDSat(to, tokenId++); } /// @notice Used to mint Genesis NFT, this function is payable /// the price of this function is equal to { genesisPrice }, /// require to be present on { _allowList } to call function mintGenesis() public payable { uint256 _genesisId = ++genesisId; setMetadata(tokenId, _genesisId, epoch); genesisController(_genesisId); require(genesisMintAllowed, "error genesisMintAllowed"); require(_allowList[msg.sender], "error allowList"); require(genesisPrice == msg.value, "error genesisPrice"); _allowList[msg.sender] = false; mintUSDSat(msg.sender, tokenId++); } /// @notice Used to gift Generation NFT, you need a Genesis NFT to call this function function giftGenerations(uint256 _genesisId, address to) public { ++generationId; generationController(_genesisId); setMetadata(tokenId, _genesisId, epoch); mintUSDSat(to, tokenId++); } /// @notice Used to mint Generation NFT, you need a Genesis NFT to call this function function mintGenerations(uint256 _genesisId) public { ++generationId; generationController(_genesisId); setMetadata(tokenId, _genesisId, epoch); mintUSDSat(msg.sender, tokenId++); } /// @notice Token is minted on { ADDRESS_SIGN } and instantly transferred to { msg.sender } as { to }, /// this is to ensure the token creation is signed with { ADDRESS_SIGN } /// This function is private and can be only called by the contract function mintUSDSat(address to, uint256 _tokenId) private { emit PermanentURI(_compileMetadata(_tokenId), _tokenId); _safeMint(ADDRESS_SIGN, _tokenId); emit Signed(epoch, _tokenId, block.number); _safeTransfer(ADDRESS_SIGN, to, _tokenId, ""); emit Minted(epoch, _tokenId, to); } // Contract URI functions ********************************************* /// @notice Used to set the { ContractCID } metadata from ipfs, /// this function is dedicated to contract owner according /// to { onlyOwner } modifier function setContractCID(string memory CID) public onlyOwner { ContractCID = string(abi.encodePacked("ipfs://", CID)); } /// @notice Used to render { ContractCID } as { contractURI } according to /// Opensea contract metadata standard function contractURI() public view virtual returns (string memory) { return ContractCID; } // Utilitaries functions ********************************************** /// @notice Used to fetch all entry for { epoch } into { epochMintingRegistry } function getMapRegisteryForEpoch(uint256 _epoch) public view returns (bool[210] memory result) { uint i = 1; while (i <= maxGenesisSupply) { result[i] = epochMintingRegistry[_epoch][i]; i++; } } /// @notice Used to fetch all { tokenIds } from { owner } function exposeHeldIds(address owner) public view returns(uint[] memory) { uint tokenCount = balanceOf(owner); uint[] memory tokenIds = new uint[](tokenCount); uint i = 0; while (i < tokenCount) { tokenIds[i] = tokenOfOwnerByIndex(owner, i); i++; } return tokenIds; } // ERC721 Spec functions ********************************************** /// @notice Used to render metadata as { tokenURI } according to ERC721 standard function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token"); return _compileMetadata(_tokenId); } /// @dev ERC721 required override function _beforeTokenTransfer(address from, address to, uint256 _tokenId) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, _tokenId); } /// @dev ERC721 required override function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } }
/// ``.. /// `.` `````.``.-````-`` `.` /// ` ``````.`..///.-..----. --..--`.-....`..-.```` ``` /// `` `.`..--...`:::/::-``..``..:-.://///---..-....----- /// ``-:::/+++:::/-.-///://oso+::++/--:--../+:/:..:-....-://:/:-`` /// `-+/++/+o+://+::-:soo+oosss+s+//o:/:--`--:://://:ooso/-.--.-:-.` /// ``.+ooso++o+:+:+sosyhsyshhddyo+:/sds/yoo++/+:--/--.--:..--..``.```` /// ``:++/---:+/::::///oyhhyy+++:hddhhNNho///ohosyhs+/-:/+/---.....-.. ` /// ``-:-...-/+///++///+o+:-:o+o/oydmNmNNdddhsoyo/oyyyho///:-.--.-.``. `` /// ```--`..-:+/:--:::-.-///++++ydsdNNMNdmMNMmNysddyoooosso+//-.-`....````` ..` /// .```:-:::/-.-+o++/+:/+/o/hNNNNhmdNMMNNMMdyydNNmdyys+++oo++-`--.:.-.`````... /// ..--.`-..`.-`-hh++-/:+shho+hsysyyhhhmNNmmNMMmNNNdmmy+:+sh/o+y/+-`+./::.```` ` /// -/` ``.-``.//o++y+//ssyh+hhdmmdmmddmhdmNdmdsh+oNNMmmddoodh/s:yss.--+.//+`.` `. /// `.`-.` -`..+h+yo++ooyyyyyoyhy+shmNNmmdhhdhyyhymdyyhdmshoohs+y:oy+/+o/:/++.`- .` /// ``.`.``-.-++syyyhhhhhhhhmhysosyyoooosssdhhhdmmdhdmdsy+ss+/+ho/hody-s+-:+::--`` ` /// .`` ``-//s+:ohmdmddNmNmhhshhddNNNhyyhhhdNNhmNNmNNmmyso+yhhso++hhdy.:/ ::-:--``.` /// .```.-`.//shdmNNmddyysohmMmdmNNmmNshdmNhso+-/ohNoyhmmsysosd++hy/osss/.:-o/-.:/--. /// ``..:++-+hhy/syhhhdhdNNddNMmNsNMNyyso+//:-.`-/..+hmdsmdy+ossos:+o/h/+..//-s.`.:::o/ /// `.-.oy//hm+o:-..-+/shdNNNNNNhsNdo/oyoyyhoh+/so//+/mNmyhh+/s+dy/+s::+:`-`-:s--:-.::+`-` /// .`:h-`+y+./oyhhdddhyohMMNmmNmdhoo/oyyhddhmNNNmhsoodmdhs+///++:+-:.:/--/-/o/--+//...:` /// ``+o``yoodNNNNNMhdyyo+ymhsymyshhyys+sssssNmdmmdmy+oso/++:://+/-`::-:--:/::+.//o:-.--: /// `:-:-`oNhyhdNNNmyys+/:://oohy++/+hmmmmNNNNhohydmmyhy++////ooy./----.-:---/::-o+:...-/ /// ``-.-` yms+mmNmMMmNho/:o++++hhh++:mMmNmmmNMNdhdms+ysyy//:-+o:.-.`.``.-:/::-:-+/y/.- -` /// ..:` hh+oNNmMNNNmss/:-+oyhs+o+.-yhdNmdhmmydmms+o///:///+/+--/`-``.o::/:-o//-/y::/.- /// `.-``hh+yNdmdohdy:++/./myhds/./shNhhyy++o:oyos/s+:s//+////.:- ...`--`..`-.:--o:+::` /// `-/+yyho.`.-+oso///+/Nmddh//y+:s:.../soy+:o+.:sdyo++++o:.-. `.:.:-```:.`:``/o:`:` /// ./.`..sMN+:::yh+s+ysyhhddh+ymdsd/:/+o+ysydhohoh/o+/so++o+/o.--..`-:::``:-`+-`:+--.` /// ``:``..-NNy++/yyysohmo+NNmy/+:+hMNmy+yydmNMNddhs:yyydmmmso:o///..-.-+-:o:/.o/-/+-`` /// ``+.`..-mMhsyo+++oo+yoshyyo+/`+hNmhyy+sdmdssssho-MMMNMNh//+/oo+/+:-....`.s+/`..-` /// .+ `oNMmdhhsohhmmydmNms/yy.oNmmdy+++/+ss+odNm+mNmdddo-s+:+/++/-:--//`/o+s/.-`` /// `/` dNNNhooddNmNymMNNdsoo+y+shhhmyymhss+hddms+hdhmdo+/+-/oo+/.///+sh:-/-s/` /// `::`hdNmh+ooNmdohNNMMmsooohh+oysydhdooo/syysodmNmys+/o+//+y/:.+/hmso.-//s- /// -+ohdmmhyhdysysyyhmysoyddhhoo+shdhdyddmddmNmmhssds/::/oo/..:/+Nmo+`-:so /// .oyhdmmNNdm+s:/:os/+/ssyyds+/ssdNNyhdmmhdmmdymymy///o:/``/+-dmdoo++:o` /// `ysyMNhhmoo+h-:/+o/+:.:/:/+doo+dNdhddmhmmmy++yhds/+-+::..o/+Nmosyhs+- /// s+dNNyNhsdhNhsy:+:oo/soo+dNmmooyosohMhsymmhyy+++:+:/+/-/o+yNh+hMNs. /// +yhNNMd+dmydmdy/+/sshydmhdNNmNooyhhhhshohmNh+:+oso++ssy+/odyhhNmh` /// `yyhdms+dMh+oyshhyhysdmNd+ohyNN+++mNddmNy+yo//+o/hddddymmyhosNmms` /// oydos:oMmhoyyhysssysdmMmNmhNmNNh/+mmNmddh+/+o+::+s+hmhmdyNNNNy: /// `/dNm/+Ndhy+oshdhhdyo::ohmdyhhNysy:smshmdo/o:so//:s++ymhyohdy-` /// `sNNN/hNm/:do+o:+/++++s:/+shyymmddy/ydmmh/s/+oss//oysy++o+o+` /// oNNMNmm:/hyy/:/o/+hhsosysoo-ohhhss/hmmhd/dyh++/soyooy++o+:. /// :/dMNh/smhh+//+s+--:+/so+ohhy/:sydmmmmm+/mdddhy++/ohs//-o/` /// `/odmhyhsyh++/-:+:::/:/o/:ooddy/+yodNNh+ydhmmmy++/hhyo+://` /// `:os/+o//oshss/yhs+//:+/-/:soooo/+sso+dddydss+:+sy///+:++ /// ./o/s//hhNho+shyyyoyyso+/ys+/+-:y+:/soooyyh++sNyo++/:/+ /// -/:osmmhyo:++++/+/osshdssooo/:/h//://++oyhsshmdo+//s/- /// .osmhydh::/+++/o+ohhysddyoo++os+-+++///yhhhmNs+o/:// /// -.++yss//////+/+/+soo++shyhsyy+::/:+y+yhdmdoo//:/:- /// ``.oss/:////++://+o//:://+oo-:o++/shhhmmh+o+++///-` /// ..:+++oo/+///ys:///://+::-sy+osh+osdyo+o/::/s:/y-` /// `odoyhds+/yysyydss+///+/:+oshdmNo+:+/oo/+++++:hy//` /// `://hyoyy/o/++shhy:+y:/:o/+omNmhsoohhsso+++:+o+sy:/++ /// -/---oddooss+oosy+ohNdo+++oyNhsdo/++shhhoo:s+oydmyo//o+ /// :y.`.``yyd++shoyydhhyymdhyyhyhhs+////+/+s/+:odmmyso.:ohy. /// .yy/o-..+h/+o/+//++ssoohhhssso+++:/:/yy+//sydmNddo+/./ohy+. /// .dmmhs+osdoos///o//++/+shdsoshoys+ssss++shmNNNyyds+:-s-//:+. /// -shmNmyhddsyss++/+ysddhyyydhdmyssNddyydyhNmdNmddso/::s:--`.-.` /// `+dmNhhdmddsooyyooossysshdhmoss+/+mNdyymydMdyMdyoo+/--/:/:`...-.` /// .:smNNMmsMNNmdhyyo/yymmdmdyo+ooooshysyysNNNmmmNyss/+o-`-:-/:```.`` ``` /// `.-+o/sdNNNmhdddNmmdsso/sdshyyyyhsdddyohymdmNdmmmmmyoo+/.... -os.`.``-.`` /// `/-:-/+.hymmmmdhmyNdMNmmhhs+sosoyhddyddmmho/ooymhddhdhyos-.oy..-:o+:..`` ```` ` /// ..::``--.-hoymmdNNNNNNMmhyNh+oo+soyNdmNmmmysooooymhy+so++yo..:+.--`..:.`.` `-- ``.` ` /// ```-.-.``..`:ddymmmNNdmNNNNmhN: -/oys/sdmmNdydsydmhhsmdso+/yo:/-..`.``.` ``:.`.````-. ` /// ````-:/.```:::syyydmddNhNNdsdMMs`./oddmd./odNdy+yssss++ooo/o+//-`:/:..:`-.```/-:.`.```..`` ` /// ```..-`` --.`.--o+sNhoyMmho+omhmo+Ns::dhdmmdy:.oNoyhhs+/o+o++s+hhoo+.`-:....``.-:-`..-````.-``.`` /// @title Dollars Nakamoto by Pascal Boyart /// @author jolan.eth /// @notice This contract will allow you to yield farm Dollars Nakamoto NFT. /// During epoch 0 you will be able to mint a Genesis NFT, /// Over time, epoch will increment allowing you to mint more editions. /// Minting generations editions is allowed only 1 time per epoch and per Genesis NFT. /// Generations editions do not allow you to mint other generations.
NatSpecSingleLine
tokenURI
function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token"); return _compileMetadata(_tokenId); }
/// @notice Used to render metadata as { tokenURI } according to ERC721 standard
NatSpecSingleLine
v0.8.10+commit.fc410830
MIT
ipfs://627efb7c58e0f1a820013031c32ab417b2b86eb0e16948f99bf7e29ad6e50407
{ "func_code_index": [ 16992, 17231 ] }
2,687
USDSat
USDSat.sol
0xbeda58401038c864c9fc9145f28e47b7b00a0e86
Solidity
USDSat
contract USDSat is USDSatMetadata, ERC721, ERC721Enumerable, Ownable, ReentrancyGuard { string SYMBOL = "USDSat"; string NAME = "Dollars Nakamoto"; string ContractCID; /// @notice Address used to sign NFT on mint address public ADDRESS_SIGN = 0x1Af70e564847bE46e4bA286c0b0066Da8372F902; /// @notice Ether shareholder address address public ADDRESS_PBOY = 0x709e17B3Ec505F80eAb064d0F2A71c743cE225B3; /// @notice Ether shareholder address address public ADDRESS_JOLAN = 0x51BdFa2Cbb25591AF58b202aCdcdB33325a325c2; /// @notice Equity per shareholder in % uint256 public SHARE_PBOY = 90; /// @notice Equity per shareholder in % uint256 public SHARE_JOLAN = 10; /// @notice Mapping used to represent allowed addresses to call { mintGenesis } mapping (address => bool) public _allowList; /// @notice Represent the current epoch uint256 public epoch = 0; /// @notice Represent the maximum epoch possible uint256 public epochMax = 10; /// @notice Represent the block length of an epoch uint256 public epochLen = 41016; /// @notice Index of the NFT /// @dev Start at 1 because var++ uint256 public tokenId = 1; /// @notice Index of the Genesis NFT /// @dev Start at 0 because ++var uint256 public genesisId = 0; /// @notice Index of the Generation NFT /// @dev Start at 0 because ++var uint256 public generationId = 0; /// @notice Maximum total supply uint256 public maxTokenSupply = 2100; /// @notice Maximum Genesis supply uint256 public maxGenesisSupply = 210; /// @notice Maximum supply per generation uint256 public maxGenerationSupply = 210; /// @notice Price of the Genesis NFT (Generations NFT are free) uint256 public genesisPrice = 0.5 ether; /// @notice Define the ending block uint256 public blockOmega; /// @notice Define the starting block uint256 public blockGenesis; /// @notice Define in which block the Meta must occur uint256 public blockMeta; /// @notice Used to inflate blockMeta each epoch incrementation uint256 public inflateRatio = 2; /// @notice Open Genesis mint when true bool public genesisMintAllowed = false; /// @notice Open Generation mint when true bool public generationMintAllowed = false; /// @notice Multi dimensionnal mapping to keep a track of the minting reentrancy over epoch mapping(uint256 => mapping(uint256 => bool)) public epochMintingRegistry; event Omega(uint256 _blockNumber); event Genesis(uint256 indexed _epoch, uint256 _blockNumber); event Meta(uint256 indexed _epoch, uint256 _blockNumber); event Withdraw(uint256 indexed _share, address _shareholder); event Shareholder(uint256 indexed _sharePercent, address _shareholder); event Securized(uint256 indexed _epoch, uint256 _epochLen, uint256 _blockMeta, uint256 _inflateRatio); event PermanentURI(string _value, uint256 indexed _id); event Minted(uint256 indexed _epoch, uint256 indexed _tokenId, address indexed _owner); event Signed(uint256 indexed _epoch, uint256 indexed _tokenId, uint256 indexed _blockNumber); constructor() ERC721(NAME, SYMBOL) {} // Withdraw functions ************************************************* /// @notice Allow Pboy to modify ADDRESS_PBOY /// This function is dedicated to the represented shareholder according to require(). function setPboy(address PBOY) public { require(msg.sender == ADDRESS_PBOY, "error msg.sender"); ADDRESS_PBOY = PBOY; emit Shareholder(SHARE_PBOY, ADDRESS_PBOY); } /// @notice Allow Jolan to modify ADDRESS_JOLAN /// This function is dedicated to the represented shareholder according to require(). function setJolan(address JOLAN) public { require(msg.sender == ADDRESS_JOLAN, "error msg.sender"); ADDRESS_JOLAN = JOLAN; emit Shareholder(SHARE_JOLAN, ADDRESS_JOLAN); } /// @notice Used to withdraw ETH balance of the contract, this function is dedicated /// to contract owner according to { onlyOwner } modifier. function withdrawEquity() public onlyOwner nonReentrant { uint256 balance = address(this).balance; address[2] memory shareholders = [ ADDRESS_PBOY, ADDRESS_JOLAN ]; uint256[2] memory _shares = [ SHARE_PBOY * balance / 100, SHARE_JOLAN * balance / 100 ]; uint i = 0; while (i < 2) { require(payable(shareholders[i]).send(_shares[i])); emit Withdraw(_shares[i], shareholders[i]); i++; } } // Epoch functions **************************************************** /// @notice Used to manage authorization and reentrancy of the genesis NFT mint /// @param _genesisId Used to increment { genesisId } and write { epochMintingRegistry } function genesisController(uint256 _genesisId) private { require(epoch == 0, "error epoch"); require(genesisId <= maxGenesisSupply, "error genesisId"); require(!epochMintingRegistry[epoch][_genesisId], "error epochMintingRegistry"); /// @dev Set { _genesisId } for { epoch } as true epochMintingRegistry[epoch][_genesisId] = true; /// @dev When { genesisId } reaches { maxGenesisSupply } the function /// will compute the data to increment the epoch according /// /// { blockGenesis } is set only once, at this time /// { blockMeta } is set to { blockGenesis } because epoch=0 /// Then it is computed into the function epochRegulator() /// /// Once the epoch is regulated, the new generation start /// straight away, { generationMintAllowed } is set to true if (genesisId == maxGenesisSupply) { blockGenesis = block.number; blockMeta = blockGenesis; emit Genesis(epoch, blockGenesis); epochRegulator(); } } /// @notice Used to manage authorization and reentrancy of the Generation NFT mint /// @param _genesisId Used to write { epochMintingRegistry } and verify minting allowance function generationController(uint256 _genesisId) private { require(blockGenesis > 0, "error blockGenesis"); require(blockMeta > 0, "error blockMeta"); require(blockOmega > 0, "error blockOmega"); /// @dev If { block.number } >= { blockMeta } the function /// will compute the data to increment the epoch according /// /// Once the epoch is regulated, the new generation start /// straight away, { generationMintAllowed } is set to true /// /// { generationId } is reset to 1 if (block.number >= blockMeta) { epochRegulator(); generationId = 1; } /// @dev Be sure the mint is open if condition are favorable if (block.number < blockMeta && generationId <= maxGenerationSupply) { generationMintAllowed = true; } require(maxTokenSupply >= tokenId, "error maxTokenSupply"); require(epoch > 0 && epoch < epochMax, "error epoch"); require(ownerOf(_genesisId) == msg.sender, "error ownerOf"); require(generationMintAllowed, "error generationMintAllowed"); require(generationId <= maxGenerationSupply, "error generationId"); require(epochMintingRegistry[0][_genesisId], "error epochMintingRegistry"); require(!epochMintingRegistry[epoch][_genesisId], "error epochMintingRegistry"); /// @dev Set { _genesisId } for { epoch } as true epochMintingRegistry[epoch][_genesisId] = true; /// @dev If { generationId } reaches { maxGenerationSupply } the modifier /// will set { generationMintAllowed } to false to stop the mint /// on this generation /// /// { generationId } is reset to 0 /// /// This condition will not block the function because as long as /// { block.number } >= { blockMeta } minting will reopen /// according and this condition will become obsolete until /// the condition is reached again if (generationId == maxGenerationSupply) { generationMintAllowed = false; generationId = 0; } } /// @notice Used to protect epoch block length from difficulty bomb of the /// Ethereum network. A difficulty bomb heavily increases the difficulty /// on the network, likely also causing an increase in block time. /// If the block time increases too much, the epoch generation could become /// exponentially higher than what is desired, ending with an undesired Ice-Age. /// To protect against this, the emergencySecure() function is allowed to /// manually reconfigure the epoch block length and the block Meta /// to match the network conditions if necessary. /// /// It can also be useful if the block time decreases for some reason with consensus change. /// /// This function is dedicated to contract owner according to { onlyOwner } modifier function emergencySecure(uint256 _epoch, uint256 _epochLen, uint256 _blockMeta, uint256 _inflateRatio) public onlyOwner { require(epoch > 0, "error epoch"); require(_epoch > 0, "error _epoch"); require(maxTokenSupply >= tokenId, "error maxTokenSupply"); epoch = _epoch; epochLen = _epochLen; blockMeta = _blockMeta; inflateRatio = _inflateRatio; computeBlockOmega(); emit Securized(epoch, epochLen, blockMeta, inflateRatio); } /// @notice Used to compute blockOmega() function, { blockOmega } represents /// the block when it won't ever be possible to mint another Dollars Nakamoto NFT. /// It is possible to be computed because of the deterministic state of the current protocol /// The following algorithm simulate the 10 epochs of the protocol block computation to result blockOmega function computeBlockOmega() private { uint256 i = 0; uint256 _blockMeta = 0; uint256 _epochLen = epochLen; while (i < epochMax) { if (i > 0) _epochLen *= inflateRatio; if (i == 9) { blockOmega = blockGenesis + _blockMeta; emit Omega(blockOmega); break; } _blockMeta += _epochLen; i++; } } /// @notice Used to regulate the epoch incrementation and block computation, known as Metas /// @dev When epoch=0, the { blockOmega } will be computed /// When epoch!=0 the block length { epochLen } will be multiplied /// by { inflateRatio } thus making the block length required for each /// epoch longer according /// /// { blockMeta } += { epochLen } result the exact block of the next Meta /// Allow generation mint after incrementing the epoch function epochRegulator() private { if (epoch == 0) computeBlockOmega(); if (epoch > 0) epochLen *= inflateRatio; blockMeta += epochLen; emit Meta(epoch, blockMeta); epoch++; if (block.number >= blockMeta && epoch < epochMax) { epochRegulator(); } generationMintAllowed = true; } // Mint functions ***************************************************** /// @notice Used to add/remove address from { _allowList } function setBatchGenesisAllowance(address[] memory batch) public onlyOwner { uint len = batch.length; require(len > 0, "error len"); uint i = 0; while (i < len) { _allowList[batch[i]] = _allowList[batch[i]] ? false : true; i++; } } /// @notice Used to transfer { _allowList } slot to another address function transferListSlot(address to) public { require(epoch == 0, "error epoch"); require(_allowList[msg.sender], "error msg.sender"); require(!_allowList[to], "error to"); _allowList[msg.sender] = false; _allowList[to] = true; } /// @notice Used to open the mint of Genesis NFT function setGenesisMint() public onlyOwner { genesisMintAllowed = true; } /// @notice Used to gift Genesis NFT, this function is dedicated /// to contract owner according to { onlyOwner } modifier function giftGenesis(address to) public onlyOwner { uint256 _genesisId = ++genesisId; setMetadata(tokenId, _genesisId, epoch); genesisController(_genesisId); mintUSDSat(to, tokenId++); } /// @notice Used to mint Genesis NFT, this function is payable /// the price of this function is equal to { genesisPrice }, /// require to be present on { _allowList } to call function mintGenesis() public payable { uint256 _genesisId = ++genesisId; setMetadata(tokenId, _genesisId, epoch); genesisController(_genesisId); require(genesisMintAllowed, "error genesisMintAllowed"); require(_allowList[msg.sender], "error allowList"); require(genesisPrice == msg.value, "error genesisPrice"); _allowList[msg.sender] = false; mintUSDSat(msg.sender, tokenId++); } /// @notice Used to gift Generation NFT, you need a Genesis NFT to call this function function giftGenerations(uint256 _genesisId, address to) public { ++generationId; generationController(_genesisId); setMetadata(tokenId, _genesisId, epoch); mintUSDSat(to, tokenId++); } /// @notice Used to mint Generation NFT, you need a Genesis NFT to call this function function mintGenerations(uint256 _genesisId) public { ++generationId; generationController(_genesisId); setMetadata(tokenId, _genesisId, epoch); mintUSDSat(msg.sender, tokenId++); } /// @notice Token is minted on { ADDRESS_SIGN } and instantly transferred to { msg.sender } as { to }, /// this is to ensure the token creation is signed with { ADDRESS_SIGN } /// This function is private and can be only called by the contract function mintUSDSat(address to, uint256 _tokenId) private { emit PermanentURI(_compileMetadata(_tokenId), _tokenId); _safeMint(ADDRESS_SIGN, _tokenId); emit Signed(epoch, _tokenId, block.number); _safeTransfer(ADDRESS_SIGN, to, _tokenId, ""); emit Minted(epoch, _tokenId, to); } // Contract URI functions ********************************************* /// @notice Used to set the { ContractCID } metadata from ipfs, /// this function is dedicated to contract owner according /// to { onlyOwner } modifier function setContractCID(string memory CID) public onlyOwner { ContractCID = string(abi.encodePacked("ipfs://", CID)); } /// @notice Used to render { ContractCID } as { contractURI } according to /// Opensea contract metadata standard function contractURI() public view virtual returns (string memory) { return ContractCID; } // Utilitaries functions ********************************************** /// @notice Used to fetch all entry for { epoch } into { epochMintingRegistry } function getMapRegisteryForEpoch(uint256 _epoch) public view returns (bool[210] memory result) { uint i = 1; while (i <= maxGenesisSupply) { result[i] = epochMintingRegistry[_epoch][i]; i++; } } /// @notice Used to fetch all { tokenIds } from { owner } function exposeHeldIds(address owner) public view returns(uint[] memory) { uint tokenCount = balanceOf(owner); uint[] memory tokenIds = new uint[](tokenCount); uint i = 0; while (i < tokenCount) { tokenIds[i] = tokenOfOwnerByIndex(owner, i); i++; } return tokenIds; } // ERC721 Spec functions ********************************************** /// @notice Used to render metadata as { tokenURI } according to ERC721 standard function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token"); return _compileMetadata(_tokenId); } /// @dev ERC721 required override function _beforeTokenTransfer(address from, address to, uint256 _tokenId) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, _tokenId); } /// @dev ERC721 required override function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } }
/// ``.. /// `.` `````.``.-````-`` `.` /// ` ``````.`..///.-..----. --..--`.-....`..-.```` ``` /// `` `.`..--...`:::/::-``..``..:-.://///---..-....----- /// ``-:::/+++:::/-.-///://oso+::++/--:--../+:/:..:-....-://:/:-`` /// `-+/++/+o+://+::-:soo+oosss+s+//o:/:--`--:://://:ooso/-.--.-:-.` /// ``.+ooso++o+:+:+sosyhsyshhddyo+:/sds/yoo++/+:--/--.--:..--..``.```` /// ``:++/---:+/::::///oyhhyy+++:hddhhNNho///ohosyhs+/-:/+/---.....-.. ` /// ``-:-...-/+///++///+o+:-:o+o/oydmNmNNdddhsoyo/oyyyho///:-.--.-.``. `` /// ```--`..-:+/:--:::-.-///++++ydsdNNMNdmMNMmNysddyoooosso+//-.-`....````` ..` /// .```:-:::/-.-+o++/+:/+/o/hNNNNhmdNMMNNMMdyydNNmdyys+++oo++-`--.:.-.`````... /// ..--.`-..`.-`-hh++-/:+shho+hsysyyhhhmNNmmNMMmNNNdmmy+:+sh/o+y/+-`+./::.```` ` /// -/` ``.-``.//o++y+//ssyh+hhdmmdmmddmhdmNdmdsh+oNNMmmddoodh/s:yss.--+.//+`.` `. /// `.`-.` -`..+h+yo++ooyyyyyoyhy+shmNNmmdhhdhyyhymdyyhdmshoohs+y:oy+/+o/:/++.`- .` /// ``.`.``-.-++syyyhhhhhhhhmhysosyyoooosssdhhhdmmdhdmdsy+ss+/+ho/hody-s+-:+::--`` ` /// .`` ``-//s+:ohmdmddNmNmhhshhddNNNhyyhhhdNNhmNNmNNmmyso+yhhso++hhdy.:/ ::-:--``.` /// .```.-`.//shdmNNmddyysohmMmdmNNmmNshdmNhso+-/ohNoyhmmsysosd++hy/osss/.:-o/-.:/--. /// ``..:++-+hhy/syhhhdhdNNddNMmNsNMNyyso+//:-.`-/..+hmdsmdy+ossos:+o/h/+..//-s.`.:::o/ /// `.-.oy//hm+o:-..-+/shdNNNNNNhsNdo/oyoyyhoh+/so//+/mNmyhh+/s+dy/+s::+:`-`-:s--:-.::+`-` /// .`:h-`+y+./oyhhdddhyohMMNmmNmdhoo/oyyhddhmNNNmhsoodmdhs+///++:+-:.:/--/-/o/--+//...:` /// ``+o``yoodNNNNNMhdyyo+ymhsymyshhyys+sssssNmdmmdmy+oso/++:://+/-`::-:--:/::+.//o:-.--: /// `:-:-`oNhyhdNNNmyys+/:://oohy++/+hmmmmNNNNhohydmmyhy++////ooy./----.-:---/::-o+:...-/ /// ``-.-` yms+mmNmMMmNho/:o++++hhh++:mMmNmmmNMNdhdms+ysyy//:-+o:.-.`.``.-:/::-:-+/y/.- -` /// ..:` hh+oNNmMNNNmss/:-+oyhs+o+.-yhdNmdhmmydmms+o///:///+/+--/`-``.o::/:-o//-/y::/.- /// `.-``hh+yNdmdohdy:++/./myhds/./shNhhyy++o:oyos/s+:s//+////.:- ...`--`..`-.:--o:+::` /// `-/+yyho.`.-+oso///+/Nmddh//y+:s:.../soy+:o+.:sdyo++++o:.-. `.:.:-```:.`:``/o:`:` /// ./.`..sMN+:::yh+s+ysyhhddh+ymdsd/:/+o+ysydhohoh/o+/so++o+/o.--..`-:::``:-`+-`:+--.` /// ``:``..-NNy++/yyysohmo+NNmy/+:+hMNmy+yydmNMNddhs:yyydmmmso:o///..-.-+-:o:/.o/-/+-`` /// ``+.`..-mMhsyo+++oo+yoshyyo+/`+hNmhyy+sdmdssssho-MMMNMNh//+/oo+/+:-....`.s+/`..-` /// .+ `oNMmdhhsohhmmydmNms/yy.oNmmdy+++/+ss+odNm+mNmdddo-s+:+/++/-:--//`/o+s/.-`` /// `/` dNNNhooddNmNymMNNdsoo+y+shhhmyymhss+hddms+hdhmdo+/+-/oo+/.///+sh:-/-s/` /// `::`hdNmh+ooNmdohNNMMmsooohh+oysydhdooo/syysodmNmys+/o+//+y/:.+/hmso.-//s- /// -+ohdmmhyhdysysyyhmysoyddhhoo+shdhdyddmddmNmmhssds/::/oo/..:/+Nmo+`-:so /// .oyhdmmNNdm+s:/:os/+/ssyyds+/ssdNNyhdmmhdmmdymymy///o:/``/+-dmdoo++:o` /// `ysyMNhhmoo+h-:/+o/+:.:/:/+doo+dNdhddmhmmmy++yhds/+-+::..o/+Nmosyhs+- /// s+dNNyNhsdhNhsy:+:oo/soo+dNmmooyosohMhsymmhyy+++:+:/+/-/o+yNh+hMNs. /// +yhNNMd+dmydmdy/+/sshydmhdNNmNooyhhhhshohmNh+:+oso++ssy+/odyhhNmh` /// `yyhdms+dMh+oyshhyhysdmNd+ohyNN+++mNddmNy+yo//+o/hddddymmyhosNmms` /// oydos:oMmhoyyhysssysdmMmNmhNmNNh/+mmNmddh+/+o+::+s+hmhmdyNNNNy: /// `/dNm/+Ndhy+oshdhhdyo::ohmdyhhNysy:smshmdo/o:so//:s++ymhyohdy-` /// `sNNN/hNm/:do+o:+/++++s:/+shyymmddy/ydmmh/s/+oss//oysy++o+o+` /// oNNMNmm:/hyy/:/o/+hhsosysoo-ohhhss/hmmhd/dyh++/soyooy++o+:. /// :/dMNh/smhh+//+s+--:+/so+ohhy/:sydmmmmm+/mdddhy++/ohs//-o/` /// `/odmhyhsyh++/-:+:::/:/o/:ooddy/+yodNNh+ydhmmmy++/hhyo+://` /// `:os/+o//oshss/yhs+//:+/-/:soooo/+sso+dddydss+:+sy///+:++ /// ./o/s//hhNho+shyyyoyyso+/ys+/+-:y+:/soooyyh++sNyo++/:/+ /// -/:osmmhyo:++++/+/osshdssooo/:/h//://++oyhsshmdo+//s/- /// .osmhydh::/+++/o+ohhysddyoo++os+-+++///yhhhmNs+o/:// /// -.++yss//////+/+/+soo++shyhsyy+::/:+y+yhdmdoo//:/:- /// ``.oss/:////++://+o//:://+oo-:o++/shhhmmh+o+++///-` /// ..:+++oo/+///ys:///://+::-sy+osh+osdyo+o/::/s:/y-` /// `odoyhds+/yysyydss+///+/:+oshdmNo+:+/oo/+++++:hy//` /// `://hyoyy/o/++shhy:+y:/:o/+omNmhsoohhsso+++:+o+sy:/++ /// -/---oddooss+oosy+ohNdo+++oyNhsdo/++shhhoo:s+oydmyo//o+ /// :y.`.``yyd++shoyydhhyymdhyyhyhhs+////+/+s/+:odmmyso.:ohy. /// .yy/o-..+h/+o/+//++ssoohhhssso+++:/:/yy+//sydmNddo+/./ohy+. /// .dmmhs+osdoos///o//++/+shdsoshoys+ssss++shmNNNyyds+:-s-//:+. /// -shmNmyhddsyss++/+ysddhyyydhdmyssNddyydyhNmdNmddso/::s:--`.-.` /// `+dmNhhdmddsooyyooossysshdhmoss+/+mNdyymydMdyMdyoo+/--/:/:`...-.` /// .:smNNMmsMNNmdhyyo/yymmdmdyo+ooooshysyysNNNmmmNyss/+o-`-:-/:```.`` ``` /// `.-+o/sdNNNmhdddNmmdsso/sdshyyyyhsdddyohymdmNdmmmmmyoo+/.... -os.`.``-.`` /// `/-:-/+.hymmmmdhmyNdMNmmhhs+sosoyhddyddmmho/ooymhddhdhyos-.oy..-:o+:..`` ```` ` /// ..::``--.-hoymmdNNNNNNMmhyNh+oo+soyNdmNmmmysooooymhy+so++yo..:+.--`..:.`.` `-- ``.` ` /// ```-.-.``..`:ddymmmNNdmNNNNmhN: -/oys/sdmmNdydsydmhhsmdso+/yo:/-..`.``.` ``:.`.````-. ` /// ````-:/.```:::syyydmddNhNNdsdMMs`./oddmd./odNdy+yssss++ooo/o+//-`:/:..:`-.```/-:.`.```..`` ` /// ```..-`` --.`.--o+sNhoyMmho+omhmo+Ns::dhdmmdy:.oNoyhhs+/o+o++s+hhoo+.`-:....``.-:-`..-````.-``.`` /// @title Dollars Nakamoto by Pascal Boyart /// @author jolan.eth /// @notice This contract will allow you to yield farm Dollars Nakamoto NFT. /// During epoch 0 you will be able to mint a Genesis NFT, /// Over time, epoch will increment allowing you to mint more editions. /// Minting generations editions is allowed only 1 time per epoch and per Genesis NFT. /// Generations editions do not allow you to mint other generations.
NatSpecSingleLine
_beforeTokenTransfer
function _beforeTokenTransfer(address from, address to, uint256 _tokenId) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, _tokenId); }
/// @dev ERC721 required override
NatSpecSingleLine
v0.8.10+commit.fc410830
MIT
ipfs://627efb7c58e0f1a820013031c32ab417b2b86eb0e16948f99bf7e29ad6e50407
{ "func_code_index": [ 17273, 17466 ] }
2,688
USDSat
USDSat.sol
0xbeda58401038c864c9fc9145f28e47b7b00a0e86
Solidity
USDSat
contract USDSat is USDSatMetadata, ERC721, ERC721Enumerable, Ownable, ReentrancyGuard { string SYMBOL = "USDSat"; string NAME = "Dollars Nakamoto"; string ContractCID; /// @notice Address used to sign NFT on mint address public ADDRESS_SIGN = 0x1Af70e564847bE46e4bA286c0b0066Da8372F902; /// @notice Ether shareholder address address public ADDRESS_PBOY = 0x709e17B3Ec505F80eAb064d0F2A71c743cE225B3; /// @notice Ether shareholder address address public ADDRESS_JOLAN = 0x51BdFa2Cbb25591AF58b202aCdcdB33325a325c2; /// @notice Equity per shareholder in % uint256 public SHARE_PBOY = 90; /// @notice Equity per shareholder in % uint256 public SHARE_JOLAN = 10; /// @notice Mapping used to represent allowed addresses to call { mintGenesis } mapping (address => bool) public _allowList; /// @notice Represent the current epoch uint256 public epoch = 0; /// @notice Represent the maximum epoch possible uint256 public epochMax = 10; /// @notice Represent the block length of an epoch uint256 public epochLen = 41016; /// @notice Index of the NFT /// @dev Start at 1 because var++ uint256 public tokenId = 1; /// @notice Index of the Genesis NFT /// @dev Start at 0 because ++var uint256 public genesisId = 0; /// @notice Index of the Generation NFT /// @dev Start at 0 because ++var uint256 public generationId = 0; /// @notice Maximum total supply uint256 public maxTokenSupply = 2100; /// @notice Maximum Genesis supply uint256 public maxGenesisSupply = 210; /// @notice Maximum supply per generation uint256 public maxGenerationSupply = 210; /// @notice Price of the Genesis NFT (Generations NFT are free) uint256 public genesisPrice = 0.5 ether; /// @notice Define the ending block uint256 public blockOmega; /// @notice Define the starting block uint256 public blockGenesis; /// @notice Define in which block the Meta must occur uint256 public blockMeta; /// @notice Used to inflate blockMeta each epoch incrementation uint256 public inflateRatio = 2; /// @notice Open Genesis mint when true bool public genesisMintAllowed = false; /// @notice Open Generation mint when true bool public generationMintAllowed = false; /// @notice Multi dimensionnal mapping to keep a track of the minting reentrancy over epoch mapping(uint256 => mapping(uint256 => bool)) public epochMintingRegistry; event Omega(uint256 _blockNumber); event Genesis(uint256 indexed _epoch, uint256 _blockNumber); event Meta(uint256 indexed _epoch, uint256 _blockNumber); event Withdraw(uint256 indexed _share, address _shareholder); event Shareholder(uint256 indexed _sharePercent, address _shareholder); event Securized(uint256 indexed _epoch, uint256 _epochLen, uint256 _blockMeta, uint256 _inflateRatio); event PermanentURI(string _value, uint256 indexed _id); event Minted(uint256 indexed _epoch, uint256 indexed _tokenId, address indexed _owner); event Signed(uint256 indexed _epoch, uint256 indexed _tokenId, uint256 indexed _blockNumber); constructor() ERC721(NAME, SYMBOL) {} // Withdraw functions ************************************************* /// @notice Allow Pboy to modify ADDRESS_PBOY /// This function is dedicated to the represented shareholder according to require(). function setPboy(address PBOY) public { require(msg.sender == ADDRESS_PBOY, "error msg.sender"); ADDRESS_PBOY = PBOY; emit Shareholder(SHARE_PBOY, ADDRESS_PBOY); } /// @notice Allow Jolan to modify ADDRESS_JOLAN /// This function is dedicated to the represented shareholder according to require(). function setJolan(address JOLAN) public { require(msg.sender == ADDRESS_JOLAN, "error msg.sender"); ADDRESS_JOLAN = JOLAN; emit Shareholder(SHARE_JOLAN, ADDRESS_JOLAN); } /// @notice Used to withdraw ETH balance of the contract, this function is dedicated /// to contract owner according to { onlyOwner } modifier. function withdrawEquity() public onlyOwner nonReentrant { uint256 balance = address(this).balance; address[2] memory shareholders = [ ADDRESS_PBOY, ADDRESS_JOLAN ]; uint256[2] memory _shares = [ SHARE_PBOY * balance / 100, SHARE_JOLAN * balance / 100 ]; uint i = 0; while (i < 2) { require(payable(shareholders[i]).send(_shares[i])); emit Withdraw(_shares[i], shareholders[i]); i++; } } // Epoch functions **************************************************** /// @notice Used to manage authorization and reentrancy of the genesis NFT mint /// @param _genesisId Used to increment { genesisId } and write { epochMintingRegistry } function genesisController(uint256 _genesisId) private { require(epoch == 0, "error epoch"); require(genesisId <= maxGenesisSupply, "error genesisId"); require(!epochMintingRegistry[epoch][_genesisId], "error epochMintingRegistry"); /// @dev Set { _genesisId } for { epoch } as true epochMintingRegistry[epoch][_genesisId] = true; /// @dev When { genesisId } reaches { maxGenesisSupply } the function /// will compute the data to increment the epoch according /// /// { blockGenesis } is set only once, at this time /// { blockMeta } is set to { blockGenesis } because epoch=0 /// Then it is computed into the function epochRegulator() /// /// Once the epoch is regulated, the new generation start /// straight away, { generationMintAllowed } is set to true if (genesisId == maxGenesisSupply) { blockGenesis = block.number; blockMeta = blockGenesis; emit Genesis(epoch, blockGenesis); epochRegulator(); } } /// @notice Used to manage authorization and reentrancy of the Generation NFT mint /// @param _genesisId Used to write { epochMintingRegistry } and verify minting allowance function generationController(uint256 _genesisId) private { require(blockGenesis > 0, "error blockGenesis"); require(blockMeta > 0, "error blockMeta"); require(blockOmega > 0, "error blockOmega"); /// @dev If { block.number } >= { blockMeta } the function /// will compute the data to increment the epoch according /// /// Once the epoch is regulated, the new generation start /// straight away, { generationMintAllowed } is set to true /// /// { generationId } is reset to 1 if (block.number >= blockMeta) { epochRegulator(); generationId = 1; } /// @dev Be sure the mint is open if condition are favorable if (block.number < blockMeta && generationId <= maxGenerationSupply) { generationMintAllowed = true; } require(maxTokenSupply >= tokenId, "error maxTokenSupply"); require(epoch > 0 && epoch < epochMax, "error epoch"); require(ownerOf(_genesisId) == msg.sender, "error ownerOf"); require(generationMintAllowed, "error generationMintAllowed"); require(generationId <= maxGenerationSupply, "error generationId"); require(epochMintingRegistry[0][_genesisId], "error epochMintingRegistry"); require(!epochMintingRegistry[epoch][_genesisId], "error epochMintingRegistry"); /// @dev Set { _genesisId } for { epoch } as true epochMintingRegistry[epoch][_genesisId] = true; /// @dev If { generationId } reaches { maxGenerationSupply } the modifier /// will set { generationMintAllowed } to false to stop the mint /// on this generation /// /// { generationId } is reset to 0 /// /// This condition will not block the function because as long as /// { block.number } >= { blockMeta } minting will reopen /// according and this condition will become obsolete until /// the condition is reached again if (generationId == maxGenerationSupply) { generationMintAllowed = false; generationId = 0; } } /// @notice Used to protect epoch block length from difficulty bomb of the /// Ethereum network. A difficulty bomb heavily increases the difficulty /// on the network, likely also causing an increase in block time. /// If the block time increases too much, the epoch generation could become /// exponentially higher than what is desired, ending with an undesired Ice-Age. /// To protect against this, the emergencySecure() function is allowed to /// manually reconfigure the epoch block length and the block Meta /// to match the network conditions if necessary. /// /// It can also be useful if the block time decreases for some reason with consensus change. /// /// This function is dedicated to contract owner according to { onlyOwner } modifier function emergencySecure(uint256 _epoch, uint256 _epochLen, uint256 _blockMeta, uint256 _inflateRatio) public onlyOwner { require(epoch > 0, "error epoch"); require(_epoch > 0, "error _epoch"); require(maxTokenSupply >= tokenId, "error maxTokenSupply"); epoch = _epoch; epochLen = _epochLen; blockMeta = _blockMeta; inflateRatio = _inflateRatio; computeBlockOmega(); emit Securized(epoch, epochLen, blockMeta, inflateRatio); } /// @notice Used to compute blockOmega() function, { blockOmega } represents /// the block when it won't ever be possible to mint another Dollars Nakamoto NFT. /// It is possible to be computed because of the deterministic state of the current protocol /// The following algorithm simulate the 10 epochs of the protocol block computation to result blockOmega function computeBlockOmega() private { uint256 i = 0; uint256 _blockMeta = 0; uint256 _epochLen = epochLen; while (i < epochMax) { if (i > 0) _epochLen *= inflateRatio; if (i == 9) { blockOmega = blockGenesis + _blockMeta; emit Omega(blockOmega); break; } _blockMeta += _epochLen; i++; } } /// @notice Used to regulate the epoch incrementation and block computation, known as Metas /// @dev When epoch=0, the { blockOmega } will be computed /// When epoch!=0 the block length { epochLen } will be multiplied /// by { inflateRatio } thus making the block length required for each /// epoch longer according /// /// { blockMeta } += { epochLen } result the exact block of the next Meta /// Allow generation mint after incrementing the epoch function epochRegulator() private { if (epoch == 0) computeBlockOmega(); if (epoch > 0) epochLen *= inflateRatio; blockMeta += epochLen; emit Meta(epoch, blockMeta); epoch++; if (block.number >= blockMeta && epoch < epochMax) { epochRegulator(); } generationMintAllowed = true; } // Mint functions ***************************************************** /// @notice Used to add/remove address from { _allowList } function setBatchGenesisAllowance(address[] memory batch) public onlyOwner { uint len = batch.length; require(len > 0, "error len"); uint i = 0; while (i < len) { _allowList[batch[i]] = _allowList[batch[i]] ? false : true; i++; } } /// @notice Used to transfer { _allowList } slot to another address function transferListSlot(address to) public { require(epoch == 0, "error epoch"); require(_allowList[msg.sender], "error msg.sender"); require(!_allowList[to], "error to"); _allowList[msg.sender] = false; _allowList[to] = true; } /// @notice Used to open the mint of Genesis NFT function setGenesisMint() public onlyOwner { genesisMintAllowed = true; } /// @notice Used to gift Genesis NFT, this function is dedicated /// to contract owner according to { onlyOwner } modifier function giftGenesis(address to) public onlyOwner { uint256 _genesisId = ++genesisId; setMetadata(tokenId, _genesisId, epoch); genesisController(_genesisId); mintUSDSat(to, tokenId++); } /// @notice Used to mint Genesis NFT, this function is payable /// the price of this function is equal to { genesisPrice }, /// require to be present on { _allowList } to call function mintGenesis() public payable { uint256 _genesisId = ++genesisId; setMetadata(tokenId, _genesisId, epoch); genesisController(_genesisId); require(genesisMintAllowed, "error genesisMintAllowed"); require(_allowList[msg.sender], "error allowList"); require(genesisPrice == msg.value, "error genesisPrice"); _allowList[msg.sender] = false; mintUSDSat(msg.sender, tokenId++); } /// @notice Used to gift Generation NFT, you need a Genesis NFT to call this function function giftGenerations(uint256 _genesisId, address to) public { ++generationId; generationController(_genesisId); setMetadata(tokenId, _genesisId, epoch); mintUSDSat(to, tokenId++); } /// @notice Used to mint Generation NFT, you need a Genesis NFT to call this function function mintGenerations(uint256 _genesisId) public { ++generationId; generationController(_genesisId); setMetadata(tokenId, _genesisId, epoch); mintUSDSat(msg.sender, tokenId++); } /// @notice Token is minted on { ADDRESS_SIGN } and instantly transferred to { msg.sender } as { to }, /// this is to ensure the token creation is signed with { ADDRESS_SIGN } /// This function is private and can be only called by the contract function mintUSDSat(address to, uint256 _tokenId) private { emit PermanentURI(_compileMetadata(_tokenId), _tokenId); _safeMint(ADDRESS_SIGN, _tokenId); emit Signed(epoch, _tokenId, block.number); _safeTransfer(ADDRESS_SIGN, to, _tokenId, ""); emit Minted(epoch, _tokenId, to); } // Contract URI functions ********************************************* /// @notice Used to set the { ContractCID } metadata from ipfs, /// this function is dedicated to contract owner according /// to { onlyOwner } modifier function setContractCID(string memory CID) public onlyOwner { ContractCID = string(abi.encodePacked("ipfs://", CID)); } /// @notice Used to render { ContractCID } as { contractURI } according to /// Opensea contract metadata standard function contractURI() public view virtual returns (string memory) { return ContractCID; } // Utilitaries functions ********************************************** /// @notice Used to fetch all entry for { epoch } into { epochMintingRegistry } function getMapRegisteryForEpoch(uint256 _epoch) public view returns (bool[210] memory result) { uint i = 1; while (i <= maxGenesisSupply) { result[i] = epochMintingRegistry[_epoch][i]; i++; } } /// @notice Used to fetch all { tokenIds } from { owner } function exposeHeldIds(address owner) public view returns(uint[] memory) { uint tokenCount = balanceOf(owner); uint[] memory tokenIds = new uint[](tokenCount); uint i = 0; while (i < tokenCount) { tokenIds[i] = tokenOfOwnerByIndex(owner, i); i++; } return tokenIds; } // ERC721 Spec functions ********************************************** /// @notice Used to render metadata as { tokenURI } according to ERC721 standard function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token"); return _compileMetadata(_tokenId); } /// @dev ERC721 required override function _beforeTokenTransfer(address from, address to, uint256 _tokenId) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, _tokenId); } /// @dev ERC721 required override function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } }
/// ``.. /// `.` `````.``.-````-`` `.` /// ` ``````.`..///.-..----. --..--`.-....`..-.```` ``` /// `` `.`..--...`:::/::-``..``..:-.://///---..-....----- /// ``-:::/+++:::/-.-///://oso+::++/--:--../+:/:..:-....-://:/:-`` /// `-+/++/+o+://+::-:soo+oosss+s+//o:/:--`--:://://:ooso/-.--.-:-.` /// ``.+ooso++o+:+:+sosyhsyshhddyo+:/sds/yoo++/+:--/--.--:..--..``.```` /// ``:++/---:+/::::///oyhhyy+++:hddhhNNho///ohosyhs+/-:/+/---.....-.. ` /// ``-:-...-/+///++///+o+:-:o+o/oydmNmNNdddhsoyo/oyyyho///:-.--.-.``. `` /// ```--`..-:+/:--:::-.-///++++ydsdNNMNdmMNMmNysddyoooosso+//-.-`....````` ..` /// .```:-:::/-.-+o++/+:/+/o/hNNNNhmdNMMNNMMdyydNNmdyys+++oo++-`--.:.-.`````... /// ..--.`-..`.-`-hh++-/:+shho+hsysyyhhhmNNmmNMMmNNNdmmy+:+sh/o+y/+-`+./::.```` ` /// -/` ``.-``.//o++y+//ssyh+hhdmmdmmddmhdmNdmdsh+oNNMmmddoodh/s:yss.--+.//+`.` `. /// `.`-.` -`..+h+yo++ooyyyyyoyhy+shmNNmmdhhdhyyhymdyyhdmshoohs+y:oy+/+o/:/++.`- .` /// ``.`.``-.-++syyyhhhhhhhhmhysosyyoooosssdhhhdmmdhdmdsy+ss+/+ho/hody-s+-:+::--`` ` /// .`` ``-//s+:ohmdmddNmNmhhshhddNNNhyyhhhdNNhmNNmNNmmyso+yhhso++hhdy.:/ ::-:--``.` /// .```.-`.//shdmNNmddyysohmMmdmNNmmNshdmNhso+-/ohNoyhmmsysosd++hy/osss/.:-o/-.:/--. /// ``..:++-+hhy/syhhhdhdNNddNMmNsNMNyyso+//:-.`-/..+hmdsmdy+ossos:+o/h/+..//-s.`.:::o/ /// `.-.oy//hm+o:-..-+/shdNNNNNNhsNdo/oyoyyhoh+/so//+/mNmyhh+/s+dy/+s::+:`-`-:s--:-.::+`-` /// .`:h-`+y+./oyhhdddhyohMMNmmNmdhoo/oyyhddhmNNNmhsoodmdhs+///++:+-:.:/--/-/o/--+//...:` /// ``+o``yoodNNNNNMhdyyo+ymhsymyshhyys+sssssNmdmmdmy+oso/++:://+/-`::-:--:/::+.//o:-.--: /// `:-:-`oNhyhdNNNmyys+/:://oohy++/+hmmmmNNNNhohydmmyhy++////ooy./----.-:---/::-o+:...-/ /// ``-.-` yms+mmNmMMmNho/:o++++hhh++:mMmNmmmNMNdhdms+ysyy//:-+o:.-.`.``.-:/::-:-+/y/.- -` /// ..:` hh+oNNmMNNNmss/:-+oyhs+o+.-yhdNmdhmmydmms+o///:///+/+--/`-``.o::/:-o//-/y::/.- /// `.-``hh+yNdmdohdy:++/./myhds/./shNhhyy++o:oyos/s+:s//+////.:- ...`--`..`-.:--o:+::` /// `-/+yyho.`.-+oso///+/Nmddh//y+:s:.../soy+:o+.:sdyo++++o:.-. `.:.:-```:.`:``/o:`:` /// ./.`..sMN+:::yh+s+ysyhhddh+ymdsd/:/+o+ysydhohoh/o+/so++o+/o.--..`-:::``:-`+-`:+--.` /// ``:``..-NNy++/yyysohmo+NNmy/+:+hMNmy+yydmNMNddhs:yyydmmmso:o///..-.-+-:o:/.o/-/+-`` /// ``+.`..-mMhsyo+++oo+yoshyyo+/`+hNmhyy+sdmdssssho-MMMNMNh//+/oo+/+:-....`.s+/`..-` /// .+ `oNMmdhhsohhmmydmNms/yy.oNmmdy+++/+ss+odNm+mNmdddo-s+:+/++/-:--//`/o+s/.-`` /// `/` dNNNhooddNmNymMNNdsoo+y+shhhmyymhss+hddms+hdhmdo+/+-/oo+/.///+sh:-/-s/` /// `::`hdNmh+ooNmdohNNMMmsooohh+oysydhdooo/syysodmNmys+/o+//+y/:.+/hmso.-//s- /// -+ohdmmhyhdysysyyhmysoyddhhoo+shdhdyddmddmNmmhssds/::/oo/..:/+Nmo+`-:so /// .oyhdmmNNdm+s:/:os/+/ssyyds+/ssdNNyhdmmhdmmdymymy///o:/``/+-dmdoo++:o` /// `ysyMNhhmoo+h-:/+o/+:.:/:/+doo+dNdhddmhmmmy++yhds/+-+::..o/+Nmosyhs+- /// s+dNNyNhsdhNhsy:+:oo/soo+dNmmooyosohMhsymmhyy+++:+:/+/-/o+yNh+hMNs. /// +yhNNMd+dmydmdy/+/sshydmhdNNmNooyhhhhshohmNh+:+oso++ssy+/odyhhNmh` /// `yyhdms+dMh+oyshhyhysdmNd+ohyNN+++mNddmNy+yo//+o/hddddymmyhosNmms` /// oydos:oMmhoyyhysssysdmMmNmhNmNNh/+mmNmddh+/+o+::+s+hmhmdyNNNNy: /// `/dNm/+Ndhy+oshdhhdyo::ohmdyhhNysy:smshmdo/o:so//:s++ymhyohdy-` /// `sNNN/hNm/:do+o:+/++++s:/+shyymmddy/ydmmh/s/+oss//oysy++o+o+` /// oNNMNmm:/hyy/:/o/+hhsosysoo-ohhhss/hmmhd/dyh++/soyooy++o+:. /// :/dMNh/smhh+//+s+--:+/so+ohhy/:sydmmmmm+/mdddhy++/ohs//-o/` /// `/odmhyhsyh++/-:+:::/:/o/:ooddy/+yodNNh+ydhmmmy++/hhyo+://` /// `:os/+o//oshss/yhs+//:+/-/:soooo/+sso+dddydss+:+sy///+:++ /// ./o/s//hhNho+shyyyoyyso+/ys+/+-:y+:/soooyyh++sNyo++/:/+ /// -/:osmmhyo:++++/+/osshdssooo/:/h//://++oyhsshmdo+//s/- /// .osmhydh::/+++/o+ohhysddyoo++os+-+++///yhhhmNs+o/:// /// -.++yss//////+/+/+soo++shyhsyy+::/:+y+yhdmdoo//:/:- /// ``.oss/:////++://+o//:://+oo-:o++/shhhmmh+o+++///-` /// ..:+++oo/+///ys:///://+::-sy+osh+osdyo+o/::/s:/y-` /// `odoyhds+/yysyydss+///+/:+oshdmNo+:+/oo/+++++:hy//` /// `://hyoyy/o/++shhy:+y:/:o/+omNmhsoohhsso+++:+o+sy:/++ /// -/---oddooss+oosy+ohNdo+++oyNhsdo/++shhhoo:s+oydmyo//o+ /// :y.`.``yyd++shoyydhhyymdhyyhyhhs+////+/+s/+:odmmyso.:ohy. /// .yy/o-..+h/+o/+//++ssoohhhssso+++:/:/yy+//sydmNddo+/./ohy+. /// .dmmhs+osdoos///o//++/+shdsoshoys+ssss++shmNNNyyds+:-s-//:+. /// -shmNmyhddsyss++/+ysddhyyydhdmyssNddyydyhNmdNmddso/::s:--`.-.` /// `+dmNhhdmddsooyyooossysshdhmoss+/+mNdyymydMdyMdyoo+/--/:/:`...-.` /// .:smNNMmsMNNmdhyyo/yymmdmdyo+ooooshysyysNNNmmmNyss/+o-`-:-/:```.`` ``` /// `.-+o/sdNNNmhdddNmmdsso/sdshyyyyhsdddyohymdmNdmmmmmyoo+/.... -os.`.``-.`` /// `/-:-/+.hymmmmdhmyNdMNmmhhs+sosoyhddyddmmho/ooymhddhdhyos-.oy..-:o+:..`` ```` ` /// ..::``--.-hoymmdNNNNNNMmhyNh+oo+soyNdmNmmmysooooymhy+so++yo..:+.--`..:.`.` `-- ``.` ` /// ```-.-.``..`:ddymmmNNdmNNNNmhN: -/oys/sdmmNdydsydmhhsmdso+/yo:/-..`.``.` ``:.`.````-. ` /// ````-:/.```:::syyydmddNhNNdsdMMs`./oddmd./odNdy+yssss++ooo/o+//-`:/:..:`-.```/-:.`.```..`` ` /// ```..-`` --.`.--o+sNhoyMmho+omhmo+Ns::dhdmmdy:.oNoyhhs+/o+o++s+hhoo+.`-:....``.-:-`..-````.-``.`` /// @title Dollars Nakamoto by Pascal Boyart /// @author jolan.eth /// @notice This contract will allow you to yield farm Dollars Nakamoto NFT. /// During epoch 0 you will be able to mint a Genesis NFT, /// Over time, epoch will increment allowing you to mint more editions. /// Minting generations editions is allowed only 1 time per epoch and per Genesis NFT. /// Generations editions do not allow you to mint other generations.
NatSpecSingleLine
supportsInterface
function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); }
/// @dev ERC721 required override
NatSpecSingleLine
v0.8.10+commit.fc410830
MIT
ipfs://627efb7c58e0f1a820013031c32ab417b2b86eb0e16948f99bf7e29ad6e50407
{ "func_code_index": [ 17508, 17689 ] }
2,689
PAaveIntegration
contracts/masset/peripheral/AaveV2Integration.sol
0x4094aec22f40f11c29941d144c3dc887b33f5504
Solidity
AaveV2Integration
contract AaveV2Integration is AbstractIntegration { using SafeERC20 for IERC20; // Core address for the given platform */ address public immutable platformAddress; address public immutable rewardToken; event RewardTokenApproved(address rewardToken, address account); /** * @param _nexus Address of the Nexus * @param _lp Address of LP * @param _platformAddress Generic platform address * @param _rewardToken Reward token, if any */ constructor( address _nexus, address _lp, address _platformAddress, address _rewardToken ) AbstractIntegration(_nexus, _lp) { require(_platformAddress != address(0), "Invalid platform address"); platformAddress = _platformAddress; rewardToken = _rewardToken; } /*************************************** ADMIN ****************************************/ /** * @dev Approves Liquidator to spend reward tokens */ function approveRewardToken() external onlyGovernor { address liquidator = nexus.getModule(keccak256("Liquidator")); require(liquidator != address(0), "Liquidator address cannot be zero"); MassetHelpers.safeInfiniteApprove(rewardToken, liquidator); emit RewardTokenApproved(rewardToken, liquidator); } /*************************************** CORE ****************************************/ /** * @dev Deposit a quantity of bAsset into the platform. Credited aTokens * remain here in the vault. Can only be called by whitelisted addresses * (mAsset and corresponding BasketManager) * @param _bAsset Address for the bAsset * @param _amount Units of bAsset to deposit * @param _hasTxFee Is the bAsset known to have a tx fee? * @return quantityDeposited Quantity of bAsset that entered the platform */ function deposit( address _bAsset, uint256 _amount, bool _hasTxFee ) external override onlyLP nonReentrant returns (uint256 quantityDeposited) { require(_amount > 0, "Must deposit something"); IAaveATokenV2 aToken = _getATokenFor(_bAsset); quantityDeposited = _amount; if (_hasTxFee) { // If we charge a fee, account for it uint256 prevBal = _checkBalance(aToken); _getLendingPool().deposit(_bAsset, _amount, address(this), 36); uint256 newBal = _checkBalance(aToken); quantityDeposited = _min(quantityDeposited, newBal - prevBal); } else { _getLendingPool().deposit(_bAsset, _amount, address(this), 36); } emit Deposit(_bAsset, address(aToken), quantityDeposited); } /** * @dev Withdraw a quantity of bAsset from the platform * @param _receiver Address to which the bAsset should be sent * @param _bAsset Address of the bAsset * @param _amount Units of bAsset to withdraw * @param _hasTxFee Is the bAsset known to have a tx fee? */ function withdraw( address _receiver, address _bAsset, uint256 _amount, bool _hasTxFee ) external override onlyLP nonReentrant { _withdraw(_receiver, _bAsset, _amount, _amount, _hasTxFee); } /** * @dev Withdraw a quantity of bAsset from the platform * @param _receiver Address to which the bAsset should be sent * @param _bAsset Address of the bAsset * @param _amount Units of bAsset to send to recipient * @param _totalAmount Total units to pull from lending platform * @param _hasTxFee Is the bAsset known to have a tx fee? */ function withdraw( address _receiver, address _bAsset, uint256 _amount, uint256 _totalAmount, bool _hasTxFee ) external override onlyLP nonReentrant { _withdraw(_receiver, _bAsset, _amount, _totalAmount, _hasTxFee); } /** @dev Withdraws _totalAmount from the lending pool, sending _amount to user */ function _withdraw( address _receiver, address _bAsset, uint256 _amount, uint256 _totalAmount, bool _hasTxFee ) internal { require(_totalAmount > 0, "Must withdraw something"); IAaveATokenV2 aToken = _getATokenFor(_bAsset); if (_hasTxFee) { require(_amount == _totalAmount, "Cache inactive for assets with fee"); _getLendingPool().withdraw(_bAsset, _amount, _receiver); } else { _getLendingPool().withdraw(_bAsset, _totalAmount, address(this)); // Send redeemed bAsset to the receiver IERC20(_bAsset).safeTransfer(_receiver, _amount); } emit PlatformWithdrawal(_bAsset, address(aToken), _totalAmount, _amount); } /** * @dev Withdraw a quantity of bAsset from the cache. * @param _receiver Address to which the bAsset should be sent * @param _bAsset Address of the bAsset * @param _amount Units of bAsset to withdraw */ function withdrawRaw( address _receiver, address _bAsset, uint256 _amount ) external override onlyLP nonReentrant { require(_amount > 0, "Must withdraw something"); require(_receiver != address(0), "Must specify recipient"); IERC20(_bAsset).safeTransfer(_receiver, _amount); emit Withdrawal(_bAsset, address(0), _amount); } /** * @dev Get the total bAsset value held in the platform * This includes any interest that was generated since depositing * Aave gradually increases the balances of all aToken holders, as the interest grows * @param _bAsset Address of the bAsset * @return balance Total value of the bAsset in the platform */ function checkBalance(address _bAsset) external view override returns (uint256 balance) { // balance is always with token aToken decimals IAaveATokenV2 aToken = _getATokenFor(_bAsset); return _checkBalance(aToken); } /*************************************** APPROVALS ****************************************/ /** * @dev Internal method to respond to the addition of new bAsset / pTokens * We need to approve the Aave lending pool core conrtact and give it permission * to spend the bAsset * @param _bAsset Address of the bAsset to approve */ function _abstractSetPToken( address _bAsset, address /*_pToken*/ ) internal override { address lendingPool = address(_getLendingPool()); // approve the pool to spend the bAsset MassetHelpers.safeInfiniteApprove(_bAsset, lendingPool); } /*************************************** HELPERS ****************************************/ /** * @dev Get the current address of the Aave lending pool, which is the gateway to * depositing. * @return Current lending pool implementation */ function _getLendingPool() internal view returns (IAaveLendingPoolV2) { address lendingPool = ILendingPoolAddressesProviderV2(platformAddress).getLendingPool(); require(lendingPool != address(0), "Lending pool does not exist"); return IAaveLendingPoolV2(lendingPool); } /** * @dev Get the pToken wrapped in the IAaveAToken interface for this bAsset, to use * for withdrawing or balance checking. Fails if the pToken doesn't exist in our mappings. * @param _bAsset Address of the bAsset * @return aToken Corresponding to this bAsset */ function _getATokenFor(address _bAsset) internal view returns (IAaveATokenV2) { address aToken = bAssetToPToken[_bAsset]; require(aToken != address(0), "aToken does not exist"); return IAaveATokenV2(aToken); } /** * @dev Get the total bAsset value held in the platform * @param _aToken aToken for which to check balance * @return balance Total value of the bAsset in the platform */ function _checkBalance(IAaveATokenV2 _aToken) internal view returns (uint256 balance) { return _aToken.balanceOf(address(this)); } }
/** * @title AaveV2Integration * @author mStable * @notice A simple connection to deposit and withdraw bAssets from Aave * @dev VERSION: 1.0 * DATE: 2020-16-11 */
NatSpecMultiLine
approveRewardToken
function approveRewardToken() external onlyGovernor { address liquidator = nexus.getModule(keccak256("Liquidator")); require(liquidator != address(0), "Liquidator address cannot be zero"); MassetHelpers.safeInfiniteApprove(rewardToken, liquidator); emit RewardTokenApproved(rewardToken, liquidator); }
/** * @dev Approves Liquidator to spend reward tokens */
NatSpecMultiLine
v0.8.6+commit.11564f7e
{ "func_code_index": [ 1036, 1379 ] }
2,690
PAaveIntegration
contracts/masset/peripheral/AaveV2Integration.sol
0x4094aec22f40f11c29941d144c3dc887b33f5504
Solidity
AaveV2Integration
contract AaveV2Integration is AbstractIntegration { using SafeERC20 for IERC20; // Core address for the given platform */ address public immutable platformAddress; address public immutable rewardToken; event RewardTokenApproved(address rewardToken, address account); /** * @param _nexus Address of the Nexus * @param _lp Address of LP * @param _platformAddress Generic platform address * @param _rewardToken Reward token, if any */ constructor( address _nexus, address _lp, address _platformAddress, address _rewardToken ) AbstractIntegration(_nexus, _lp) { require(_platformAddress != address(0), "Invalid platform address"); platformAddress = _platformAddress; rewardToken = _rewardToken; } /*************************************** ADMIN ****************************************/ /** * @dev Approves Liquidator to spend reward tokens */ function approveRewardToken() external onlyGovernor { address liquidator = nexus.getModule(keccak256("Liquidator")); require(liquidator != address(0), "Liquidator address cannot be zero"); MassetHelpers.safeInfiniteApprove(rewardToken, liquidator); emit RewardTokenApproved(rewardToken, liquidator); } /*************************************** CORE ****************************************/ /** * @dev Deposit a quantity of bAsset into the platform. Credited aTokens * remain here in the vault. Can only be called by whitelisted addresses * (mAsset and corresponding BasketManager) * @param _bAsset Address for the bAsset * @param _amount Units of bAsset to deposit * @param _hasTxFee Is the bAsset known to have a tx fee? * @return quantityDeposited Quantity of bAsset that entered the platform */ function deposit( address _bAsset, uint256 _amount, bool _hasTxFee ) external override onlyLP nonReentrant returns (uint256 quantityDeposited) { require(_amount > 0, "Must deposit something"); IAaveATokenV2 aToken = _getATokenFor(_bAsset); quantityDeposited = _amount; if (_hasTxFee) { // If we charge a fee, account for it uint256 prevBal = _checkBalance(aToken); _getLendingPool().deposit(_bAsset, _amount, address(this), 36); uint256 newBal = _checkBalance(aToken); quantityDeposited = _min(quantityDeposited, newBal - prevBal); } else { _getLendingPool().deposit(_bAsset, _amount, address(this), 36); } emit Deposit(_bAsset, address(aToken), quantityDeposited); } /** * @dev Withdraw a quantity of bAsset from the platform * @param _receiver Address to which the bAsset should be sent * @param _bAsset Address of the bAsset * @param _amount Units of bAsset to withdraw * @param _hasTxFee Is the bAsset known to have a tx fee? */ function withdraw( address _receiver, address _bAsset, uint256 _amount, bool _hasTxFee ) external override onlyLP nonReentrant { _withdraw(_receiver, _bAsset, _amount, _amount, _hasTxFee); } /** * @dev Withdraw a quantity of bAsset from the platform * @param _receiver Address to which the bAsset should be sent * @param _bAsset Address of the bAsset * @param _amount Units of bAsset to send to recipient * @param _totalAmount Total units to pull from lending platform * @param _hasTxFee Is the bAsset known to have a tx fee? */ function withdraw( address _receiver, address _bAsset, uint256 _amount, uint256 _totalAmount, bool _hasTxFee ) external override onlyLP nonReentrant { _withdraw(_receiver, _bAsset, _amount, _totalAmount, _hasTxFee); } /** @dev Withdraws _totalAmount from the lending pool, sending _amount to user */ function _withdraw( address _receiver, address _bAsset, uint256 _amount, uint256 _totalAmount, bool _hasTxFee ) internal { require(_totalAmount > 0, "Must withdraw something"); IAaveATokenV2 aToken = _getATokenFor(_bAsset); if (_hasTxFee) { require(_amount == _totalAmount, "Cache inactive for assets with fee"); _getLendingPool().withdraw(_bAsset, _amount, _receiver); } else { _getLendingPool().withdraw(_bAsset, _totalAmount, address(this)); // Send redeemed bAsset to the receiver IERC20(_bAsset).safeTransfer(_receiver, _amount); } emit PlatformWithdrawal(_bAsset, address(aToken), _totalAmount, _amount); } /** * @dev Withdraw a quantity of bAsset from the cache. * @param _receiver Address to which the bAsset should be sent * @param _bAsset Address of the bAsset * @param _amount Units of bAsset to withdraw */ function withdrawRaw( address _receiver, address _bAsset, uint256 _amount ) external override onlyLP nonReentrant { require(_amount > 0, "Must withdraw something"); require(_receiver != address(0), "Must specify recipient"); IERC20(_bAsset).safeTransfer(_receiver, _amount); emit Withdrawal(_bAsset, address(0), _amount); } /** * @dev Get the total bAsset value held in the platform * This includes any interest that was generated since depositing * Aave gradually increases the balances of all aToken holders, as the interest grows * @param _bAsset Address of the bAsset * @return balance Total value of the bAsset in the platform */ function checkBalance(address _bAsset) external view override returns (uint256 balance) { // balance is always with token aToken decimals IAaveATokenV2 aToken = _getATokenFor(_bAsset); return _checkBalance(aToken); } /*************************************** APPROVALS ****************************************/ /** * @dev Internal method to respond to the addition of new bAsset / pTokens * We need to approve the Aave lending pool core conrtact and give it permission * to spend the bAsset * @param _bAsset Address of the bAsset to approve */ function _abstractSetPToken( address _bAsset, address /*_pToken*/ ) internal override { address lendingPool = address(_getLendingPool()); // approve the pool to spend the bAsset MassetHelpers.safeInfiniteApprove(_bAsset, lendingPool); } /*************************************** HELPERS ****************************************/ /** * @dev Get the current address of the Aave lending pool, which is the gateway to * depositing. * @return Current lending pool implementation */ function _getLendingPool() internal view returns (IAaveLendingPoolV2) { address lendingPool = ILendingPoolAddressesProviderV2(platformAddress).getLendingPool(); require(lendingPool != address(0), "Lending pool does not exist"); return IAaveLendingPoolV2(lendingPool); } /** * @dev Get the pToken wrapped in the IAaveAToken interface for this bAsset, to use * for withdrawing or balance checking. Fails if the pToken doesn't exist in our mappings. * @param _bAsset Address of the bAsset * @return aToken Corresponding to this bAsset */ function _getATokenFor(address _bAsset) internal view returns (IAaveATokenV2) { address aToken = bAssetToPToken[_bAsset]; require(aToken != address(0), "aToken does not exist"); return IAaveATokenV2(aToken); } /** * @dev Get the total bAsset value held in the platform * @param _aToken aToken for which to check balance * @return balance Total value of the bAsset in the platform */ function _checkBalance(IAaveATokenV2 _aToken) internal view returns (uint256 balance) { return _aToken.balanceOf(address(this)); } }
/** * @title AaveV2Integration * @author mStable * @notice A simple connection to deposit and withdraw bAssets from Aave * @dev VERSION: 1.0 * DATE: 2020-16-11 */
NatSpecMultiLine
deposit
function deposit( address _bAsset, uint256 _amount, bool _hasTxFee ) external override onlyLP nonReentrant returns (uint256 quantityDeposited) { require(_amount > 0, "Must deposit something"); IAaveATokenV2 aToken = _getATokenFor(_bAsset); quantityDeposited = _amount; if (_hasTxFee) { // If we charge a fee, account for it uint256 prevBal = _checkBalance(aToken); _getLendingPool().deposit(_bAsset, _amount, address(this), 36); uint256 newBal = _checkBalance(aToken); quantityDeposited = _min(quantityDeposited, newBal - prevBal); } else { _getLendingPool().deposit(_bAsset, _amount, address(this), 36); } emit Deposit(_bAsset, address(aToken), quantityDeposited); }
/** * @dev Deposit a quantity of bAsset into the platform. Credited aTokens * remain here in the vault. Can only be called by whitelisted addresses * (mAsset and corresponding BasketManager) * @param _bAsset Address for the bAsset * @param _amount Units of bAsset to deposit * @param _hasTxFee Is the bAsset known to have a tx fee? * @return quantityDeposited Quantity of bAsset that entered the platform */
NatSpecMultiLine
v0.8.6+commit.11564f7e
{ "func_code_index": [ 1999, 2834 ] }
2,691
PAaveIntegration
contracts/masset/peripheral/AaveV2Integration.sol
0x4094aec22f40f11c29941d144c3dc887b33f5504
Solidity
AaveV2Integration
contract AaveV2Integration is AbstractIntegration { using SafeERC20 for IERC20; // Core address for the given platform */ address public immutable platformAddress; address public immutable rewardToken; event RewardTokenApproved(address rewardToken, address account); /** * @param _nexus Address of the Nexus * @param _lp Address of LP * @param _platformAddress Generic platform address * @param _rewardToken Reward token, if any */ constructor( address _nexus, address _lp, address _platformAddress, address _rewardToken ) AbstractIntegration(_nexus, _lp) { require(_platformAddress != address(0), "Invalid platform address"); platformAddress = _platformAddress; rewardToken = _rewardToken; } /*************************************** ADMIN ****************************************/ /** * @dev Approves Liquidator to spend reward tokens */ function approveRewardToken() external onlyGovernor { address liquidator = nexus.getModule(keccak256("Liquidator")); require(liquidator != address(0), "Liquidator address cannot be zero"); MassetHelpers.safeInfiniteApprove(rewardToken, liquidator); emit RewardTokenApproved(rewardToken, liquidator); } /*************************************** CORE ****************************************/ /** * @dev Deposit a quantity of bAsset into the platform. Credited aTokens * remain here in the vault. Can only be called by whitelisted addresses * (mAsset and corresponding BasketManager) * @param _bAsset Address for the bAsset * @param _amount Units of bAsset to deposit * @param _hasTxFee Is the bAsset known to have a tx fee? * @return quantityDeposited Quantity of bAsset that entered the platform */ function deposit( address _bAsset, uint256 _amount, bool _hasTxFee ) external override onlyLP nonReentrant returns (uint256 quantityDeposited) { require(_amount > 0, "Must deposit something"); IAaveATokenV2 aToken = _getATokenFor(_bAsset); quantityDeposited = _amount; if (_hasTxFee) { // If we charge a fee, account for it uint256 prevBal = _checkBalance(aToken); _getLendingPool().deposit(_bAsset, _amount, address(this), 36); uint256 newBal = _checkBalance(aToken); quantityDeposited = _min(quantityDeposited, newBal - prevBal); } else { _getLendingPool().deposit(_bAsset, _amount, address(this), 36); } emit Deposit(_bAsset, address(aToken), quantityDeposited); } /** * @dev Withdraw a quantity of bAsset from the platform * @param _receiver Address to which the bAsset should be sent * @param _bAsset Address of the bAsset * @param _amount Units of bAsset to withdraw * @param _hasTxFee Is the bAsset known to have a tx fee? */ function withdraw( address _receiver, address _bAsset, uint256 _amount, bool _hasTxFee ) external override onlyLP nonReentrant { _withdraw(_receiver, _bAsset, _amount, _amount, _hasTxFee); } /** * @dev Withdraw a quantity of bAsset from the platform * @param _receiver Address to which the bAsset should be sent * @param _bAsset Address of the bAsset * @param _amount Units of bAsset to send to recipient * @param _totalAmount Total units to pull from lending platform * @param _hasTxFee Is the bAsset known to have a tx fee? */ function withdraw( address _receiver, address _bAsset, uint256 _amount, uint256 _totalAmount, bool _hasTxFee ) external override onlyLP nonReentrant { _withdraw(_receiver, _bAsset, _amount, _totalAmount, _hasTxFee); } /** @dev Withdraws _totalAmount from the lending pool, sending _amount to user */ function _withdraw( address _receiver, address _bAsset, uint256 _amount, uint256 _totalAmount, bool _hasTxFee ) internal { require(_totalAmount > 0, "Must withdraw something"); IAaveATokenV2 aToken = _getATokenFor(_bAsset); if (_hasTxFee) { require(_amount == _totalAmount, "Cache inactive for assets with fee"); _getLendingPool().withdraw(_bAsset, _amount, _receiver); } else { _getLendingPool().withdraw(_bAsset, _totalAmount, address(this)); // Send redeemed bAsset to the receiver IERC20(_bAsset).safeTransfer(_receiver, _amount); } emit PlatformWithdrawal(_bAsset, address(aToken), _totalAmount, _amount); } /** * @dev Withdraw a quantity of bAsset from the cache. * @param _receiver Address to which the bAsset should be sent * @param _bAsset Address of the bAsset * @param _amount Units of bAsset to withdraw */ function withdrawRaw( address _receiver, address _bAsset, uint256 _amount ) external override onlyLP nonReentrant { require(_amount > 0, "Must withdraw something"); require(_receiver != address(0), "Must specify recipient"); IERC20(_bAsset).safeTransfer(_receiver, _amount); emit Withdrawal(_bAsset, address(0), _amount); } /** * @dev Get the total bAsset value held in the platform * This includes any interest that was generated since depositing * Aave gradually increases the balances of all aToken holders, as the interest grows * @param _bAsset Address of the bAsset * @return balance Total value of the bAsset in the platform */ function checkBalance(address _bAsset) external view override returns (uint256 balance) { // balance is always with token aToken decimals IAaveATokenV2 aToken = _getATokenFor(_bAsset); return _checkBalance(aToken); } /*************************************** APPROVALS ****************************************/ /** * @dev Internal method to respond to the addition of new bAsset / pTokens * We need to approve the Aave lending pool core conrtact and give it permission * to spend the bAsset * @param _bAsset Address of the bAsset to approve */ function _abstractSetPToken( address _bAsset, address /*_pToken*/ ) internal override { address lendingPool = address(_getLendingPool()); // approve the pool to spend the bAsset MassetHelpers.safeInfiniteApprove(_bAsset, lendingPool); } /*************************************** HELPERS ****************************************/ /** * @dev Get the current address of the Aave lending pool, which is the gateway to * depositing. * @return Current lending pool implementation */ function _getLendingPool() internal view returns (IAaveLendingPoolV2) { address lendingPool = ILendingPoolAddressesProviderV2(platformAddress).getLendingPool(); require(lendingPool != address(0), "Lending pool does not exist"); return IAaveLendingPoolV2(lendingPool); } /** * @dev Get the pToken wrapped in the IAaveAToken interface for this bAsset, to use * for withdrawing or balance checking. Fails if the pToken doesn't exist in our mappings. * @param _bAsset Address of the bAsset * @return aToken Corresponding to this bAsset */ function _getATokenFor(address _bAsset) internal view returns (IAaveATokenV2) { address aToken = bAssetToPToken[_bAsset]; require(aToken != address(0), "aToken does not exist"); return IAaveATokenV2(aToken); } /** * @dev Get the total bAsset value held in the platform * @param _aToken aToken for which to check balance * @return balance Total value of the bAsset in the platform */ function _checkBalance(IAaveATokenV2 _aToken) internal view returns (uint256 balance) { return _aToken.balanceOf(address(this)); } }
/** * @title AaveV2Integration * @author mStable * @notice A simple connection to deposit and withdraw bAssets from Aave * @dev VERSION: 1.0 * DATE: 2020-16-11 */
NatSpecMultiLine
withdraw
function withdraw( address _receiver, address _bAsset, uint256 _amount, bool _hasTxFee ) external override onlyLP nonReentrant { _withdraw(_receiver, _bAsset, _amount, _amount, _hasTxFee); }
/** * @dev Withdraw a quantity of bAsset from the platform * @param _receiver Address to which the bAsset should be sent * @param _bAsset Address of the bAsset * @param _amount Units of bAsset to withdraw * @param _hasTxFee Is the bAsset known to have a tx fee? */
NatSpecMultiLine
v0.8.6+commit.11564f7e
{ "func_code_index": [ 3155, 3397 ] }
2,692
PAaveIntegration
contracts/masset/peripheral/AaveV2Integration.sol
0x4094aec22f40f11c29941d144c3dc887b33f5504
Solidity
AaveV2Integration
contract AaveV2Integration is AbstractIntegration { using SafeERC20 for IERC20; // Core address for the given platform */ address public immutable platformAddress; address public immutable rewardToken; event RewardTokenApproved(address rewardToken, address account); /** * @param _nexus Address of the Nexus * @param _lp Address of LP * @param _platformAddress Generic platform address * @param _rewardToken Reward token, if any */ constructor( address _nexus, address _lp, address _platformAddress, address _rewardToken ) AbstractIntegration(_nexus, _lp) { require(_platformAddress != address(0), "Invalid platform address"); platformAddress = _platformAddress; rewardToken = _rewardToken; } /*************************************** ADMIN ****************************************/ /** * @dev Approves Liquidator to spend reward tokens */ function approveRewardToken() external onlyGovernor { address liquidator = nexus.getModule(keccak256("Liquidator")); require(liquidator != address(0), "Liquidator address cannot be zero"); MassetHelpers.safeInfiniteApprove(rewardToken, liquidator); emit RewardTokenApproved(rewardToken, liquidator); } /*************************************** CORE ****************************************/ /** * @dev Deposit a quantity of bAsset into the platform. Credited aTokens * remain here in the vault. Can only be called by whitelisted addresses * (mAsset and corresponding BasketManager) * @param _bAsset Address for the bAsset * @param _amount Units of bAsset to deposit * @param _hasTxFee Is the bAsset known to have a tx fee? * @return quantityDeposited Quantity of bAsset that entered the platform */ function deposit( address _bAsset, uint256 _amount, bool _hasTxFee ) external override onlyLP nonReentrant returns (uint256 quantityDeposited) { require(_amount > 0, "Must deposit something"); IAaveATokenV2 aToken = _getATokenFor(_bAsset); quantityDeposited = _amount; if (_hasTxFee) { // If we charge a fee, account for it uint256 prevBal = _checkBalance(aToken); _getLendingPool().deposit(_bAsset, _amount, address(this), 36); uint256 newBal = _checkBalance(aToken); quantityDeposited = _min(quantityDeposited, newBal - prevBal); } else { _getLendingPool().deposit(_bAsset, _amount, address(this), 36); } emit Deposit(_bAsset, address(aToken), quantityDeposited); } /** * @dev Withdraw a quantity of bAsset from the platform * @param _receiver Address to which the bAsset should be sent * @param _bAsset Address of the bAsset * @param _amount Units of bAsset to withdraw * @param _hasTxFee Is the bAsset known to have a tx fee? */ function withdraw( address _receiver, address _bAsset, uint256 _amount, bool _hasTxFee ) external override onlyLP nonReentrant { _withdraw(_receiver, _bAsset, _amount, _amount, _hasTxFee); } /** * @dev Withdraw a quantity of bAsset from the platform * @param _receiver Address to which the bAsset should be sent * @param _bAsset Address of the bAsset * @param _amount Units of bAsset to send to recipient * @param _totalAmount Total units to pull from lending platform * @param _hasTxFee Is the bAsset known to have a tx fee? */ function withdraw( address _receiver, address _bAsset, uint256 _amount, uint256 _totalAmount, bool _hasTxFee ) external override onlyLP nonReentrant { _withdraw(_receiver, _bAsset, _amount, _totalAmount, _hasTxFee); } /** @dev Withdraws _totalAmount from the lending pool, sending _amount to user */ function _withdraw( address _receiver, address _bAsset, uint256 _amount, uint256 _totalAmount, bool _hasTxFee ) internal { require(_totalAmount > 0, "Must withdraw something"); IAaveATokenV2 aToken = _getATokenFor(_bAsset); if (_hasTxFee) { require(_amount == _totalAmount, "Cache inactive for assets with fee"); _getLendingPool().withdraw(_bAsset, _amount, _receiver); } else { _getLendingPool().withdraw(_bAsset, _totalAmount, address(this)); // Send redeemed bAsset to the receiver IERC20(_bAsset).safeTransfer(_receiver, _amount); } emit PlatformWithdrawal(_bAsset, address(aToken), _totalAmount, _amount); } /** * @dev Withdraw a quantity of bAsset from the cache. * @param _receiver Address to which the bAsset should be sent * @param _bAsset Address of the bAsset * @param _amount Units of bAsset to withdraw */ function withdrawRaw( address _receiver, address _bAsset, uint256 _amount ) external override onlyLP nonReentrant { require(_amount > 0, "Must withdraw something"); require(_receiver != address(0), "Must specify recipient"); IERC20(_bAsset).safeTransfer(_receiver, _amount); emit Withdrawal(_bAsset, address(0), _amount); } /** * @dev Get the total bAsset value held in the platform * This includes any interest that was generated since depositing * Aave gradually increases the balances of all aToken holders, as the interest grows * @param _bAsset Address of the bAsset * @return balance Total value of the bAsset in the platform */ function checkBalance(address _bAsset) external view override returns (uint256 balance) { // balance is always with token aToken decimals IAaveATokenV2 aToken = _getATokenFor(_bAsset); return _checkBalance(aToken); } /*************************************** APPROVALS ****************************************/ /** * @dev Internal method to respond to the addition of new bAsset / pTokens * We need to approve the Aave lending pool core conrtact and give it permission * to spend the bAsset * @param _bAsset Address of the bAsset to approve */ function _abstractSetPToken( address _bAsset, address /*_pToken*/ ) internal override { address lendingPool = address(_getLendingPool()); // approve the pool to spend the bAsset MassetHelpers.safeInfiniteApprove(_bAsset, lendingPool); } /*************************************** HELPERS ****************************************/ /** * @dev Get the current address of the Aave lending pool, which is the gateway to * depositing. * @return Current lending pool implementation */ function _getLendingPool() internal view returns (IAaveLendingPoolV2) { address lendingPool = ILendingPoolAddressesProviderV2(platformAddress).getLendingPool(); require(lendingPool != address(0), "Lending pool does not exist"); return IAaveLendingPoolV2(lendingPool); } /** * @dev Get the pToken wrapped in the IAaveAToken interface for this bAsset, to use * for withdrawing or balance checking. Fails if the pToken doesn't exist in our mappings. * @param _bAsset Address of the bAsset * @return aToken Corresponding to this bAsset */ function _getATokenFor(address _bAsset) internal view returns (IAaveATokenV2) { address aToken = bAssetToPToken[_bAsset]; require(aToken != address(0), "aToken does not exist"); return IAaveATokenV2(aToken); } /** * @dev Get the total bAsset value held in the platform * @param _aToken aToken for which to check balance * @return balance Total value of the bAsset in the platform */ function _checkBalance(IAaveATokenV2 _aToken) internal view returns (uint256 balance) { return _aToken.balanceOf(address(this)); } }
/** * @title AaveV2Integration * @author mStable * @notice A simple connection to deposit and withdraw bAssets from Aave * @dev VERSION: 1.0 * DATE: 2020-16-11 */
NatSpecMultiLine
withdraw
function withdraw( address _receiver, address _bAsset, uint256 _amount, uint256 _totalAmount, bool _hasTxFee ) external override onlyLP nonReentrant { _withdraw(_receiver, _bAsset, _amount, _totalAmount, _hasTxFee); }
/** * @dev Withdraw a quantity of bAsset from the platform * @param _receiver Address to which the bAsset should be sent * @param _bAsset Address of the bAsset * @param _amount Units of bAsset to send to recipient * @param _totalAmount Total units to pull from lending platform * @param _hasTxFee Is the bAsset known to have a tx fee? */
NatSpecMultiLine
v0.8.6+commit.11564f7e
{ "func_code_index": [ 3797, 4074 ] }
2,693
PAaveIntegration
contracts/masset/peripheral/AaveV2Integration.sol
0x4094aec22f40f11c29941d144c3dc887b33f5504
Solidity
AaveV2Integration
contract AaveV2Integration is AbstractIntegration { using SafeERC20 for IERC20; // Core address for the given platform */ address public immutable platformAddress; address public immutable rewardToken; event RewardTokenApproved(address rewardToken, address account); /** * @param _nexus Address of the Nexus * @param _lp Address of LP * @param _platformAddress Generic platform address * @param _rewardToken Reward token, if any */ constructor( address _nexus, address _lp, address _platformAddress, address _rewardToken ) AbstractIntegration(_nexus, _lp) { require(_platformAddress != address(0), "Invalid platform address"); platformAddress = _platformAddress; rewardToken = _rewardToken; } /*************************************** ADMIN ****************************************/ /** * @dev Approves Liquidator to spend reward tokens */ function approveRewardToken() external onlyGovernor { address liquidator = nexus.getModule(keccak256("Liquidator")); require(liquidator != address(0), "Liquidator address cannot be zero"); MassetHelpers.safeInfiniteApprove(rewardToken, liquidator); emit RewardTokenApproved(rewardToken, liquidator); } /*************************************** CORE ****************************************/ /** * @dev Deposit a quantity of bAsset into the platform. Credited aTokens * remain here in the vault. Can only be called by whitelisted addresses * (mAsset and corresponding BasketManager) * @param _bAsset Address for the bAsset * @param _amount Units of bAsset to deposit * @param _hasTxFee Is the bAsset known to have a tx fee? * @return quantityDeposited Quantity of bAsset that entered the platform */ function deposit( address _bAsset, uint256 _amount, bool _hasTxFee ) external override onlyLP nonReentrant returns (uint256 quantityDeposited) { require(_amount > 0, "Must deposit something"); IAaveATokenV2 aToken = _getATokenFor(_bAsset); quantityDeposited = _amount; if (_hasTxFee) { // If we charge a fee, account for it uint256 prevBal = _checkBalance(aToken); _getLendingPool().deposit(_bAsset, _amount, address(this), 36); uint256 newBal = _checkBalance(aToken); quantityDeposited = _min(quantityDeposited, newBal - prevBal); } else { _getLendingPool().deposit(_bAsset, _amount, address(this), 36); } emit Deposit(_bAsset, address(aToken), quantityDeposited); } /** * @dev Withdraw a quantity of bAsset from the platform * @param _receiver Address to which the bAsset should be sent * @param _bAsset Address of the bAsset * @param _amount Units of bAsset to withdraw * @param _hasTxFee Is the bAsset known to have a tx fee? */ function withdraw( address _receiver, address _bAsset, uint256 _amount, bool _hasTxFee ) external override onlyLP nonReentrant { _withdraw(_receiver, _bAsset, _amount, _amount, _hasTxFee); } /** * @dev Withdraw a quantity of bAsset from the platform * @param _receiver Address to which the bAsset should be sent * @param _bAsset Address of the bAsset * @param _amount Units of bAsset to send to recipient * @param _totalAmount Total units to pull from lending platform * @param _hasTxFee Is the bAsset known to have a tx fee? */ function withdraw( address _receiver, address _bAsset, uint256 _amount, uint256 _totalAmount, bool _hasTxFee ) external override onlyLP nonReentrant { _withdraw(_receiver, _bAsset, _amount, _totalAmount, _hasTxFee); } /** @dev Withdraws _totalAmount from the lending pool, sending _amount to user */ function _withdraw( address _receiver, address _bAsset, uint256 _amount, uint256 _totalAmount, bool _hasTxFee ) internal { require(_totalAmount > 0, "Must withdraw something"); IAaveATokenV2 aToken = _getATokenFor(_bAsset); if (_hasTxFee) { require(_amount == _totalAmount, "Cache inactive for assets with fee"); _getLendingPool().withdraw(_bAsset, _amount, _receiver); } else { _getLendingPool().withdraw(_bAsset, _totalAmount, address(this)); // Send redeemed bAsset to the receiver IERC20(_bAsset).safeTransfer(_receiver, _amount); } emit PlatformWithdrawal(_bAsset, address(aToken), _totalAmount, _amount); } /** * @dev Withdraw a quantity of bAsset from the cache. * @param _receiver Address to which the bAsset should be sent * @param _bAsset Address of the bAsset * @param _amount Units of bAsset to withdraw */ function withdrawRaw( address _receiver, address _bAsset, uint256 _amount ) external override onlyLP nonReentrant { require(_amount > 0, "Must withdraw something"); require(_receiver != address(0), "Must specify recipient"); IERC20(_bAsset).safeTransfer(_receiver, _amount); emit Withdrawal(_bAsset, address(0), _amount); } /** * @dev Get the total bAsset value held in the platform * This includes any interest that was generated since depositing * Aave gradually increases the balances of all aToken holders, as the interest grows * @param _bAsset Address of the bAsset * @return balance Total value of the bAsset in the platform */ function checkBalance(address _bAsset) external view override returns (uint256 balance) { // balance is always with token aToken decimals IAaveATokenV2 aToken = _getATokenFor(_bAsset); return _checkBalance(aToken); } /*************************************** APPROVALS ****************************************/ /** * @dev Internal method to respond to the addition of new bAsset / pTokens * We need to approve the Aave lending pool core conrtact and give it permission * to spend the bAsset * @param _bAsset Address of the bAsset to approve */ function _abstractSetPToken( address _bAsset, address /*_pToken*/ ) internal override { address lendingPool = address(_getLendingPool()); // approve the pool to spend the bAsset MassetHelpers.safeInfiniteApprove(_bAsset, lendingPool); } /*************************************** HELPERS ****************************************/ /** * @dev Get the current address of the Aave lending pool, which is the gateway to * depositing. * @return Current lending pool implementation */ function _getLendingPool() internal view returns (IAaveLendingPoolV2) { address lendingPool = ILendingPoolAddressesProviderV2(platformAddress).getLendingPool(); require(lendingPool != address(0), "Lending pool does not exist"); return IAaveLendingPoolV2(lendingPool); } /** * @dev Get the pToken wrapped in the IAaveAToken interface for this bAsset, to use * for withdrawing or balance checking. Fails if the pToken doesn't exist in our mappings. * @param _bAsset Address of the bAsset * @return aToken Corresponding to this bAsset */ function _getATokenFor(address _bAsset) internal view returns (IAaveATokenV2) { address aToken = bAssetToPToken[_bAsset]; require(aToken != address(0), "aToken does not exist"); return IAaveATokenV2(aToken); } /** * @dev Get the total bAsset value held in the platform * @param _aToken aToken for which to check balance * @return balance Total value of the bAsset in the platform */ function _checkBalance(IAaveATokenV2 _aToken) internal view returns (uint256 balance) { return _aToken.balanceOf(address(this)); } }
/** * @title AaveV2Integration * @author mStable * @notice A simple connection to deposit and withdraw bAssets from Aave * @dev VERSION: 1.0 * DATE: 2020-16-11 */
NatSpecMultiLine
_withdraw
function _withdraw( address _receiver, address _bAsset, uint256 _amount, uint256 _totalAmount, bool _hasTxFee ) internal { require(_totalAmount > 0, "Must withdraw something"); IAaveATokenV2 aToken = _getATokenFor(_bAsset); if (_hasTxFee) { require(_amount == _totalAmount, "Cache inactive for assets with fee"); _getLendingPool().withdraw(_bAsset, _amount, _receiver); } else { _getLendingPool().withdraw(_bAsset, _totalAmount, address(this)); // Send redeemed bAsset to the receiver IERC20(_bAsset).safeTransfer(_receiver, _amount); } emit PlatformWithdrawal(_bAsset, address(aToken), _totalAmount, _amount); }
/** @dev Withdraws _totalAmount from the lending pool, sending _amount to user */
NatSpecMultiLine
v0.8.6+commit.11564f7e
{ "func_code_index": [ 4162, 4937 ] }
2,694
PAaveIntegration
contracts/masset/peripheral/AaveV2Integration.sol
0x4094aec22f40f11c29941d144c3dc887b33f5504
Solidity
AaveV2Integration
contract AaveV2Integration is AbstractIntegration { using SafeERC20 for IERC20; // Core address for the given platform */ address public immutable platformAddress; address public immutable rewardToken; event RewardTokenApproved(address rewardToken, address account); /** * @param _nexus Address of the Nexus * @param _lp Address of LP * @param _platformAddress Generic platform address * @param _rewardToken Reward token, if any */ constructor( address _nexus, address _lp, address _platformAddress, address _rewardToken ) AbstractIntegration(_nexus, _lp) { require(_platformAddress != address(0), "Invalid platform address"); platformAddress = _platformAddress; rewardToken = _rewardToken; } /*************************************** ADMIN ****************************************/ /** * @dev Approves Liquidator to spend reward tokens */ function approveRewardToken() external onlyGovernor { address liquidator = nexus.getModule(keccak256("Liquidator")); require(liquidator != address(0), "Liquidator address cannot be zero"); MassetHelpers.safeInfiniteApprove(rewardToken, liquidator); emit RewardTokenApproved(rewardToken, liquidator); } /*************************************** CORE ****************************************/ /** * @dev Deposit a quantity of bAsset into the platform. Credited aTokens * remain here in the vault. Can only be called by whitelisted addresses * (mAsset and corresponding BasketManager) * @param _bAsset Address for the bAsset * @param _amount Units of bAsset to deposit * @param _hasTxFee Is the bAsset known to have a tx fee? * @return quantityDeposited Quantity of bAsset that entered the platform */ function deposit( address _bAsset, uint256 _amount, bool _hasTxFee ) external override onlyLP nonReentrant returns (uint256 quantityDeposited) { require(_amount > 0, "Must deposit something"); IAaveATokenV2 aToken = _getATokenFor(_bAsset); quantityDeposited = _amount; if (_hasTxFee) { // If we charge a fee, account for it uint256 prevBal = _checkBalance(aToken); _getLendingPool().deposit(_bAsset, _amount, address(this), 36); uint256 newBal = _checkBalance(aToken); quantityDeposited = _min(quantityDeposited, newBal - prevBal); } else { _getLendingPool().deposit(_bAsset, _amount, address(this), 36); } emit Deposit(_bAsset, address(aToken), quantityDeposited); } /** * @dev Withdraw a quantity of bAsset from the platform * @param _receiver Address to which the bAsset should be sent * @param _bAsset Address of the bAsset * @param _amount Units of bAsset to withdraw * @param _hasTxFee Is the bAsset known to have a tx fee? */ function withdraw( address _receiver, address _bAsset, uint256 _amount, bool _hasTxFee ) external override onlyLP nonReentrant { _withdraw(_receiver, _bAsset, _amount, _amount, _hasTxFee); } /** * @dev Withdraw a quantity of bAsset from the platform * @param _receiver Address to which the bAsset should be sent * @param _bAsset Address of the bAsset * @param _amount Units of bAsset to send to recipient * @param _totalAmount Total units to pull from lending platform * @param _hasTxFee Is the bAsset known to have a tx fee? */ function withdraw( address _receiver, address _bAsset, uint256 _amount, uint256 _totalAmount, bool _hasTxFee ) external override onlyLP nonReentrant { _withdraw(_receiver, _bAsset, _amount, _totalAmount, _hasTxFee); } /** @dev Withdraws _totalAmount from the lending pool, sending _amount to user */ function _withdraw( address _receiver, address _bAsset, uint256 _amount, uint256 _totalAmount, bool _hasTxFee ) internal { require(_totalAmount > 0, "Must withdraw something"); IAaveATokenV2 aToken = _getATokenFor(_bAsset); if (_hasTxFee) { require(_amount == _totalAmount, "Cache inactive for assets with fee"); _getLendingPool().withdraw(_bAsset, _amount, _receiver); } else { _getLendingPool().withdraw(_bAsset, _totalAmount, address(this)); // Send redeemed bAsset to the receiver IERC20(_bAsset).safeTransfer(_receiver, _amount); } emit PlatformWithdrawal(_bAsset, address(aToken), _totalAmount, _amount); } /** * @dev Withdraw a quantity of bAsset from the cache. * @param _receiver Address to which the bAsset should be sent * @param _bAsset Address of the bAsset * @param _amount Units of bAsset to withdraw */ function withdrawRaw( address _receiver, address _bAsset, uint256 _amount ) external override onlyLP nonReentrant { require(_amount > 0, "Must withdraw something"); require(_receiver != address(0), "Must specify recipient"); IERC20(_bAsset).safeTransfer(_receiver, _amount); emit Withdrawal(_bAsset, address(0), _amount); } /** * @dev Get the total bAsset value held in the platform * This includes any interest that was generated since depositing * Aave gradually increases the balances of all aToken holders, as the interest grows * @param _bAsset Address of the bAsset * @return balance Total value of the bAsset in the platform */ function checkBalance(address _bAsset) external view override returns (uint256 balance) { // balance is always with token aToken decimals IAaveATokenV2 aToken = _getATokenFor(_bAsset); return _checkBalance(aToken); } /*************************************** APPROVALS ****************************************/ /** * @dev Internal method to respond to the addition of new bAsset / pTokens * We need to approve the Aave lending pool core conrtact and give it permission * to spend the bAsset * @param _bAsset Address of the bAsset to approve */ function _abstractSetPToken( address _bAsset, address /*_pToken*/ ) internal override { address lendingPool = address(_getLendingPool()); // approve the pool to spend the bAsset MassetHelpers.safeInfiniteApprove(_bAsset, lendingPool); } /*************************************** HELPERS ****************************************/ /** * @dev Get the current address of the Aave lending pool, which is the gateway to * depositing. * @return Current lending pool implementation */ function _getLendingPool() internal view returns (IAaveLendingPoolV2) { address lendingPool = ILendingPoolAddressesProviderV2(platformAddress).getLendingPool(); require(lendingPool != address(0), "Lending pool does not exist"); return IAaveLendingPoolV2(lendingPool); } /** * @dev Get the pToken wrapped in the IAaveAToken interface for this bAsset, to use * for withdrawing or balance checking. Fails if the pToken doesn't exist in our mappings. * @param _bAsset Address of the bAsset * @return aToken Corresponding to this bAsset */ function _getATokenFor(address _bAsset) internal view returns (IAaveATokenV2) { address aToken = bAssetToPToken[_bAsset]; require(aToken != address(0), "aToken does not exist"); return IAaveATokenV2(aToken); } /** * @dev Get the total bAsset value held in the platform * @param _aToken aToken for which to check balance * @return balance Total value of the bAsset in the platform */ function _checkBalance(IAaveATokenV2 _aToken) internal view returns (uint256 balance) { return _aToken.balanceOf(address(this)); } }
/** * @title AaveV2Integration * @author mStable * @notice A simple connection to deposit and withdraw bAssets from Aave * @dev VERSION: 1.0 * DATE: 2020-16-11 */
NatSpecMultiLine
withdrawRaw
function withdrawRaw( address _receiver, address _bAsset, uint256 _amount ) external override onlyLP nonReentrant { require(_amount > 0, "Must withdraw something"); require(_receiver != address(0), "Must specify recipient"); IERC20(_bAsset).safeTransfer(_receiver, _amount); emit Withdrawal(_bAsset, address(0), _amount); }
/** * @dev Withdraw a quantity of bAsset from the cache. * @param _receiver Address to which the bAsset should be sent * @param _bAsset Address of the bAsset * @param _amount Units of bAsset to withdraw */
NatSpecMultiLine
v0.8.6+commit.11564f7e
{ "func_code_index": [ 5190, 5583 ] }
2,695
PAaveIntegration
contracts/masset/peripheral/AaveV2Integration.sol
0x4094aec22f40f11c29941d144c3dc887b33f5504
Solidity
AaveV2Integration
contract AaveV2Integration is AbstractIntegration { using SafeERC20 for IERC20; // Core address for the given platform */ address public immutable platformAddress; address public immutable rewardToken; event RewardTokenApproved(address rewardToken, address account); /** * @param _nexus Address of the Nexus * @param _lp Address of LP * @param _platformAddress Generic platform address * @param _rewardToken Reward token, if any */ constructor( address _nexus, address _lp, address _platformAddress, address _rewardToken ) AbstractIntegration(_nexus, _lp) { require(_platformAddress != address(0), "Invalid platform address"); platformAddress = _platformAddress; rewardToken = _rewardToken; } /*************************************** ADMIN ****************************************/ /** * @dev Approves Liquidator to spend reward tokens */ function approveRewardToken() external onlyGovernor { address liquidator = nexus.getModule(keccak256("Liquidator")); require(liquidator != address(0), "Liquidator address cannot be zero"); MassetHelpers.safeInfiniteApprove(rewardToken, liquidator); emit RewardTokenApproved(rewardToken, liquidator); } /*************************************** CORE ****************************************/ /** * @dev Deposit a quantity of bAsset into the platform. Credited aTokens * remain here in the vault. Can only be called by whitelisted addresses * (mAsset and corresponding BasketManager) * @param _bAsset Address for the bAsset * @param _amount Units of bAsset to deposit * @param _hasTxFee Is the bAsset known to have a tx fee? * @return quantityDeposited Quantity of bAsset that entered the platform */ function deposit( address _bAsset, uint256 _amount, bool _hasTxFee ) external override onlyLP nonReentrant returns (uint256 quantityDeposited) { require(_amount > 0, "Must deposit something"); IAaveATokenV2 aToken = _getATokenFor(_bAsset); quantityDeposited = _amount; if (_hasTxFee) { // If we charge a fee, account for it uint256 prevBal = _checkBalance(aToken); _getLendingPool().deposit(_bAsset, _amount, address(this), 36); uint256 newBal = _checkBalance(aToken); quantityDeposited = _min(quantityDeposited, newBal - prevBal); } else { _getLendingPool().deposit(_bAsset, _amount, address(this), 36); } emit Deposit(_bAsset, address(aToken), quantityDeposited); } /** * @dev Withdraw a quantity of bAsset from the platform * @param _receiver Address to which the bAsset should be sent * @param _bAsset Address of the bAsset * @param _amount Units of bAsset to withdraw * @param _hasTxFee Is the bAsset known to have a tx fee? */ function withdraw( address _receiver, address _bAsset, uint256 _amount, bool _hasTxFee ) external override onlyLP nonReentrant { _withdraw(_receiver, _bAsset, _amount, _amount, _hasTxFee); } /** * @dev Withdraw a quantity of bAsset from the platform * @param _receiver Address to which the bAsset should be sent * @param _bAsset Address of the bAsset * @param _amount Units of bAsset to send to recipient * @param _totalAmount Total units to pull from lending platform * @param _hasTxFee Is the bAsset known to have a tx fee? */ function withdraw( address _receiver, address _bAsset, uint256 _amount, uint256 _totalAmount, bool _hasTxFee ) external override onlyLP nonReentrant { _withdraw(_receiver, _bAsset, _amount, _totalAmount, _hasTxFee); } /** @dev Withdraws _totalAmount from the lending pool, sending _amount to user */ function _withdraw( address _receiver, address _bAsset, uint256 _amount, uint256 _totalAmount, bool _hasTxFee ) internal { require(_totalAmount > 0, "Must withdraw something"); IAaveATokenV2 aToken = _getATokenFor(_bAsset); if (_hasTxFee) { require(_amount == _totalAmount, "Cache inactive for assets with fee"); _getLendingPool().withdraw(_bAsset, _amount, _receiver); } else { _getLendingPool().withdraw(_bAsset, _totalAmount, address(this)); // Send redeemed bAsset to the receiver IERC20(_bAsset).safeTransfer(_receiver, _amount); } emit PlatformWithdrawal(_bAsset, address(aToken), _totalAmount, _amount); } /** * @dev Withdraw a quantity of bAsset from the cache. * @param _receiver Address to which the bAsset should be sent * @param _bAsset Address of the bAsset * @param _amount Units of bAsset to withdraw */ function withdrawRaw( address _receiver, address _bAsset, uint256 _amount ) external override onlyLP nonReentrant { require(_amount > 0, "Must withdraw something"); require(_receiver != address(0), "Must specify recipient"); IERC20(_bAsset).safeTransfer(_receiver, _amount); emit Withdrawal(_bAsset, address(0), _amount); } /** * @dev Get the total bAsset value held in the platform * This includes any interest that was generated since depositing * Aave gradually increases the balances of all aToken holders, as the interest grows * @param _bAsset Address of the bAsset * @return balance Total value of the bAsset in the platform */ function checkBalance(address _bAsset) external view override returns (uint256 balance) { // balance is always with token aToken decimals IAaveATokenV2 aToken = _getATokenFor(_bAsset); return _checkBalance(aToken); } /*************************************** APPROVALS ****************************************/ /** * @dev Internal method to respond to the addition of new bAsset / pTokens * We need to approve the Aave lending pool core conrtact and give it permission * to spend the bAsset * @param _bAsset Address of the bAsset to approve */ function _abstractSetPToken( address _bAsset, address /*_pToken*/ ) internal override { address lendingPool = address(_getLendingPool()); // approve the pool to spend the bAsset MassetHelpers.safeInfiniteApprove(_bAsset, lendingPool); } /*************************************** HELPERS ****************************************/ /** * @dev Get the current address of the Aave lending pool, which is the gateway to * depositing. * @return Current lending pool implementation */ function _getLendingPool() internal view returns (IAaveLendingPoolV2) { address lendingPool = ILendingPoolAddressesProviderV2(platformAddress).getLendingPool(); require(lendingPool != address(0), "Lending pool does not exist"); return IAaveLendingPoolV2(lendingPool); } /** * @dev Get the pToken wrapped in the IAaveAToken interface for this bAsset, to use * for withdrawing or balance checking. Fails if the pToken doesn't exist in our mappings. * @param _bAsset Address of the bAsset * @return aToken Corresponding to this bAsset */ function _getATokenFor(address _bAsset) internal view returns (IAaveATokenV2) { address aToken = bAssetToPToken[_bAsset]; require(aToken != address(0), "aToken does not exist"); return IAaveATokenV2(aToken); } /** * @dev Get the total bAsset value held in the platform * @param _aToken aToken for which to check balance * @return balance Total value of the bAsset in the platform */ function _checkBalance(IAaveATokenV2 _aToken) internal view returns (uint256 balance) { return _aToken.balanceOf(address(this)); } }
/** * @title AaveV2Integration * @author mStable * @notice A simple connection to deposit and withdraw bAssets from Aave * @dev VERSION: 1.0 * DATE: 2020-16-11 */
NatSpecMultiLine
checkBalance
function checkBalance(address _bAsset) external view override returns (uint256 balance) { // balance is always with token aToken decimals IAaveATokenV2 aToken = _getATokenFor(_bAsset); return _checkBalance(aToken); }
/** * @dev Get the total bAsset value held in the platform * This includes any interest that was generated since depositing * Aave gradually increases the balances of all aToken holders, as the interest grows * @param _bAsset Address of the bAsset * @return balance Total value of the bAsset in the platform */
NatSpecMultiLine
v0.8.6+commit.11564f7e
{ "func_code_index": [ 5947, 6195 ] }
2,696
PAaveIntegration
contracts/masset/peripheral/AaveV2Integration.sol
0x4094aec22f40f11c29941d144c3dc887b33f5504
Solidity
AaveV2Integration
contract AaveV2Integration is AbstractIntegration { using SafeERC20 for IERC20; // Core address for the given platform */ address public immutable platformAddress; address public immutable rewardToken; event RewardTokenApproved(address rewardToken, address account); /** * @param _nexus Address of the Nexus * @param _lp Address of LP * @param _platformAddress Generic platform address * @param _rewardToken Reward token, if any */ constructor( address _nexus, address _lp, address _platformAddress, address _rewardToken ) AbstractIntegration(_nexus, _lp) { require(_platformAddress != address(0), "Invalid platform address"); platformAddress = _platformAddress; rewardToken = _rewardToken; } /*************************************** ADMIN ****************************************/ /** * @dev Approves Liquidator to spend reward tokens */ function approveRewardToken() external onlyGovernor { address liquidator = nexus.getModule(keccak256("Liquidator")); require(liquidator != address(0), "Liquidator address cannot be zero"); MassetHelpers.safeInfiniteApprove(rewardToken, liquidator); emit RewardTokenApproved(rewardToken, liquidator); } /*************************************** CORE ****************************************/ /** * @dev Deposit a quantity of bAsset into the platform. Credited aTokens * remain here in the vault. Can only be called by whitelisted addresses * (mAsset and corresponding BasketManager) * @param _bAsset Address for the bAsset * @param _amount Units of bAsset to deposit * @param _hasTxFee Is the bAsset known to have a tx fee? * @return quantityDeposited Quantity of bAsset that entered the platform */ function deposit( address _bAsset, uint256 _amount, bool _hasTxFee ) external override onlyLP nonReentrant returns (uint256 quantityDeposited) { require(_amount > 0, "Must deposit something"); IAaveATokenV2 aToken = _getATokenFor(_bAsset); quantityDeposited = _amount; if (_hasTxFee) { // If we charge a fee, account for it uint256 prevBal = _checkBalance(aToken); _getLendingPool().deposit(_bAsset, _amount, address(this), 36); uint256 newBal = _checkBalance(aToken); quantityDeposited = _min(quantityDeposited, newBal - prevBal); } else { _getLendingPool().deposit(_bAsset, _amount, address(this), 36); } emit Deposit(_bAsset, address(aToken), quantityDeposited); } /** * @dev Withdraw a quantity of bAsset from the platform * @param _receiver Address to which the bAsset should be sent * @param _bAsset Address of the bAsset * @param _amount Units of bAsset to withdraw * @param _hasTxFee Is the bAsset known to have a tx fee? */ function withdraw( address _receiver, address _bAsset, uint256 _amount, bool _hasTxFee ) external override onlyLP nonReentrant { _withdraw(_receiver, _bAsset, _amount, _amount, _hasTxFee); } /** * @dev Withdraw a quantity of bAsset from the platform * @param _receiver Address to which the bAsset should be sent * @param _bAsset Address of the bAsset * @param _amount Units of bAsset to send to recipient * @param _totalAmount Total units to pull from lending platform * @param _hasTxFee Is the bAsset known to have a tx fee? */ function withdraw( address _receiver, address _bAsset, uint256 _amount, uint256 _totalAmount, bool _hasTxFee ) external override onlyLP nonReentrant { _withdraw(_receiver, _bAsset, _amount, _totalAmount, _hasTxFee); } /** @dev Withdraws _totalAmount from the lending pool, sending _amount to user */ function _withdraw( address _receiver, address _bAsset, uint256 _amount, uint256 _totalAmount, bool _hasTxFee ) internal { require(_totalAmount > 0, "Must withdraw something"); IAaveATokenV2 aToken = _getATokenFor(_bAsset); if (_hasTxFee) { require(_amount == _totalAmount, "Cache inactive for assets with fee"); _getLendingPool().withdraw(_bAsset, _amount, _receiver); } else { _getLendingPool().withdraw(_bAsset, _totalAmount, address(this)); // Send redeemed bAsset to the receiver IERC20(_bAsset).safeTransfer(_receiver, _amount); } emit PlatformWithdrawal(_bAsset, address(aToken), _totalAmount, _amount); } /** * @dev Withdraw a quantity of bAsset from the cache. * @param _receiver Address to which the bAsset should be sent * @param _bAsset Address of the bAsset * @param _amount Units of bAsset to withdraw */ function withdrawRaw( address _receiver, address _bAsset, uint256 _amount ) external override onlyLP nonReentrant { require(_amount > 0, "Must withdraw something"); require(_receiver != address(0), "Must specify recipient"); IERC20(_bAsset).safeTransfer(_receiver, _amount); emit Withdrawal(_bAsset, address(0), _amount); } /** * @dev Get the total bAsset value held in the platform * This includes any interest that was generated since depositing * Aave gradually increases the balances of all aToken holders, as the interest grows * @param _bAsset Address of the bAsset * @return balance Total value of the bAsset in the platform */ function checkBalance(address _bAsset) external view override returns (uint256 balance) { // balance is always with token aToken decimals IAaveATokenV2 aToken = _getATokenFor(_bAsset); return _checkBalance(aToken); } /*************************************** APPROVALS ****************************************/ /** * @dev Internal method to respond to the addition of new bAsset / pTokens * We need to approve the Aave lending pool core conrtact and give it permission * to spend the bAsset * @param _bAsset Address of the bAsset to approve */ function _abstractSetPToken( address _bAsset, address /*_pToken*/ ) internal override { address lendingPool = address(_getLendingPool()); // approve the pool to spend the bAsset MassetHelpers.safeInfiniteApprove(_bAsset, lendingPool); } /*************************************** HELPERS ****************************************/ /** * @dev Get the current address of the Aave lending pool, which is the gateway to * depositing. * @return Current lending pool implementation */ function _getLendingPool() internal view returns (IAaveLendingPoolV2) { address lendingPool = ILendingPoolAddressesProviderV2(platformAddress).getLendingPool(); require(lendingPool != address(0), "Lending pool does not exist"); return IAaveLendingPoolV2(lendingPool); } /** * @dev Get the pToken wrapped in the IAaveAToken interface for this bAsset, to use * for withdrawing or balance checking. Fails if the pToken doesn't exist in our mappings. * @param _bAsset Address of the bAsset * @return aToken Corresponding to this bAsset */ function _getATokenFor(address _bAsset) internal view returns (IAaveATokenV2) { address aToken = bAssetToPToken[_bAsset]; require(aToken != address(0), "aToken does not exist"); return IAaveATokenV2(aToken); } /** * @dev Get the total bAsset value held in the platform * @param _aToken aToken for which to check balance * @return balance Total value of the bAsset in the platform */ function _checkBalance(IAaveATokenV2 _aToken) internal view returns (uint256 balance) { return _aToken.balanceOf(address(this)); } }
/** * @title AaveV2Integration * @author mStable * @notice A simple connection to deposit and withdraw bAssets from Aave * @dev VERSION: 1.0 * DATE: 2020-16-11 */
NatSpecMultiLine
_abstractSetPToken
function _abstractSetPToken( address _bAsset, address /*_pToken*/ ) internal override { address lendingPool = address(_getLendingPool()); // approve the pool to spend the bAsset MassetHelpers.safeInfiniteApprove(_bAsset, lendingPool); }
/** * @dev Internal method to respond to the addition of new bAsset / pTokens * We need to approve the Aave lending pool core conrtact and give it permission * to spend the bAsset * @param _bAsset Address of the bAsset to approve */
NatSpecMultiLine
v0.8.6+commit.11564f7e
{ "func_code_index": [ 6591, 6879 ] }
2,697
PAaveIntegration
contracts/masset/peripheral/AaveV2Integration.sol
0x4094aec22f40f11c29941d144c3dc887b33f5504
Solidity
AaveV2Integration
contract AaveV2Integration is AbstractIntegration { using SafeERC20 for IERC20; // Core address for the given platform */ address public immutable platformAddress; address public immutable rewardToken; event RewardTokenApproved(address rewardToken, address account); /** * @param _nexus Address of the Nexus * @param _lp Address of LP * @param _platformAddress Generic platform address * @param _rewardToken Reward token, if any */ constructor( address _nexus, address _lp, address _platformAddress, address _rewardToken ) AbstractIntegration(_nexus, _lp) { require(_platformAddress != address(0), "Invalid platform address"); platformAddress = _platformAddress; rewardToken = _rewardToken; } /*************************************** ADMIN ****************************************/ /** * @dev Approves Liquidator to spend reward tokens */ function approveRewardToken() external onlyGovernor { address liquidator = nexus.getModule(keccak256("Liquidator")); require(liquidator != address(0), "Liquidator address cannot be zero"); MassetHelpers.safeInfiniteApprove(rewardToken, liquidator); emit RewardTokenApproved(rewardToken, liquidator); } /*************************************** CORE ****************************************/ /** * @dev Deposit a quantity of bAsset into the platform. Credited aTokens * remain here in the vault. Can only be called by whitelisted addresses * (mAsset and corresponding BasketManager) * @param _bAsset Address for the bAsset * @param _amount Units of bAsset to deposit * @param _hasTxFee Is the bAsset known to have a tx fee? * @return quantityDeposited Quantity of bAsset that entered the platform */ function deposit( address _bAsset, uint256 _amount, bool _hasTxFee ) external override onlyLP nonReentrant returns (uint256 quantityDeposited) { require(_amount > 0, "Must deposit something"); IAaveATokenV2 aToken = _getATokenFor(_bAsset); quantityDeposited = _amount; if (_hasTxFee) { // If we charge a fee, account for it uint256 prevBal = _checkBalance(aToken); _getLendingPool().deposit(_bAsset, _amount, address(this), 36); uint256 newBal = _checkBalance(aToken); quantityDeposited = _min(quantityDeposited, newBal - prevBal); } else { _getLendingPool().deposit(_bAsset, _amount, address(this), 36); } emit Deposit(_bAsset, address(aToken), quantityDeposited); } /** * @dev Withdraw a quantity of bAsset from the platform * @param _receiver Address to which the bAsset should be sent * @param _bAsset Address of the bAsset * @param _amount Units of bAsset to withdraw * @param _hasTxFee Is the bAsset known to have a tx fee? */ function withdraw( address _receiver, address _bAsset, uint256 _amount, bool _hasTxFee ) external override onlyLP nonReentrant { _withdraw(_receiver, _bAsset, _amount, _amount, _hasTxFee); } /** * @dev Withdraw a quantity of bAsset from the platform * @param _receiver Address to which the bAsset should be sent * @param _bAsset Address of the bAsset * @param _amount Units of bAsset to send to recipient * @param _totalAmount Total units to pull from lending platform * @param _hasTxFee Is the bAsset known to have a tx fee? */ function withdraw( address _receiver, address _bAsset, uint256 _amount, uint256 _totalAmount, bool _hasTxFee ) external override onlyLP nonReentrant { _withdraw(_receiver, _bAsset, _amount, _totalAmount, _hasTxFee); } /** @dev Withdraws _totalAmount from the lending pool, sending _amount to user */ function _withdraw( address _receiver, address _bAsset, uint256 _amount, uint256 _totalAmount, bool _hasTxFee ) internal { require(_totalAmount > 0, "Must withdraw something"); IAaveATokenV2 aToken = _getATokenFor(_bAsset); if (_hasTxFee) { require(_amount == _totalAmount, "Cache inactive for assets with fee"); _getLendingPool().withdraw(_bAsset, _amount, _receiver); } else { _getLendingPool().withdraw(_bAsset, _totalAmount, address(this)); // Send redeemed bAsset to the receiver IERC20(_bAsset).safeTransfer(_receiver, _amount); } emit PlatformWithdrawal(_bAsset, address(aToken), _totalAmount, _amount); } /** * @dev Withdraw a quantity of bAsset from the cache. * @param _receiver Address to which the bAsset should be sent * @param _bAsset Address of the bAsset * @param _amount Units of bAsset to withdraw */ function withdrawRaw( address _receiver, address _bAsset, uint256 _amount ) external override onlyLP nonReentrant { require(_amount > 0, "Must withdraw something"); require(_receiver != address(0), "Must specify recipient"); IERC20(_bAsset).safeTransfer(_receiver, _amount); emit Withdrawal(_bAsset, address(0), _amount); } /** * @dev Get the total bAsset value held in the platform * This includes any interest that was generated since depositing * Aave gradually increases the balances of all aToken holders, as the interest grows * @param _bAsset Address of the bAsset * @return balance Total value of the bAsset in the platform */ function checkBalance(address _bAsset) external view override returns (uint256 balance) { // balance is always with token aToken decimals IAaveATokenV2 aToken = _getATokenFor(_bAsset); return _checkBalance(aToken); } /*************************************** APPROVALS ****************************************/ /** * @dev Internal method to respond to the addition of new bAsset / pTokens * We need to approve the Aave lending pool core conrtact and give it permission * to spend the bAsset * @param _bAsset Address of the bAsset to approve */ function _abstractSetPToken( address _bAsset, address /*_pToken*/ ) internal override { address lendingPool = address(_getLendingPool()); // approve the pool to spend the bAsset MassetHelpers.safeInfiniteApprove(_bAsset, lendingPool); } /*************************************** HELPERS ****************************************/ /** * @dev Get the current address of the Aave lending pool, which is the gateway to * depositing. * @return Current lending pool implementation */ function _getLendingPool() internal view returns (IAaveLendingPoolV2) { address lendingPool = ILendingPoolAddressesProviderV2(platformAddress).getLendingPool(); require(lendingPool != address(0), "Lending pool does not exist"); return IAaveLendingPoolV2(lendingPool); } /** * @dev Get the pToken wrapped in the IAaveAToken interface for this bAsset, to use * for withdrawing or balance checking. Fails if the pToken doesn't exist in our mappings. * @param _bAsset Address of the bAsset * @return aToken Corresponding to this bAsset */ function _getATokenFor(address _bAsset) internal view returns (IAaveATokenV2) { address aToken = bAssetToPToken[_bAsset]; require(aToken != address(0), "aToken does not exist"); return IAaveATokenV2(aToken); } /** * @dev Get the total bAsset value held in the platform * @param _aToken aToken for which to check balance * @return balance Total value of the bAsset in the platform */ function _checkBalance(IAaveATokenV2 _aToken) internal view returns (uint256 balance) { return _aToken.balanceOf(address(this)); } }
/** * @title AaveV2Integration * @author mStable * @notice A simple connection to deposit and withdraw bAssets from Aave * @dev VERSION: 1.0 * DATE: 2020-16-11 */
NatSpecMultiLine
_getLendingPool
function _getLendingPool() internal view returns (IAaveLendingPoolV2) { address lendingPool = ILendingPoolAddressesProviderV2(platformAddress).getLendingPool(); require(lendingPool != address(0), "Lending pool does not exist"); return IAaveLendingPoolV2(lendingPool); }
/** * @dev Get the current address of the Aave lending pool, which is the gateway to * depositing. * @return Current lending pool implementation */
NatSpecMultiLine
v0.8.6+commit.11564f7e
{ "func_code_index": [ 7178, 7479 ] }
2,698
PAaveIntegration
contracts/masset/peripheral/AaveV2Integration.sol
0x4094aec22f40f11c29941d144c3dc887b33f5504
Solidity
AaveV2Integration
contract AaveV2Integration is AbstractIntegration { using SafeERC20 for IERC20; // Core address for the given platform */ address public immutable platformAddress; address public immutable rewardToken; event RewardTokenApproved(address rewardToken, address account); /** * @param _nexus Address of the Nexus * @param _lp Address of LP * @param _platformAddress Generic platform address * @param _rewardToken Reward token, if any */ constructor( address _nexus, address _lp, address _platformAddress, address _rewardToken ) AbstractIntegration(_nexus, _lp) { require(_platformAddress != address(0), "Invalid platform address"); platformAddress = _platformAddress; rewardToken = _rewardToken; } /*************************************** ADMIN ****************************************/ /** * @dev Approves Liquidator to spend reward tokens */ function approveRewardToken() external onlyGovernor { address liquidator = nexus.getModule(keccak256("Liquidator")); require(liquidator != address(0), "Liquidator address cannot be zero"); MassetHelpers.safeInfiniteApprove(rewardToken, liquidator); emit RewardTokenApproved(rewardToken, liquidator); } /*************************************** CORE ****************************************/ /** * @dev Deposit a quantity of bAsset into the platform. Credited aTokens * remain here in the vault. Can only be called by whitelisted addresses * (mAsset and corresponding BasketManager) * @param _bAsset Address for the bAsset * @param _amount Units of bAsset to deposit * @param _hasTxFee Is the bAsset known to have a tx fee? * @return quantityDeposited Quantity of bAsset that entered the platform */ function deposit( address _bAsset, uint256 _amount, bool _hasTxFee ) external override onlyLP nonReentrant returns (uint256 quantityDeposited) { require(_amount > 0, "Must deposit something"); IAaveATokenV2 aToken = _getATokenFor(_bAsset); quantityDeposited = _amount; if (_hasTxFee) { // If we charge a fee, account for it uint256 prevBal = _checkBalance(aToken); _getLendingPool().deposit(_bAsset, _amount, address(this), 36); uint256 newBal = _checkBalance(aToken); quantityDeposited = _min(quantityDeposited, newBal - prevBal); } else { _getLendingPool().deposit(_bAsset, _amount, address(this), 36); } emit Deposit(_bAsset, address(aToken), quantityDeposited); } /** * @dev Withdraw a quantity of bAsset from the platform * @param _receiver Address to which the bAsset should be sent * @param _bAsset Address of the bAsset * @param _amount Units of bAsset to withdraw * @param _hasTxFee Is the bAsset known to have a tx fee? */ function withdraw( address _receiver, address _bAsset, uint256 _amount, bool _hasTxFee ) external override onlyLP nonReentrant { _withdraw(_receiver, _bAsset, _amount, _amount, _hasTxFee); } /** * @dev Withdraw a quantity of bAsset from the platform * @param _receiver Address to which the bAsset should be sent * @param _bAsset Address of the bAsset * @param _amount Units of bAsset to send to recipient * @param _totalAmount Total units to pull from lending platform * @param _hasTxFee Is the bAsset known to have a tx fee? */ function withdraw( address _receiver, address _bAsset, uint256 _amount, uint256 _totalAmount, bool _hasTxFee ) external override onlyLP nonReentrant { _withdraw(_receiver, _bAsset, _amount, _totalAmount, _hasTxFee); } /** @dev Withdraws _totalAmount from the lending pool, sending _amount to user */ function _withdraw( address _receiver, address _bAsset, uint256 _amount, uint256 _totalAmount, bool _hasTxFee ) internal { require(_totalAmount > 0, "Must withdraw something"); IAaveATokenV2 aToken = _getATokenFor(_bAsset); if (_hasTxFee) { require(_amount == _totalAmount, "Cache inactive for assets with fee"); _getLendingPool().withdraw(_bAsset, _amount, _receiver); } else { _getLendingPool().withdraw(_bAsset, _totalAmount, address(this)); // Send redeemed bAsset to the receiver IERC20(_bAsset).safeTransfer(_receiver, _amount); } emit PlatformWithdrawal(_bAsset, address(aToken), _totalAmount, _amount); } /** * @dev Withdraw a quantity of bAsset from the cache. * @param _receiver Address to which the bAsset should be sent * @param _bAsset Address of the bAsset * @param _amount Units of bAsset to withdraw */ function withdrawRaw( address _receiver, address _bAsset, uint256 _amount ) external override onlyLP nonReentrant { require(_amount > 0, "Must withdraw something"); require(_receiver != address(0), "Must specify recipient"); IERC20(_bAsset).safeTransfer(_receiver, _amount); emit Withdrawal(_bAsset, address(0), _amount); } /** * @dev Get the total bAsset value held in the platform * This includes any interest that was generated since depositing * Aave gradually increases the balances of all aToken holders, as the interest grows * @param _bAsset Address of the bAsset * @return balance Total value of the bAsset in the platform */ function checkBalance(address _bAsset) external view override returns (uint256 balance) { // balance is always with token aToken decimals IAaveATokenV2 aToken = _getATokenFor(_bAsset); return _checkBalance(aToken); } /*************************************** APPROVALS ****************************************/ /** * @dev Internal method to respond to the addition of new bAsset / pTokens * We need to approve the Aave lending pool core conrtact and give it permission * to spend the bAsset * @param _bAsset Address of the bAsset to approve */ function _abstractSetPToken( address _bAsset, address /*_pToken*/ ) internal override { address lendingPool = address(_getLendingPool()); // approve the pool to spend the bAsset MassetHelpers.safeInfiniteApprove(_bAsset, lendingPool); } /*************************************** HELPERS ****************************************/ /** * @dev Get the current address of the Aave lending pool, which is the gateway to * depositing. * @return Current lending pool implementation */ function _getLendingPool() internal view returns (IAaveLendingPoolV2) { address lendingPool = ILendingPoolAddressesProviderV2(platformAddress).getLendingPool(); require(lendingPool != address(0), "Lending pool does not exist"); return IAaveLendingPoolV2(lendingPool); } /** * @dev Get the pToken wrapped in the IAaveAToken interface for this bAsset, to use * for withdrawing or balance checking. Fails if the pToken doesn't exist in our mappings. * @param _bAsset Address of the bAsset * @return aToken Corresponding to this bAsset */ function _getATokenFor(address _bAsset) internal view returns (IAaveATokenV2) { address aToken = bAssetToPToken[_bAsset]; require(aToken != address(0), "aToken does not exist"); return IAaveATokenV2(aToken); } /** * @dev Get the total bAsset value held in the platform * @param _aToken aToken for which to check balance * @return balance Total value of the bAsset in the platform */ function _checkBalance(IAaveATokenV2 _aToken) internal view returns (uint256 balance) { return _aToken.balanceOf(address(this)); } }
/** * @title AaveV2Integration * @author mStable * @notice A simple connection to deposit and withdraw bAssets from Aave * @dev VERSION: 1.0 * DATE: 2020-16-11 */
NatSpecMultiLine
_getATokenFor
function _getATokenFor(address _bAsset) internal view returns (IAaveATokenV2) { address aToken = bAssetToPToken[_bAsset]; require(aToken != address(0), "aToken does not exist"); return IAaveATokenV2(aToken); }
/** * @dev Get the pToken wrapped in the IAaveAToken interface for this bAsset, to use * for withdrawing or balance checking. Fails if the pToken doesn't exist in our mappings. * @param _bAsset Address of the bAsset * @return aToken Corresponding to this bAsset */
NatSpecMultiLine
v0.8.6+commit.11564f7e
{ "func_code_index": [ 7782, 8023 ] }
2,699