Unnamed: 0
int64
0
7.36k
comments
stringlengths
3
35.2k
code_string
stringlengths
1
527k
code
stringlengths
1
527k
__index_level_0__
int64
0
88.6k
26
// View function to see pending ROLLs on frontend.
function pendingRoll(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accRollPerShare = pool.accRollPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 rollReward = multiplier.mul(rollPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accRollPerShare = accRollPerShare.add(rollReward.mul(1e18).div(lpSupply)); } return user.amount.mul(accRollPerShare).div(1e18).sub(user.rewardDebt); }
function pendingRoll(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accRollPerShare = pool.accRollPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 rollReward = multiplier.mul(rollPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accRollPerShare = accRollPerShare.add(rollReward.mul(1e18).div(lpSupply)); } return user.amount.mul(accRollPerShare).div(1e18).sub(user.rewardDebt); }
4,736
12
// Determine if the "_from" address is a contract
function _humanSender(address _from) private view returns (bool) { uint codeLength; assembly { codeLength := extcodesize(_from) } return (codeLength == 0); // If this is "true" sender is most likely a Wallet }
function _humanSender(address _from) private view returns (bool) { uint codeLength; assembly { codeLength := extcodesize(_from) } return (codeLength == 0); // If this is "true" sender is most likely a Wallet }
13,392
95
// Lib_PredeployAddresses /
library Lib_PredeployAddresses { address internal constant L2_TO_L1_MESSAGE_PASSER = 0x4200000000000000000000000000000000000000; address internal constant L1_MESSAGE_SENDER = 0x4200000000000000000000000000000000000001; address internal constant DEPLOYER_WHITELIST = 0x4200000000000000000000000000000000000002; address internal constant MVM_CHAIN_CONFIG = 0x4200000000000000000000000000000000000005; address internal constant OVM_ETH = 0x420000000000000000000000000000000000000A; address internal constant MVM_COINBASE = 0xDeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000; address internal constant L2_CROSS_DOMAIN_MESSENGER = 0x4200000000000000000000000000000000000007; address internal constant LIB_ADDRESS_MANAGER = 0x4200000000000000000000000000000000000008; address internal constant PROXY_EOA = 0x4200000000000000000000000000000000000009; address internal constant L2_STANDARD_BRIDGE = 0x4200000000000000000000000000000000000010; address payable internal constant SEQUENCER_FEE_WALLET = payable(0x4200000000000000000000000000000000000011); address internal constant L2_STANDARD_TOKEN_FACTORY = 0x4200000000000000000000000000000000000012; address internal constant L1_BLOCK_NUMBER = 0x4200000000000000000000000000000000000013; address internal constant OVM_GASPRICE_ORACLE = 0x420000000000000000000000000000000000000F; }
library Lib_PredeployAddresses { address internal constant L2_TO_L1_MESSAGE_PASSER = 0x4200000000000000000000000000000000000000; address internal constant L1_MESSAGE_SENDER = 0x4200000000000000000000000000000000000001; address internal constant DEPLOYER_WHITELIST = 0x4200000000000000000000000000000000000002; address internal constant MVM_CHAIN_CONFIG = 0x4200000000000000000000000000000000000005; address internal constant OVM_ETH = 0x420000000000000000000000000000000000000A; address internal constant MVM_COINBASE = 0xDeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000; address internal constant L2_CROSS_DOMAIN_MESSENGER = 0x4200000000000000000000000000000000000007; address internal constant LIB_ADDRESS_MANAGER = 0x4200000000000000000000000000000000000008; address internal constant PROXY_EOA = 0x4200000000000000000000000000000000000009; address internal constant L2_STANDARD_BRIDGE = 0x4200000000000000000000000000000000000010; address payable internal constant SEQUENCER_FEE_WALLET = payable(0x4200000000000000000000000000000000000011); address internal constant L2_STANDARD_TOKEN_FACTORY = 0x4200000000000000000000000000000000000012; address internal constant L1_BLOCK_NUMBER = 0x4200000000000000000000000000000000000013; address internal constant OVM_GASPRICE_ORACLE = 0x420000000000000000000000000000000000000F; }
34,429
10
// implementation from https:github.com/Uniswap/uniswap-lib/commit/99f3f28770640ba1bb1ff460ac7c5292fb8291a0 original implementation: https:github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.solL687
function sqrt(uint x) internal pure returns (uint) { if (x == 0) return 0; uint xx = x; uint r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint r1 = x / r; return (r < r1 ? r : r1); }
function sqrt(uint x) internal pure returns (uint) { if (x == 0) return 0; uint xx = x; uint r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint r1 = x / r; return (r < r1 ? r : r1); }
9,124
26
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met require (_value <= _allowance);
balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true;
balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true;
5,728
10
// the min nif being staked in the governance required for consumers receiving UNT
uint256 public minNifConsumptionStake = 10 * 10**18; //150000 * 10**18;
uint256 public minNifConsumptionStake = 10 * 10**18; //150000 * 10**18;
10,321
8
// Slightly modified SafeMath library - includes a min and max function, removes useless div function
library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function add(int256 a, int256 b) internal pure returns (int256 c) { if (b > 0) { c = a + b; assert(c >= a); } else { c = a + b; assert(c <= a); } } function max(uint256 a, uint256 b) internal pure returns (uint256) { return a > b ? a : b; } function max(int256 a, int256 b) internal pure returns (uint256) { return a > b ? uint256(a) : uint256(b); } function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function sub(int256 a, int256 b) internal pure returns (int256 c) { if (b > 0) { c = a - b; assert(c <= a); } else { c = a - b; assert(c >= a); } } }
library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function add(int256 a, int256 b) internal pure returns (int256 c) { if (b > 0) { c = a + b; assert(c >= a); } else { c = a + b; assert(c <= a); } } function max(uint256 a, uint256 b) internal pure returns (uint256) { return a > b ? a : b; } function max(int256 a, int256 b) internal pure returns (uint256) { return a > b ? uint256(a) : uint256(b); } function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function sub(int256 a, int256 b) internal pure returns (int256 c) { if (b > 0) { c = a - b; assert(c <= a); } else { c = a - b; assert(c >= a); } } }
35,980
84
// initialize fixed-length memory arrays
_strategies = new address[](k); _amounts = new uint256[](k); address _strategy; uint256 _balance;
_strategies = new address[](k); _amounts = new uint256[](k); address _strategy; uint256 _balance;
27,586
79
// Protocol control center.
import { ProtocolControl } from "./ProtocolControl.sol"; // Royalties import "@openzeppelin/contracts/interfaces/IERC2981.sol"; import "@openzeppelin/contracts/utils/Multicall.sol"; contract NFTCollection is ERC1155PresetMinterPauserSupplyHolder, ERC2771Context, IERC2981, Multicall { /// @dev The protocol control center. ProtocolControl internal controlCenter; /// @dev The token Id of the next token to be minted. uint256 public nextTokenId; /// @dev NFT sale royalties -- see EIP 2981 uint256 public royaltyBps; /// @dev Collection level metadata. string public _contractURI; /// @dev Only TRANSFER_ROLE holders can have tokens transferred from or to them, during restricted transfers. bytes32 public constant TRANSFER_ROLE = keccak256("TRANSFER_ROLE"); /// @dev Whether transfers on tokens are restricted. bool public transfersRestricted; /// @dev Whether the ERC 1155 token is a wrapped ERC 20 / 721 token. enum UnderlyingType { None, ERC20, ERC721 } /// @dev The state of a token. struct TokenState { address creator; string uri; UnderlyingType underlyingType; } /// @dev The state of the underlying ERC 721 token, if any. struct ERC721Wrapped { address source; uint256 tokenId; } /// @dev The state of the underlying ERC 20 token, if any. struct ERC20Wrapped { address source; uint256 shares; uint256 underlyingTokenAmount; } event RestrictedTransferUpdated(bool transferable); /// @dev Emitted when native ERC 1155 tokens are created. event NativeTokens(address indexed creator, uint256[] tokenIds, string[] tokenURIs, uint256[] tokenSupplies); /// @dev Emitted when ERC 721 wrapped as an ERC 1155 token is minted. event ERC721WrappedToken( address indexed creator, address indexed sourceOfUnderlying, uint256 tokenIdOfUnderlying, uint256 tokenId, string tokenURI ); /// @dev Emitted when an underlying ERC 721 token is redeemed. event ERC721Redeemed( address indexed redeemer, address indexed sourceOfUnderlying, uint256 tokenIdOfUnderlying, uint256 tokenId ); /// @dev Emitted when ERC 20 wrapped as an ERC 1155 token is minted. event ERC20WrappedToken( address indexed creator, address indexed sourceOfUnderlying, uint256 totalAmountOfUnderlying, uint256 shares, uint256 tokenId, string tokenURI ); /// @dev Emitted when an underlying ERC 20 token is redeemed. event ERC20Redeemed( address indexed redeemer, uint256 indexed tokenId, address indexed sourceOfUnderlying, uint256 tokenAmountReceived, uint256 sharesRedeemed ); /// @dev Emitted when the EIP 2981 royalty of the contract is updated. event RoyaltyUpdated(uint256 royaltyBps); /// @dev NFT tokenId => token state. mapping(uint256 => TokenState) public tokenState; /// @dev NFT tokenId => state of underlying ERC721 token. mapping(uint256 => ERC721Wrapped) public erc721WrappedTokens; /// @dev NFT tokenId => state of underlying ERC20 token. mapping(uint256 => ERC20Wrapped) public erc20WrappedTokens; /// @dev Checks whether the caller is a protocol admin. modifier onlyProtocolAdmin() { require( controlCenter.hasRole(controlCenter.DEFAULT_ADMIN_ROLE(), _msgSender()), "NFTCollection: only a protocol admin can call this function." ); _; } modifier onlyModuleAdmin() { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "only module admin role"); _; } /// @dev Checks whether the caller has MINTER_ROLE. modifier onlyMinterRole() { require( hasRole(MINTER_ROLE, _msgSender()), "NFTCollection: Only accounts with MINTER_ROLE can call this function." ); _; } constructor( address payable _controlCenter, address _trustedForwarder, string memory _uri, uint256 _royaltyBps ) ERC1155PresetMinterPauserSupplyHolder(_uri) ERC2771Context(_trustedForwarder) { // Set the protocol control center controlCenter = ProtocolControl(_controlCenter); // Set contract URI _contractURI = _uri; // Grant TRANSFER_ROLE to deployer. _setupRole(TRANSFER_ROLE, _msgSender()); setRoyaltyBps(_royaltyBps); } /** * Public functions */ /// @notice Create native ERC 1155 NFTs. function createNativeTokens( address to, string[] calldata _nftURIs, uint256[] calldata _nftSupplies, bytes memory data ) public whenNotPaused onlyMinterRole returns (uint256[] memory nftIds) { require(_nftURIs.length == _nftSupplies.length, "NFTCollection: Must specify equal number of config values."); require(_nftURIs.length > 0, "NFTCollection: Must create at least one NFT."); // Get creator address tokenCreator = _msgSender(); // Get tokenIds. nftIds = new uint256[](_nftURIs.length); // Store token state for each token. uint256 id = nextTokenId; for (uint256 i = 0; i < _nftURIs.length; i++) { nftIds[i] = id; tokenState[id] = TokenState({ creator: tokenCreator, uri: _nftURIs[i], underlyingType: UnderlyingType.None }); id += 1; } // Update contract level tokenId. nextTokenId = id; // Mint NFTs to token creator. _mintBatch(to, nftIds, _nftSupplies, data); emit NativeTokens(tokenCreator, nftIds, _nftURIs, _nftSupplies); } /// @dev See {ERC1155Minter}. function mint( address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require(id < nextTokenId, "NFTCollection: cannot call this fn for creating new NFTs."); require( tokenState[id].underlyingType == UnderlyingType.None, "NFTCollection: cannot freely mint more of ERC20 or ERC721." ); super.mint(to, id, amount, data); } /// @dev See {ERC1155Minter}. function mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { bool validIds = true; bool validTokenType = true; for (uint256 i = 0; i < ids.length; ++i) { if (ids[i] >= nextTokenId && validIds) { validIds = false; } if (tokenState[ids[i]].underlyingType != UnderlyingType.None && validTokenType) { validTokenType = false; } } require(validIds, "NFTCollection: cannot call this fn for creating new NFTs."); require(validTokenType, "NFTCollection: cannot freely mint more of ERC20 or ERC721."); super.mintBatch(to, ids, amounts, data); } /** * External functions */ /// @dev Wraps an ERC721 NFT as an ERC1155 NFT. function wrapERC721( address _nftContract, uint256 _tokenId, string calldata _nftURI ) external whenNotPaused onlyMinterRole { require( IERC721(_nftContract).ownerOf(_tokenId) == _msgSender(), "NFTCollection: Only the owner of the NFT can wrap it." ); require( IERC721(_nftContract).getApproved(_tokenId) == address(this) || IERC721(_nftContract).isApprovedForAll(_msgSender(), address(this)), "NFTCollection: Must approve the contract to transfer the NFT." ); // Get token creator address tokenCreator = _msgSender(); // Get tokenId uint256 id = nextTokenId; nextTokenId += 1; // Transfer the NFT to this contract. IERC721(_nftContract).safeTransferFrom(tokenCreator, address(this), _tokenId); // Mint wrapped NFT to token creator. _mint(tokenCreator, id, 1, ""); // Store wrapped NFT state. tokenState[id] = TokenState({ creator: tokenCreator, uri: _nftURI, underlyingType: UnderlyingType.ERC721 }); // Map the native NFT tokenId to the underlying NFT erc721WrappedTokens[id] = ERC721Wrapped({ source: _nftContract, tokenId: _tokenId }); emit ERC721WrappedToken(tokenCreator, _nftContract, _tokenId, id, _nftURI); } /// @dev Lets a wrapped nft owner redeem the underlying ERC721 NFT. function redeemERC721(uint256 _nftId) external { // Get redeemer address redeemer = _msgSender(); require(balanceOf(redeemer, _nftId) > 0, "NFTCollection: Cannot redeem an NFT you do not own."); // Burn the native NFT token _burn(redeemer, _nftId, 1); // Transfer the NFT to redeemer IERC721(erc721WrappedTokens[_nftId].source).safeTransferFrom( address(this), redeemer, erc721WrappedTokens[_nftId].tokenId ); emit ERC721Redeemed(redeemer, erc721WrappedTokens[_nftId].source, erc721WrappedTokens[_nftId].tokenId, _nftId); } /// @dev Wraps ERC20 tokens as ERC1155 NFTs. function wrapERC20( address _tokenContract, uint256 _tokenAmount, uint256 _numOfNftsToMint, string calldata _nftURI ) external whenNotPaused onlyMinterRole { // Get creator address tokenCreator = _msgSender(); require( IERC20(_tokenContract).balanceOf(tokenCreator) >= _tokenAmount, "NFTCollection: Must own the amount of tokens being wrapped." ); require( IERC20(_tokenContract).allowance(tokenCreator, address(this)) >= _tokenAmount, "NFTCollection: Must approve this contract to transfer tokens." ); require( IERC20(_tokenContract).transferFrom(tokenCreator, address(this), _tokenAmount), "NFTCollection: Failed to transfer ERC20 tokens." ); // Get NFT tokenId uint256 id = nextTokenId; nextTokenId += 1; // Mint NFTs to token creator _mint(tokenCreator, id, _numOfNftsToMint, ""); tokenState[id] = TokenState({ creator: tokenCreator, uri: _nftURI, underlyingType: UnderlyingType.ERC20 }); erc20WrappedTokens[id] = ERC20Wrapped({ source: _tokenContract, shares: _numOfNftsToMint, underlyingTokenAmount: _tokenAmount }); emit ERC20WrappedToken(tokenCreator, _tokenContract, _tokenAmount, _numOfNftsToMint, id, _nftURI); } /// @dev Lets the nft owner redeem their ERC20 tokens. function redeemERC20(uint256 _nftId, uint256 _amount) external { // Get redeemer address redeemer = _msgSender(); require(balanceOf(redeemer, _nftId) >= _amount, "NFTCollection: Cannot redeem an NFT you do not own."); // Burn the native NFT token _burn(redeemer, _nftId, _amount); // Get the ERC20 token amount to distribute uint256 amountToDistribute = (erc20WrappedTokens[_nftId].underlyingTokenAmount * _amount) / erc20WrappedTokens[_nftId].shares; // Transfer the ERC20 tokens to redeemer require( IERC20(erc20WrappedTokens[_nftId].source).transfer(redeemer, amountToDistribute), "NFTCollection: Failed to transfer ERC20 tokens." ); emit ERC20Redeemed(redeemer, _nftId, erc20WrappedTokens[_nftId].source, amountToDistribute, _amount); } /** * External: setter functions */ /// @dev Lets a protocol admin update the royalties paid on pack sales. function setRoyaltyBps(uint256 _royaltyBps) public onlyModuleAdmin { require( _royaltyBps < controlCenter.MAX_BPS(), "NFTCollection: Invalid bps provided; must be less than 10,000." ); royaltyBps = _royaltyBps; emit RoyaltyUpdated(_royaltyBps); } /// @dev Sets contract URI for the storefront-level metadata of the contract. function setContractURI(string calldata _URI) external onlyProtocolAdmin { _contractURI = _URI; } /// @dev Lets a protocol admin restrict token transfers. function setRestrictedTransfer(bool _restrictedTransfer) external onlyModuleAdmin { transfersRestricted = _restrictedTransfer; emit RestrictedTransferUpdated(_restrictedTransfer); } /** * Internal functions. */ /// @dev Runs on every transfer. function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal override { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); if (transfersRestricted && from != address(0) && to != address(0)) { require( hasRole(TRANSFER_ROLE, from) || hasRole(TRANSFER_ROLE, to), "NFTCollection: Transfers are restricted to or from TRANSFER_ROLE holders" ); } } /// @dev See EIP-2771 function _msgSender() internal view virtual override(Context, ERC2771Context) returns (address sender) { return ERC2771Context._msgSender(); } /// @dev See EIP-2771 function _msgData() internal view virtual override(Context, ERC2771Context) returns (bytes calldata) { return ERC2771Context._msgData(); } /** * Rest: view functions */ /// @dev See ERC 165 function supportsInterface(bytes4 interfaceId) public view virtual override(ERC1155PresetMinterPauserSupplyHolder, IERC165) returns (bool) { return super.supportsInterface(interfaceId) || interfaceId == type(IERC2981).interfaceId; } /// @dev See EIP 2918 function royaltyInfo(uint256, uint256 salePrice) external view virtual override returns (address receiver, uint256 royaltyAmount) { receiver = controlCenter.getRoyaltyTreasury(address(this)); royaltyAmount = (salePrice * royaltyBps) / controlCenter.MAX_BPS(); } /// @dev See EIP 1155 function uri(uint256 _nftId) public view override returns (string memory) { return tokenState[_nftId].uri; } /// @dev Alternative function to return a token's URI function tokenURI(uint256 _nftId) public view returns (string memory) { return tokenState[_nftId].uri; } /// @dev Returns the URI for the storefront-level metadata of the contract. function contractURI() public view returns (string memory) { return _contractURI; } /// @dev Returns the creator of an NFT function creator(uint256 _nftId) external view returns (address) { return tokenState[_nftId].creator; } }
import { ProtocolControl } from "./ProtocolControl.sol"; // Royalties import "@openzeppelin/contracts/interfaces/IERC2981.sol"; import "@openzeppelin/contracts/utils/Multicall.sol"; contract NFTCollection is ERC1155PresetMinterPauserSupplyHolder, ERC2771Context, IERC2981, Multicall { /// @dev The protocol control center. ProtocolControl internal controlCenter; /// @dev The token Id of the next token to be minted. uint256 public nextTokenId; /// @dev NFT sale royalties -- see EIP 2981 uint256 public royaltyBps; /// @dev Collection level metadata. string public _contractURI; /// @dev Only TRANSFER_ROLE holders can have tokens transferred from or to them, during restricted transfers. bytes32 public constant TRANSFER_ROLE = keccak256("TRANSFER_ROLE"); /// @dev Whether transfers on tokens are restricted. bool public transfersRestricted; /// @dev Whether the ERC 1155 token is a wrapped ERC 20 / 721 token. enum UnderlyingType { None, ERC20, ERC721 } /// @dev The state of a token. struct TokenState { address creator; string uri; UnderlyingType underlyingType; } /// @dev The state of the underlying ERC 721 token, if any. struct ERC721Wrapped { address source; uint256 tokenId; } /// @dev The state of the underlying ERC 20 token, if any. struct ERC20Wrapped { address source; uint256 shares; uint256 underlyingTokenAmount; } event RestrictedTransferUpdated(bool transferable); /// @dev Emitted when native ERC 1155 tokens are created. event NativeTokens(address indexed creator, uint256[] tokenIds, string[] tokenURIs, uint256[] tokenSupplies); /// @dev Emitted when ERC 721 wrapped as an ERC 1155 token is minted. event ERC721WrappedToken( address indexed creator, address indexed sourceOfUnderlying, uint256 tokenIdOfUnderlying, uint256 tokenId, string tokenURI ); /// @dev Emitted when an underlying ERC 721 token is redeemed. event ERC721Redeemed( address indexed redeemer, address indexed sourceOfUnderlying, uint256 tokenIdOfUnderlying, uint256 tokenId ); /// @dev Emitted when ERC 20 wrapped as an ERC 1155 token is minted. event ERC20WrappedToken( address indexed creator, address indexed sourceOfUnderlying, uint256 totalAmountOfUnderlying, uint256 shares, uint256 tokenId, string tokenURI ); /// @dev Emitted when an underlying ERC 20 token is redeemed. event ERC20Redeemed( address indexed redeemer, uint256 indexed tokenId, address indexed sourceOfUnderlying, uint256 tokenAmountReceived, uint256 sharesRedeemed ); /// @dev Emitted when the EIP 2981 royalty of the contract is updated. event RoyaltyUpdated(uint256 royaltyBps); /// @dev NFT tokenId => token state. mapping(uint256 => TokenState) public tokenState; /// @dev NFT tokenId => state of underlying ERC721 token. mapping(uint256 => ERC721Wrapped) public erc721WrappedTokens; /// @dev NFT tokenId => state of underlying ERC20 token. mapping(uint256 => ERC20Wrapped) public erc20WrappedTokens; /// @dev Checks whether the caller is a protocol admin. modifier onlyProtocolAdmin() { require( controlCenter.hasRole(controlCenter.DEFAULT_ADMIN_ROLE(), _msgSender()), "NFTCollection: only a protocol admin can call this function." ); _; } modifier onlyModuleAdmin() { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "only module admin role"); _; } /// @dev Checks whether the caller has MINTER_ROLE. modifier onlyMinterRole() { require( hasRole(MINTER_ROLE, _msgSender()), "NFTCollection: Only accounts with MINTER_ROLE can call this function." ); _; } constructor( address payable _controlCenter, address _trustedForwarder, string memory _uri, uint256 _royaltyBps ) ERC1155PresetMinterPauserSupplyHolder(_uri) ERC2771Context(_trustedForwarder) { // Set the protocol control center controlCenter = ProtocolControl(_controlCenter); // Set contract URI _contractURI = _uri; // Grant TRANSFER_ROLE to deployer. _setupRole(TRANSFER_ROLE, _msgSender()); setRoyaltyBps(_royaltyBps); } /** * Public functions */ /// @notice Create native ERC 1155 NFTs. function createNativeTokens( address to, string[] calldata _nftURIs, uint256[] calldata _nftSupplies, bytes memory data ) public whenNotPaused onlyMinterRole returns (uint256[] memory nftIds) { require(_nftURIs.length == _nftSupplies.length, "NFTCollection: Must specify equal number of config values."); require(_nftURIs.length > 0, "NFTCollection: Must create at least one NFT."); // Get creator address tokenCreator = _msgSender(); // Get tokenIds. nftIds = new uint256[](_nftURIs.length); // Store token state for each token. uint256 id = nextTokenId; for (uint256 i = 0; i < _nftURIs.length; i++) { nftIds[i] = id; tokenState[id] = TokenState({ creator: tokenCreator, uri: _nftURIs[i], underlyingType: UnderlyingType.None }); id += 1; } // Update contract level tokenId. nextTokenId = id; // Mint NFTs to token creator. _mintBatch(to, nftIds, _nftSupplies, data); emit NativeTokens(tokenCreator, nftIds, _nftURIs, _nftSupplies); } /// @dev See {ERC1155Minter}. function mint( address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require(id < nextTokenId, "NFTCollection: cannot call this fn for creating new NFTs."); require( tokenState[id].underlyingType == UnderlyingType.None, "NFTCollection: cannot freely mint more of ERC20 or ERC721." ); super.mint(to, id, amount, data); } /// @dev See {ERC1155Minter}. function mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { bool validIds = true; bool validTokenType = true; for (uint256 i = 0; i < ids.length; ++i) { if (ids[i] >= nextTokenId && validIds) { validIds = false; } if (tokenState[ids[i]].underlyingType != UnderlyingType.None && validTokenType) { validTokenType = false; } } require(validIds, "NFTCollection: cannot call this fn for creating new NFTs."); require(validTokenType, "NFTCollection: cannot freely mint more of ERC20 or ERC721."); super.mintBatch(to, ids, amounts, data); } /** * External functions */ /// @dev Wraps an ERC721 NFT as an ERC1155 NFT. function wrapERC721( address _nftContract, uint256 _tokenId, string calldata _nftURI ) external whenNotPaused onlyMinterRole { require( IERC721(_nftContract).ownerOf(_tokenId) == _msgSender(), "NFTCollection: Only the owner of the NFT can wrap it." ); require( IERC721(_nftContract).getApproved(_tokenId) == address(this) || IERC721(_nftContract).isApprovedForAll(_msgSender(), address(this)), "NFTCollection: Must approve the contract to transfer the NFT." ); // Get token creator address tokenCreator = _msgSender(); // Get tokenId uint256 id = nextTokenId; nextTokenId += 1; // Transfer the NFT to this contract. IERC721(_nftContract).safeTransferFrom(tokenCreator, address(this), _tokenId); // Mint wrapped NFT to token creator. _mint(tokenCreator, id, 1, ""); // Store wrapped NFT state. tokenState[id] = TokenState({ creator: tokenCreator, uri: _nftURI, underlyingType: UnderlyingType.ERC721 }); // Map the native NFT tokenId to the underlying NFT erc721WrappedTokens[id] = ERC721Wrapped({ source: _nftContract, tokenId: _tokenId }); emit ERC721WrappedToken(tokenCreator, _nftContract, _tokenId, id, _nftURI); } /// @dev Lets a wrapped nft owner redeem the underlying ERC721 NFT. function redeemERC721(uint256 _nftId) external { // Get redeemer address redeemer = _msgSender(); require(balanceOf(redeemer, _nftId) > 0, "NFTCollection: Cannot redeem an NFT you do not own."); // Burn the native NFT token _burn(redeemer, _nftId, 1); // Transfer the NFT to redeemer IERC721(erc721WrappedTokens[_nftId].source).safeTransferFrom( address(this), redeemer, erc721WrappedTokens[_nftId].tokenId ); emit ERC721Redeemed(redeemer, erc721WrappedTokens[_nftId].source, erc721WrappedTokens[_nftId].tokenId, _nftId); } /// @dev Wraps ERC20 tokens as ERC1155 NFTs. function wrapERC20( address _tokenContract, uint256 _tokenAmount, uint256 _numOfNftsToMint, string calldata _nftURI ) external whenNotPaused onlyMinterRole { // Get creator address tokenCreator = _msgSender(); require( IERC20(_tokenContract).balanceOf(tokenCreator) >= _tokenAmount, "NFTCollection: Must own the amount of tokens being wrapped." ); require( IERC20(_tokenContract).allowance(tokenCreator, address(this)) >= _tokenAmount, "NFTCollection: Must approve this contract to transfer tokens." ); require( IERC20(_tokenContract).transferFrom(tokenCreator, address(this), _tokenAmount), "NFTCollection: Failed to transfer ERC20 tokens." ); // Get NFT tokenId uint256 id = nextTokenId; nextTokenId += 1; // Mint NFTs to token creator _mint(tokenCreator, id, _numOfNftsToMint, ""); tokenState[id] = TokenState({ creator: tokenCreator, uri: _nftURI, underlyingType: UnderlyingType.ERC20 }); erc20WrappedTokens[id] = ERC20Wrapped({ source: _tokenContract, shares: _numOfNftsToMint, underlyingTokenAmount: _tokenAmount }); emit ERC20WrappedToken(tokenCreator, _tokenContract, _tokenAmount, _numOfNftsToMint, id, _nftURI); } /// @dev Lets the nft owner redeem their ERC20 tokens. function redeemERC20(uint256 _nftId, uint256 _amount) external { // Get redeemer address redeemer = _msgSender(); require(balanceOf(redeemer, _nftId) >= _amount, "NFTCollection: Cannot redeem an NFT you do not own."); // Burn the native NFT token _burn(redeemer, _nftId, _amount); // Get the ERC20 token amount to distribute uint256 amountToDistribute = (erc20WrappedTokens[_nftId].underlyingTokenAmount * _amount) / erc20WrappedTokens[_nftId].shares; // Transfer the ERC20 tokens to redeemer require( IERC20(erc20WrappedTokens[_nftId].source).transfer(redeemer, amountToDistribute), "NFTCollection: Failed to transfer ERC20 tokens." ); emit ERC20Redeemed(redeemer, _nftId, erc20WrappedTokens[_nftId].source, amountToDistribute, _amount); } /** * External: setter functions */ /// @dev Lets a protocol admin update the royalties paid on pack sales. function setRoyaltyBps(uint256 _royaltyBps) public onlyModuleAdmin { require( _royaltyBps < controlCenter.MAX_BPS(), "NFTCollection: Invalid bps provided; must be less than 10,000." ); royaltyBps = _royaltyBps; emit RoyaltyUpdated(_royaltyBps); } /// @dev Sets contract URI for the storefront-level metadata of the contract. function setContractURI(string calldata _URI) external onlyProtocolAdmin { _contractURI = _URI; } /// @dev Lets a protocol admin restrict token transfers. function setRestrictedTransfer(bool _restrictedTransfer) external onlyModuleAdmin { transfersRestricted = _restrictedTransfer; emit RestrictedTransferUpdated(_restrictedTransfer); } /** * Internal functions. */ /// @dev Runs on every transfer. function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal override { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); if (transfersRestricted && from != address(0) && to != address(0)) { require( hasRole(TRANSFER_ROLE, from) || hasRole(TRANSFER_ROLE, to), "NFTCollection: Transfers are restricted to or from TRANSFER_ROLE holders" ); } } /// @dev See EIP-2771 function _msgSender() internal view virtual override(Context, ERC2771Context) returns (address sender) { return ERC2771Context._msgSender(); } /// @dev See EIP-2771 function _msgData() internal view virtual override(Context, ERC2771Context) returns (bytes calldata) { return ERC2771Context._msgData(); } /** * Rest: view functions */ /// @dev See ERC 165 function supportsInterface(bytes4 interfaceId) public view virtual override(ERC1155PresetMinterPauserSupplyHolder, IERC165) returns (bool) { return super.supportsInterface(interfaceId) || interfaceId == type(IERC2981).interfaceId; } /// @dev See EIP 2918 function royaltyInfo(uint256, uint256 salePrice) external view virtual override returns (address receiver, uint256 royaltyAmount) { receiver = controlCenter.getRoyaltyTreasury(address(this)); royaltyAmount = (salePrice * royaltyBps) / controlCenter.MAX_BPS(); } /// @dev See EIP 1155 function uri(uint256 _nftId) public view override returns (string memory) { return tokenState[_nftId].uri; } /// @dev Alternative function to return a token's URI function tokenURI(uint256 _nftId) public view returns (string memory) { return tokenState[_nftId].uri; } /// @dev Returns the URI for the storefront-level metadata of the contract. function contractURI() public view returns (string memory) { return _contractURI; } /// @dev Returns the creator of an NFT function creator(uint256 _nftId) external view returns (address) { return tokenState[_nftId].creator; } }
2,147
55
// Finding option with most votes
uint256 winningOption = 0; uint256 maxVotedCount = 0; for (uint256 i = 0; i < voteCounts.length; i++) { if (voteCounts[i] > maxVotedCount) { winningOption = i + 1; maxVotedCount = voteCounts[i]; } else if (voteCounts[i] == maxVotedCount) {
uint256 winningOption = 0; uint256 maxVotedCount = 0; for (uint256 i = 0; i < voteCounts.length; i++) { if (voteCounts[i] > maxVotedCount) { winningOption = i + 1; maxVotedCount = voteCounts[i]; } else if (voteCounts[i] == maxVotedCount) {
33,654
4
// Fallback function
function() external payable { }
function() external payable { }
41,216
1
// Decode bytes array
using Bytes for bytes;
using Bytes for bytes;
17,158
141
// Retrieve any shares tokens not accounted for in the cache./to Address of the recipient of the shares tokens./ return retrieved The amount of shares tokens sent.
function retrieveShares(address to) external virtual override returns (uint128 retrieved) { retrieved = _getSharesBalance() - sharesCached; // Cache can never be above balances sharesToken.safeTransfer(to, retrieved); }
function retrieveShares(address to) external virtual override returns (uint128 retrieved) { retrieved = _getSharesBalance() - sharesCached; // Cache can never be above balances sharesToken.safeTransfer(to, retrieved); }
25,447
78
// Allows the proxy owner to upgrade the current version of the proxy and call the new implementationto initialize whatever is needed through a low level call. implementation representing the address of the new implementation to be set. data represents the msg.data to bet sent in the low level call. This parameter may include the functionsignature of the implementation to be called with the needed payload /
function upgradeToAndCall(address implementation, bytes memory data) payable public onlyProxyOwner { upgradeTo(implementation); (bool success, ) = address(this).call{value: msg.value}(data); require(success); }
function upgradeToAndCall(address implementation, bytes memory data) payable public onlyProxyOwner { upgradeTo(implementation); (bool success, ) = address(this).call{value: msg.value}(data); require(success); }
32,091
5
// ERC-20 Transfer event
event Transfer(address indexed from, address indexed to, uint256 tokens);
event Transfer(address indexed from, address indexed to, uint256 tokens);
10,168
230
// MasterChef is the master of Taal. He can make Taal and he is a fair guy. Note that it's ownable and the owner wields tremendous power. The ownership will be transferred to a governance smart contract once TAL is sufficiently distributed and the community can show to govern itself. Have fun reading it. Hopefully it's bug-free. God bless.
contract MasterChef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of TALs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accTaalPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accTaalPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. TALs to distribute per block. uint256 lastRewardBlock; // Last block number that TALs distribution occurs. uint256 accTaalPerShare; // Accumulated TALs per share, times 1e12. See below. } // The TAL TOKEN! TaalToken public taal; // The SYRUP TOKEN! SyrupBar public syrup; // Dev address. address public devaddr; // TAL tokens created per block. uint256 public taalPerBlock; // Bonus muliplier for early taal makers. uint256 public BONUS_MULTIPLIER = 1; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigratorChef public migrator; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when TAL mining starts. uint256 public startBlock; uint256 private lastAdjust; uint256 public CUT_INTERVAL = 30; // default = 30 days event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( TaalToken _taal, SyrupBar _syrup, address _devaddr, uint256 _taalPerBlock, uint256 _startBlock ) public { taal = _taal; syrup = _syrup; devaddr = _devaddr; taalPerBlock = _taalPerBlock; startBlock = _startBlock; // staking pool poolInfo.push(PoolInfo({ lpToken: _taal, allocPoint: 1000, lastRewardBlock: startBlock, accTaalPerShare: 0 })); totalAllocPoint = 1000; lastAdjust = block.timestamp; } function _adjustTaalPerBlock() internal { // TAL emission decreases in half per 30 days as default if (lastAdjust + CUT_INTERVAL * 1 days <= block.timestamp) { taalPerBlock = taalPerBlock.mul(1).div(10); // cut up 10% lastAdjust = block.timestamp; } } // Set CUT_INTERVAL, should input number in days. function updateCutInterval(uint256 _cutInterval) public onlyOwner { CUT_INTERVAL = _cutInterval; } // Return the time left that TAL rewards cut in half. function getCutting() public view returns (uint256) { return lastAdjust + CUT_INTERVAL.mul(1 days) - block.timestamp; } function updateMultiplier(uint256 multiplierNumber) public onlyOwner { BONUS_MULTIPLIER = multiplierNumber; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accTaalPerShare: 0 })); updateStakingPool(); } // Update the given pool's TAL allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 prevAllocPoint = poolInfo[_pid].allocPoint; poolInfo[_pid].allocPoint = _allocPoint; if (prevAllocPoint != _allocPoint) { totalAllocPoint = totalAllocPoint.sub(prevAllocPoint).add(_allocPoint); updateStakingPool(); } } function updateStakingPool() internal { uint256 length = poolInfo.length; uint256 points = 0; for (uint256 pid = 1; pid < length; ++pid) { points = points.add(poolInfo[pid].allocPoint); } if (points != 0) { points = points.div(3); totalAllocPoint = totalAllocPoint.sub(poolInfo[0].allocPoint).add(points); poolInfo[0].allocPoint = points; } } // Set the migrator contract. Can only be called by the owner. function setMigrator(IMigratorChef _migrator) public onlyOwner { migrator = _migrator; } // Set the taalPerBlock. Can only be called by the owner. function setTaalPerBlock(uint256 _taalPerBlock) public onlyOwner { taalPerBlock = _taalPerBlock; } // Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good. function migrate(uint256 _pid) public { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 lpToken = pool.lpToken; uint256 bal = lpToken.balanceOf(address(this)); lpToken.safeApprove(address(migrator), bal); IERC20 newLpToken = migrator.migrate(lpToken); require(bal == newLpToken.balanceOf(address(this)), "migrate: bad"); pool.lpToken = newLpToken; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } // View function to see pending TALs on frontend. function pendingTaal(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accTaalPerShare = pool.accTaalPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 taalReward = multiplier.mul(taalPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accTaalPerShare = accTaalPerShare.add(taalReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accTaalPerShare).div(1e12).sub(user.rewardDebt); } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } _adjustTaalPerBlock(); uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 taalReward = multiplier.mul(taalPerBlock).mul(pool.allocPoint).div(totalAllocPoint); taal.mint(devaddr, (taalReward.mul(15)).div(100)); // 15% for Dev taal.mint(address(syrup), taalReward); pool.accTaalPerShare = pool.accTaalPerShare.add(taalReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for TAL allocation. function deposit(uint256 _pid, uint256 _amount) public { require (_pid != 0, 'deposit TAL by staking'); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accTaalPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeTaalTransfer(msg.sender, pending); } } if (_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accTaalPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { require (_pid != 0, 'withdraw TAL by unstaking'); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accTaalPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeTaalTransfer(msg.sender, pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accTaalPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // Stake TAL tokens to MasterChef function enterStaking(uint256 _amount) public { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[0][msg.sender]; updatePool(0); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accTaalPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeTaalTransfer(msg.sender, pending); } } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accTaalPerShare).div(1e12); syrup.mint(msg.sender, _amount); emit Deposit(msg.sender, 0, _amount); } // Withdraw TAL tokens from STAKING. function leaveStaking(uint256 _amount) public { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[0][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(0); uint256 pending = user.amount.mul(pool.accTaalPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeTaalTransfer(msg.sender, pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accTaalPerShare).div(1e12); syrup.burn(msg.sender, _amount); emit Withdraw(msg.sender, 0, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe taal transfer function, just in case if rounding error causes pool to not have enough TALs. function safeTaalTransfer(address _to, uint256 _amount) internal { syrup.safeTaalTransfer(_to, _amount); } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } }
contract MasterChef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of TALs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accTaalPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accTaalPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. TALs to distribute per block. uint256 lastRewardBlock; // Last block number that TALs distribution occurs. uint256 accTaalPerShare; // Accumulated TALs per share, times 1e12. See below. } // The TAL TOKEN! TaalToken public taal; // The SYRUP TOKEN! SyrupBar public syrup; // Dev address. address public devaddr; // TAL tokens created per block. uint256 public taalPerBlock; // Bonus muliplier for early taal makers. uint256 public BONUS_MULTIPLIER = 1; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigratorChef public migrator; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when TAL mining starts. uint256 public startBlock; uint256 private lastAdjust; uint256 public CUT_INTERVAL = 30; // default = 30 days event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( TaalToken _taal, SyrupBar _syrup, address _devaddr, uint256 _taalPerBlock, uint256 _startBlock ) public { taal = _taal; syrup = _syrup; devaddr = _devaddr; taalPerBlock = _taalPerBlock; startBlock = _startBlock; // staking pool poolInfo.push(PoolInfo({ lpToken: _taal, allocPoint: 1000, lastRewardBlock: startBlock, accTaalPerShare: 0 })); totalAllocPoint = 1000; lastAdjust = block.timestamp; } function _adjustTaalPerBlock() internal { // TAL emission decreases in half per 30 days as default if (lastAdjust + CUT_INTERVAL * 1 days <= block.timestamp) { taalPerBlock = taalPerBlock.mul(1).div(10); // cut up 10% lastAdjust = block.timestamp; } } // Set CUT_INTERVAL, should input number in days. function updateCutInterval(uint256 _cutInterval) public onlyOwner { CUT_INTERVAL = _cutInterval; } // Return the time left that TAL rewards cut in half. function getCutting() public view returns (uint256) { return lastAdjust + CUT_INTERVAL.mul(1 days) - block.timestamp; } function updateMultiplier(uint256 multiplierNumber) public onlyOwner { BONUS_MULTIPLIER = multiplierNumber; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accTaalPerShare: 0 })); updateStakingPool(); } // Update the given pool's TAL allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 prevAllocPoint = poolInfo[_pid].allocPoint; poolInfo[_pid].allocPoint = _allocPoint; if (prevAllocPoint != _allocPoint) { totalAllocPoint = totalAllocPoint.sub(prevAllocPoint).add(_allocPoint); updateStakingPool(); } } function updateStakingPool() internal { uint256 length = poolInfo.length; uint256 points = 0; for (uint256 pid = 1; pid < length; ++pid) { points = points.add(poolInfo[pid].allocPoint); } if (points != 0) { points = points.div(3); totalAllocPoint = totalAllocPoint.sub(poolInfo[0].allocPoint).add(points); poolInfo[0].allocPoint = points; } } // Set the migrator contract. Can only be called by the owner. function setMigrator(IMigratorChef _migrator) public onlyOwner { migrator = _migrator; } // Set the taalPerBlock. Can only be called by the owner. function setTaalPerBlock(uint256 _taalPerBlock) public onlyOwner { taalPerBlock = _taalPerBlock; } // Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good. function migrate(uint256 _pid) public { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 lpToken = pool.lpToken; uint256 bal = lpToken.balanceOf(address(this)); lpToken.safeApprove(address(migrator), bal); IERC20 newLpToken = migrator.migrate(lpToken); require(bal == newLpToken.balanceOf(address(this)), "migrate: bad"); pool.lpToken = newLpToken; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } // View function to see pending TALs on frontend. function pendingTaal(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accTaalPerShare = pool.accTaalPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 taalReward = multiplier.mul(taalPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accTaalPerShare = accTaalPerShare.add(taalReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accTaalPerShare).div(1e12).sub(user.rewardDebt); } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } _adjustTaalPerBlock(); uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 taalReward = multiplier.mul(taalPerBlock).mul(pool.allocPoint).div(totalAllocPoint); taal.mint(devaddr, (taalReward.mul(15)).div(100)); // 15% for Dev taal.mint(address(syrup), taalReward); pool.accTaalPerShare = pool.accTaalPerShare.add(taalReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for TAL allocation. function deposit(uint256 _pid, uint256 _amount) public { require (_pid != 0, 'deposit TAL by staking'); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accTaalPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeTaalTransfer(msg.sender, pending); } } if (_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accTaalPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { require (_pid != 0, 'withdraw TAL by unstaking'); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accTaalPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeTaalTransfer(msg.sender, pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accTaalPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // Stake TAL tokens to MasterChef function enterStaking(uint256 _amount) public { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[0][msg.sender]; updatePool(0); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accTaalPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeTaalTransfer(msg.sender, pending); } } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accTaalPerShare).div(1e12); syrup.mint(msg.sender, _amount); emit Deposit(msg.sender, 0, _amount); } // Withdraw TAL tokens from STAKING. function leaveStaking(uint256 _amount) public { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[0][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(0); uint256 pending = user.amount.mul(pool.accTaalPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeTaalTransfer(msg.sender, pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accTaalPerShare).div(1e12); syrup.burn(msg.sender, _amount); emit Withdraw(msg.sender, 0, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe taal transfer function, just in case if rounding error causes pool to not have enough TALs. function safeTaalTransfer(address _to, uint256 _amount) internal { syrup.safeTaalTransfer(_to, _amount); } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } }
49,768
42
// join the MEV reward pool once it's deposited to official one.
IRewardPool(rewardPool).joinpool(info.claimAddr, DEPOSIT_SIZE);
IRewardPool(rewardPool).joinpool(info.claimAddr, DEPOSIT_SIZE);
6,866
9
// Set params such that they'll pass `StakingProxy.assertValidStorageParams`
epochDurationInSeconds = 5 days; cobbDouglasAlphaNumerator = 1; cobbDouglasAlphaDenominator = 1; rewardDelegatedStakeWeight = PPM_DENOMINATOR; minimumPoolStake = 100;
epochDurationInSeconds = 5 days; cobbDouglasAlphaNumerator = 1; cobbDouglasAlphaDenominator = 1; rewardDelegatedStakeWeight = PPM_DENOMINATOR; minimumPoolStake = 100;
21,660
29
// This event is triggered whenever a call to claim succeeds.
event Claimed(uint256 index, address account, uint256 amount);
event Claimed(uint256 index, address account, uint256 amount);
8,473
2
// toggle instant reveal
bool public instantRevealActive = false;
bool public instantRevealActive = false;
34,060
20
// adding constructor arguments to bytecodetokenName. tokenSymbol. /
function _getERC721Data(string memory tokenName, string memory tokenSymbol, string memory baseUri) view internal returns(bytes memory)
function _getERC721Data(string memory tokenName, string memory tokenSymbol, string memory baseUri) view internal returns(bytes memory)
1,160
19
// validate input
require(bytes(_name).length > 0, "ERR_INVALID_NAME"); require(bytes(_symbol).length > 0, "ERR_INVALID_SYMBOL"); name = _name; symbol = _symbol; decimals = _decimals; totalSupply = _totalSupply; balanceOf[msg.sender] = _totalSupply;
require(bytes(_name).length > 0, "ERR_INVALID_NAME"); require(bytes(_symbol).length > 0, "ERR_INVALID_SYMBOL"); name = _name; symbol = _symbol; decimals = _decimals; totalSupply = _totalSupply; balanceOf[msg.sender] = _totalSupply;
13,354
14
// 这里不需抛出异常,只需重置未付款
pendingReturns[msg.sender] = amount; return false;
pendingReturns[msg.sender] = amount; return false;
18,232
18
// Various setters/
function setReservedTokens(uint256 _reservedTokens) external onlyOwner { reservedTokens = _reservedTokens; }
function setReservedTokens(uint256 _reservedTokens) external onlyOwner { reservedTokens = _reservedTokens; }
79,659
71
// Seed for randomness
uint256 private _seed;
uint256 private _seed;
52,542
122
// is the token balance of this contract address over the min number of tokens that we need to initiate a swap + send lock? also, don't get caught in a circular sending event. also, don't swap & liquify if sender is uniswap pair.
uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= numTokensToExchangeForMarketing; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; }
uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= numTokensToExchangeForMarketing; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; }
2,107
244
// ICurveStableSwapEurs interface/Enzyme Council <[email protected]>
interface ICurveStableSwapEurs { function add_liquidity(uint256[2] calldata, uint256) external returns (uint256); function remove_liquidity(uint256, uint256[2] calldata) external returns (uint256[2] memory); function remove_liquidity_one_coin( uint256, int128, uint256 ) external returns (uint256); }
interface ICurveStableSwapEurs { function add_liquidity(uint256[2] calldata, uint256) external returns (uint256); function remove_liquidity(uint256, uint256[2] calldata) external returns (uint256[2] memory); function remove_liquidity_one_coin( uint256, int128, uint256 ) external returns (uint256); }
20,447
229
// turn on our toggle for harvests
harvestNow = true; if (!mintReth) {
harvestNow = true; if (!mintReth) {
3,716
332
// Copy whole words back to front We use a signed comparisson here to allow dEnd to become negative (happens when source and dest < 32). Valid addresses in local memory will never be larger than 2255, so they can be safely re-interpreted as signed. Note: the first check is always true, this could have been a do-while loop. solhint-disable-next-line no-empty-blocks
for {} slt(dest, dEnd) {} {
for {} slt(dest, dEnd) {} {
16,107
6
// execute an exact-in flash swap (specify an exact amount to pay) _tokenIn token address to sell _tokenOut token address to receive _fee pool fee _amountIn amount to sell _amountOutMinimum minimum amount to receive _callSource function call source _data arbitrary data assigned with the call/
function _exactInFlashSwap(address _tokenIn, address _tokenOut, uint24 _fee, uint256 _amountIn, uint256 _amountOutMinimum, uint8 _callSource, bytes memory _data) internal { uint256 amountOut = _exactInputInternal( _amountIn, address(this), uint160(0), SwapCallbackData({path: abi.encodePacked(_tokenIn, _fee, _tokenOut), caller: msg.sender, callSource: _callSource, callData: _data}) ); require(amountOut >= _amountOutMinimum, "amount out less than min"); }
function _exactInFlashSwap(address _tokenIn, address _tokenOut, uint24 _fee, uint256 _amountIn, uint256 _amountOutMinimum, uint8 _callSource, bytes memory _data) internal { uint256 amountOut = _exactInputInternal( _amountIn, address(this), uint160(0), SwapCallbackData({path: abi.encodePacked(_tokenIn, _fee, _tokenOut), caller: msg.sender, callSource: _callSource, callData: _data}) ); require(amountOut >= _amountOutMinimum, "amount out less than min"); }
43,212
51
// Event to show ownership transfer is pending currentOwner representing the address of the current owner pendingOwner representing the address of the pending owner /
event NewPendingOwner(address currentOwner, address pendingOwner);
event NewPendingOwner(address currentOwner, address pendingOwner);
18,798
11
// buy Usage an open sale, completing the sale and transferring/Usage of the NFT if enough Ether is supplied./_tokenId - ID of token to buy./_mateId - ID of token owned
function buyMating(uint256 _tokenId,uint256 _mateId) external onlyOwnerOf(_mateId) payable whenNotPaused returns(uint256 newFishID)
function buyMating(uint256 _tokenId,uint256 _mateId) external onlyOwnerOf(_mateId) payable whenNotPaused returns(uint256 newFishID)
23,327
77
// 定義一個事件「建立租約」 在什麼時間建立了租約、租約地址、房東地址、房客數量
event LeaseContractCreated( uint256 timestamp, address newLeaseContractAddress, address landlord, uint8 capacity );
event LeaseContractCreated( uint256 timestamp, address newLeaseContractAddress, address landlord, uint8 capacity );
6,607
9
// Set the proxy contract address which will call this contract. Can only beset once during contract initialization. target-Address of proxy contract using this contract. Should only be set once during contract init. /
function setControllerProxy(address target) internal initializer returns (bool) { _controllerProxy = target; return true; }
function setControllerProxy(address target) internal initializer returns (bool) { _controllerProxy = target; return true; }
26,641
131
// Minimum fee to create a token through the factory
uint256 public minimumFee; uint256 public integratorFeePct;
uint256 public minimumFee; uint256 public integratorFeePct;
22,575
18
// calculates the amount of credits to be created
uint256 creditBondAmount = _getCreditsAmount(ethAmount);
uint256 creditBondAmount = _getCreditsAmount(ethAmount);
39,969
30
// Helper function to calculate merkle tree interior nodes by sorting and concatenating and hashing a pair of children nodes, left and right.note: EVM scratch space is used to efficiently calculate hashes. _left The left hash. _right The right hash.return parent The parent hash. /
function sortConcatAndHash(bytes32 _left, bytes32 _right) internal pure returns (bytes32 parent) { // sort sibling hashes as a convention for efficient proof validation if (_left < _right) { // efficient hash using EVM scratch space assembly { mstore(0x00, _left) mstore(0x20, _right) parent := keccak256(0x00, 0x40) } } else { assembly { mstore(0x00, _right) mstore(0x20, _left) parent := keccak256(0x00, 0x40) } } }
function sortConcatAndHash(bytes32 _left, bytes32 _right) internal pure returns (bytes32 parent) { // sort sibling hashes as a convention for efficient proof validation if (_left < _right) { // efficient hash using EVM scratch space assembly { mstore(0x00, _left) mstore(0x20, _right) parent := keccak256(0x00, 0x40) } } else { assembly { mstore(0x00, _right) mstore(0x20, _left) parent := keccak256(0x00, 0x40) } } }
22,743
31
// Only the user who related with the token allowance can see the allowance value
require(msg.sender == _owner || msg.sender == _spender); return allowed[_owner][_spender];
require(msg.sender == _owner || msg.sender == _spender); return allowed[_owner][_spender];
47,481
15
// Coupon payment - a cash amount is paid on every Coupon Payment Date, equal to Denomination times Coupon.
Payment memory payment; payment.payment_date = currAccrual.coupon_payment_date; payment.payment_amount = (denomination * accrued_coupon) / (10 ** decimals) / (10 ** decimals); // this is because accrued_coupon is daysIn / totalDays return payment;
Payment memory payment; payment.payment_date = currAccrual.coupon_payment_date; payment.payment_amount = (denomination * accrued_coupon) / (10 ** decimals) / (10 ** decimals); // this is because accrued_coupon is daysIn / totalDays return payment;
3,677
315
// can be set only once
require(m_funds == address(0)); m_funds = FundsRegistry(_funds);
require(m_funds == address(0)); m_funds = FundsRegistry(_funds);
16,238
54
// Destoys `amount` tokens from `account`, reducing thetotal supply. Emits a `Transfer` event with `to` set to the zero address. Requirements - `account` cannot be the zero address.- `account` must have at least `amount` tokens. /
function _burn(address account, uint256 value) internal { require(account != address(0), "ERC20: burn from the zero address"); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); }
function _burn(address account, uint256 value) internal { require(account != address(0), "ERC20: burn from the zero address"); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); }
16,074
45
// Price is per "token ETH"; tokensPerWeek is in "token wei".
require(weekShares[week].mul(1e18) <= currentPrice * tokensPerWeek, "Oversold");
require(weekShares[week].mul(1e18) <= currentPrice * tokensPerWeek, "Oversold");
11,932
2
// Next 5 lines from https:ethereum.stackexchange.com/a/83577
if (result.length < 68) revert(); assembly { result := add(result, 0x04) }
if (result.length < 68) revert(); assembly { result := add(result, 0x04) }
20,986
5
// Delete function to be called by authorized issuers owners The owners of the attestations to be deleted collectionIds The collection ids of the attestations to be deleted /
function deleteAttestations( address[] calldata owners, uint256[] calldata collectionIds
function deleteAttestations( address[] calldata owners, uint256[] calldata collectionIds
25,437
120
// Determine the current price
updatePrices();
updatePrices();
30,446
53
// Burns a specific amount of tokens from the target address and decrements allowancefrom address The address which you want to send tokens fromvalue uint256 The amount of token to be burned/
function burnFrom(address from, uint256 value) public returns (bool) { _burnFrom(from, value); return true; }
function burnFrom(address from, uint256 value) public returns (bool) { _burnFrom(from, value); return true; }
1,798
27
// sets the amount of tokens to gift threshold _value new value of the amount to gift/
function setGiftTokenAmount(uint256 _value) { giftTokenAmount = _value; }
function setGiftTokenAmount(uint256 _value) { giftTokenAmount = _value; }
47,116
29
// Returns the current balance. Ignores COMP that was not liquidated and invested./
function investedUnderlyingBalance() public view returns (uint256) { // NOTE: The use of virtual price is okay for appreciating assets inside IDLE, // but would be wrong and exploitable if funds were lost by IDLE, indicated by // the virtualPrice being greater than the token price. if (protected) { require(virtualPrice <= idleTokenHelper.getRedeemPrice(idleUnderlying), "virtual price is higher than needed"); } uint256 invested = IERC20(idleUnderlying).balanceOf(address(this)).mul(virtualPrice).div(1e18); return invested.add(IERC20(underlying).balanceOf(address(this))); }
function investedUnderlyingBalance() public view returns (uint256) { // NOTE: The use of virtual price is okay for appreciating assets inside IDLE, // but would be wrong and exploitable if funds were lost by IDLE, indicated by // the virtualPrice being greater than the token price. if (protected) { require(virtualPrice <= idleTokenHelper.getRedeemPrice(idleUnderlying), "virtual price is higher than needed"); } uint256 invested = IERC20(idleUnderlying).balanceOf(address(this)).mul(virtualPrice).div(1e18); return invested.add(IERC20(underlying).balanceOf(address(this))); }
44,915
3
// Permite al propietario actual ceder el control del contrato./
function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); }
function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); }
10,891
42
// function to update the freeToUnstakeBalance and totalLockedBalance
function _updateStakeholderBalances(address _stakeholderAddress) private { // We verify first that the address corresponds to an actual stakeholder require( stakeholders[_stakeholderAddress].stakings.length != 0, "Not a stakeholder!" ); //use temporary variable to avoid writing to storage multiple times uint256 freeToUnstakeBalTemp; uint256 totalLockedBalTemp; for ( uint256 i = 0; i < stakeholders[_stakeholderAddress].stakings.length; i++ ) { Staking memory _staking = stakeholders[_stakeholderAddress] .stakings[i]; int256 amount = _staking.amount; if (_staking.lockDuration == 0) { // in case we deal with flex staking if (amount < 0) { //we deal with an unstaking event uint256 amountpos = SafeCast.toUint256(-amount); if (amountpos <= freeToUnstakeBalTemp) { freeToUnstakeBalTemp -= amountpos; } else { freeToUnstakeBalTemp = 0; } } else { //we deal with a staking event if (block.timestamp - _staking.timestamp > 30 days) { freeToUnstakeBalTemp += SafeCast.toUint256(amount); } } } else { // in case we deal with locked Staking if ( block.timestamp - _staking.timestamp > _staking.lockDuration ) { //lockTime finished freeToUnstakeBalTemp += SafeCast.toUint256(amount); } else { //staking still locked totalLockedBalTemp += SafeCast.toUint256(amount); } } } stakeholders[_stakeholderAddress] .freeToUnstakeBalance = freeToUnstakeBalTemp; stakeholders[_stakeholderAddress] .totalLockedBalance = totalLockedBalTemp; // update lastBalancesUpdate stakeholders[_stakeholderAddress].lastBalancesUpdate = block.timestamp; }
function _updateStakeholderBalances(address _stakeholderAddress) private { // We verify first that the address corresponds to an actual stakeholder require( stakeholders[_stakeholderAddress].stakings.length != 0, "Not a stakeholder!" ); //use temporary variable to avoid writing to storage multiple times uint256 freeToUnstakeBalTemp; uint256 totalLockedBalTemp; for ( uint256 i = 0; i < stakeholders[_stakeholderAddress].stakings.length; i++ ) { Staking memory _staking = stakeholders[_stakeholderAddress] .stakings[i]; int256 amount = _staking.amount; if (_staking.lockDuration == 0) { // in case we deal with flex staking if (amount < 0) { //we deal with an unstaking event uint256 amountpos = SafeCast.toUint256(-amount); if (amountpos <= freeToUnstakeBalTemp) { freeToUnstakeBalTemp -= amountpos; } else { freeToUnstakeBalTemp = 0; } } else { //we deal with a staking event if (block.timestamp - _staking.timestamp > 30 days) { freeToUnstakeBalTemp += SafeCast.toUint256(amount); } } } else { // in case we deal with locked Staking if ( block.timestamp - _staking.timestamp > _staking.lockDuration ) { //lockTime finished freeToUnstakeBalTemp += SafeCast.toUint256(amount); } else { //staking still locked totalLockedBalTemp += SafeCast.toUint256(amount); } } } stakeholders[_stakeholderAddress] .freeToUnstakeBalance = freeToUnstakeBalTemp; stakeholders[_stakeholderAddress] .totalLockedBalance = totalLockedBalTemp; // update lastBalancesUpdate stakeholders[_stakeholderAddress].lastBalancesUpdate = block.timestamp; }
37,516
25
// NFTfiSigningUtils NFTfi Helper contract for NFTfi. This contract manages verifying signatures from off-chain NFTfi orders.Based on the version of this same contract used on NFTfi V1 /
library NFTfiSigningUtils { /* ********* */ /* FUNCTIONS */ /* ********* */ /** * @dev This function gets the current chain ID. */ function getChainID() public view returns (uint256) { uint256 id; // solhint-disable-next-line no-inline-assembly assembly { id := chainid() } return id; } /** * @notice This function is when the lender accepts a borrower's binding listing terms, to validate the lender's * signature that the borrower provided off-chain to verify that it did indeed made such listing. * * @param _listingTerms - The listing terms struct containing: * - loanERC20Denomination: The address of the ERC20 contract of the currency being used as principal/interest * for this loan. * - minLoanPrincipalAmount: The minumum sum of money transferred from lender to borrower at the beginning of * the loan, measured in loanERC20Denomination's smallest units. * - maxLoanPrincipalAmount: The sum of money transferred from lender to borrower at the beginning of * the loan, measured in loanERC20Denomination's smallest units. * - maximumRepaymentAmount: The maximum amount of money that the borrower would be required to retrieve their * collateral, measured in the smallest units of the ERC20 currency used for the loan. The borrower will always have * to pay this amount to retrieve their collateral, regardless of whether they repay early. * - nftCollateralContract: The address of the ERC721 contract of the NFT collateral. * - nftCollateralId: The ID within the NFTCollateralContract for the NFT being used as collateral for this * loan. The NFT is stored within this contract during the duration of the loan. * - revenueSharePartner: The address of the partner that will receive the revenue share. * - minLoanDuration: The minumum amount of time (measured in seconds) that can elapse before the lender can * liquidate the loan and seize the underlying collateral NFT. * - maxLoanDuration: The maximum amount of time (measured in seconds) that can elapse before the lender can * liquidate the loan and seize the underlying collateral NFT. * - maxInterestRateForDurationInBasisPoints: This is maximum the interest rate (measured in basis points, e.g. * hundreths of a percent) for the loan, that must be repaid pro-rata by the borrower at the conclusion of the loan * or risk seizure of their nft collateral. Note if the type of the loan is fixed then this value is not used and * is irrelevant so it should be set to 0. * - referralFeeInBasisPoints: The percent (measured in basis points) of the loan principal amount that will be * taken as a fee to pay to the referrer, 0 if the lender is not paying referral fee. * @param _signature - The offer struct containing: * - signer: The address of the signer. The borrower for `acceptOffer` the lender for `acceptListing`. * - nonce: The nonce referred here is not the same as an Ethereum account's nonce. * We are referring instead to a nonce that is used by the lender or the borrower when they are first signing * off-chain NFTfi orders. These nonce can be any uint256 value that the user has not previously used to sign an * off-chain order. Each nonce can be used at most once per user within NFTfi, regardless of whether they are the * lender or the borrower in that situation. This serves two purposes: * - First, it prevents replay attacks where an attacker would submit a user's off-chain order more than once. * - Second, it allows a user to cancel an off-chain order by calling * NFTfi.cancelLoanCommitmentBeforeLoanHasBegun(), which marks the nonce as used and prevents any future loan from * using the user's off-chain order that contains that nonce. * - expiry: Date when the signature expires * - signature: The ECDSA signature of the borrower, obtained off-chain ahead of time, signing the following * combination of parameters: * - listingTerms.loanERC20Denomination, * - listingTerms.minLoanPrincipalAmount, * - listingTerms.maxLoanPrincipalAmount, * - listingTerms.nftCollateralContract, * - listingTerms.nftCollateralId, * - listingTerms.revenueSharePartner, * - listingTerms.minLoanDuration, * - listingTerms.maxLoanDuration, * - listingTerms.maxInterestRateForDurationInBasisPoints, * - listingTerms.referralFeeInBasisPoints, * - signature.signer, * - signature.nonce, * - signature.expiry, * - address of this contract * - chainId */ function isValidBorrowerSignature(LoanData.ListingTerms memory _listingTerms, LoanData.Signature memory _signature) external view returns (bool) { return isValidBorrowerSignature(_listingTerms, _signature, address(this)); } /** * @dev This function overload the previous function to allow the caller to specify the address of the contract * */ function isValidBorrowerSignature( LoanData.ListingTerms memory _listingTerms, LoanData.Signature memory _signature, address _loanContract ) public view returns (bool) { require(block.timestamp <= _signature.expiry, "Borrower Signature has expired"); require(_loanContract != address(0), "Loan is zero address"); if (_signature.signer == address(0)) { return false; } else { bytes32 message = keccak256( abi.encodePacked( getEncodedListing(_listingTerms), getEncodedSignature(_signature), _loanContract, getChainID() ) ); return SignatureChecker.isValidSignatureNow( _signature.signer, ECDSA.toEthSignedMessageHash(message), _signature.signature ); } } /** * @notice This function is when the lender accepts a borrower's binding listing terms, to validate the lender's * signature that the borrower provided off-chain to verify that it did indeed made such listing. * * @param _listingTerms - The listing terms struct containing: * - loanERC20Denomination: The address of the ERC20 contract of the currency being used as principal/interest * for this loan. * - minLoanPrincipalAmount: The minumum sum of money transferred from lender to borrower at the beginning of * the loan, measured in loanERC20Denomination's smallest units. * - maxLoanPrincipalAmount: The sum of money transferred from lender to borrower at the beginning of * the loan, measured in loanERC20Denomination's smallest units. * - maximumRepaymentAmount: The maximum amount of money that the borrower would be required to retrieve their * collateral, measured in the smallest units of the ERC20 currency used for the loan. The borrower will always have * to pay this amount to retrieve their collateral, regardless of whether they repay early. * - nftCollateralContract: The address of the ERC721 contract of the NFT collateral. * - nftCollateralId: The ID within the NFTCollateralContract for the NFT being used as collateral for this * loan. The NFT is stored within this contract during the duration of the loan. * - revenueSharePartner: The address of the partner that will receive the revenue share. * - minLoanDuration: The minumum amount of time (measured in seconds) that can elapse before the lender can * liquidate the loan and seize the underlying collateral NFT. * - maxLoanDuration: The maximum amount of time (measured in seconds) that can elapse before the lender can * liquidate the loan and seize the underlying collateral NFT. * - maxInterestRateForDurationInBasisPoints: This is maximum the interest rate (measured in basis points, e.g. * hundreths of a percent) for the loan, that must be repaid pro-rata by the borrower at the conclusion of the loan * or risk seizure of their nft collateral. Note if the type of the loan is fixed then this value is not used and * is irrelevant so it should be set to 0. * - referralFeeInBasisPoints: The percent (measured in basis points) of the loan principal amount that will be * taken as a fee to pay to the referrer, 0 if the lender is not paying referral fee. * @param _bundleElements - the lists of erc721-20-1155 tokens that are to be bundled * @param _signature - The offer struct containing: * - signer: The address of the signer. The borrower for `acceptOffer` the lender for `acceptListing`. * - nonce: The nonce referred here is not the same as an Ethereum account's nonce. * We are referring instead to a nonce that is used by the lender or the borrower when they are first signing * off-chain NFTfi orders. These nonce can be any uint256 value that the user has not previously used to sign an * off-chain order. Each nonce can be used at most once per user within NFTfi, regardless of whether they are the * lender or the borrower in that situation. This serves two purposes: * - First, it prevents replay attacks where an attacker would submit a user's off-chain order more than once. * - Second, it allows a user to cancel an off-chain order by calling * NFTfi.cancelLoanCommitmentBeforeLoanHasBegun(), which marks the nonce as used and prevents any future loan from * using the user's off-chain order that contains that nonce. * - expiry: Date when the signature expires * - signature: The ECDSA signature of the borrower, obtained off-chain ahead of time, signing the following * combination of parameters: * - listingTerms.loanERC20Denomination, * - listingTerms.minLoanPrincipalAmount, * - listingTerms.maxLoanPrincipalAmount, * - listingTerms.nftCollateralContract, * - listingTerms.nftCollateralId, * - listingTerms.revenueSharePartner, * - listingTerms.minLoanDuration, * - listingTerms.maxLoanDuration, * - listingTerms.maxInterestRateForDurationInBasisPoints, * - listingTerms.referralFeeInBasisPoints, * - bundleElements * - signature.signer, * - signature.nonce, * - signature.expiry, * - address of this contract * - chainId */ function isValidBorrowerSignatureBundle( LoanData.ListingTerms memory _listingTerms, IBundleBuilder.BundleElements memory _bundleElements, LoanData.Signature memory _signature ) external view returns (bool) { return isValidBorrowerSignatureBundle(_listingTerms, _bundleElements, _signature, address(this)); } /** * @dev This function overload the previous function to allow the caller to specify the address of the contract * */ function isValidBorrowerSignatureBundle( LoanData.ListingTerms memory _listingTerms, IBundleBuilder.BundleElements memory _bundleElements, LoanData.Signature memory _signature, address _loanContract ) public view returns (bool) { require(block.timestamp <= _signature.expiry, "Borrower Signature has expired"); require(_loanContract != address(0), "Loan is zero address"); if (_signature.signer == address(0)) { return false; } else { bytes32 message = keccak256( abi.encodePacked( getEncodedListing(_listingTerms), abi.encode(_bundleElements), getEncodedSignature(_signature), _loanContract, getChainID() ) ); return SignatureChecker.isValidSignatureNow( _signature.signer, ECDSA.toEthSignedMessageHash(message), _signature.signature ); } } /** * @notice This function is when the borrower accepts a lender's offer, to validate the lender's signature that the * lender provided off-chain to verify that it did indeed made such offer. * * @param _offer - The offer struct containing: * - loanERC20Denomination: The address of the ERC20 contract of the currency being used as principal/interest * for this loan. * - loanPrincipalAmount: The original sum of money transferred from lender to borrower at the beginning of * the loan, measured in loanERC20Denomination's smallest units. * - maximumRepaymentAmount: The maximum amount of money that the borrower would be required to retrieve their * collateral, measured in the smallest units of the ERC20 currency used for the loan. The borrower will always have * to pay this amount to retrieve their collateral, regardless of whether they repay early. * - nftCollateralContract: The address of the ERC721 contract of the NFT collateral. * - nftCollateralId: The ID within the NFTCollateralContract for the NFT being used as collateral for this * loan. The NFT is stored within this contract during the duration of the loan. * - referrer: The address of the referrer who found the lender matching the listing, Zero address to signal * this there is no referrer. * - loanDuration: The amount of time (measured in seconds) that can elapse before the lender can liquidate the * loan and seize the underlying collateral NFT. * - loanInterestRateForDurationInBasisPoints: This is the interest rate (measured in basis points, e.g. * hundreths of a percent) for the loan, that must be repaid pro-rata by the borrower at the conclusion of the loan * or risk seizure of their nft collateral. Note if the type of the loan is fixed then this value is not used and * is irrelevant so it should be set to 0. * - loanAdminFeeInBasisPoints: The percent (measured in basis points) of the interest earned that will be * taken as a fee by the contract admins when the loan is repaid. The fee is stored in the loan struct to prevent an * attack where the contract admins could adjust the fee right before a loan is repaid, and take all of the interest * earned. * @param _signature - The signature structure containing: * - signer: The address of the signer. The borrower for `acceptOffer` the lender for `acceptListing`. * - nonce: The nonce referred here is not the same as an Ethereum account's nonce. * We are referring instead to a nonce that is used by the lender or the borrower when they are first signing * off-chain NFTfi orders. These nonce can be any uint256 value that the user has not previously used to sign an * off-chain order. Each nonce can be used at most once per user within NFTfi, regardless of whether they are the * lender or the borrower in that situation. This serves two purposes: * - First, it prevents replay attacks where an attacker would submit a user's off-chain order more than once. * - Second, it allows a user to cancel an off-chain order by calling * NFTfi.cancelLoanCommitmentBeforeLoanHasBegun(), which marks the nonce as used and prevents any future loan from * using the user's off-chain order that contains that nonce. * - expiry: Date when the signature expires * - signature: The ECDSA signature of the lender, obtained off-chain ahead of time, signing the following * combination of parameters: * - offer.loanERC20Denomination * - offer.loanPrincipalAmount * - offer.maximumRepaymentAmount * - offer.nftCollateralContract * - offer.nftCollateralId * - offer.referrer * - offer.loanDuration * - offer.loanAdminFeeInBasisPoints * - signature.signer, * - signature.nonce, * - signature.expiry, * - address of this contract * - chainId */ function isValidLenderSignature(LoanData.Offer memory _offer, LoanData.Signature memory _signature) external view returns (bool) { return isValidLenderSignature(_offer, _signature, address(this)); } /** * @dev This function overload the previous function to allow the caller to specify the address of the contract * */ function isValidLenderSignature( LoanData.Offer memory _offer, LoanData.Signature memory _signature, address _loanContract ) public view returns (bool) { require(block.timestamp <= _signature.expiry, "Lender Signature has expired"); require(_loanContract != address(0), "Loan is zero address"); if (_signature.signer == address(0)) { return false; } else { bytes32 message = keccak256( abi.encodePacked(getEncodedOffer(_offer), getEncodedSignature(_signature), _loanContract, getChainID()) ); return SignatureChecker.isValidSignatureNow( _signature.signer, ECDSA.toEthSignedMessageHash(message), _signature.signature ); } } /** * @notice This function is when the borrower accepts a lender's offer, to validate the lender's signature that the * lender provided off-chain to verify that it did indeed made such offer. * * @param _offer - The offer struct containing: * - loanERC20Denomination: The address of the ERC20 contract of the currency being used as principal/interest * for this loan. * - loanPrincipalAmount: The original sum of money transferred from lender to borrower at the beginning of * the loan, measured in loanERC20Denomination's smallest units. * - maximumRepaymentAmount: The maximum amount of money that the borrower would be required to retrieve their * collateral, measured in the smallest units of the ERC20 currency used for the loan. The borrower will always have * to pay this amount to retrieve their collateral, regardless of whether they repay early. * - nftCollateralContract: The address of the ERC721 contract of the NFT collateral. * - nftCollateralId: The ID within the NFTCollateralContract for the NFT being used as collateral for this * loan. The NFT is stored within this contract during the duration of the loan. * - referrer: The address of the referrer who found the lender matching the listing, Zero address to signal * this there is no referrer. * - loanDuration: The amount of time (measured in seconds) that can elapse before the lender can liquidate the * loan and seize the underlying collateral NFT. * - loanInterestRateForDurationInBasisPoints: This is the interest rate (measured in basis points, e.g. * hundreths of a percent) for the loan, that must be repaid pro-rata by the borrower at the conclusion of the loan * or risk seizure of their nft collateral. Note if the type of the loan is fixed then this value is not used and * is irrelevant so it should be set to 0. * - loanAdminFeeInBasisPoints: The percent (measured in basis points) of the interest earned that will be * taken as a fee by the contract admins when the loan is repaid. The fee is stored in the loan struct to prevent an * attack where the contract admins could adjust the fee right before a loan is repaid, and take all of the interest * earned. * @param _bundleElements - the lists of erc721-20-1155 tokens that are to be bundled * @param _signature - The signature structure containing: * - signer: The address of the signer. The borrower for `acceptOffer` the lender for `acceptListing`. * - nonce: The nonce referred here is not the same as an Ethereum account's nonce. * We are referring instead to a nonce that is used by the lender or the borrower when they are first signing * off-chain NFTfi orders. These nonce can be any uint256 value that the user has not previously used to sign an * off-chain order. Each nonce can be used at most once per user within NFTfi, regardless of whether they are the * lender or the borrower in that situation. This serves two purposes: * - First, it prevents replay attacks where an attacker would submit a user's off-chain order more than once. * - Second, it allows a user to cancel an off-chain order by calling * NFTfi.cancelLoanCommitmentBeforeLoanHasBegun(), which marks the nonce as used and prevents any future loan from * using the user's off-chain order that contains that nonce. * - expiry: Date when the signature expires * - signature: The ECDSA signature of the lender, obtained off-chain ahead of time, signing the following * combination of parameters: * - offer.loanERC20Denomination * - offer.loanPrincipalAmount * - offer.maximumRepaymentAmount * - offer.nftCollateralContract * - offer.nftCollateralId * - offer.referrer * - offer.loanDuration * - offer.loanAdminFeeInBasisPoints * - bundleElements * - signature.signer, * - signature.nonce, * - signature.expiry, * - address of this contract * - chainId */ function isValidLenderSignatureBundle( LoanData.Offer memory _offer, IBundleBuilder.BundleElements memory _bundleElements, LoanData.Signature memory _signature ) external view returns (bool) { return isValidLenderSignatureBundle(_offer, _bundleElements, _signature, address(this)); } /** * @dev This function overload the previous function to allow the caller to specify the address of the contract * */ function isValidLenderSignatureBundle( LoanData.Offer memory _offer, IBundleBuilder.BundleElements memory _bundleElements, LoanData.Signature memory _signature, address _loanContract ) public view returns (bool) { require(block.timestamp <= _signature.expiry, "Lender Signature has expired"); require(_loanContract != address(0), "Loan is zero address"); if (_signature.signer == address(0)) { return false; } else { bytes32 message = keccak256( abi.encodePacked( getEncodedOffer(_offer), abi.encode(_bundleElements), getEncodedSignature(_signature), _loanContract, getChainID() ) ); return SignatureChecker.isValidSignatureNow( _signature.signer, ECDSA.toEthSignedMessageHash(message), _signature.signature ); } } /** * @notice This function is called in renegotiateLoan() to validate the lender's signature that the lender provided * off-chain to verify that they did indeed want to agree to this loan renegotiation according to these terms. * * @param _loanId - The unique identifier for the loan to be renegotiated * @param _newLoanDuration - The new amount of time (measured in seconds) that can elapse before the lender can * liquidate the loan and seize the underlying collateral NFT. * @param _newMaximumRepaymentAmount - The new maximum amount of money that the borrower would be required to * retrieve their collateral, measured in the smallest units of the ERC20 currency used for the loan. The * borrower will always have to pay this amount to retrieve their collateral, regardless of whether they repay * early. * @param _renegotiationFee Agreed upon fee in ether that borrower pays for the lender for the renegitiation * @param _signature - The signature structure containing: * - signer: The address of the signer. The borrower for `acceptOffer` the lender for `acceptListing`. * - nonce: The nonce referred here is not the same as an Ethereum account's nonce. * We are referring instead to a nonce that is used by the lender or the borrower when they are first signing * off-chain NFTfi orders. These nonce can be any uint256 value that the user has not previously used to sign an * off-chain order. Each nonce can be used at most once per user within NFTfi, regardless of whether they are the * lender or the borrower in that situation. This serves two purposes: * - First, it prevents replay attacks where an attacker would submit a user's off-chain order more than once. * - Second, it allows a user to cancel an off-chain order by calling NFTfi.cancelLoanCommitmentBeforeLoanHasBegun() * , which marks the nonce as used and prevents any future loan from using the user's off-chain order that contains * that nonce. * - expiry - The date when the renegotiation offer expires * - lenderSignature - The ECDSA signature of the lender, obtained off-chain ahead of time, signing the * following combination of parameters: * - _loanId * - _newLoanDuration * - _newMaximumRepaymentAmount * - _lender * - _lenderNonce * - _expiry * - address of this contract * - chainId */ function isValidLenderRenegotiationSignature( uint256 _loanId, uint32 _newLoanDuration, uint256 _newMaximumRepaymentAmount, uint256 _renegotiationFee, LoanData.Signature memory _signature ) external view returns (bool) { return isValidLenderRenegotiationSignature( _loanId, _newLoanDuration, _newMaximumRepaymentAmount, _renegotiationFee, _signature, address(this) ); } /** * @dev This function overload the previous function to allow the caller to specify the address of the contract * */ function isValidLenderRenegotiationSignature( uint256 _loanId, uint32 _newLoanDuration, uint256 _newMaximumRepaymentAmount, uint256 _renegotiationFee, LoanData.Signature memory _signature, address _loanContract ) public view returns (bool) { require(block.timestamp <= _signature.expiry, "Renegotiation Signature has expired"); require(_loanContract != address(0), "Loan is zero address"); if (_signature.signer == address(0)) { return false; } else { bytes32 message = keccak256( abi.encodePacked( _loanId, _newLoanDuration, _newMaximumRepaymentAmount, _renegotiationFee, getEncodedSignature(_signature), _loanContract, getChainID() ) ); return SignatureChecker.isValidSignatureNow( _signature.signer, ECDSA.toEthSignedMessageHash(message), _signature.signature ); } } /** * @dev We need this to avoid stack too deep errors. */ function getEncodedListing(LoanData.ListingTerms memory _listingTerms) internal pure returns (bytes memory) { return abi.encodePacked( _listingTerms.loanERC20Denomination, _listingTerms.minLoanPrincipalAmount, _listingTerms.maxLoanPrincipalAmount, _listingTerms.nftCollateralContract, _listingTerms.nftCollateralId, _listingTerms.revenueSharePartner, _listingTerms.minLoanDuration, _listingTerms.maxLoanDuration, _listingTerms.maxInterestRateForDurationInBasisPoints, _listingTerms.referralFeeInBasisPoints ); } /** * @dev We need this to avoid stack too deep errors. */ function getEncodedOffer(LoanData.Offer memory _offer) internal pure returns (bytes memory) { return abi.encodePacked( _offer.loanERC20Denomination, _offer.loanPrincipalAmount, _offer.maximumRepaymentAmount, _offer.nftCollateralContract, _offer.nftCollateralId, _offer.referrer, _offer.loanDuration, _offer.loanAdminFeeInBasisPoints ); } /** * @dev We need this to avoid stack too deep errors. */ function getEncodedSignature(LoanData.Signature memory _signature) internal pure returns (bytes memory) { return abi.encodePacked(_signature.signer, _signature.nonce, _signature.expiry); } }
library NFTfiSigningUtils { /* ********* */ /* FUNCTIONS */ /* ********* */ /** * @dev This function gets the current chain ID. */ function getChainID() public view returns (uint256) { uint256 id; // solhint-disable-next-line no-inline-assembly assembly { id := chainid() } return id; } /** * @notice This function is when the lender accepts a borrower's binding listing terms, to validate the lender's * signature that the borrower provided off-chain to verify that it did indeed made such listing. * * @param _listingTerms - The listing terms struct containing: * - loanERC20Denomination: The address of the ERC20 contract of the currency being used as principal/interest * for this loan. * - minLoanPrincipalAmount: The minumum sum of money transferred from lender to borrower at the beginning of * the loan, measured in loanERC20Denomination's smallest units. * - maxLoanPrincipalAmount: The sum of money transferred from lender to borrower at the beginning of * the loan, measured in loanERC20Denomination's smallest units. * - maximumRepaymentAmount: The maximum amount of money that the borrower would be required to retrieve their * collateral, measured in the smallest units of the ERC20 currency used for the loan. The borrower will always have * to pay this amount to retrieve their collateral, regardless of whether they repay early. * - nftCollateralContract: The address of the ERC721 contract of the NFT collateral. * - nftCollateralId: The ID within the NFTCollateralContract for the NFT being used as collateral for this * loan. The NFT is stored within this contract during the duration of the loan. * - revenueSharePartner: The address of the partner that will receive the revenue share. * - minLoanDuration: The minumum amount of time (measured in seconds) that can elapse before the lender can * liquidate the loan and seize the underlying collateral NFT. * - maxLoanDuration: The maximum amount of time (measured in seconds) that can elapse before the lender can * liquidate the loan and seize the underlying collateral NFT. * - maxInterestRateForDurationInBasisPoints: This is maximum the interest rate (measured in basis points, e.g. * hundreths of a percent) for the loan, that must be repaid pro-rata by the borrower at the conclusion of the loan * or risk seizure of their nft collateral. Note if the type of the loan is fixed then this value is not used and * is irrelevant so it should be set to 0. * - referralFeeInBasisPoints: The percent (measured in basis points) of the loan principal amount that will be * taken as a fee to pay to the referrer, 0 if the lender is not paying referral fee. * @param _signature - The offer struct containing: * - signer: The address of the signer. The borrower for `acceptOffer` the lender for `acceptListing`. * - nonce: The nonce referred here is not the same as an Ethereum account's nonce. * We are referring instead to a nonce that is used by the lender or the borrower when they are first signing * off-chain NFTfi orders. These nonce can be any uint256 value that the user has not previously used to sign an * off-chain order. Each nonce can be used at most once per user within NFTfi, regardless of whether they are the * lender or the borrower in that situation. This serves two purposes: * - First, it prevents replay attacks where an attacker would submit a user's off-chain order more than once. * - Second, it allows a user to cancel an off-chain order by calling * NFTfi.cancelLoanCommitmentBeforeLoanHasBegun(), which marks the nonce as used and prevents any future loan from * using the user's off-chain order that contains that nonce. * - expiry: Date when the signature expires * - signature: The ECDSA signature of the borrower, obtained off-chain ahead of time, signing the following * combination of parameters: * - listingTerms.loanERC20Denomination, * - listingTerms.minLoanPrincipalAmount, * - listingTerms.maxLoanPrincipalAmount, * - listingTerms.nftCollateralContract, * - listingTerms.nftCollateralId, * - listingTerms.revenueSharePartner, * - listingTerms.minLoanDuration, * - listingTerms.maxLoanDuration, * - listingTerms.maxInterestRateForDurationInBasisPoints, * - listingTerms.referralFeeInBasisPoints, * - signature.signer, * - signature.nonce, * - signature.expiry, * - address of this contract * - chainId */ function isValidBorrowerSignature(LoanData.ListingTerms memory _listingTerms, LoanData.Signature memory _signature) external view returns (bool) { return isValidBorrowerSignature(_listingTerms, _signature, address(this)); } /** * @dev This function overload the previous function to allow the caller to specify the address of the contract * */ function isValidBorrowerSignature( LoanData.ListingTerms memory _listingTerms, LoanData.Signature memory _signature, address _loanContract ) public view returns (bool) { require(block.timestamp <= _signature.expiry, "Borrower Signature has expired"); require(_loanContract != address(0), "Loan is zero address"); if (_signature.signer == address(0)) { return false; } else { bytes32 message = keccak256( abi.encodePacked( getEncodedListing(_listingTerms), getEncodedSignature(_signature), _loanContract, getChainID() ) ); return SignatureChecker.isValidSignatureNow( _signature.signer, ECDSA.toEthSignedMessageHash(message), _signature.signature ); } } /** * @notice This function is when the lender accepts a borrower's binding listing terms, to validate the lender's * signature that the borrower provided off-chain to verify that it did indeed made such listing. * * @param _listingTerms - The listing terms struct containing: * - loanERC20Denomination: The address of the ERC20 contract of the currency being used as principal/interest * for this loan. * - minLoanPrincipalAmount: The minumum sum of money transferred from lender to borrower at the beginning of * the loan, measured in loanERC20Denomination's smallest units. * - maxLoanPrincipalAmount: The sum of money transferred from lender to borrower at the beginning of * the loan, measured in loanERC20Denomination's smallest units. * - maximumRepaymentAmount: The maximum amount of money that the borrower would be required to retrieve their * collateral, measured in the smallest units of the ERC20 currency used for the loan. The borrower will always have * to pay this amount to retrieve their collateral, regardless of whether they repay early. * - nftCollateralContract: The address of the ERC721 contract of the NFT collateral. * - nftCollateralId: The ID within the NFTCollateralContract for the NFT being used as collateral for this * loan. The NFT is stored within this contract during the duration of the loan. * - revenueSharePartner: The address of the partner that will receive the revenue share. * - minLoanDuration: The minumum amount of time (measured in seconds) that can elapse before the lender can * liquidate the loan and seize the underlying collateral NFT. * - maxLoanDuration: The maximum amount of time (measured in seconds) that can elapse before the lender can * liquidate the loan and seize the underlying collateral NFT. * - maxInterestRateForDurationInBasisPoints: This is maximum the interest rate (measured in basis points, e.g. * hundreths of a percent) for the loan, that must be repaid pro-rata by the borrower at the conclusion of the loan * or risk seizure of their nft collateral. Note if the type of the loan is fixed then this value is not used and * is irrelevant so it should be set to 0. * - referralFeeInBasisPoints: The percent (measured in basis points) of the loan principal amount that will be * taken as a fee to pay to the referrer, 0 if the lender is not paying referral fee. * @param _bundleElements - the lists of erc721-20-1155 tokens that are to be bundled * @param _signature - The offer struct containing: * - signer: The address of the signer. The borrower for `acceptOffer` the lender for `acceptListing`. * - nonce: The nonce referred here is not the same as an Ethereum account's nonce. * We are referring instead to a nonce that is used by the lender or the borrower when they are first signing * off-chain NFTfi orders. These nonce can be any uint256 value that the user has not previously used to sign an * off-chain order. Each nonce can be used at most once per user within NFTfi, regardless of whether they are the * lender or the borrower in that situation. This serves two purposes: * - First, it prevents replay attacks where an attacker would submit a user's off-chain order more than once. * - Second, it allows a user to cancel an off-chain order by calling * NFTfi.cancelLoanCommitmentBeforeLoanHasBegun(), which marks the nonce as used and prevents any future loan from * using the user's off-chain order that contains that nonce. * - expiry: Date when the signature expires * - signature: The ECDSA signature of the borrower, obtained off-chain ahead of time, signing the following * combination of parameters: * - listingTerms.loanERC20Denomination, * - listingTerms.minLoanPrincipalAmount, * - listingTerms.maxLoanPrincipalAmount, * - listingTerms.nftCollateralContract, * - listingTerms.nftCollateralId, * - listingTerms.revenueSharePartner, * - listingTerms.minLoanDuration, * - listingTerms.maxLoanDuration, * - listingTerms.maxInterestRateForDurationInBasisPoints, * - listingTerms.referralFeeInBasisPoints, * - bundleElements * - signature.signer, * - signature.nonce, * - signature.expiry, * - address of this contract * - chainId */ function isValidBorrowerSignatureBundle( LoanData.ListingTerms memory _listingTerms, IBundleBuilder.BundleElements memory _bundleElements, LoanData.Signature memory _signature ) external view returns (bool) { return isValidBorrowerSignatureBundle(_listingTerms, _bundleElements, _signature, address(this)); } /** * @dev This function overload the previous function to allow the caller to specify the address of the contract * */ function isValidBorrowerSignatureBundle( LoanData.ListingTerms memory _listingTerms, IBundleBuilder.BundleElements memory _bundleElements, LoanData.Signature memory _signature, address _loanContract ) public view returns (bool) { require(block.timestamp <= _signature.expiry, "Borrower Signature has expired"); require(_loanContract != address(0), "Loan is zero address"); if (_signature.signer == address(0)) { return false; } else { bytes32 message = keccak256( abi.encodePacked( getEncodedListing(_listingTerms), abi.encode(_bundleElements), getEncodedSignature(_signature), _loanContract, getChainID() ) ); return SignatureChecker.isValidSignatureNow( _signature.signer, ECDSA.toEthSignedMessageHash(message), _signature.signature ); } } /** * @notice This function is when the borrower accepts a lender's offer, to validate the lender's signature that the * lender provided off-chain to verify that it did indeed made such offer. * * @param _offer - The offer struct containing: * - loanERC20Denomination: The address of the ERC20 contract of the currency being used as principal/interest * for this loan. * - loanPrincipalAmount: The original sum of money transferred from lender to borrower at the beginning of * the loan, measured in loanERC20Denomination's smallest units. * - maximumRepaymentAmount: The maximum amount of money that the borrower would be required to retrieve their * collateral, measured in the smallest units of the ERC20 currency used for the loan. The borrower will always have * to pay this amount to retrieve their collateral, regardless of whether they repay early. * - nftCollateralContract: The address of the ERC721 contract of the NFT collateral. * - nftCollateralId: The ID within the NFTCollateralContract for the NFT being used as collateral for this * loan. The NFT is stored within this contract during the duration of the loan. * - referrer: The address of the referrer who found the lender matching the listing, Zero address to signal * this there is no referrer. * - loanDuration: The amount of time (measured in seconds) that can elapse before the lender can liquidate the * loan and seize the underlying collateral NFT. * - loanInterestRateForDurationInBasisPoints: This is the interest rate (measured in basis points, e.g. * hundreths of a percent) for the loan, that must be repaid pro-rata by the borrower at the conclusion of the loan * or risk seizure of their nft collateral. Note if the type of the loan is fixed then this value is not used and * is irrelevant so it should be set to 0. * - loanAdminFeeInBasisPoints: The percent (measured in basis points) of the interest earned that will be * taken as a fee by the contract admins when the loan is repaid. The fee is stored in the loan struct to prevent an * attack where the contract admins could adjust the fee right before a loan is repaid, and take all of the interest * earned. * @param _signature - The signature structure containing: * - signer: The address of the signer. The borrower for `acceptOffer` the lender for `acceptListing`. * - nonce: The nonce referred here is not the same as an Ethereum account's nonce. * We are referring instead to a nonce that is used by the lender or the borrower when they are first signing * off-chain NFTfi orders. These nonce can be any uint256 value that the user has not previously used to sign an * off-chain order. Each nonce can be used at most once per user within NFTfi, regardless of whether they are the * lender or the borrower in that situation. This serves two purposes: * - First, it prevents replay attacks where an attacker would submit a user's off-chain order more than once. * - Second, it allows a user to cancel an off-chain order by calling * NFTfi.cancelLoanCommitmentBeforeLoanHasBegun(), which marks the nonce as used and prevents any future loan from * using the user's off-chain order that contains that nonce. * - expiry: Date when the signature expires * - signature: The ECDSA signature of the lender, obtained off-chain ahead of time, signing the following * combination of parameters: * - offer.loanERC20Denomination * - offer.loanPrincipalAmount * - offer.maximumRepaymentAmount * - offer.nftCollateralContract * - offer.nftCollateralId * - offer.referrer * - offer.loanDuration * - offer.loanAdminFeeInBasisPoints * - signature.signer, * - signature.nonce, * - signature.expiry, * - address of this contract * - chainId */ function isValidLenderSignature(LoanData.Offer memory _offer, LoanData.Signature memory _signature) external view returns (bool) { return isValidLenderSignature(_offer, _signature, address(this)); } /** * @dev This function overload the previous function to allow the caller to specify the address of the contract * */ function isValidLenderSignature( LoanData.Offer memory _offer, LoanData.Signature memory _signature, address _loanContract ) public view returns (bool) { require(block.timestamp <= _signature.expiry, "Lender Signature has expired"); require(_loanContract != address(0), "Loan is zero address"); if (_signature.signer == address(0)) { return false; } else { bytes32 message = keccak256( abi.encodePacked(getEncodedOffer(_offer), getEncodedSignature(_signature), _loanContract, getChainID()) ); return SignatureChecker.isValidSignatureNow( _signature.signer, ECDSA.toEthSignedMessageHash(message), _signature.signature ); } } /** * @notice This function is when the borrower accepts a lender's offer, to validate the lender's signature that the * lender provided off-chain to verify that it did indeed made such offer. * * @param _offer - The offer struct containing: * - loanERC20Denomination: The address of the ERC20 contract of the currency being used as principal/interest * for this loan. * - loanPrincipalAmount: The original sum of money transferred from lender to borrower at the beginning of * the loan, measured in loanERC20Denomination's smallest units. * - maximumRepaymentAmount: The maximum amount of money that the borrower would be required to retrieve their * collateral, measured in the smallest units of the ERC20 currency used for the loan. The borrower will always have * to pay this amount to retrieve their collateral, regardless of whether they repay early. * - nftCollateralContract: The address of the ERC721 contract of the NFT collateral. * - nftCollateralId: The ID within the NFTCollateralContract for the NFT being used as collateral for this * loan. The NFT is stored within this contract during the duration of the loan. * - referrer: The address of the referrer who found the lender matching the listing, Zero address to signal * this there is no referrer. * - loanDuration: The amount of time (measured in seconds) that can elapse before the lender can liquidate the * loan and seize the underlying collateral NFT. * - loanInterestRateForDurationInBasisPoints: This is the interest rate (measured in basis points, e.g. * hundreths of a percent) for the loan, that must be repaid pro-rata by the borrower at the conclusion of the loan * or risk seizure of their nft collateral. Note if the type of the loan is fixed then this value is not used and * is irrelevant so it should be set to 0. * - loanAdminFeeInBasisPoints: The percent (measured in basis points) of the interest earned that will be * taken as a fee by the contract admins when the loan is repaid. The fee is stored in the loan struct to prevent an * attack where the contract admins could adjust the fee right before a loan is repaid, and take all of the interest * earned. * @param _bundleElements - the lists of erc721-20-1155 tokens that are to be bundled * @param _signature - The signature structure containing: * - signer: The address of the signer. The borrower for `acceptOffer` the lender for `acceptListing`. * - nonce: The nonce referred here is not the same as an Ethereum account's nonce. * We are referring instead to a nonce that is used by the lender or the borrower when they are first signing * off-chain NFTfi orders. These nonce can be any uint256 value that the user has not previously used to sign an * off-chain order. Each nonce can be used at most once per user within NFTfi, regardless of whether they are the * lender or the borrower in that situation. This serves two purposes: * - First, it prevents replay attacks where an attacker would submit a user's off-chain order more than once. * - Second, it allows a user to cancel an off-chain order by calling * NFTfi.cancelLoanCommitmentBeforeLoanHasBegun(), which marks the nonce as used and prevents any future loan from * using the user's off-chain order that contains that nonce. * - expiry: Date when the signature expires * - signature: The ECDSA signature of the lender, obtained off-chain ahead of time, signing the following * combination of parameters: * - offer.loanERC20Denomination * - offer.loanPrincipalAmount * - offer.maximumRepaymentAmount * - offer.nftCollateralContract * - offer.nftCollateralId * - offer.referrer * - offer.loanDuration * - offer.loanAdminFeeInBasisPoints * - bundleElements * - signature.signer, * - signature.nonce, * - signature.expiry, * - address of this contract * - chainId */ function isValidLenderSignatureBundle( LoanData.Offer memory _offer, IBundleBuilder.BundleElements memory _bundleElements, LoanData.Signature memory _signature ) external view returns (bool) { return isValidLenderSignatureBundle(_offer, _bundleElements, _signature, address(this)); } /** * @dev This function overload the previous function to allow the caller to specify the address of the contract * */ function isValidLenderSignatureBundle( LoanData.Offer memory _offer, IBundleBuilder.BundleElements memory _bundleElements, LoanData.Signature memory _signature, address _loanContract ) public view returns (bool) { require(block.timestamp <= _signature.expiry, "Lender Signature has expired"); require(_loanContract != address(0), "Loan is zero address"); if (_signature.signer == address(0)) { return false; } else { bytes32 message = keccak256( abi.encodePacked( getEncodedOffer(_offer), abi.encode(_bundleElements), getEncodedSignature(_signature), _loanContract, getChainID() ) ); return SignatureChecker.isValidSignatureNow( _signature.signer, ECDSA.toEthSignedMessageHash(message), _signature.signature ); } } /** * @notice This function is called in renegotiateLoan() to validate the lender's signature that the lender provided * off-chain to verify that they did indeed want to agree to this loan renegotiation according to these terms. * * @param _loanId - The unique identifier for the loan to be renegotiated * @param _newLoanDuration - The new amount of time (measured in seconds) that can elapse before the lender can * liquidate the loan and seize the underlying collateral NFT. * @param _newMaximumRepaymentAmount - The new maximum amount of money that the borrower would be required to * retrieve their collateral, measured in the smallest units of the ERC20 currency used for the loan. The * borrower will always have to pay this amount to retrieve their collateral, regardless of whether they repay * early. * @param _renegotiationFee Agreed upon fee in ether that borrower pays for the lender for the renegitiation * @param _signature - The signature structure containing: * - signer: The address of the signer. The borrower for `acceptOffer` the lender for `acceptListing`. * - nonce: The nonce referred here is not the same as an Ethereum account's nonce. * We are referring instead to a nonce that is used by the lender or the borrower when they are first signing * off-chain NFTfi orders. These nonce can be any uint256 value that the user has not previously used to sign an * off-chain order. Each nonce can be used at most once per user within NFTfi, regardless of whether they are the * lender or the borrower in that situation. This serves two purposes: * - First, it prevents replay attacks where an attacker would submit a user's off-chain order more than once. * - Second, it allows a user to cancel an off-chain order by calling NFTfi.cancelLoanCommitmentBeforeLoanHasBegun() * , which marks the nonce as used and prevents any future loan from using the user's off-chain order that contains * that nonce. * - expiry - The date when the renegotiation offer expires * - lenderSignature - The ECDSA signature of the lender, obtained off-chain ahead of time, signing the * following combination of parameters: * - _loanId * - _newLoanDuration * - _newMaximumRepaymentAmount * - _lender * - _lenderNonce * - _expiry * - address of this contract * - chainId */ function isValidLenderRenegotiationSignature( uint256 _loanId, uint32 _newLoanDuration, uint256 _newMaximumRepaymentAmount, uint256 _renegotiationFee, LoanData.Signature memory _signature ) external view returns (bool) { return isValidLenderRenegotiationSignature( _loanId, _newLoanDuration, _newMaximumRepaymentAmount, _renegotiationFee, _signature, address(this) ); } /** * @dev This function overload the previous function to allow the caller to specify the address of the contract * */ function isValidLenderRenegotiationSignature( uint256 _loanId, uint32 _newLoanDuration, uint256 _newMaximumRepaymentAmount, uint256 _renegotiationFee, LoanData.Signature memory _signature, address _loanContract ) public view returns (bool) { require(block.timestamp <= _signature.expiry, "Renegotiation Signature has expired"); require(_loanContract != address(0), "Loan is zero address"); if (_signature.signer == address(0)) { return false; } else { bytes32 message = keccak256( abi.encodePacked( _loanId, _newLoanDuration, _newMaximumRepaymentAmount, _renegotiationFee, getEncodedSignature(_signature), _loanContract, getChainID() ) ); return SignatureChecker.isValidSignatureNow( _signature.signer, ECDSA.toEthSignedMessageHash(message), _signature.signature ); } } /** * @dev We need this to avoid stack too deep errors. */ function getEncodedListing(LoanData.ListingTerms memory _listingTerms) internal pure returns (bytes memory) { return abi.encodePacked( _listingTerms.loanERC20Denomination, _listingTerms.minLoanPrincipalAmount, _listingTerms.maxLoanPrincipalAmount, _listingTerms.nftCollateralContract, _listingTerms.nftCollateralId, _listingTerms.revenueSharePartner, _listingTerms.minLoanDuration, _listingTerms.maxLoanDuration, _listingTerms.maxInterestRateForDurationInBasisPoints, _listingTerms.referralFeeInBasisPoints ); } /** * @dev We need this to avoid stack too deep errors. */ function getEncodedOffer(LoanData.Offer memory _offer) internal pure returns (bytes memory) { return abi.encodePacked( _offer.loanERC20Denomination, _offer.loanPrincipalAmount, _offer.maximumRepaymentAmount, _offer.nftCollateralContract, _offer.nftCollateralId, _offer.referrer, _offer.loanDuration, _offer.loanAdminFeeInBasisPoints ); } /** * @dev We need this to avoid stack too deep errors. */ function getEncodedSignature(LoanData.Signature memory _signature) internal pure returns (bytes memory) { return abi.encodePacked(_signature.signer, _signature.nonce, _signature.expiry); } }
40,359
48
// Integer division of two unsigned integers truncating the quotient, reverts on division by zero. /
function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, 'SafeMath#div: DIVISION_BY_ZERO'); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; }
function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, 'SafeMath#div: DIVISION_BY_ZERO'); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; }
21,138
226
// Decode a `Witnet.CBOR` structure into a native `int128[]` value./_cborValue An instance of `Witnet.CBOR`./ return The value represented by the input, as an `int128[]` value.
function decodeInt128Array(Witnet.CBOR memory _cborValue) external pure returns(int128[] memory) { require(_cborValue.majorType == 4, "WitnetDecoderLib: Tried to read `int128[]` from a `Witnet.CBOR` with majorType != 4"); uint64 length = readLength(_cborValue.buffer, _cborValue.additionalInformation); require(length < _UINT64_MAX, "WitnetDecoderLib: Indefinite-length CBOR arrays are not supported"); int128[] memory array = new int128[](length); for (uint64 i = 0; i < length; i++) { Witnet.CBOR memory item = valueFromBuffer(_cborValue.buffer); array[i] = decodeInt128(item); } return array; }
function decodeInt128Array(Witnet.CBOR memory _cborValue) external pure returns(int128[] memory) { require(_cborValue.majorType == 4, "WitnetDecoderLib: Tried to read `int128[]` from a `Witnet.CBOR` with majorType != 4"); uint64 length = readLength(_cborValue.buffer, _cborValue.additionalInformation); require(length < _UINT64_MAX, "WitnetDecoderLib: Indefinite-length CBOR arrays are not supported"); int128[] memory array = new int128[](length); for (uint64 i = 0; i < length; i++) { Witnet.CBOR memory item = valueFromBuffer(_cborValue.buffer); array[i] = decodeInt128(item); } return array; }
19,903
5
// Recovers signer address from a message by using the signaturehash bytes32 message, the hash is the signed message. What is recovered is the signer address.signature bytes signature, the signature is generated using web3.eth.sign()/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { bytes32 r; bytes32 s; uint8 v; // Divide the signature in r, s and v variables with inline assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (v < 27) { v += 27; } // If the version is correct return the signer address if (v != 27 && v != 28) { return (address(0)); } return ecrecover(hash, v, r, s); }
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { bytes32 r; bytes32 s; uint8 v; // Divide the signature in r, s and v variables with inline assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (v < 27) { v += 27; } // If the version is correct return the signer address if (v != 27 && v != 28) { return (address(0)); } return ecrecover(hash, v, r, s); }
20,232
73
// EToken2 Asset with manager implementation contract. Manager[s] should be a contract which will implement token movement logic.In case normal users transfers should be restricted, so that only managercan move balances, isTransferAllowed should be set to false. /
contract AssetWithManager is AssetWithAmbi { bool public isTransferAllowed = true; event TransferAllowedSet(bool isAllowed); function isManager(address _caller) public view returns(bool) { return address(ambi2) != address(0) && ambi2.hasRole(address(this), 'manager', _caller); } function setTransferAllowed(bool _value) public onlyRole('admin') returns(bool) { isTransferAllowed = _value; emit TransferAllowedSet(_value); return true; } function _transferWithReference( address _to, uint _value, string memory _reference, address _sender) internal returns(bool) { if (isManager(_sender) || isTransferAllowed) { return super._transferWithReference( _to, _value, _reference, _sender); } return false; } function _transferFromWithReference( address _from, address _to, uint _value, string memory _reference, address _sender) internal returns(bool) { if (isManager(_sender)) { return super._transferWithReference( _to, _value, _reference, _from); } if (isTransferAllowed) { return super._transferFromWithReference( _from, _to, _value, _reference, _sender); } return false; } function _transferToICAPWithReference( bytes32 _icap, uint _value, string memory _reference, address _sender) internal returns(bool) { if (isManager(_sender) || isTransferAllowed) { return super._transferToICAPWithReference( _icap, _value, _reference, _sender); } return false; } function _transferFromToICAPWithReference( address _from, bytes32 _icap, uint _value, string memory _reference, address _sender) internal returns(bool) { if (isManager(_sender)) { return super._transferToICAPWithReference( _icap, _value, _reference, _from); } if (isTransferAllowed) { return super._transferFromToICAPWithReference( _from, _icap, _value, _reference, _sender); } return false; } }
contract AssetWithManager is AssetWithAmbi { bool public isTransferAllowed = true; event TransferAllowedSet(bool isAllowed); function isManager(address _caller) public view returns(bool) { return address(ambi2) != address(0) && ambi2.hasRole(address(this), 'manager', _caller); } function setTransferAllowed(bool _value) public onlyRole('admin') returns(bool) { isTransferAllowed = _value; emit TransferAllowedSet(_value); return true; } function _transferWithReference( address _to, uint _value, string memory _reference, address _sender) internal returns(bool) { if (isManager(_sender) || isTransferAllowed) { return super._transferWithReference( _to, _value, _reference, _sender); } return false; } function _transferFromWithReference( address _from, address _to, uint _value, string memory _reference, address _sender) internal returns(bool) { if (isManager(_sender)) { return super._transferWithReference( _to, _value, _reference, _from); } if (isTransferAllowed) { return super._transferFromWithReference( _from, _to, _value, _reference, _sender); } return false; } function _transferToICAPWithReference( bytes32 _icap, uint _value, string memory _reference, address _sender) internal returns(bool) { if (isManager(_sender) || isTransferAllowed) { return super._transferToICAPWithReference( _icap, _value, _reference, _sender); } return false; } function _transferFromToICAPWithReference( address _from, bytes32 _icap, uint _value, string memory _reference, address _sender) internal returns(bool) { if (isManager(_sender)) { return super._transferToICAPWithReference( _icap, _value, _reference, _from); } if (isTransferAllowed) { return super._transferFromToICAPWithReference( _from, _icap, _value, _reference, _sender); } return false; } }
12,892
43
// Function to init balances mapping on token launch /
function initBalances(address[] calldata _accounts, uint64[] calldata _amounts) external onlyOwner { require(!balancesInitialized); require(_accounts.length > 0 && _accounts.length == _amounts.length); uint256 total = 0; for (uint256 i = 0; i < _amounts.length; i++) total = total.add(uint256(_amounts[i])); require(total <= MAX_TOTAL_SUPPLY); for (uint256 j = 0; j < _accounts.length; j++) _mint(_accounts[j], uint256(_amounts[j])); }
function initBalances(address[] calldata _accounts, uint64[] calldata _amounts) external onlyOwner { require(!balancesInitialized); require(_accounts.length > 0 && _accounts.length == _amounts.length); uint256 total = 0; for (uint256 i = 0; i < _amounts.length; i++) total = total.add(uint256(_amounts[i])); require(total <= MAX_TOTAL_SUPPLY); for (uint256 j = 0; j < _accounts.length; j++) _mint(_accounts[j], uint256(_amounts[j])); }
61,550
9
// Approves the spender to spend the caller's tokens. _spender The spender address. _value The amount of tokens to approve.return A boolean indicating whether the approval was successful or not. /
function approve(address _spender, uint256 _value) external override returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; }
function approve(address _spender, uint256 _value) external override returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; }
17,363
8
// Revokes {role} from {account}. If {account} had been granted {role}, emits a {RoleRevoked} event. role - Role to revoke. account - Account to revoke role from.Note: This function can only be called by the admin. /
function revokeRole(bytes32 role, address account) public onlyAdmin { _revokeRole(role, account); }
function revokeRole(bytes32 role, address account) public onlyAdmin { _revokeRole(role, account); }
35,171
1
// Create a new staking pool. The sender will be the staking pal of this pool./ Note that a staking pal must be payable./rigoblockPoolAddress Adds rigoblock pool to the created staking pool for convenience if non-null./ return poolId The unique pool id generated for this pool.
function createStakingPool(address rigoblockPoolAddress) external override returns (bytes32 poolId)
function createStakingPool(address rigoblockPoolAddress) external override returns (bytes32 poolId)
1,700
135
// A unique identifier for this particular loan, sourced from the continuously increasing parameter totalNumLoans.
uint256 loanId;
uint256 loanId;
10,212
31
// Admin function to withdraw stuck ERC-20 tokens from this contract Withdraws to the `to` address. This contract doesn't use ERC-20 tokens,but this is a failsafe if tokens are sent to it by accident. token The address of the ERC-20 token to withdraw to The address to withdraw tokens to /
function withdrawStuckToken(address token, address to) public onlyOwnerOrAdmin { _withdrawToken(token, to); }
function withdrawStuckToken(address token, address to) public onlyOwnerOrAdmin { _withdrawToken(token, to); }
26,505
4
// Changes the owner of this contract./
function changeOwner(address newOwner) public onlyOwner() { owner = newOwner; }
function changeOwner(address newOwner) public onlyOwner() { owner = newOwner; }
7,037
24
// User featuring the sprite owns its kitty, but hasn't listed the kitty for sale
broughtSprites[spriteId].owner = kittyOwnerNotForSale; numberOfSpritesOwnedByUser[msg.sender]++;
broughtSprites[spriteId].owner = kittyOwnerNotForSale; numberOfSpritesOwnedByUser[msg.sender]++;
1,677
76
// /
contract ProxyStorage { address public owner; address public pendingOwner; bool initialized; BalanceSheet balances_Deprecated; AllowanceSheet allowances_Deprecated; uint256 totalSupply_; bool private paused_Deprecated = false; address private globalPause_Deprecated; uint256 public burnMin = 0; uint256 public burnMax = 0; Registry public registry; string name_Deprecated; string symbol_Deprecated; uint[] gasRefundPool_Deprecated; uint256 private redemptionAddressCount_Deprecated; uint256 public minimumGasPriceForFutureRefunds; mapping (address => uint256) _balanceOf; mapping (address => mapping (address => uint256)) _allowance; mapping (bytes32 => mapping (address => uint256)) attributes; // reward token storage mapping(address => FinancialOpportunity) finOps; mapping(address => mapping(address => uint256)) finOpBalances; mapping(address => uint256) finOpSupply; // true reward allocation // proportion: 1000 = 100% struct RewardAllocation { uint proportion; address finOp; } mapping(address => RewardAllocation[]) _rewardDistribution; uint256 maxRewardProportion = 1000; /* Additionally, we have several keccak-based storage locations. * If you add more keccak-based storage mappings, such as mappings, you must document them here. * If the length of the keccak input is the same as an existing mapping, it is possible there could be a preimage collision. * A preimage collision can be used to attack the contract by treating one storage location as another, * which would always be a critical issue. * Carefully examine future keccak-based storage to ensure there can be no preimage collisions. ******************************************************************************************************* ** length input usage ******************************************************************************************************* ** 19 "trueXXX.proxy.owner" Proxy Owner ** 27 "trueXXX.pending.proxy.owner" Pending Proxy Owner ** 28 "trueXXX.proxy.implementation" Proxy Implementation ** 32 uint256(11) gasRefundPool_Deprecated ** 64 uint256(address),uint256(14) balanceOf ** 64 uint256(address),keccak256(uint256(address),uint256(15)) allowance ** 64 uint256(address),keccak256(bytes32,uint256(16)) attributes **/ }
contract ProxyStorage { address public owner; address public pendingOwner; bool initialized; BalanceSheet balances_Deprecated; AllowanceSheet allowances_Deprecated; uint256 totalSupply_; bool private paused_Deprecated = false; address private globalPause_Deprecated; uint256 public burnMin = 0; uint256 public burnMax = 0; Registry public registry; string name_Deprecated; string symbol_Deprecated; uint[] gasRefundPool_Deprecated; uint256 private redemptionAddressCount_Deprecated; uint256 public minimumGasPriceForFutureRefunds; mapping (address => uint256) _balanceOf; mapping (address => mapping (address => uint256)) _allowance; mapping (bytes32 => mapping (address => uint256)) attributes; // reward token storage mapping(address => FinancialOpportunity) finOps; mapping(address => mapping(address => uint256)) finOpBalances; mapping(address => uint256) finOpSupply; // true reward allocation // proportion: 1000 = 100% struct RewardAllocation { uint proportion; address finOp; } mapping(address => RewardAllocation[]) _rewardDistribution; uint256 maxRewardProportion = 1000; /* Additionally, we have several keccak-based storage locations. * If you add more keccak-based storage mappings, such as mappings, you must document them here. * If the length of the keccak input is the same as an existing mapping, it is possible there could be a preimage collision. * A preimage collision can be used to attack the contract by treating one storage location as another, * which would always be a critical issue. * Carefully examine future keccak-based storage to ensure there can be no preimage collisions. ******************************************************************************************************* ** length input usage ******************************************************************************************************* ** 19 "trueXXX.proxy.owner" Proxy Owner ** 27 "trueXXX.pending.proxy.owner" Pending Proxy Owner ** 28 "trueXXX.proxy.implementation" Proxy Implementation ** 32 uint256(11) gasRefundPool_Deprecated ** 64 uint256(address),uint256(14) balanceOf ** 64 uint256(address),keccak256(uint256(address),uint256(15)) allowance ** 64 uint256(address),keccak256(bytes32,uint256(16)) attributes **/ }
32,553
10
// Returns the defualt royalty recipient and BPS for this contract's NFTs. /
function getDefaultRoyaltyInfo() external view override returns (address, uint16) { RoyaltyStorage.Data storage data = RoyaltyStorage.royaltyStorage(); return (data.royaltyRecipient, uint16(data.royaltyBps)); }
function getDefaultRoyaltyInfo() external view override returns (address, uint16) { RoyaltyStorage.Data storage data = RoyaltyStorage.royaltyStorage(); return (data.royaltyRecipient, uint16(data.royaltyBps)); }
955
37
// Will reset job's syncronicity if last reward was more than epoch ago
_updateJobPeriod(_job); _jobLiquidityCredits[_job] = _jobPeriodCredits[_job]; rewardedAt[_job] += rewardPeriodTime; _rewarded = true;
_updateJobPeriod(_job); _jobLiquidityCredits[_job] = _jobPeriodCredits[_job]; rewardedAt[_job] += rewardPeriodTime; _rewarded = true;
22,724
94
// The prediction is tied if the price change is less than this
uint public constant TIE_PRICE_CHANGE_TOLERANCE = 0.001 * 10 ** 18; uint public constant FEE_PERCENT_X_100 = 10e2;
uint public constant TIE_PRICE_CHANGE_TOLERANCE = 0.001 * 10 ** 18; uint public constant FEE_PERCENT_X_100 = 10e2;
8,390
1
// permits of members
mapping(address => mapping(string => bool)) public permits;
mapping(address => mapping(string => bool)) public permits;
25,878
45
// loop assumes that the token address and amount is mapped to the same index in both arrays meaning: the user is sending _amounts[0] of _tokens[0]
for (uint256 i; i < tokensLength; i++) { address _token = _tokens[i]; uint256 _amount = _amounts[i]; require(_amount > 0, Errors.INVALID_TOKEN_AMOUNT); require(_token != address(0), Errors.INVALID_TOKEN_ADDRESS);
for (uint256 i; i < tokensLength; i++) { address _token = _tokens[i]; uint256 _amount = _amounts[i]; require(_amount > 0, Errors.INVALID_TOKEN_AMOUNT); require(_token != address(0), Errors.INVALID_TOKEN_ADDRESS);
14,271
10
// extract signature parts from coupon
(bytes32 r, bytes32 s, uint8 v) = splitSignature(claimCoupon);
(bytes32 r, bytes32 s, uint8 v) = splitSignature(claimCoupon);
39,575
47
// transfer the fee to teamaddress
require( token.transfer(teamAddress, fee), "transfer failed" );
require( token.transfer(teamAddress, fee), "transfer failed" );
8,536
617
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 private constant PERMIT_SIGNATURE_HASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
bytes32 private constant PERMIT_SIGNATURE_HASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
38,503
92
// Leaves the contract without owner. It will not be possible to call`onlyOwner` functions anymore. Can only be called by the current owner. NOTE: Renouncing ownership will leave the contract without an owner,thereby removing any functionality that is only available to the owner. /
function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); }
function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); }
67
2
// The expected owner of adopted pet is this contract
address expectedAdopter = address(this);
address expectedAdopter = address(this);
33,197
60
// Set 'contract address', called from constructor whitelistedPTokenEmissionContract: whitelistedPTokenEmission contract address
* Emits a {SetWhitelistedPTokenEmissionContract} event with '_contract' set to the WhitelistedPTokenEmission contract address. * */ function setWhitelistedPTokenEmissionContract( address whitelistedPTokenEmissionContract ) public virtual override { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "ST11"); _whitelistedPTokenEmissionContract = whitelistedPTokenEmissionContract; emit SetWhitelistedPTokenEmissionContract( whitelistedPTokenEmissionContract ); }
* Emits a {SetWhitelistedPTokenEmissionContract} event with '_contract' set to the WhitelistedPTokenEmission contract address. * */ function setWhitelistedPTokenEmissionContract( address whitelistedPTokenEmissionContract ) public virtual override { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "ST11"); _whitelistedPTokenEmissionContract = whitelistedPTokenEmissionContract; emit SetWhitelistedPTokenEmissionContract( whitelistedPTokenEmissionContract ); }
14,167
8
// User is struct which holds all the details for a particular user creating a CV on Blockvitae
struct UserMain { UserDetail personal; // personal details of the user UserSocial social; // social details of the user UserWorkExp[] work; // work experience of the user UserEducation[] education; // education of the user UserProject[] projects; // projects of the user UserSkill skills; // skills of the user UserIntroduction introduction; // introduction of the user UserPublication[] publications; // publications by the user bool exists; // true everytime add new new struct address owner; // owner of the user profile }
struct UserMain { UserDetail personal; // personal details of the user UserSocial social; // social details of the user UserWorkExp[] work; // work experience of the user UserEducation[] education; // education of the user UserProject[] projects; // projects of the user UserSkill skills; // skills of the user UserIntroduction introduction; // introduction of the user UserPublication[] publications; // publications by the user bool exists; // true everytime add new new struct address owner; // owner of the user profile }
6,726
1
// The number of leaves per node
uint8 internal constant LEAVES_PER_NODE = 5;
uint8 internal constant LEAVES_PER_NODE = 5;
6,237
8
// pure不能读写变量, 即不可以涉及到合约的成员变量和成员函数
function f4() pure public returns(uint){ //return v1;//error //f2(); //error //return 1; //ok }
function f4() pure public returns(uint){ //return v1;//error //f2(); //error //return 1; //ok }
47,412
34
// AMM's net positions are the inverse of the user's net position
pricing.postTradeAmmNetStdVega = -globalCache.netStdVega; pricing.callDelta = pricesDeltaStdVega.callDelta; emit ListingGreeksUpdated( listingCache.id, pricesDeltaStdVega.callDelta, pricesDeltaStdVega.putDelta, pricesDeltaStdVega.stdVega, greekCacheGlobals.spotPrice, boardCache.iv,
pricing.postTradeAmmNetStdVega = -globalCache.netStdVega; pricing.callDelta = pricesDeltaStdVega.callDelta; emit ListingGreeksUpdated( listingCache.id, pricesDeltaStdVega.callDelta, pricesDeltaStdVega.putDelta, pricesDeltaStdVega.stdVega, greekCacheGlobals.spotPrice, boardCache.iv,
16,571
77
// Returns the current implementation.
* NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyImplementation}. * * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call. * `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc` */ function implementation() external ifAdmin returns (address implementation_) { implementation_ = _implementation(); }
* NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyImplementation}. * * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call. * `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc` */ function implementation() external ifAdmin returns (address implementation_) { implementation_ = _implementation(); }
5,858
353
// Get component price from price oracle. If price does not exist, revert.
uint256 componentPrice = priceOracle.getPrice(_component, masterQuoteAsset); if (masterQuoteAsset != _quoteAsset) { uint256 quoteToMaster = priceOracle.getPrice(_quoteAsset, masterQuoteAsset); componentPrice = componentPrice.preciseDiv(quoteToMaster); }
uint256 componentPrice = priceOracle.getPrice(_component, masterQuoteAsset); if (masterQuoteAsset != _quoteAsset) { uint256 quoteToMaster = priceOracle.getPrice(_quoteAsset, masterQuoteAsset); componentPrice = componentPrice.preciseDiv(quoteToMaster); }
18,355
24
// Moves `amount` of tokens from `from` to `to`.
* This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. */ function _transfer( address from, address to, uint256 amount ) internal virtual { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; } _balances[to] += amount; emit Transfer(from, to, amount); _afterTokenTransfer(from, to, amount); }
* This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. */ function _transfer( address from, address to, uint256 amount ) internal virtual { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; } _balances[to] += amount; emit Transfer(from, to, amount); _afterTokenTransfer(from, to, amount); }
1,782
359
// max number of paid contributions to the pode sale
uint256 public constant maxPodeContributionTokens = 500; constructor( address payable _fundsMultisig, uint256 _podeStartTimestamp, uint256 _podeEndTimestamp, uint256 _podeLockTimestamp, string memory _tokenURI
uint256 public constant maxPodeContributionTokens = 500; constructor( address payable _fundsMultisig, uint256 _podeStartTimestamp, uint256 _podeEndTimestamp, uint256 _podeLockTimestamp, string memory _tokenURI
2,841
202
// A map from an account to a token to the forced withdrawal (always full balance) The `uint16' represents ERC20 token ID (if < NFT_TOKEN_ID_START) or NFT balance slot (if >= NFT_TOKEN_ID_START)
mapping (uint32 => mapping (uint16 => ForcedWithdrawal)) pendingForcedWithdrawals;
mapping (uint32 => mapping (uint16 => ForcedWithdrawal)) pendingForcedWithdrawals;
54,541
2
// Only MINTER_ROLE holders can sign off on `MintRequest`s and lazy mint tokens.
bytes32 private minterRole;
bytes32 private minterRole;
22,598
24
// has to be the creator or someone with the password
require(msg.sender == creator || hash_pwd == keccak256(_password)); require(sale == 0x0); require(!bought_tokens); sale = _sale;
require(msg.sender == creator || hash_pwd == keccak256(_password)); require(sale == 0x0); require(!bought_tokens); sale = _sale;
6,718
478
// the next request count to be used in generating a nonce starts at 1 in order to ensure consistent gas costreturn returns the next request count to be used in a nonce /
function getNextRequestCount() internal view returns (uint256) { return s_requestCount; }
function getNextRequestCount() internal view returns (uint256) { return s_requestCount; }
72,396
209
// https:docs.synthetix.io/contracts/source/contracts/eternalstorage/This contract is based on the code available from this blogImplements support for storing a keccak256 key and value pairs. It is the more flexibleand extensible option. This ensures data schema changes can be implemented withoutrequiring upgrades to the storage contract. /
contract EternalStorage is Owned, State { constructor(address _owner, address _associatedContract) public Owned(_owner) State(_associatedContract) {} /* ========== DATA TYPES ========== */ mapping(bytes32 => uint) internal UIntStorage; mapping(bytes32 => string) internal StringStorage; mapping(bytes32 => address) internal AddressStorage; mapping(bytes32 => bytes) internal BytesStorage; mapping(bytes32 => bytes32) internal Bytes32Storage; mapping(bytes32 => bool) internal BooleanStorage; mapping(bytes32 => int) internal IntStorage; // UIntStorage; function getUIntValue(bytes32 record) external view returns (uint) { return UIntStorage[record]; } function setUIntValue(bytes32 record, uint value) external onlyAssociatedContract { UIntStorage[record] = value; } function deleteUIntValue(bytes32 record) external onlyAssociatedContract { delete UIntStorage[record]; } // StringStorage function getStringValue(bytes32 record) external view returns (string memory) { return StringStorage[record]; } function setStringValue(bytes32 record, string calldata value) external onlyAssociatedContract { StringStorage[record] = value; } function deleteStringValue(bytes32 record) external onlyAssociatedContract { delete StringStorage[record]; } // AddressStorage function getAddressValue(bytes32 record) external view returns (address) { return AddressStorage[record]; } function setAddressValue(bytes32 record, address value) external onlyAssociatedContract { AddressStorage[record] = value; } function deleteAddressValue(bytes32 record) external onlyAssociatedContract { delete AddressStorage[record]; } // BytesStorage function getBytesValue(bytes32 record) external view returns (bytes memory) { return BytesStorage[record]; } function setBytesValue(bytes32 record, bytes calldata value) external onlyAssociatedContract { BytesStorage[record] = value; } function deleteBytesValue(bytes32 record) external onlyAssociatedContract { delete BytesStorage[record]; } // Bytes32Storage function getBytes32Value(bytes32 record) external view returns (bytes32) { return Bytes32Storage[record]; } function setBytes32Value(bytes32 record, bytes32 value) external onlyAssociatedContract { Bytes32Storage[record] = value; } function deleteBytes32Value(bytes32 record) external onlyAssociatedContract { delete Bytes32Storage[record]; } // BooleanStorage function getBooleanValue(bytes32 record) external view returns (bool) { return BooleanStorage[record]; } function setBooleanValue(bytes32 record, bool value) external onlyAssociatedContract { BooleanStorage[record] = value; } function deleteBooleanValue(bytes32 record) external onlyAssociatedContract { delete BooleanStorage[record]; } // IntStorage function getIntValue(bytes32 record) external view returns (int) { return IntStorage[record]; } function setIntValue(bytes32 record, int value) external onlyAssociatedContract { IntStorage[record] = value; } function deleteIntValue(bytes32 record) external onlyAssociatedContract { delete IntStorage[record]; } }
contract EternalStorage is Owned, State { constructor(address _owner, address _associatedContract) public Owned(_owner) State(_associatedContract) {} /* ========== DATA TYPES ========== */ mapping(bytes32 => uint) internal UIntStorage; mapping(bytes32 => string) internal StringStorage; mapping(bytes32 => address) internal AddressStorage; mapping(bytes32 => bytes) internal BytesStorage; mapping(bytes32 => bytes32) internal Bytes32Storage; mapping(bytes32 => bool) internal BooleanStorage; mapping(bytes32 => int) internal IntStorage; // UIntStorage; function getUIntValue(bytes32 record) external view returns (uint) { return UIntStorage[record]; } function setUIntValue(bytes32 record, uint value) external onlyAssociatedContract { UIntStorage[record] = value; } function deleteUIntValue(bytes32 record) external onlyAssociatedContract { delete UIntStorage[record]; } // StringStorage function getStringValue(bytes32 record) external view returns (string memory) { return StringStorage[record]; } function setStringValue(bytes32 record, string calldata value) external onlyAssociatedContract { StringStorage[record] = value; } function deleteStringValue(bytes32 record) external onlyAssociatedContract { delete StringStorage[record]; } // AddressStorage function getAddressValue(bytes32 record) external view returns (address) { return AddressStorage[record]; } function setAddressValue(bytes32 record, address value) external onlyAssociatedContract { AddressStorage[record] = value; } function deleteAddressValue(bytes32 record) external onlyAssociatedContract { delete AddressStorage[record]; } // BytesStorage function getBytesValue(bytes32 record) external view returns (bytes memory) { return BytesStorage[record]; } function setBytesValue(bytes32 record, bytes calldata value) external onlyAssociatedContract { BytesStorage[record] = value; } function deleteBytesValue(bytes32 record) external onlyAssociatedContract { delete BytesStorage[record]; } // Bytes32Storage function getBytes32Value(bytes32 record) external view returns (bytes32) { return Bytes32Storage[record]; } function setBytes32Value(bytes32 record, bytes32 value) external onlyAssociatedContract { Bytes32Storage[record] = value; } function deleteBytes32Value(bytes32 record) external onlyAssociatedContract { delete Bytes32Storage[record]; } // BooleanStorage function getBooleanValue(bytes32 record) external view returns (bool) { return BooleanStorage[record]; } function setBooleanValue(bytes32 record, bool value) external onlyAssociatedContract { BooleanStorage[record] = value; } function deleteBooleanValue(bytes32 record) external onlyAssociatedContract { delete BooleanStorage[record]; } // IntStorage function getIntValue(bytes32 record) external view returns (int) { return IntStorage[record]; } function setIntValue(bytes32 record, int value) external onlyAssociatedContract { IntStorage[record] = value; } function deleteIntValue(bytes32 record) external onlyAssociatedContract { delete IntStorage[record]; } }
20,643
18
// External function to update the parameters of the interest rate model baseRatePerYear The approximate target base APR, as a mantissa (scaled by 1e18). For DAI, this is calculated from DSR and SF. Input not used. gapPerYear The Additional margin per year separating the base borrow rate from the roof. (scaled by 1e18) jumpMultiplierPerYear The jumpMultiplierPerYear after hitting a specified utilization point kink_ The utilization point at which the jump multiplier is applied /
function updateJumpRateModel(uint baseRatePerYear, uint gapPerYear, uint jumpMultiplierPerYear, uint kink_) external override { require(msg.sender == owner, "only the owner may call this function."); gapPerBlock = gapPerYear / blocksPerYear; updateJumpRateModelInternal(0, 0, jumpMultiplierPerYear, kink_); poke(); }
function updateJumpRateModel(uint baseRatePerYear, uint gapPerYear, uint jumpMultiplierPerYear, uint kink_) external override { require(msg.sender == owner, "only the owner may call this function."); gapPerBlock = gapPerYear / blocksPerYear; updateJumpRateModelInternal(0, 0, jumpMultiplierPerYear, kink_); poke(); }
58,172
56
// and check if the offer is sucessful after this sale @WARNING add logic to only set success based on something our clients want
if (!bSuccess) { bSuccess = true; }
if (!bSuccess) { bSuccess = true; }
7,729
12
// Returns whether the wearable can be minted._collectionAddress - collectionn address_optionId - item option id return whether a wearable can be minted/
function canMint(address _collectionAddress, uint256 _optionId, uint256 _amount) public view returns (bool) { CollectionData storage collection = collectionsData[_collectionAddress]; return collection.availableQtyPerOptionId[_optionId] >= _amount; }
function canMint(address _collectionAddress, uint256 _optionId, uint256 _amount) public view returns (bool) { CollectionData storage collection = collectionsData[_collectionAddress]; return collection.availableQtyPerOptionId[_optionId] >= _amount; }
61,925
69
// Queues an update to a validator group's commission.If there was a previously scheduled update, that is overwritten. commission Fixidity representation of the commission this group receives on epochpayments made to its members. Must be in the range [0, 1.0]. /
function setNextCommissionUpdate(uint256 commission) external { address account = getAccounts().validatorSignerToAccount(msg.sender); require(isValidatorGroup(account), "Not a validator group"); ValidatorGroup storage group = groups[account]; require(commission <= FixidityLib.fixed1().unwrap(), "Commission can't be greater than 100%"); require(commission != group.commission.unwrap(), "Commission must be different"); group.nextCommission = FixidityLib.wrap(commission); group.nextCommissionBlock = block.number.add(commissionUpdateDelay); emit ValidatorGroupCommissionUpdateQueued(account, commission, group.nextCommissionBlock); }
function setNextCommissionUpdate(uint256 commission) external { address account = getAccounts().validatorSignerToAccount(msg.sender); require(isValidatorGroup(account), "Not a validator group"); ValidatorGroup storage group = groups[account]; require(commission <= FixidityLib.fixed1().unwrap(), "Commission can't be greater than 100%"); require(commission != group.commission.unwrap(), "Commission must be different"); group.nextCommission = FixidityLib.wrap(commission); group.nextCommissionBlock = block.number.add(commissionUpdateDelay); emit ValidatorGroupCommissionUpdateQueued(account, commission, group.nextCommissionBlock); }
23,640
1
// This is the interface that {BeaconProxy} expects of its beacon./ Must return an address that can be used as a delegate call target. {BeaconProxy} will check that this address is a contract. /
function implementation() external view returns (address);
function implementation() external view returns (address);
23,735
9
// ReimburseTFUEL > 0 if tokenRequest > tokenAllowed
uint256 reimburseTFUEL; if (tokenQuantityRequest > tokenQuantityAllowed) { reimburseTFUEL = (tokenQuantityRequest.sub(tokenQuantityAllowed)) .div(rate); tokenQuantityRequest = tokenQuantityAllowed; }
uint256 reimburseTFUEL; if (tokenQuantityRequest > tokenQuantityAllowed) { reimburseTFUEL = (tokenQuantityRequest.sub(tokenQuantityAllowed)) .div(rate); tokenQuantityRequest = tokenQuantityAllowed; }
12,523
4
// Mints Crypto DRMS Token Assets/
function mintToken(string memory metadataURI) public payable { require(totalSupply().add(1) <= MAX_TOKENS, "Purchase would exceed max supply of Tokens"); require(tokenPrice.mul(1) <= msg.value, "Ether value sent is not correct"); uint mintIndex = totalSupply(); if (totalSupply() < MAX_TOKENS) { _safeMint(msg.sender, mintIndex); _setTokenURI(mintIndex, metadataURI); } }
function mintToken(string memory metadataURI) public payable { require(totalSupply().add(1) <= MAX_TOKENS, "Purchase would exceed max supply of Tokens"); require(tokenPrice.mul(1) <= msg.value, "Ether value sent is not correct"); uint mintIndex = totalSupply(); if (totalSupply() < MAX_TOKENS) { _safeMint(msg.sender, mintIndex); _setTokenURI(mintIndex, metadataURI); } }
41,120
101
// Must match BConst.MIN_BOUND_TOKENS and BConst.MAX_BOUND_TOKENS
uint256 public constant MIN_ASSET_LIMIT = 2; uint256 public constant MAX_ASSET_LIMIT = 8; uint256 public constant MAX_UINT = uint256(-1);
uint256 public constant MIN_ASSET_LIMIT = 2; uint256 public constant MAX_ASSET_LIMIT = 8; uint256 public constant MAX_UINT = uint256(-1);
6,300
89
// Mapping from address of a person who bought some tokens during "reserve"stage to information about how many tokens he bought to how much etherinvested. /
mapping (address => Investor) internal investors;
mapping (address => Investor) internal investors;
45,120
73
// Set the signer's active status to true.
_signers[signer] = true;
_signers[signer] = true;
38,947
113
// otherwise return Pending
return LoanStatus.Pending;
return LoanStatus.Pending;
11,380
106
// addresses of time-locked founder vaults
address [4] public timeLockAddresses;
address [4] public timeLockAddresses;
50,431