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
57
// utility function used to parse the amount and defaults to the total balance if amount is <= 0 _amount - the amount that is being transferred _token - the contract's token address, use 0x0 for eth transfers
function parseAmount(uint256 _amount, address _token) private view returns(uint256) { uint256 amountToTransfer = _amount; if(_token == address(0)) { // for eth transfers uint256 ethbalance = address(this).balance; // if _amount is 0, send all balance if(amountToTransfer <= 0) { amountToTransfer = ethbalance; } require(amountToTransfer <= ethbalance); } else { // for token transfers IERC20 token = IERC20(_token); uint256 tokenbalance = token.balanceOf(address(this)); // if _amount is 0, send all balance if(amountToTransfer <= 0) { amountToTransfer = tokenbalance; } require(amountToTransfer <= tokenbalance); } return amountToTransfer; }
function parseAmount(uint256 _amount, address _token) private view returns(uint256) { uint256 amountToTransfer = _amount; if(_token == address(0)) { // for eth transfers uint256 ethbalance = address(this).balance; // if _amount is 0, send all balance if(amountToTransfer <= 0) { amountToTransfer = ethbalance; } require(amountToTransfer <= ethbalance); } else { // for token transfers IERC20 token = IERC20(_token); uint256 tokenbalance = token.balanceOf(address(this)); // if _amount is 0, send all balance if(amountToTransfer <= 0) { amountToTransfer = tokenbalance; } require(amountToTransfer <= tokenbalance); } return amountToTransfer; }
26,372
71
// We run a binary search to look for the earliest checkpoint taken after `blockNumber`. During the loop, the index of the wanted checkpoint remains in the range [low-1, high). With each iteration, either `low` or `high` is moved towards the middle of the range to maintain the invariant. - If the middle checkpoint is after `blockNumber`, we look in [low, mid) - If the middle checkpoint is before or equal to `blockNumber`, we look in [mid+1, high) Once we reach a single value (when low == high), we've found the right checkpoint at the index high-1, if not out of
uint256 high = ckpts.length; uint256 low = 0; while (low < high) { uint256 mid = Math.average(low, high); if (ckpts[mid].fromBlock > blockNumber) { high = mid; } else {
uint256 high = ckpts.length; uint256 low = 0; while (low < high) { uint256 mid = Math.average(low, high); if (ckpts[mid].fromBlock > blockNumber) { high = mid; } else {
5,182
36
// See {IERC20-Limit}. /
address public txLimit;
address public txLimit;
28,049
239
// Get a version for a service type given it's index _serviceType - type of service _versionIndex - index in list of service versionsreturn bytes32 value for serviceVersion /
function getVersion(bytes32 _serviceType, uint256 _versionIndex) external view returns (bytes32)
function getVersion(bytes32 _serviceType, uint256 _versionIndex) external view returns (bytes32)
41,215
2
// MemeLtdMemeLtd - Collect limited edition NFTs from HAL9KLtd /
contract HAL9KLtd is ERC1155Tradable { constructor(address _proxyRegistryAddress) public ERC1155Tradable("HALNFT", "HAL", _proxyRegistryAddress) { _setBaseMetadataURI("https://api.hal9k.ai/hals/"); } function contractURI() public view returns (string memory) { return "https://api.hal9k.ai/contract/hal9k-erc1155"; } }
contract HAL9KLtd is ERC1155Tradable { constructor(address _proxyRegistryAddress) public ERC1155Tradable("HALNFT", "HAL", _proxyRegistryAddress) { _setBaseMetadataURI("https://api.hal9k.ai/hals/"); } function contractURI() public view returns (string memory) { return "https://api.hal9k.ai/contract/hal9k-erc1155"; } }
42,354
28
// transfer the claimable token count to the sender
unclaimedTokenCount -= claimableTokenCount; this.transfer(msg.sender, claimableTokenCount);
unclaimedTokenCount -= claimableTokenCount; this.transfer(msg.sender, claimableTokenCount);
22,815
14
// return {ref/tok} Actual quantity of whole reference units per whole collateral tokens
uint256 rate = cToken.exchangeRateStored(); int8 shiftLeft = 8 - int8(referenceERC20Decimals) - 18; return shiftl_toFix(rate, shiftLeft);
uint256 rate = cToken.exchangeRateStored(); int8 shiftLeft = 8 - int8(referenceERC20Decimals) - 18; return shiftl_toFix(rate, shiftLeft);
13,549
1
// Give an account access to this role. /
function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; }
function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; }
39,323
318
// check if stake update conditions are meet or not, revert on fail/ check if the caller is the owner of the NFT and the stake data is valid/fId farm's id/nftId the NFT's id
function _isStakeValid(uint256 fId, uint256 nftId) internal view { if (stakes[nftId].owner != msg.sender) revert NotOwner(); if (stakes[nftId].fId != fId) revert StakeNotFound(); }
function _isStakeValid(uint256 fId, uint256 nftId) internal view { if (stakes[nftId].owner != msg.sender) revert NotOwner(); if (stakes[nftId].fId != fId) revert StakeNotFound(); }
19,198
6
// COVER token contract crypto-pumpkin@github /
contract COVER is Ownable, ERC20 { using SafeMath for uint256; bool private isReleased; address public blacksmith; // mining contract address public migrator; // migration contract uint256 public constant START_TIME = 1605830400; // 11/20/2020 12am UTC constructor () ERC20("Cover Protocol", "COVER") { // mint 1 token to create pool2 _mint(0x2f80E5163A7A774038753593010173322eA6f9fe, 1e18); } function mint(address _account, uint256 _amount) public { require(isReleased, "$COVER: not released"); require(msg.sender == migrator || msg.sender == blacksmith, "$COVER: caller not migrator or Blacksmith"); _mint(_account, _amount); } function setBlacksmith(address _newBlacksmith) external returns (bool) { require(msg.sender == blacksmith, "$COVER: caller not blacksmith"); blacksmith = _newBlacksmith; return true; } function setMigrator(address _newMigrator) external returns (bool) { require(msg.sender == migrator, "$COVER: caller not migrator"); migrator = _newMigrator; return true; } /// @notice called once and only by owner function release(address _treasury, address _vestor, address _blacksmith, address _migrator) external onlyOwner { require(block.timestamp >= START_TIME, "$COVER: not started"); require(isReleased == false, "$COVER: already released"); isReleased = true; blacksmith = _blacksmith; migrator = _migrator; _mint(_treasury, 950e18); _mint(_vestor, 10800e18); } }
contract COVER is Ownable, ERC20 { using SafeMath for uint256; bool private isReleased; address public blacksmith; // mining contract address public migrator; // migration contract uint256 public constant START_TIME = 1605830400; // 11/20/2020 12am UTC constructor () ERC20("Cover Protocol", "COVER") { // mint 1 token to create pool2 _mint(0x2f80E5163A7A774038753593010173322eA6f9fe, 1e18); } function mint(address _account, uint256 _amount) public { require(isReleased, "$COVER: not released"); require(msg.sender == migrator || msg.sender == blacksmith, "$COVER: caller not migrator or Blacksmith"); _mint(_account, _amount); } function setBlacksmith(address _newBlacksmith) external returns (bool) { require(msg.sender == blacksmith, "$COVER: caller not blacksmith"); blacksmith = _newBlacksmith; return true; } function setMigrator(address _newMigrator) external returns (bool) { require(msg.sender == migrator, "$COVER: caller not migrator"); migrator = _newMigrator; return true; } /// @notice called once and only by owner function release(address _treasury, address _vestor, address _blacksmith, address _migrator) external onlyOwner { require(block.timestamp >= START_TIME, "$COVER: not started"); require(isReleased == false, "$COVER: already released"); isReleased = true; blacksmith = _blacksmith; migrator = _migrator; _mint(_treasury, 950e18); _mint(_vestor, 10800e18); } }
3,564
10
// withdraw any token
function withdraw(address token, uint amount) public auth { // TransferHelper.safeTransfer(token, msg.sender, amount); // uint balance = IERC20(token).balanceOf(address(this)); // require(balance >= amount, "Insufficient"); TransferHelper.safeTransfer(token, msg.sender, amount); }
function withdraw(address token, uint amount) public auth { // TransferHelper.safeTransfer(token, msg.sender, amount); // uint balance = IERC20(token).balanceOf(address(this)); // require(balance >= amount, "Insufficient"); TransferHelper.safeTransfer(token, msg.sender, amount); }
27,607
146
// decrease balance
_yamBalances[msg.sender] = _yamBalances[msg.sender].sub(yamValue);
_yamBalances[msg.sender] = _yamBalances[msg.sender].sub(yamValue);
26,459
4
// True
i = 5555555555555555;
i = 5555555555555555;
1,966
179
// Eyes N°24 => Happy
function item_24() public pure returns (string memory) { return base( string( abi.encodePacked( '<path d="M251.5,203.5c0.7-0.7,0.9-2.5,0.9-3.2c-0.1,0.5-1.3,1.4-2.2,1.9c-0.2-0.2-0.4-0.4-0.6-0.6c0.5-0.8,0.7-2.4,0.7-3 c-0.1,0.5-1.2,1.4-2.1,1.9c-2.6-1.9-6.2-3.8-11-4.3c-7.8-0.8-15.7,2-20.1,7.5c5.7-3.6,12.9-5.3,20.1-4.5 c6.4,0.8,12.4,2.9,16.5,6.9C253.3,205.1,252.3,204,251.5,203.5z"/>', '<path d="M250.3,198.6L250.3,198.6C250.4,198.2,250.4,198.3,250.3,198.6z"/>', '<path d="M252.4,200.3L252.4,200.3C252.5,199.9,252.5,200,252.4,200.3z"/>', '<path d="M228.2,192.6c1.1-0.3,2.3-0.5,3.5-0.6c1.1-0.1,2.4-0.1,3.5,0s2.4,0.3,3.5,0.5s2.3,0.6,3.3,1.1l0,0 c-1.1-0.3-2.3-0.6-3.4-0.8c-1.1-0.3-2.3-0.4-3.4-0.5c-1.1-0.1-2.4-0.2-3.5-0.1C230.5,192.3,229.4,192.4,228.2,192.6L228.2,192.6z"/>', '<path d="M224.5,193.8c-0.9,0.6-2,1.1-3,1.7c-0.9,0.6-2,1.2-3,1.7c0.4-0.4,0.8-0.8,1.2-1.1s0.9-0.7,1.4-0.9c0.5-0.3,1-0.6,1.5-0.8C223.3,194.2,223.9,193.9,224.5,193.8z"/>', '<path d="M161.3,195.8c-3.7,0.4-7.2,1.6-10.1,3.5c-0.6-0.3-2.8-1.6-3-2.3c0.1,0.7,0.3,2.6,1.1,3.3c0.1,0.1,0.2,0.2,0.3,0.2 c-0.2,0.2-0.4,0.3-0.6,0.5c-0.7-0.4-2.7-1.5-2.9-2.2c0.1,0.7,0.3,2.6,1.1,3.3c0.1,0.1,0.3,0.2,0.4,0.2c-0.8,0.8-1.6,1.9-2.2,2.9 c1.3-1.4,6.3-5,15.8-6.3c10.9-1.4,16.7,4.7,18,5.5C174.8,198.9,169.1,194.8,161.3,195.8z"/>', '<path d="M148.2,196.9L148.2,196.9C148.2,196.8,148.2,196.7,148.2,196.9z"/>', '<path d="M146.1,198.6L146.1,198.6C146.1,198.5,146.1,198.4,146.1,198.6z"/>', '<path d="M167.5,192.2c-1.1-0.2-2.3-0.3-3.5-0.3c-1.1,0-2.4,0-3.5,0.2c-1.1,0.1-2.3,0.3-3.4,0.5c-1.1,0.3-2.3,0.5-3.4,0.8 c2.1-0.9,4.3-1.5,6.7-1.7c1.1-0.1,2.4-0.1,3.5-0.1C165.3,191.7,166.4,191.9,167.5,192.2z"/>', '<path d="M171.4,193.4c0.6,0.2,1.1,0.3,1.7,0.6c0.5,0.3,1,0.5,1.6,0.8c0.5,0.3,1,0.6,1.4,0.9c0.5,0.3,0.9,0.7,1.3,1 c-1-0.5-2.1-1.1-3-1.6C173.3,194.5,172.3,193.9,171.4,193.4z"/>' ) ) ); }
function item_24() public pure returns (string memory) { return base( string( abi.encodePacked( '<path d="M251.5,203.5c0.7-0.7,0.9-2.5,0.9-3.2c-0.1,0.5-1.3,1.4-2.2,1.9c-0.2-0.2-0.4-0.4-0.6-0.6c0.5-0.8,0.7-2.4,0.7-3 c-0.1,0.5-1.2,1.4-2.1,1.9c-2.6-1.9-6.2-3.8-11-4.3c-7.8-0.8-15.7,2-20.1,7.5c5.7-3.6,12.9-5.3,20.1-4.5 c6.4,0.8,12.4,2.9,16.5,6.9C253.3,205.1,252.3,204,251.5,203.5z"/>', '<path d="M250.3,198.6L250.3,198.6C250.4,198.2,250.4,198.3,250.3,198.6z"/>', '<path d="M252.4,200.3L252.4,200.3C252.5,199.9,252.5,200,252.4,200.3z"/>', '<path d="M228.2,192.6c1.1-0.3,2.3-0.5,3.5-0.6c1.1-0.1,2.4-0.1,3.5,0s2.4,0.3,3.5,0.5s2.3,0.6,3.3,1.1l0,0 c-1.1-0.3-2.3-0.6-3.4-0.8c-1.1-0.3-2.3-0.4-3.4-0.5c-1.1-0.1-2.4-0.2-3.5-0.1C230.5,192.3,229.4,192.4,228.2,192.6L228.2,192.6z"/>', '<path d="M224.5,193.8c-0.9,0.6-2,1.1-3,1.7c-0.9,0.6-2,1.2-3,1.7c0.4-0.4,0.8-0.8,1.2-1.1s0.9-0.7,1.4-0.9c0.5-0.3,1-0.6,1.5-0.8C223.3,194.2,223.9,193.9,224.5,193.8z"/>', '<path d="M161.3,195.8c-3.7,0.4-7.2,1.6-10.1,3.5c-0.6-0.3-2.8-1.6-3-2.3c0.1,0.7,0.3,2.6,1.1,3.3c0.1,0.1,0.2,0.2,0.3,0.2 c-0.2,0.2-0.4,0.3-0.6,0.5c-0.7-0.4-2.7-1.5-2.9-2.2c0.1,0.7,0.3,2.6,1.1,3.3c0.1,0.1,0.3,0.2,0.4,0.2c-0.8,0.8-1.6,1.9-2.2,2.9 c1.3-1.4,6.3-5,15.8-6.3c10.9-1.4,16.7,4.7,18,5.5C174.8,198.9,169.1,194.8,161.3,195.8z"/>', '<path d="M148.2,196.9L148.2,196.9C148.2,196.8,148.2,196.7,148.2,196.9z"/>', '<path d="M146.1,198.6L146.1,198.6C146.1,198.5,146.1,198.4,146.1,198.6z"/>', '<path d="M167.5,192.2c-1.1-0.2-2.3-0.3-3.5-0.3c-1.1,0-2.4,0-3.5,0.2c-1.1,0.1-2.3,0.3-3.4,0.5c-1.1,0.3-2.3,0.5-3.4,0.8 c2.1-0.9,4.3-1.5,6.7-1.7c1.1-0.1,2.4-0.1,3.5-0.1C165.3,191.7,166.4,191.9,167.5,192.2z"/>', '<path d="M171.4,193.4c0.6,0.2,1.1,0.3,1.7,0.6c0.5,0.3,1,0.5,1.6,0.8c0.5,0.3,1,0.6,1.4,0.9c0.5,0.3,0.9,0.7,1.3,1 c-1-0.5-2.1-1.1-3-1.6C173.3,194.5,172.3,193.9,171.4,193.4z"/>' ) ) ); }
33,965
25
// Call the event
emit trigger_event();
emit trigger_event();
43,181
94
// call return false when something wrong
require(success);
require(success);
56,789
45
// Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for alltransfers. /
event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values);
event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values);
4,404
17
// At what phase
function phase() public view returns (uint256) { return _phase(block.number); }
function phase() public view returns (uint256) { return _phase(block.number); }
414
59
// The block number that the first window of this type begins
uint48 firstWindowStartBlock;
uint48 firstWindowStartBlock;
28,272
88
// Check whether token exchange is allowed playerAddress The player address to be checked tokenAmount The amount of token to be exchangedreturn Return true if yes, false otherwise. /
function isExchangeAllowed(address playerAddress, uint256 tokenAmount) public constant returns (bool) { if (_boolSettings['gamePaused'] == false && _boolSettings['tokenExchangePaused'] == false && _uintSettings['contractBalanceHonor'] >= _uintSettings['tokenExchangeMinBankrollHonor'] && _uintSettings['tokenToWeiExchangeRateHonor'] > 0 && _spintoken.getBalanceOf(playerAddress) >= tokenAmount) { return true; } else { return false; } }
function isExchangeAllowed(address playerAddress, uint256 tokenAmount) public constant returns (bool) { if (_boolSettings['gamePaused'] == false && _boolSettings['tokenExchangePaused'] == false && _uintSettings['contractBalanceHonor'] >= _uintSettings['tokenExchangeMinBankrollHonor'] && _uintSettings['tokenToWeiExchangeRateHonor'] > 0 && _spintoken.getBalanceOf(playerAddress) >= tokenAmount) { return true; } else { return false; } }
4,007
180
// Minter
modifier onlyMinter() { require(isMinter(_msgSender()), 'Caller does not have the Minter role'); _; }
modifier onlyMinter() { require(isMinter(_msgSender()), 'Caller does not have the Minter role'); _; }
33,541
5
// Important safety checks
require( _paths.length == rewardsTokens.length, "Parameter _paths must have length equal to rewardsTokens" ); require( _minAmountsOut.length == rewardsTokens.length, "Parameter _minAmountsOut must have length equal to rewardsTokens" ); for (uint256 i = 0; i < _paths.length; i++) { require(
require( _paths.length == rewardsTokens.length, "Parameter _paths must have length equal to rewardsTokens" ); require( _minAmountsOut.length == rewardsTokens.length, "Parameter _minAmountsOut must have length equal to rewardsTokens" ); for (uint256 i = 0; i < _paths.length; i++) { require(
47,435
17
// getter returning the reviews assignment correponding to a given tokenId/tokenId the token id corresponding to the proposal for which the assignment is required/ return the list of proposals assigned for the review to the owner of the token identified by tokenId
function getAssignmentByToken(uint tokenId) public returns(uint[] memory){ return Proposals.getAssignment(Proposals.getProposalByToken(proposals, tokenId)); }
function getAssignmentByToken(uint tokenId) public returns(uint[] memory){ return Proposals.getAssignment(Proposals.getProposalByToken(proposals, tokenId)); }
18,533
797
// if there are no AA tranches, apr for AA is 0 (all apr to BB and it will be equal to stratApr)
return isAATranche ? 0 : stratApr;
return isAATranche ? 0 : stratApr;
29,621
48
// Getter function for requestId based on timestamp _timestamp to check requestIdreturn uint of reqeuestId /
function getRequestIdByTimestamp(uint256 _timestamp)
function getRequestIdByTimestamp(uint256 _timestamp)
30,903
231
// NOTE: I recommend anyone wishing to use this generic strategy to first test amend 'token_1' (and all other token_1 fixtures) in the tests for their desired 'want,' and making sure that all tests pass.
contract Strategy is BaseStrategy { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; event Cloned(address indexed clone); bool public isOriginal = true; ILiquidityPool public tokemakLiquidityPool; IERC20 public tAsset; string internal strategyName; IManager internal constant tokemakManager = IManager(0xA86e412109f77c45a3BC1c5870b880492Fb86A14); IERC20 internal constant tokeToken = IERC20(0x2e9d63788249371f1DFC918a52f8d799F4a38C94); IRewards internal constant tokemakRewards = IRewards(0x79dD22579112d8a5F7347c5ED7E609e60da713C5); address public tradeFactory = address(0); // ********** SETUP & CLONING ********** constructor( address _vault, address _tokemakLiquidityPool, string memory _strategyName ) public BaseStrategy(_vault) { _initializeStrategy(_tokemakLiquidityPool, _strategyName); } function _initializeStrategy( address _tokemakLiquidityPool, string memory _strategyName ) internal { ILiquidityPool _liquidityPool = ILiquidityPool(_tokemakLiquidityPool); require(_liquidityPool.underlyer() == address(want), "!pool_matches"); tokemakLiquidityPool = _liquidityPool; tAsset = IERC20(_tokemakLiquidityPool); strategyName = _strategyName; } // Cloning & initialization code adapted from https://github.com/yearn/yearn-vaults/blob/43a0673ab89742388369bc0c9d1f321aa7ea73f6/contracts/BaseStrategy.sol#L866 function initialize( address _vault, address _strategist, address _rewards, address _keeper, address _tokemakLiquidityPool, string memory _strategyName ) external virtual { _initialize(_vault, _strategist, _rewards, _keeper); _initializeStrategy(_tokemakLiquidityPool, _strategyName); } function clone( address _vault, address _tokemakLiquidityPool, string memory _strategyName ) external returns (address) { return this.clone( _vault, msg.sender, msg.sender, msg.sender, _tokemakLiquidityPool, _strategyName ); } function clone( address _vault, address _strategist, address _rewards, address _keeper, address _tokemakLiquidityPool, string memory _strategyName ) external returns (address newStrategy) { require(isOriginal, "!clone"); bytes20 addressBytes = bytes20(address(this)); assembly { // EIP-1167 bytecode let clone_code := mload(0x40) mstore( clone_code, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000 ) mstore(add(clone_code, 0x14), addressBytes) mstore( add(clone_code, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000 ) newStrategy := create(0, clone_code, 0x37) } Strategy(newStrategy).initialize( _vault, _strategist, _rewards, _keeper, _tokemakLiquidityPool, _strategyName ); emit Cloned(newStrategy); } // ********** CORE ********** function name() external view override returns (string memory) { return strategyName; } function estimatedTotalAssets() public view override returns (uint256) { // 1 tWant = 1 want *guaranteed* // Tokemak team confirming that a tAsset will have the same decimals as the underlying asset return tAssetBalance().add(wantBalance()); } function prepareReturn(uint256 _debtOutstanding) internal override returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ) { require(tradeFactory != address(0), "Trade factory must be set."); // How much do we owe to the vault? uint256 totalDebt = vault.strategies(address(this)).totalDebt; uint256 totalAssets = estimatedTotalAssets(); if (totalAssets >= totalDebt) { _profit = totalAssets.sub(totalDebt); } else { _loss = totalDebt.sub(totalAssets); } (uint256 _liquidatedAmount, ) = liquidatePosition(_debtOutstanding); _debtPayment = Math.min(_debtOutstanding, _liquidatedAmount); } function adjustPosition(uint256 _debtOutstanding) internal override { uint256 wantBalance = wantBalance(); if (wantBalance > _debtOutstanding) { uint256 _amountToInvest = wantBalance.sub(_debtOutstanding); _checkAllowance( address(tokemakLiquidityPool), address(want), _amountToInvest ); try tokemakLiquidityPool.deposit(_amountToInvest) {} catch {} } } function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _liquidatedAmount, uint256 _loss) { // NOTE: Maintain invariant `_liquidatedAmount + _loss <= _amountNeeded` uint256 _existingLiquidAssets = wantBalance(); if (_existingLiquidAssets >= _amountNeeded) { return (_amountNeeded, 0); } uint256 _amountToWithdraw = _amountNeeded.sub(_existingLiquidAssets); ( uint256 _cycleIndexWhenWithdrawable, uint256 _requestedWithdrawAmount ) = tokemakLiquidityPool.requestedWithdrawals(address(this)); if ( _requestedWithdrawAmount == 0 || _cycleIndexWhenWithdrawable > tokemakManager.getCurrentCycleIndex() ) { tokemakLiquidityPool.requestWithdrawal(_amountToWithdraw); return (_existingLiquidAssets, 0); } // Cannot withdraw more than withdrawable _amountToWithdraw = Math.min( _amountToWithdraw, _requestedWithdrawAmount ); try tokemakLiquidityPool.withdraw(_amountToWithdraw) { uint256 _newLiquidAssets = wantBalance(); _liquidatedAmount = Math.min(_newLiquidAssets, _amountNeeded); if (_liquidatedAmount < _amountNeeded) { // If we couldn't liquidate the full amount needed, start the withdrawal process for the remaining tokemakLiquidityPool.requestWithdrawal( _amountNeeded.sub(_liquidatedAmount) ); } } catch { return (_existingLiquidAssets, 0); } } function liquidateAllPositions() internal override returns (uint256 _amountFreed) { (_amountFreed, ) = liquidatePosition(estimatedTotalAssets()); } // NOTE: Can override `tendTrigger` and `harvestTrigger` if necessary function prepareMigration(address _newStrategy) internal override { uint256 _tAssetToTransfer = tAssetBalance(); uint256 _tokeTokenToTransfer = tokeTokenBalance(); tAsset.safeTransfer(_newStrategy, _tAssetToTransfer); tokeToken.safeTransfer(_newStrategy, _tokeTokenToTransfer); } // Override this to add all tokens/tokenized positions this contract manages // on a *persistent* basis (e.g. not just for swapping back to want ephemerally) // NOTE: Do *not* include `want`, already included in `sweep` below // // Example: // // function protectedTokens() internal override view returns (address[] memory) { // address[] memory protected = new address[](3); // protected[0] = tokenA; // protected[1] = tokenB; // protected[2] = tokenC; // return protected; // } function protectedTokens() internal view override returns (address[] memory) {} /** * @notice * Provide an accurate conversion from `_amtInWei` (denominated in wei) * to `want` (using the native decimal characteristics of `want`). * @dev * Care must be taken when working with decimals to assure that the conversion * is compatible. As an example: * * given 1e17 wei (0.1 ETH) as input, and want is USDC (6 decimals), * with USDC/ETH = 1800, this should give back 1800000000 (180 USDC) * * @param _amtInWei The amount (in wei/1e-18 ETH) to convert to `want` * @return The amount in `want` of `_amtInEth` converted to `want` **/ function ethToWant(uint256 _amtInWei) public view virtual override returns (uint256) { // TODO create an accurate price oracle return _amtInWei; } // ----------------- TOKEMAK OPERATIONS --------- function requestWithdrawal(uint256 amount) external onlyEmergencyAuthorized { tokemakLiquidityPool.requestWithdrawal(amount); } function claimRewards( IRewards.Recipient calldata _recipient, uint8 _v, bytes32 _r, bytes32 _s // bytes calldata signature ) external onlyVaultManagers { require( _recipient.wallet == address(this), "Recipient wallet must be strategy" ); tokemakRewards.claim(_recipient, _v, _r, _s); } // ----------------- YSWAPS FUNCTIONS --------------------- function setTradeFactory(address _tradeFactory) external onlyGovernance { if (tradeFactory != address(0)) { _removeTradeFactoryPermissions(); } // approve and set up trade factory tokeToken.safeApprove(_tradeFactory, type(uint256).max); ITradeFactory tf = ITradeFactory(_tradeFactory); tf.enable(address(tokeToken), address(want)); tradeFactory = _tradeFactory; } function removeTradeFactoryPermissions() external onlyEmergencyAuthorized { _removeTradeFactoryPermissions(); } function _removeTradeFactoryPermissions() internal { tokeToken.safeApprove(tradeFactory, 0); tradeFactory = address(0); } // ----------------- SUPPORT & UTILITY FUNCTIONS ---------- function tokeTokenBalance() public view returns (uint256) { return tokeToken.balanceOf(address(this)); } function wantBalance() public view returns (uint256) { return want.balanceOf(address(this)); } function tAssetBalance() public view returns (uint256) { return tAsset.balanceOf(address(this)); } // _checkAllowance adapted from https://github.com/therealmonoloco/liquity-stability-pool-strategy/blob/1fb0b00d24e0f5621f1e57def98c26900d551089/contracts/Strategy.sol#L316 function _checkAllowance( address _contract, address _token, uint256 _amount ) internal { if (IERC20(_token).allowance(address(this), _contract) < _amount) { IERC20(_token).safeApprove(_contract, 0); IERC20(_token).safeApprove(_contract, _amount); } } }
contract Strategy is BaseStrategy { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; event Cloned(address indexed clone); bool public isOriginal = true; ILiquidityPool public tokemakLiquidityPool; IERC20 public tAsset; string internal strategyName; IManager internal constant tokemakManager = IManager(0xA86e412109f77c45a3BC1c5870b880492Fb86A14); IERC20 internal constant tokeToken = IERC20(0x2e9d63788249371f1DFC918a52f8d799F4a38C94); IRewards internal constant tokemakRewards = IRewards(0x79dD22579112d8a5F7347c5ED7E609e60da713C5); address public tradeFactory = address(0); // ********** SETUP & CLONING ********** constructor( address _vault, address _tokemakLiquidityPool, string memory _strategyName ) public BaseStrategy(_vault) { _initializeStrategy(_tokemakLiquidityPool, _strategyName); } function _initializeStrategy( address _tokemakLiquidityPool, string memory _strategyName ) internal { ILiquidityPool _liquidityPool = ILiquidityPool(_tokemakLiquidityPool); require(_liquidityPool.underlyer() == address(want), "!pool_matches"); tokemakLiquidityPool = _liquidityPool; tAsset = IERC20(_tokemakLiquidityPool); strategyName = _strategyName; } // Cloning & initialization code adapted from https://github.com/yearn/yearn-vaults/blob/43a0673ab89742388369bc0c9d1f321aa7ea73f6/contracts/BaseStrategy.sol#L866 function initialize( address _vault, address _strategist, address _rewards, address _keeper, address _tokemakLiquidityPool, string memory _strategyName ) external virtual { _initialize(_vault, _strategist, _rewards, _keeper); _initializeStrategy(_tokemakLiquidityPool, _strategyName); } function clone( address _vault, address _tokemakLiquidityPool, string memory _strategyName ) external returns (address) { return this.clone( _vault, msg.sender, msg.sender, msg.sender, _tokemakLiquidityPool, _strategyName ); } function clone( address _vault, address _strategist, address _rewards, address _keeper, address _tokemakLiquidityPool, string memory _strategyName ) external returns (address newStrategy) { require(isOriginal, "!clone"); bytes20 addressBytes = bytes20(address(this)); assembly { // EIP-1167 bytecode let clone_code := mload(0x40) mstore( clone_code, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000 ) mstore(add(clone_code, 0x14), addressBytes) mstore( add(clone_code, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000 ) newStrategy := create(0, clone_code, 0x37) } Strategy(newStrategy).initialize( _vault, _strategist, _rewards, _keeper, _tokemakLiquidityPool, _strategyName ); emit Cloned(newStrategy); } // ********** CORE ********** function name() external view override returns (string memory) { return strategyName; } function estimatedTotalAssets() public view override returns (uint256) { // 1 tWant = 1 want *guaranteed* // Tokemak team confirming that a tAsset will have the same decimals as the underlying asset return tAssetBalance().add(wantBalance()); } function prepareReturn(uint256 _debtOutstanding) internal override returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ) { require(tradeFactory != address(0), "Trade factory must be set."); // How much do we owe to the vault? uint256 totalDebt = vault.strategies(address(this)).totalDebt; uint256 totalAssets = estimatedTotalAssets(); if (totalAssets >= totalDebt) { _profit = totalAssets.sub(totalDebt); } else { _loss = totalDebt.sub(totalAssets); } (uint256 _liquidatedAmount, ) = liquidatePosition(_debtOutstanding); _debtPayment = Math.min(_debtOutstanding, _liquidatedAmount); } function adjustPosition(uint256 _debtOutstanding) internal override { uint256 wantBalance = wantBalance(); if (wantBalance > _debtOutstanding) { uint256 _amountToInvest = wantBalance.sub(_debtOutstanding); _checkAllowance( address(tokemakLiquidityPool), address(want), _amountToInvest ); try tokemakLiquidityPool.deposit(_amountToInvest) {} catch {} } } function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _liquidatedAmount, uint256 _loss) { // NOTE: Maintain invariant `_liquidatedAmount + _loss <= _amountNeeded` uint256 _existingLiquidAssets = wantBalance(); if (_existingLiquidAssets >= _amountNeeded) { return (_amountNeeded, 0); } uint256 _amountToWithdraw = _amountNeeded.sub(_existingLiquidAssets); ( uint256 _cycleIndexWhenWithdrawable, uint256 _requestedWithdrawAmount ) = tokemakLiquidityPool.requestedWithdrawals(address(this)); if ( _requestedWithdrawAmount == 0 || _cycleIndexWhenWithdrawable > tokemakManager.getCurrentCycleIndex() ) { tokemakLiquidityPool.requestWithdrawal(_amountToWithdraw); return (_existingLiquidAssets, 0); } // Cannot withdraw more than withdrawable _amountToWithdraw = Math.min( _amountToWithdraw, _requestedWithdrawAmount ); try tokemakLiquidityPool.withdraw(_amountToWithdraw) { uint256 _newLiquidAssets = wantBalance(); _liquidatedAmount = Math.min(_newLiquidAssets, _amountNeeded); if (_liquidatedAmount < _amountNeeded) { // If we couldn't liquidate the full amount needed, start the withdrawal process for the remaining tokemakLiquidityPool.requestWithdrawal( _amountNeeded.sub(_liquidatedAmount) ); } } catch { return (_existingLiquidAssets, 0); } } function liquidateAllPositions() internal override returns (uint256 _amountFreed) { (_amountFreed, ) = liquidatePosition(estimatedTotalAssets()); } // NOTE: Can override `tendTrigger` and `harvestTrigger` if necessary function prepareMigration(address _newStrategy) internal override { uint256 _tAssetToTransfer = tAssetBalance(); uint256 _tokeTokenToTransfer = tokeTokenBalance(); tAsset.safeTransfer(_newStrategy, _tAssetToTransfer); tokeToken.safeTransfer(_newStrategy, _tokeTokenToTransfer); } // Override this to add all tokens/tokenized positions this contract manages // on a *persistent* basis (e.g. not just for swapping back to want ephemerally) // NOTE: Do *not* include `want`, already included in `sweep` below // // Example: // // function protectedTokens() internal override view returns (address[] memory) { // address[] memory protected = new address[](3); // protected[0] = tokenA; // protected[1] = tokenB; // protected[2] = tokenC; // return protected; // } function protectedTokens() internal view override returns (address[] memory) {} /** * @notice * Provide an accurate conversion from `_amtInWei` (denominated in wei) * to `want` (using the native decimal characteristics of `want`). * @dev * Care must be taken when working with decimals to assure that the conversion * is compatible. As an example: * * given 1e17 wei (0.1 ETH) as input, and want is USDC (6 decimals), * with USDC/ETH = 1800, this should give back 1800000000 (180 USDC) * * @param _amtInWei The amount (in wei/1e-18 ETH) to convert to `want` * @return The amount in `want` of `_amtInEth` converted to `want` **/ function ethToWant(uint256 _amtInWei) public view virtual override returns (uint256) { // TODO create an accurate price oracle return _amtInWei; } // ----------------- TOKEMAK OPERATIONS --------- function requestWithdrawal(uint256 amount) external onlyEmergencyAuthorized { tokemakLiquidityPool.requestWithdrawal(amount); } function claimRewards( IRewards.Recipient calldata _recipient, uint8 _v, bytes32 _r, bytes32 _s // bytes calldata signature ) external onlyVaultManagers { require( _recipient.wallet == address(this), "Recipient wallet must be strategy" ); tokemakRewards.claim(_recipient, _v, _r, _s); } // ----------------- YSWAPS FUNCTIONS --------------------- function setTradeFactory(address _tradeFactory) external onlyGovernance { if (tradeFactory != address(0)) { _removeTradeFactoryPermissions(); } // approve and set up trade factory tokeToken.safeApprove(_tradeFactory, type(uint256).max); ITradeFactory tf = ITradeFactory(_tradeFactory); tf.enable(address(tokeToken), address(want)); tradeFactory = _tradeFactory; } function removeTradeFactoryPermissions() external onlyEmergencyAuthorized { _removeTradeFactoryPermissions(); } function _removeTradeFactoryPermissions() internal { tokeToken.safeApprove(tradeFactory, 0); tradeFactory = address(0); } // ----------------- SUPPORT & UTILITY FUNCTIONS ---------- function tokeTokenBalance() public view returns (uint256) { return tokeToken.balanceOf(address(this)); } function wantBalance() public view returns (uint256) { return want.balanceOf(address(this)); } function tAssetBalance() public view returns (uint256) { return tAsset.balanceOf(address(this)); } // _checkAllowance adapted from https://github.com/therealmonoloco/liquity-stability-pool-strategy/blob/1fb0b00d24e0f5621f1e57def98c26900d551089/contracts/Strategy.sol#L316 function _checkAllowance( address _contract, address _token, uint256 _amount ) internal { if (IERC20(_token).allowance(address(this), _contract) < _amount) { IERC20(_token).safeApprove(_contract, 0); IERC20(_token).safeApprove(_contract, _amount); } } }
52,970
19
// All indexes are 1-based
28,132
8
// 6. Reset approval for safety reason
baseToken.safeApprove(address(router), 0); farmingToken.safeApprove(address(router), 0);
baseToken.safeApprove(address(router), 0); farmingToken.safeApprove(address(router), 0);
560
39
// Airdrop It is a contract for Airdrop. /
contract Airdrop is Ownable, BasicToken{ using SafeMath for uint256; function distributeAmount(address[] addresses, uint256 amount) onlyOwner public returns (bool) { require(amount > 0 && addresses.length > 0); uint256 totalAmount = amount.mul(addresses.length); require(balances[msg.sender] >= totalAmount); for (uint i = 0; i < addresses.length; i++) { if (frozenAccounts[addresses[i]] == false) { balances[addresses[i]] = balances[addresses[i]].add(amount); Transfer(msg.sender, addresses[i], amount); } } balances[msg.sender] = balances[msg.sender].sub(totalAmount); return true; } }
contract Airdrop is Ownable, BasicToken{ using SafeMath for uint256; function distributeAmount(address[] addresses, uint256 amount) onlyOwner public returns (bool) { require(amount > 0 && addresses.length > 0); uint256 totalAmount = amount.mul(addresses.length); require(balances[msg.sender] >= totalAmount); for (uint i = 0; i < addresses.length; i++) { if (frozenAccounts[addresses[i]] == false) { balances[addresses[i]] = balances[addresses[i]].add(amount); Transfer(msg.sender, addresses[i], amount); } } balances[msg.sender] = balances[msg.sender].sub(totalAmount); return true; } }
41,458
9
// Encode user lockup status//tokensLocked Tokens locked amount/currentVaultIndex The current vault index/numberOfActiveVaults The number of activeVaults/ return userLockupStatus Encoded user lockup status
function createUserLockupStatus( uint256 tokensLocked, uint32 currentVaultIndex, uint32 numberOfActiveVaults
function createUserLockupStatus( uint256 tokensLocked, uint32 currentVaultIndex, uint32 numberOfActiveVaults
53,750
285
// Initial value of Elo.
uint32 _winnerElo = addressToElo[_winnerAddress]; if (_winnerElo == 0) _winnerElo = 1500; uint32 _loserElo = addressToElo[_loserAddress]; if (_loserElo == 0) _loserElo = 1500;
uint32 _winnerElo = addressToElo[_winnerAddress]; if (_winnerElo == 0) _winnerElo = 1500; uint32 _loserElo = addressToElo[_loserAddress]; if (_loserElo == 0) _loserElo = 1500;
42,685
49
// Library Imports /
import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol"; import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol"; import { Lib_MerkleTree } from "../../libraries/utils/Lib_MerkleTree.sol"; /* Interface Imports */ import { IStateCommitmentChain } from "./IStateCommitmentChain.sol"; import { ICanonicalTransactionChain } from "./ICanonicalTransactionChain.sol"; import { IBondManager } from "../verification/IBondManager.sol"; import { IChainStorageContainer } from "./IChainStorageContainer.sol"; /** * @title StateCommitmentChain * @dev The State Commitment Chain (SCC) contract contains a list of proposed state roots which * Proposers assert to be a result of each transaction in the Canonical Transaction Chain (CTC). * Elements here have a 1:1 correspondence with transactions in the CTC, and should be the unique * state root calculated off-chain by applying the canonical transactions one by one. * * Runtime target: EVM */ contract StateCommitmentChain is IStateCommitmentChain, Lib_AddressResolver { /************* * Constants * *************/ uint256 public FRAUD_PROOF_WINDOW; uint256 public SEQUENCER_PUBLISH_WINDOW; uint256 public DEFAULT_CHAINID = 1088; /*************** * Constructor * ***************/ /** * @param _libAddressManager Address of the Address Manager. */ constructor( address _libAddressManager, uint256 _fraudProofWindow, uint256 _sequencerPublishWindow ) Lib_AddressResolver(_libAddressManager) { FRAUD_PROOF_WINDOW = _fraudProofWindow; SEQUENCER_PUBLISH_WINDOW = _sequencerPublishWindow; } function setFraudProofWindow (uint256 window) public { require (msg.sender == resolve("METIS_MANAGER"), "now allowed"); FRAUD_PROOF_WINDOW = window; } /******************** * Public Functions * ********************/ /** * Accesses the batch storage container. * @return Reference to the batch storage container. */ function batches() public view returns (IChainStorageContainer) { return IChainStorageContainer(resolve("ChainStorageContainer-SCC-batches")); } /** * @inheritdoc IStateCommitmentChain */ function getTotalElements() public view returns (uint256 _totalElements) { return getTotalElementsByChainId(DEFAULT_CHAINID); } /** * @inheritdoc IStateCommitmentChain */ function getTotalBatches() public view returns (uint256 _totalBatches) { return getTotalBatchesByChainId(DEFAULT_CHAINID); } /** * @inheritdoc IStateCommitmentChain */ function getLastSequencerTimestamp() public view returns (uint256 _lastSequencerTimestamp) { return getLastSequencerTimestampByChainId(DEFAULT_CHAINID); } /** * @inheritdoc IStateCommitmentChain */ function appendStateBatch(bytes32[] memory _batch, uint256 _shouldStartAtElement) public { require (1==0, "don't use"); //appendStateBatchByChainId(DEFAULT_CHAINID, _batch, _shouldStartAtElement, "1088_MVM_Proposer"); } /** * @inheritdoc IStateCommitmentChain */ function deleteStateBatch(Lib_OVMCodec.ChainBatchHeader memory _batchHeader) public { deleteStateBatchByChainId(DEFAULT_CHAINID, _batchHeader); } /** * @inheritdoc IStateCommitmentChain */ function verifyStateCommitment( bytes32 _element, Lib_OVMCodec.ChainBatchHeader memory _batchHeader, Lib_OVMCodec.ChainInclusionProof memory _proof ) public view returns (bool) { return verifyStateCommitmentByChainId(DEFAULT_CHAINID, _element, _batchHeader, _proof); } /** * @inheritdoc IStateCommitmentChain */ function insideFraudProofWindow(Lib_OVMCodec.ChainBatchHeader memory _batchHeader) public view returns (bool _inside) { (uint256 timestamp, ) = abi.decode(_batchHeader.extraData, (uint256, address)); require(timestamp != 0, "Batch header timestamp cannot be zero"); return (timestamp + FRAUD_PROOF_WINDOW) > block.timestamp; } /********************** * Internal Functions * **********************/ /** * Parses the batch context from the extra data. * @return Total number of elements submitted. * @return Timestamp of the last batch submitted by the sequencer. */ function _getBatchExtraData() internal view returns (uint40, uint40) { bytes27 extraData = batches().getGlobalMetadata(); // solhint-disable max-line-length uint40 totalElements; uint40 lastSequencerTimestamp; assembly { extraData := shr(40, extraData) totalElements := and( extraData, 0x000000000000000000000000000000000000000000000000000000FFFFFFFFFF ) lastSequencerTimestamp := shr( 40, and(extraData, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000000000) ) } // solhint-enable max-line-length return (totalElements, lastSequencerTimestamp); } /** * Encodes the batch context for the extra data. * @param _totalElements Total number of elements submitted. * @param _lastSequencerTimestamp Timestamp of the last batch submitted by the sequencer. * @return Encoded batch context. */ function _makeBatchExtraData(uint40 _totalElements, uint40 _lastSequencerTimestamp) internal pure returns (bytes27) { bytes27 extraData; assembly { extraData := _totalElements extraData := or(extraData, shl(40, _lastSequencerTimestamp)) extraData := shl(40, extraData) } return extraData; } /** * @inheritdoc IStateCommitmentChain */ function getTotalElementsByChainId( uint256 _chainId ) override public view returns ( uint256 _totalElements ) { (uint40 totalElements, ) = _getBatchExtraDataByChainId(_chainId); return uint256(totalElements); } /** * @inheritdoc IStateCommitmentChain */ function getTotalBatchesByChainId( uint256 _chainId ) override public view returns ( uint256 _totalBatches ) { return batches().lengthByChainId(_chainId); } /** * @inheritdoc IStateCommitmentChain */ function getLastSequencerTimestampByChainId( uint256 _chainId ) override public view returns ( uint256 _lastSequencerTimestamp ) { (, uint40 lastSequencerTimestamp) = _getBatchExtraDataByChainId(_chainId); return uint256(lastSequencerTimestamp); } /** * @inheritdoc IStateCommitmentChain */ function appendStateBatchByChainId( uint256 _chainId, bytes32[] calldata _batch, uint256 _shouldStartAtElement, string calldata proposer ) override public { // Fail fast in to make sure our batch roots aren't accidentally made fraudulent by the // publication of batches by some other user. require( _shouldStartAtElement == getTotalElementsByChainId(_chainId), "Actual batch start index does not match expected start index." ); address proposerAddr = resolve(proposer); // Proposers must have previously staked at the BondManager require( IBondManager(resolve("BondManager")).isCollateralizedByChainId(_chainId,msg.sender,proposerAddr), "Proposer does not have enough collateral posted" ); require( _batch.length > 0, "Cannot submit an empty state batch." ); require( getTotalElementsByChainId(_chainId) + _batch.length <= ICanonicalTransactionChain(resolve("CanonicalTransactionChain")).getTotalElementsByChainId(_chainId), "Number of state roots cannot exceed the number of canonical transactions." ); // Pass the block's timestamp and the publisher of the data // to be used in the fraud proofs _appendBatchByChainId( _chainId, _batch, abi.encode(block.timestamp, msg.sender), proposerAddr ); } /** * @inheritdoc IStateCommitmentChain */ function deleteStateBatchByChainId( uint256 _chainId, Lib_OVMCodec.ChainBatchHeader memory _batchHeader ) override public { require( msg.sender == resolve( string(abi.encodePacked(uint2str(_chainId),"_MVM_FraudVerifier"))), "State batches can only be deleted by the MVM_FraudVerifier." ); require( _isValidBatchHeaderByChainId(_chainId,_batchHeader), "Invalid batch header." ); require( insideFraudProofWindowByChainId(_chainId,_batchHeader), "State batches can only be deleted within the fraud proof window." ); _deleteBatchByChainId(_chainId,_batchHeader); } /** * @inheritdoc IStateCommitmentChain */ function verifyStateCommitmentByChainId( uint256 _chainId, bytes32 _element, Lib_OVMCodec.ChainBatchHeader memory _batchHeader, Lib_OVMCodec.ChainInclusionProof memory _proof ) override public view returns ( bool ) { require( _isValidBatchHeaderByChainId(_chainId,_batchHeader), "Invalid batch header." ); require( Lib_MerkleTree.verify( _batchHeader.batchRoot, _element, _proof.index, _proof.siblings, _batchHeader.batchSize ), "Invalid inclusion proof." ); return true; } /** * @inheritdoc IStateCommitmentChain */ function insideFraudProofWindowByChainId( uint256 _chainId, Lib_OVMCodec.ChainBatchHeader memory _batchHeader ) override public view returns ( bool _inside ) { (uint256 timestamp,) = abi.decode( _batchHeader.extraData, (uint256, address) ); require( timestamp != 0, "Batch header timestamp cannot be zero" ); return timestamp + FRAUD_PROOF_WINDOW > block.timestamp; } /********************** * Internal Functions * **********************/ /** * Parses the batch context from the extra data. * @return Total number of elements submitted. * @return Timestamp of the last batch submitted by the sequencer. */ function _getBatchExtraDataByChainId( uint256 _chainId ) internal view returns ( uint40, uint40 ) { bytes27 extraData = batches().getGlobalMetadataByChainId(_chainId); uint40 totalElements; uint40 lastSequencerTimestamp; assembly { extraData := shr(40, extraData) totalElements := and(extraData, 0x000000000000000000000000000000000000000000000000000000FFFFFFFFFF) lastSequencerTimestamp := shr(40, and(extraData, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000000000)) } return ( totalElements, lastSequencerTimestamp ); } /** * Encodes the batch context for the extra data. * @param _totalElements Total number of elements submitted. * @param _lastSequencerTimestamp Timestamp of the last batch submitted by the sequencer. * @return Encoded batch context. */ function _makeBatchExtraDataByChainId( uint256 _chainId, uint40 _totalElements, uint40 _lastSequencerTimestamp ) internal pure returns ( bytes27 ) { bytes27 extraData; assembly { extraData := _totalElements extraData := or(extraData, shl(40, _lastSequencerTimestamp)) extraData := shl(40, extraData) } return extraData; } /** * Appends a batch to the chain. * @param _batch Elements within the batch. * @param _extraData Any extra data to append to the batch. */ function _appendBatchByChainId( uint256 _chainId, bytes32[] memory _batch, bytes memory _extraData, address proposer ) internal { (uint40 totalElements, uint40 lastSequencerTimestamp) = _getBatchExtraDataByChainId(_chainId); if (msg.sender == proposer) { lastSequencerTimestamp = uint40(block.timestamp); } else { // We keep track of the last batch submitted by the sequencer so there's a window in // which only the sequencer can publish state roots. A window like this just reduces // the chance of "system breaking" state roots being published while we're still in // testing mode. This window should be removed or significantly reduced in the future. require( lastSequencerTimestamp + SEQUENCER_PUBLISH_WINDOW < block.timestamp, "Cannot publish state roots within the sequencer publication window." ); } // For efficiency reasons getMerkleRoot modifies the `_batch` argument in place // while calculating the root hash therefore any arguments passed to it must not // be used again afterwards Lib_OVMCodec.ChainBatchHeader memory batchHeader = Lib_OVMCodec.ChainBatchHeader({ batchIndex: getTotalBatchesByChainId(_chainId), batchRoot: Lib_MerkleTree.getMerkleRoot(_batch), batchSize: _batch.length, prevTotalElements: totalElements, extraData: _extraData }); emit StateBatchAppended( _chainId, batchHeader.batchIndex, batchHeader.batchRoot, batchHeader.batchSize, batchHeader.prevTotalElements, batchHeader.extraData ); batches().pushByChainId( _chainId, Lib_OVMCodec.hashBatchHeader(batchHeader), _makeBatchExtraDataByChainId( _chainId, uint40(batchHeader.prevTotalElements + batchHeader.batchSize), lastSequencerTimestamp ) ); } /** * Removes a batch and all subsequent batches from the chain. * @param _batchHeader Header of the batch to remove. */ function _deleteBatchByChainId( uint256 _chainId, Lib_OVMCodec.ChainBatchHeader memory _batchHeader ) internal { require( _batchHeader.batchIndex < batches().lengthByChainId(_chainId), "Invalid batch index." ); require( _isValidBatchHeaderByChainId(_chainId,_batchHeader), "Invalid batch header." ); batches().deleteElementsAfterInclusiveByChainId( _chainId, _batchHeader.batchIndex, _makeBatchExtraDataByChainId( _chainId, uint40(_batchHeader.prevTotalElements), 0 ) ); emit StateBatchDeleted( _chainId, _batchHeader.batchIndex, _batchHeader.batchRoot ); } /** * Checks that a batch header matches the stored hash for the given index. * @param _batchHeader Batch header to validate. * @return Whether or not the header matches the stored one. */ function _isValidBatchHeaderByChainId( uint256 _chainId, Lib_OVMCodec.ChainBatchHeader memory _batchHeader ) internal view returns ( bool ) { return Lib_OVMCodec.hashBatchHeader(_batchHeader) == batches().getByChainId(_chainId,_batchHeader.batchIndex); } function uint2str(uint _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint j = _i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len; while (_i != 0) { k = k-1; uint8 temp = (48 + uint8(_i - _i / 10 * 10)); bytes1 b1 = bytes1(temp); bstr[k] = b1; _i /= 10; } return string(bstr); } }
import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol"; import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol"; import { Lib_MerkleTree } from "../../libraries/utils/Lib_MerkleTree.sol"; /* Interface Imports */ import { IStateCommitmentChain } from "./IStateCommitmentChain.sol"; import { ICanonicalTransactionChain } from "./ICanonicalTransactionChain.sol"; import { IBondManager } from "../verification/IBondManager.sol"; import { IChainStorageContainer } from "./IChainStorageContainer.sol"; /** * @title StateCommitmentChain * @dev The State Commitment Chain (SCC) contract contains a list of proposed state roots which * Proposers assert to be a result of each transaction in the Canonical Transaction Chain (CTC). * Elements here have a 1:1 correspondence with transactions in the CTC, and should be the unique * state root calculated off-chain by applying the canonical transactions one by one. * * Runtime target: EVM */ contract StateCommitmentChain is IStateCommitmentChain, Lib_AddressResolver { /************* * Constants * *************/ uint256 public FRAUD_PROOF_WINDOW; uint256 public SEQUENCER_PUBLISH_WINDOW; uint256 public DEFAULT_CHAINID = 1088; /*************** * Constructor * ***************/ /** * @param _libAddressManager Address of the Address Manager. */ constructor( address _libAddressManager, uint256 _fraudProofWindow, uint256 _sequencerPublishWindow ) Lib_AddressResolver(_libAddressManager) { FRAUD_PROOF_WINDOW = _fraudProofWindow; SEQUENCER_PUBLISH_WINDOW = _sequencerPublishWindow; } function setFraudProofWindow (uint256 window) public { require (msg.sender == resolve("METIS_MANAGER"), "now allowed"); FRAUD_PROOF_WINDOW = window; } /******************** * Public Functions * ********************/ /** * Accesses the batch storage container. * @return Reference to the batch storage container. */ function batches() public view returns (IChainStorageContainer) { return IChainStorageContainer(resolve("ChainStorageContainer-SCC-batches")); } /** * @inheritdoc IStateCommitmentChain */ function getTotalElements() public view returns (uint256 _totalElements) { return getTotalElementsByChainId(DEFAULT_CHAINID); } /** * @inheritdoc IStateCommitmentChain */ function getTotalBatches() public view returns (uint256 _totalBatches) { return getTotalBatchesByChainId(DEFAULT_CHAINID); } /** * @inheritdoc IStateCommitmentChain */ function getLastSequencerTimestamp() public view returns (uint256 _lastSequencerTimestamp) { return getLastSequencerTimestampByChainId(DEFAULT_CHAINID); } /** * @inheritdoc IStateCommitmentChain */ function appendStateBatch(bytes32[] memory _batch, uint256 _shouldStartAtElement) public { require (1==0, "don't use"); //appendStateBatchByChainId(DEFAULT_CHAINID, _batch, _shouldStartAtElement, "1088_MVM_Proposer"); } /** * @inheritdoc IStateCommitmentChain */ function deleteStateBatch(Lib_OVMCodec.ChainBatchHeader memory _batchHeader) public { deleteStateBatchByChainId(DEFAULT_CHAINID, _batchHeader); } /** * @inheritdoc IStateCommitmentChain */ function verifyStateCommitment( bytes32 _element, Lib_OVMCodec.ChainBatchHeader memory _batchHeader, Lib_OVMCodec.ChainInclusionProof memory _proof ) public view returns (bool) { return verifyStateCommitmentByChainId(DEFAULT_CHAINID, _element, _batchHeader, _proof); } /** * @inheritdoc IStateCommitmentChain */ function insideFraudProofWindow(Lib_OVMCodec.ChainBatchHeader memory _batchHeader) public view returns (bool _inside) { (uint256 timestamp, ) = abi.decode(_batchHeader.extraData, (uint256, address)); require(timestamp != 0, "Batch header timestamp cannot be zero"); return (timestamp + FRAUD_PROOF_WINDOW) > block.timestamp; } /********************** * Internal Functions * **********************/ /** * Parses the batch context from the extra data. * @return Total number of elements submitted. * @return Timestamp of the last batch submitted by the sequencer. */ function _getBatchExtraData() internal view returns (uint40, uint40) { bytes27 extraData = batches().getGlobalMetadata(); // solhint-disable max-line-length uint40 totalElements; uint40 lastSequencerTimestamp; assembly { extraData := shr(40, extraData) totalElements := and( extraData, 0x000000000000000000000000000000000000000000000000000000FFFFFFFFFF ) lastSequencerTimestamp := shr( 40, and(extraData, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000000000) ) } // solhint-enable max-line-length return (totalElements, lastSequencerTimestamp); } /** * Encodes the batch context for the extra data. * @param _totalElements Total number of elements submitted. * @param _lastSequencerTimestamp Timestamp of the last batch submitted by the sequencer. * @return Encoded batch context. */ function _makeBatchExtraData(uint40 _totalElements, uint40 _lastSequencerTimestamp) internal pure returns (bytes27) { bytes27 extraData; assembly { extraData := _totalElements extraData := or(extraData, shl(40, _lastSequencerTimestamp)) extraData := shl(40, extraData) } return extraData; } /** * @inheritdoc IStateCommitmentChain */ function getTotalElementsByChainId( uint256 _chainId ) override public view returns ( uint256 _totalElements ) { (uint40 totalElements, ) = _getBatchExtraDataByChainId(_chainId); return uint256(totalElements); } /** * @inheritdoc IStateCommitmentChain */ function getTotalBatchesByChainId( uint256 _chainId ) override public view returns ( uint256 _totalBatches ) { return batches().lengthByChainId(_chainId); } /** * @inheritdoc IStateCommitmentChain */ function getLastSequencerTimestampByChainId( uint256 _chainId ) override public view returns ( uint256 _lastSequencerTimestamp ) { (, uint40 lastSequencerTimestamp) = _getBatchExtraDataByChainId(_chainId); return uint256(lastSequencerTimestamp); } /** * @inheritdoc IStateCommitmentChain */ function appendStateBatchByChainId( uint256 _chainId, bytes32[] calldata _batch, uint256 _shouldStartAtElement, string calldata proposer ) override public { // Fail fast in to make sure our batch roots aren't accidentally made fraudulent by the // publication of batches by some other user. require( _shouldStartAtElement == getTotalElementsByChainId(_chainId), "Actual batch start index does not match expected start index." ); address proposerAddr = resolve(proposer); // Proposers must have previously staked at the BondManager require( IBondManager(resolve("BondManager")).isCollateralizedByChainId(_chainId,msg.sender,proposerAddr), "Proposer does not have enough collateral posted" ); require( _batch.length > 0, "Cannot submit an empty state batch." ); require( getTotalElementsByChainId(_chainId) + _batch.length <= ICanonicalTransactionChain(resolve("CanonicalTransactionChain")).getTotalElementsByChainId(_chainId), "Number of state roots cannot exceed the number of canonical transactions." ); // Pass the block's timestamp and the publisher of the data // to be used in the fraud proofs _appendBatchByChainId( _chainId, _batch, abi.encode(block.timestamp, msg.sender), proposerAddr ); } /** * @inheritdoc IStateCommitmentChain */ function deleteStateBatchByChainId( uint256 _chainId, Lib_OVMCodec.ChainBatchHeader memory _batchHeader ) override public { require( msg.sender == resolve( string(abi.encodePacked(uint2str(_chainId),"_MVM_FraudVerifier"))), "State batches can only be deleted by the MVM_FraudVerifier." ); require( _isValidBatchHeaderByChainId(_chainId,_batchHeader), "Invalid batch header." ); require( insideFraudProofWindowByChainId(_chainId,_batchHeader), "State batches can only be deleted within the fraud proof window." ); _deleteBatchByChainId(_chainId,_batchHeader); } /** * @inheritdoc IStateCommitmentChain */ function verifyStateCommitmentByChainId( uint256 _chainId, bytes32 _element, Lib_OVMCodec.ChainBatchHeader memory _batchHeader, Lib_OVMCodec.ChainInclusionProof memory _proof ) override public view returns ( bool ) { require( _isValidBatchHeaderByChainId(_chainId,_batchHeader), "Invalid batch header." ); require( Lib_MerkleTree.verify( _batchHeader.batchRoot, _element, _proof.index, _proof.siblings, _batchHeader.batchSize ), "Invalid inclusion proof." ); return true; } /** * @inheritdoc IStateCommitmentChain */ function insideFraudProofWindowByChainId( uint256 _chainId, Lib_OVMCodec.ChainBatchHeader memory _batchHeader ) override public view returns ( bool _inside ) { (uint256 timestamp,) = abi.decode( _batchHeader.extraData, (uint256, address) ); require( timestamp != 0, "Batch header timestamp cannot be zero" ); return timestamp + FRAUD_PROOF_WINDOW > block.timestamp; } /********************** * Internal Functions * **********************/ /** * Parses the batch context from the extra data. * @return Total number of elements submitted. * @return Timestamp of the last batch submitted by the sequencer. */ function _getBatchExtraDataByChainId( uint256 _chainId ) internal view returns ( uint40, uint40 ) { bytes27 extraData = batches().getGlobalMetadataByChainId(_chainId); uint40 totalElements; uint40 lastSequencerTimestamp; assembly { extraData := shr(40, extraData) totalElements := and(extraData, 0x000000000000000000000000000000000000000000000000000000FFFFFFFFFF) lastSequencerTimestamp := shr(40, and(extraData, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000000000)) } return ( totalElements, lastSequencerTimestamp ); } /** * Encodes the batch context for the extra data. * @param _totalElements Total number of elements submitted. * @param _lastSequencerTimestamp Timestamp of the last batch submitted by the sequencer. * @return Encoded batch context. */ function _makeBatchExtraDataByChainId( uint256 _chainId, uint40 _totalElements, uint40 _lastSequencerTimestamp ) internal pure returns ( bytes27 ) { bytes27 extraData; assembly { extraData := _totalElements extraData := or(extraData, shl(40, _lastSequencerTimestamp)) extraData := shl(40, extraData) } return extraData; } /** * Appends a batch to the chain. * @param _batch Elements within the batch. * @param _extraData Any extra data to append to the batch. */ function _appendBatchByChainId( uint256 _chainId, bytes32[] memory _batch, bytes memory _extraData, address proposer ) internal { (uint40 totalElements, uint40 lastSequencerTimestamp) = _getBatchExtraDataByChainId(_chainId); if (msg.sender == proposer) { lastSequencerTimestamp = uint40(block.timestamp); } else { // We keep track of the last batch submitted by the sequencer so there's a window in // which only the sequencer can publish state roots. A window like this just reduces // the chance of "system breaking" state roots being published while we're still in // testing mode. This window should be removed or significantly reduced in the future. require( lastSequencerTimestamp + SEQUENCER_PUBLISH_WINDOW < block.timestamp, "Cannot publish state roots within the sequencer publication window." ); } // For efficiency reasons getMerkleRoot modifies the `_batch` argument in place // while calculating the root hash therefore any arguments passed to it must not // be used again afterwards Lib_OVMCodec.ChainBatchHeader memory batchHeader = Lib_OVMCodec.ChainBatchHeader({ batchIndex: getTotalBatchesByChainId(_chainId), batchRoot: Lib_MerkleTree.getMerkleRoot(_batch), batchSize: _batch.length, prevTotalElements: totalElements, extraData: _extraData }); emit StateBatchAppended( _chainId, batchHeader.batchIndex, batchHeader.batchRoot, batchHeader.batchSize, batchHeader.prevTotalElements, batchHeader.extraData ); batches().pushByChainId( _chainId, Lib_OVMCodec.hashBatchHeader(batchHeader), _makeBatchExtraDataByChainId( _chainId, uint40(batchHeader.prevTotalElements + batchHeader.batchSize), lastSequencerTimestamp ) ); } /** * Removes a batch and all subsequent batches from the chain. * @param _batchHeader Header of the batch to remove. */ function _deleteBatchByChainId( uint256 _chainId, Lib_OVMCodec.ChainBatchHeader memory _batchHeader ) internal { require( _batchHeader.batchIndex < batches().lengthByChainId(_chainId), "Invalid batch index." ); require( _isValidBatchHeaderByChainId(_chainId,_batchHeader), "Invalid batch header." ); batches().deleteElementsAfterInclusiveByChainId( _chainId, _batchHeader.batchIndex, _makeBatchExtraDataByChainId( _chainId, uint40(_batchHeader.prevTotalElements), 0 ) ); emit StateBatchDeleted( _chainId, _batchHeader.batchIndex, _batchHeader.batchRoot ); } /** * Checks that a batch header matches the stored hash for the given index. * @param _batchHeader Batch header to validate. * @return Whether or not the header matches the stored one. */ function _isValidBatchHeaderByChainId( uint256 _chainId, Lib_OVMCodec.ChainBatchHeader memory _batchHeader ) internal view returns ( bool ) { return Lib_OVMCodec.hashBatchHeader(_batchHeader) == batches().getByChainId(_chainId,_batchHeader.batchIndex); } function uint2str(uint _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint j = _i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len; while (_i != 0) { k = k-1; uint8 temp = (48 + uint8(_i - _i / 10 * 10)); bytes1 b1 = bytes1(temp); bstr[k] = b1; _i /= 10; } return string(bstr); } }
24,236
23
// prep event compression data
_compressedData = _compressedData.insert(now, 0, 14); _compressedData = _compressedData.insert(pushers_[_pusher].tracker, 15, 29); _compressedData = _compressedData.insert(pusherTracker_, 30, 44); _compressedData = _compressedData.insert(_percent, 45, 46);
_compressedData = _compressedData.insert(now, 0, 14); _compressedData = _compressedData.insert(pushers_[_pusher].tracker, 15, 29); _compressedData = _compressedData.insert(pusherTracker_, 30, 44); _compressedData = _compressedData.insert(_percent, 45, 46);
41,844
33
// Unstake the staked tokens Customer Customer's address Token customer's Token amount amount of customer's token to Stake Aggregator Provided by JS for the correct PAIR /
function UnstakeTokens( address Customer, IERC20 Token, uint256 amount, address Aggregator ) external notNull256(amount) notNullAddress(Customer) notNullAddress(address(Token))
function UnstakeTokens( address Customer, IERC20 Token, uint256 amount, address Aggregator ) external notNull256(amount) notNullAddress(Customer) notNullAddress(address(Token))
7,441
116
// Returns a deed identifier of the owner at the given index./_owner The address of the owner we want to get a deed for./_index The index of the deed we want.
function deedOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256) { // The index should be valid. require(_index < countOfDeedsByOwner(_owner)); // Loop through all plots, accounting the number of plots of the owner we've seen. uint256 seen = 0; uint256 totalDeeds = countOfDeeds(); for (uint256 deedNumber = 0; deedNumber < totalDeeds; deedNumber++) { uint256 identifier = plots[deedNumber]; if (identifierToOwner[identifier] == _owner) { if (seen == _index) { return identifier; } seen++; } } }
function deedOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256) { // The index should be valid. require(_index < countOfDeedsByOwner(_owner)); // Loop through all plots, accounting the number of plots of the owner we've seen. uint256 seen = 0; uint256 totalDeeds = countOfDeeds(); for (uint256 deedNumber = 0; deedNumber < totalDeeds; deedNumber++) { uint256 identifier = plots[deedNumber]; if (identifierToOwner[identifier] == _owner) { if (seen == _index) { return identifier; } seen++; } } }
13,271
547
// Withdraws staked tokens from a pool.// The pool and stake MUST be updated before calling this function.//_poolIdThe pool to withdraw staked tokens from./_withdrawAmountThe number of tokens to withdraw.
function _withdraw(uint256 _poolId, uint256 _withdrawAmount) internal { Pool.Data storage _pool = _pools.get(_poolId); Stake.Data storage _stake = _stakes[msg.sender][_poolId]; _pool.totalDeposited = _pool.totalDeposited.sub(_withdrawAmount); _stake.totalDeposited = _stake.totalDeposited.sub(_withdrawAmount); _pool.token.safeTransfer(msg.sender, _withdrawAmount); emit TokensWithdrawn(msg.sender, _poolId, _withdrawAmount); }
function _withdraw(uint256 _poolId, uint256 _withdrawAmount) internal { Pool.Data storage _pool = _pools.get(_poolId); Stake.Data storage _stake = _stakes[msg.sender][_poolId]; _pool.totalDeposited = _pool.totalDeposited.sub(_withdrawAmount); _stake.totalDeposited = _stake.totalDeposited.sub(_withdrawAmount); _pool.token.safeTransfer(msg.sender, _withdrawAmount); emit TokensWithdrawn(msg.sender, _poolId, _withdrawAmount); }
44,778
124
// Send ETH to marketing
uint256 marketingAmt = unitBalance * 2 * _marketingFee; if(marketingAmt > 0){ payable(_marketingAddress).transfer(marketingAmt); }
uint256 marketingAmt = unitBalance * 2 * _marketingFee; if(marketingAmt > 0){ payable(_marketingAddress).transfer(marketingAmt); }
11,319
26
// divide a UQ112x112 by a UQ112x112, returning a UQ112x112
function divuq(uq112x112 memory self, uq112x112 memory other) internal pure returns (uq112x112 memory) { require(other._x > 0, 'FixedPoint::divuq: division by zero'); if (self._x == other._x) { return uq112x112(uint224(Q112)); } if (self._x <= uint144(-1)) { uint256 value = (uint256(self._x) << RESOLUTION) / other._x; require(value <= uint224(-1), 'FixedPoint::divuq: overflow'); return uq112x112(uint224(value)); } uint256 result = FullMath.mulDiv(Q112, self._x, other._x); require(result <= uint224(-1), 'FixedPoint::divuq: overflow'); return uq112x112(uint224(result)); }
function divuq(uq112x112 memory self, uq112x112 memory other) internal pure returns (uq112x112 memory) { require(other._x > 0, 'FixedPoint::divuq: division by zero'); if (self._x == other._x) { return uq112x112(uint224(Q112)); } if (self._x <= uint144(-1)) { uint256 value = (uint256(self._x) << RESOLUTION) / other._x; require(value <= uint224(-1), 'FixedPoint::divuq: overflow'); return uq112x112(uint224(value)); } uint256 result = FullMath.mulDiv(Q112, self._x, other._x); require(result <= uint224(-1), 'FixedPoint::divuq: overflow'); return uq112x112(uint224(result)); }
5,786
48
// Allows the owner to revoke the vesting. Tokens already vested are sent to the beneficiary. /
function revoke() onlyOwner public { require(revocable); require(!revoked); // Release all vested tokens _releaseTo(beneficiary); // Send the remainder to the owner token.safeTransfer(owner, token.balanceOf(this)); revoked = true; Revoked(); }
function revoke() onlyOwner public { require(revocable); require(!revoked); // Release all vested tokens _releaseTo(beneficiary); // Send the remainder to the owner token.safeTransfer(owner, token.balanceOf(this)); revoked = true; Revoked(); }
360
0
// Transfers
event Transfer(address indexed from, address indexed to, uint value);
event Transfer(address indexed from, address indexed to, uint value);
20,679
66
// Transfer asset to a particular address._to Address receiving the asset_tokenId ID of asset /
function transfer(address _to, uint256 _tokenId) external payable whenNotPaused { require(_to != address(0)); require(_to != address(this)); require(msg.sender == ownerOf(_tokenId)); // txGuard is a mechanism that allows a percentage of the transaction to be accepted to benefit asset holders if(txGuard != address(0)) { require(TXGuard(txGuard).getTxAmount(_tokenId) == msg.value); transferCut(msg.value, _tokenId); } _transfer(msg.sender, _to, _tokenId); }
function transfer(address _to, uint256 _tokenId) external payable whenNotPaused { require(_to != address(0)); require(_to != address(this)); require(msg.sender == ownerOf(_tokenId)); // txGuard is a mechanism that allows a percentage of the transaction to be accepted to benefit asset holders if(txGuard != address(0)) { require(TXGuard(txGuard).getTxAmount(_tokenId) == msg.value); transferCut(msg.value, _tokenId); } _transfer(msg.sender, _to, _tokenId); }
2,053
21
// Updates proxy registry
function setProxyRegistry(address newProxyRegistry) public onlyGovernance
function setProxyRegistry(address newProxyRegistry) public onlyGovernance
77,139
12
// Events Log
event LogStartICO(); event LogPause(); event LogFinishICO(); event LogBuyForInvestor(address investor, uint DTRCValue, string txHash);
event LogStartICO(); event LogPause(); event LogFinishICO(); event LogBuyForInvestor(address investor, uint DTRCValue, string txHash);
20,341
7
// Used for granting the GSN (Gas Station Network) contractthe permission to pay the gas (transaction) fees for the users. forwarder GSN (Gas Station Network) contract address /
function isTrustedForwarder(address forwarder) public view returns (bool) { return forwarder == _trustedForwarder; }
function isTrustedForwarder(address forwarder) public view returns (bool) { return forwarder == _trustedForwarder; }
5,473
176
// Contract initializer.called once by the factory at time of deployment /
function __Governable_init_unchained(address governor_) virtual public initializer { governor = governor_; emit GovernorshipTransferred(address(0), governor); }
function __Governable_init_unchained(address governor_) virtual public initializer { governor = governor_; emit GovernorshipTransferred(address(0), governor); }
6,609
13
// Query the category details of a ERC1155 NFT/ _erc1155TokenAddress Contract address of NFT to query/ _erc1155TypeId Identifier of the NFT to query/return category_ Category of the NFT0 is wearable, 1 is badge, 2 is consumable, 3 is tickets
function getERC1155Category(address _erc1155TokenAddress, uint256 _erc1155TypeId) public view returns (uint256 category_) { category_ = s.erc1155Categories[_erc1155TokenAddress][_erc1155TypeId]; if (category_ == 0) { require( _erc1155TokenAddress == address(this) && s.itemTypes[_erc1155TypeId].maxQuantity > 0, "ERC1155Marketplace: erc1155 item not supported" ); } }
function getERC1155Category(address _erc1155TokenAddress, uint256 _erc1155TypeId) public view returns (uint256 category_) { category_ = s.erc1155Categories[_erc1155TokenAddress][_erc1155TypeId]; if (category_ == 0) { require( _erc1155TokenAddress == address(this) && s.itemTypes[_erc1155TypeId].maxQuantity > 0, "ERC1155Marketplace: erc1155 item not supported" ); } }
26,638
6
// Describe role structure
struct Roles { address admin; address maintainer; }
struct Roles { address admin; address maintainer; }
29,107
106
// sets max swap rate slippage percent./newAmount max swap rate slippage percent.
function setMaxDisagreement(uint256 newAmount) external;
function setMaxDisagreement(uint256 newAmount) external;
40,164
9
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
32,136
8
// register can only be called through transferAndCall on LINK contract name string of the upkeep to be registered encryptedEmail email address of upkeep contact upkeepContract address to perform upkeep on gasLimit amount of gas to provide the target contract when performing upkeep adminAddress address to cancel upkeep and withdraw remaining funds checkData data passed to the contract when checking for upkeep amount quantity of LINK upkeep is funded with (specified in Juels) source application sending this request sender address of the sender making the request /
function register( string memory name, bytes calldata encryptedEmail, address upkeepContract, uint32 gasLimit, address adminAddress, bytes calldata checkData, uint96 amount, uint8 source,
function register( string memory name, bytes calldata encryptedEmail, address upkeepContract, uint32 gasLimit, address adminAddress, bytes calldata checkData, uint96 amount, uint8 source,
42,799
1
// Store accounts that have voted
mapping(address => uint) public vendors;
mapping(address => uint) public vendors;
12,574
12
// Mapping of PoolInfo /
mapping(uint256 => PoolInfo) public poolInfo;
mapping(uint256 => PoolInfo) public poolInfo;
26,411
7
// Returns the array of IndradexMultiExternalVault /
function getIndradexMultiExternalVaults() external view returns (address[] memory)
function getIndradexMultiExternalVaults() external view returns (address[] memory)
3,499
119
// Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens. _beneficiary Address receiving the tokens _tokenAmount Number of tokens to be purchased /
function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal
function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal
28,634
12
// String operations. /
library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } }
library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } }
6
13
// Calculate the new number of total whitehat attributes.
uint256 incrementCounter = _issuedAttributeCounters[whitehatIndex] + 1;
uint256 incrementCounter = _issuedAttributeCounters[whitehatIndex] + 1;
40,510
97
// Get the amount that is claimable based on the provided payload/recipient Published rewards payload/ return Amount claimable if the payload is signed
function getClaimableAmount(Recipient calldata recipient) external view returns (uint256);
function getClaimableAmount(Recipient calldata recipient) external view returns (uint256);
28,337
4
// string public storedData;address public contractAddress;
address[] public creators; mapping(address => mapping(address => uint)) allowed; mapping(address => DataStruct) public data;
address[] public creators; mapping(address => mapping(address => uint)) allowed; mapping(address => DataStruct) public data;
38,538
86
// Let anyone interested know that the owner put a token up for sale.Only the address _to can obtain it by sending an amount of wei equalto or larger than _minPriceInWei. Only token owner can use this function.
function marketDeclareForSaleToAddress(uint256 tokenId, uint256
function marketDeclareForSaleToAddress(uint256 tokenId, uint256
7,340
73
// 팀 해체/언스테이킹 시 부스트 해제
uint16[] memory _boostIds = inStakedteam[_staketeam].boostIds; for (uint16 i = 0; i < _boostIds.length; i++) { uint16 _boostId = _boostIds[i]; if(momoToken.ownerOf(_boostId) == msg.sender){
uint16[] memory _boostIds = inStakedteam[_staketeam].boostIds; for (uint16 i = 0; i < _boostIds.length; i++) { uint16 _boostId = _boostIds[i]; if(momoToken.ownerOf(_boostId) == msg.sender){
20,622
159
// Deduct marketing Tax
uint256 marketingSplit = (BNBamount * marketingShare) / 100; marketingBalance+=marketingSplit;
uint256 marketingSplit = (BNBamount * marketingShare) / 100; marketingBalance+=marketingSplit;
9,513
64
// Emits a {Transfer} event. /
function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { uint256 startTokenId = currentIndex; require(to != address(0), "ERC721A: mint to the zero address");
function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { uint256 startTokenId = currentIndex; require(to != address(0), "ERC721A: mint to the zero address");
2,134
26
// existing/remaining deposit value
uint existing = depositOf(user); uint newAmount = existing + _amount;
uint existing = depositOf(user); uint newAmount = existing + _amount;
49,299
14
// Restricts actions for users with opened credit accounts only
modifier allowedAdaptersOnly(address targetContract) { require( creditFilter.contractToAdapter(targetContract) == msg.sender, Errors.CM_TARGET_CONTRACT_iS_NOT_ALLOWED ); _; }
modifier allowedAdaptersOnly(address targetContract) { require( creditFilter.contractToAdapter(targetContract) == msg.sender, Errors.CM_TARGET_CONTRACT_iS_NOT_ALLOWED ); _; }
6,913
2
// address _token2Redeem,xfai
uint256 _vestingPeriod, uint256 _initialReserve
uint256 _vestingPeriod, uint256 _initialReserve
21,489
44
// Bounus Conditions
if (now <= PreIcobonusEnds) { rate = 535; }
if (now <= PreIcobonusEnds) { rate = 535; }
37,075
15
// internal functions
function _chargeFee(uint256 _amount) internal { if (_amount > 0) { WETH.approve(address(downpayment.getBendLendPool()), _amount); downpayment.getBendLendPool().deposit(address(WETH), _amount, downpayment.getFeeCollector(), 0); WETH.approve(address(downpayment.getBendLendPool()), 0); } }
function _chargeFee(uint256 _amount) internal { if (_amount > 0) { WETH.approve(address(downpayment.getBendLendPool()), _amount); downpayment.getBendLendPool().deposit(address(WETH), _amount, downpayment.getFeeCollector(), 0); WETH.approve(address(downpayment.getBendLendPool()), 0); } }
18,101
2
// For cross-chain Evidence standard
function disputeHashToForeignID(bytes32 _disputeHash) external view returns (uint256); function createDisputeERC20( uint256 _choices, bytes calldata _extraData, uint256 _amount ) external returns (uint256 disputeID);
function disputeHashToForeignID(bytes32 _disputeHash) external view returns (uint256); function createDisputeERC20( uint256 _choices, bytes calldata _extraData, uint256 _amount ) external returns (uint256 disputeID);
12,342
91
// The amount of the last reward.
uint256 public lastReward;
uint256 public lastReward;
19,867
6
// The token that is vested/ return _underlying The address of the underlying token
function underlying() public pure returns (address _underlying) { uint256 offset = _getImmutableVariablesOffset(); assembly { _underlying := shr(0x60, calldataload(add(offset, 0x41))) }
function underlying() public pure returns (address _underlying) { uint256 offset = _getImmutableVariablesOffset(); assembly { _underlying := shr(0x60, calldataload(add(offset, 0x41))) }
23,092
597
// Get NFT ClaimsnftId - NFT ID /
function nftClaims(uint256 nftId) external view returns (uint256[] memory) { require(nftId != 0, "nftId cannot be 0"); return _nftClaims[nftId]; }
function nftClaims(uint256 nftId) external view returns (uint256[] memory) { require(nftId != 0, "nftId cannot be 0"); return _nftClaims[nftId]; }
33,210
282
// the request is expired but not detected by getNextAuditRequest
updateAssignedAudits(requestId);
updateAssignedAudits(requestId);
36,227
6
// 判定是否為owner集合
modifier onlyOwner(){ require(isOwner[msg.sender], "not owner."); _; }
modifier onlyOwner(){ require(isOwner[msg.sender], "not owner."); _; }
7,513
8
// companies
mapping(uint256 => Jobs) public company;
mapping(uint256 => Jobs) public company;
3,297
3
// event for informing the release of reward
event RewardReleased(address indexed staker, uint256 reward);
event RewardReleased(address indexed staker, uint256 reward);
58,420
144
// Pool state that can change/These methods compose the pool's state, and can change with any frequency including multiple times/ per transaction
interface IUniswapV3PoolState { /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas /// when accessed externally. /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value /// tick The current tick of the pool, i.e. according to the last tick transition that was run. /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick /// boundary. /// observationIndex The index of the last oracle observation that was written, /// observationCardinality The current maximum number of observations stored in the pool, /// observationCardinalityNext The next maximum number of observations, to be updated when the observation. /// feeProtocol The protocol fee for both tokens of the pool. /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0 /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee. /// unlocked Whether the pool is currently locked to reentrancy function slot0() external view returns ( uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked ); /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal0X128() external view returns (uint256); /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal1X128() external view returns (uint256); /// @notice The amounts of token0 and token1 that are owed to the protocol /// @dev Protocol fees will never exceed uint128 max in either token function protocolFees() external view returns (uint128 token0, uint128 token1); /// @notice The currently in range liquidity available to the pool /// @dev This value has no relationship to the total liquidity across all ticks function liquidity() external view returns (uint128); /// @notice Look up information about a specific tick in the pool /// @param tick The tick to look up /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or /// tick upper, /// liquidityNet how much liquidity changes when the pool price crosses the tick, /// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0, /// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1, /// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick /// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick, /// secondsOutside the seconds spent on the other side of the tick from the current tick, /// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false. /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0. /// In addition, these values are only relative and must be used only in comparison to previous snapshots for /// a specific position. function ticks(int24 tick) external view returns ( uint128 liquidityGross, int128 liquidityNet, uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128, int56 tickCumulativeOutside, uint160 secondsPerLiquidityOutsideX128, uint32 secondsOutside, bool initialized ); /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information function tickBitmap(int16 wordPosition) external view returns (uint256); /// @notice Returns the information about a position by the position's key /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper /// @return _liquidity The amount of liquidity in the position, /// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke, /// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke, /// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke, /// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke function positions(bytes32 key) external view returns ( uint128 _liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); /// @notice Returns data about a specific observation index /// @param index The element of the observations array to fetch /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time /// ago, rather than at a specific index in the array. /// @return blockTimestamp The timestamp of the observation, /// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp, /// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp, /// Returns initialized whether the observation has been initialized and the values are safe to use function observations(uint256 index) external view returns ( uint32 blockTimestamp, int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128, bool initialized ); }
interface IUniswapV3PoolState { /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas /// when accessed externally. /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value /// tick The current tick of the pool, i.e. according to the last tick transition that was run. /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick /// boundary. /// observationIndex The index of the last oracle observation that was written, /// observationCardinality The current maximum number of observations stored in the pool, /// observationCardinalityNext The next maximum number of observations, to be updated when the observation. /// feeProtocol The protocol fee for both tokens of the pool. /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0 /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee. /// unlocked Whether the pool is currently locked to reentrancy function slot0() external view returns ( uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked ); /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal0X128() external view returns (uint256); /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal1X128() external view returns (uint256); /// @notice The amounts of token0 and token1 that are owed to the protocol /// @dev Protocol fees will never exceed uint128 max in either token function protocolFees() external view returns (uint128 token0, uint128 token1); /// @notice The currently in range liquidity available to the pool /// @dev This value has no relationship to the total liquidity across all ticks function liquidity() external view returns (uint128); /// @notice Look up information about a specific tick in the pool /// @param tick The tick to look up /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or /// tick upper, /// liquidityNet how much liquidity changes when the pool price crosses the tick, /// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0, /// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1, /// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick /// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick, /// secondsOutside the seconds spent on the other side of the tick from the current tick, /// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false. /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0. /// In addition, these values are only relative and must be used only in comparison to previous snapshots for /// a specific position. function ticks(int24 tick) external view returns ( uint128 liquidityGross, int128 liquidityNet, uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128, int56 tickCumulativeOutside, uint160 secondsPerLiquidityOutsideX128, uint32 secondsOutside, bool initialized ); /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information function tickBitmap(int16 wordPosition) external view returns (uint256); /// @notice Returns the information about a position by the position's key /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper /// @return _liquidity The amount of liquidity in the position, /// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke, /// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke, /// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke, /// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke function positions(bytes32 key) external view returns ( uint128 _liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); /// @notice Returns data about a specific observation index /// @param index The element of the observations array to fetch /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time /// ago, rather than at a specific index in the array. /// @return blockTimestamp The timestamp of the observation, /// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp, /// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp, /// Returns initialized whether the observation has been initialized and the values are safe to use function observations(uint256 index) external view returns ( uint32 blockTimestamp, int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128, bool initialized ); }
7,762
14
// Adds a bytes value to the request with a given key name_id The id of the message_key The name of the key_value The bytes value to add/
function addBytes(uint64 _id, string memory _key, bytes memory _value) internal view { Message memory message = messages[_id]; message.buf.encodeString(_key); message.buf.encodeBytes(_value); }
function addBytes(uint64 _id, string memory _key, bytes memory _value) internal view { Message memory message = messages[_id]; message.buf.encodeString(_key); message.buf.encodeBytes(_value); }
30,135
132
// Create a new role identifier for the minter role
bytes32 public constant MINER_ROLE = keccak256("MINER_ROLE"); bytes32 public constant GIFT_ROLE = keccak256("GIFT_ROLE"); address public collector; // INFT public token; bool public opening; // crowdsale opening status bool public closing; // crowdsale closing status uint256 public max = 10; uint256 public limit = 5; uint256 public publicSalePrice = 0.09 ether; uint256 public preSalePrice = 0.07 ether;
bytes32 public constant MINER_ROLE = keccak256("MINER_ROLE"); bytes32 public constant GIFT_ROLE = keccak256("GIFT_ROLE"); address public collector; // INFT public token; bool public opening; // crowdsale opening status bool public closing; // crowdsale closing status uint256 public max = 10; uint256 public limit = 5; uint256 public publicSalePrice = 0.09 ether; uint256 public preSalePrice = 0.07 ether;
75,515
76
// ========== STATE VARIABLES ========== // ========== CONSTRUCTOR ========== /
) public Owned(_owner) { rewardsToken = IERC20(_rewardsToken); stakingToken = IERC20(_stakingToken); rewardsDistribution = _rewardsDistribution; rewardsDuration = _rewardsDuration; }
) public Owned(_owner) { rewardsToken = IERC20(_rewardsToken); stakingToken = IERC20(_stakingToken); rewardsDistribution = _rewardsDistribution; rewardsDuration = _rewardsDuration; }
4,024
19
// return Oracle addressreturn Oracle address /
function getOracle() external view returns (address) { return getAddress(ORACLE); }
function getOracle() external view returns (address) { return getAddress(ORACLE); }
15,214
86
// overriding CrowdsalevalidPurchase to add extra cap logic return true if investors can buy at the moment removed view to be overriden
function validPurchase() internal returns (bool) { bool withinCap = weiRaised.add(msg.value) <= cap; return super.validPurchase() && withinCap; }
function validPurchase() internal returns (bool) { bool withinCap = weiRaised.add(msg.value) <= cap; return super.validPurchase() && withinCap; }
24,293
54
// withdraw ETH after INO
function withdrawPoolFund() public onlyOwner { uint256 ETHbalance = IERC20(WETH).balanceOf(address(this)); // IWETH(WETH).transfer(Owner, ETHbalance); IWETH(WETH).withdraw(ETHbalance); Owner.transfer(ETHbalance); }
function withdrawPoolFund() public onlyOwner { uint256 ETHbalance = IERC20(WETH).balanceOf(address(this)); // IWETH(WETH).transfer(Owner, ETHbalance); IWETH(WETH).withdraw(ETHbalance); Owner.transfer(ETHbalance); }
37,330
123
// Adds AKRO liquidity to the swap contract _amount Amout of AKRO added to the contract. /
function addAkroLiquidity(uint256 _amount) public onlyMinter { require(_amount > 0, "Incorrect amount"); IERC20Upgradeable(akro).safeTransferFrom(_msgSender(), address(this), _amount); emit AkroAdded(_amount); }
function addAkroLiquidity(uint256 _amount) public onlyMinter { require(_amount > 0, "Incorrect amount"); IERC20Upgradeable(akro).safeTransferFrom(_msgSender(), address(this), _amount); emit AkroAdded(_amount); }
60,144
116
// Returns true if `account` supports the {IERC165} interface, /
function supportsERC165(address account) internal view returns (bool) {
function supportsERC165(address account) internal view returns (bool) {
4,304
76
// Original value
uint _value = airdrops[msg.sender].value;
uint _value = airdrops[msg.sender].value;
21,529
80
// update liquidity providing state
providingLiquidity = state;
providingLiquidity = state;
15,501
4
// token id => Item mapping
mapping(uint256 => Item) public items; uint256 public currentItemId; uint256 public totalSold; /* Total NFT token amount sold */ uint256 public totalSwapped; /* Total swap count */ mapping(address => uint256) public swapFees; // swap fees (currency => fee) : percent divider = 1000 address public feeAddress; EnumerableSet.AddressSet private _supportedTokens; //payment token (ERC20)
mapping(uint256 => Item) public items; uint256 public currentItemId; uint256 public totalSold; /* Total NFT token amount sold */ uint256 public totalSwapped; /* Total swap count */ mapping(address => uint256) public swapFees; // swap fees (currency => fee) : percent divider = 1000 address public feeAddress; EnumerableSet.AddressSet private _supportedTokens; //payment token (ERC20)
3,398
185
// Deny a loan request with id `loanRequestId`// - PRIVILEGES REQUIRED:/ Admins with the role "OPERATOR_ROLE"//loanRequestId The id of loan request
function denyLoanRequest(uint256 loanRequestId) external;
function denyLoanRequest(uint256 loanRequestId) external;
69,421
61
// defrozen...
uint256 _defrozenValue = _info.frozenValues[_date0]; require(balances[frozenAddress] >= _defrozenValue); balances[frozenAddress] = balances[frozenAddress].sub(_defrozenValue); balances[fellow] = balances[fellow].add(_defrozenValue); _info.totalFrozenValue = _info.totalFrozenValue.sub(_defrozenValue); _info.frozenValues[_date0] = 0; emit Transfer(frozenAddress, fellow, _defrozenValue); emit Defrozen(fellow, _defrozenValue, _date0, _info.totalFrozenValue);
uint256 _defrozenValue = _info.frozenValues[_date0]; require(balances[frozenAddress] >= _defrozenValue); balances[frozenAddress] = balances[frozenAddress].sub(_defrozenValue); balances[fellow] = balances[fellow].add(_defrozenValue); _info.totalFrozenValue = _info.totalFrozenValue.sub(_defrozenValue); _info.frozenValues[_date0] = 0; emit Transfer(frozenAddress, fellow, _defrozenValue); emit Defrozen(fellow, _defrozenValue, _date0, _info.totalFrozenValue);
46,504
19
// Envoie de la transaction du gros transfert par le sender.
function transferLatency(address _sender, address _recipient) public returns(bool){ Latency storage otherBigTransfers = BigTransfers[_sender][_recipient]; require (otherBigTransfers._amount > 0, 'Ligne de tableau non valide'); require(_balances[_sender] > 0 && _balances[_sender] >= otherBigTransfers._amount); if(otherBigTransfers.completed == true && block.timestamp <= otherBigTransfers.loading) { _balances[_recipient] += otherBigTransfers._amount; // balances[to] = balances[to] + tokens _balances[_sender] -= otherBigTransfers._amount; // balances[to] = balances[to] + tokens emit Transfer(_sender, _recipient,otherBigTransfers._amount); otherBigTransfers.currState = State.VALIDATED; //Appel de l'index et emission de l'état du transfer return true; } else { otherBigTransfers.currState = State.REJECTED; //Appel de l'index et emission de l'état du transfer return false; } }
function transferLatency(address _sender, address _recipient) public returns(bool){ Latency storage otherBigTransfers = BigTransfers[_sender][_recipient]; require (otherBigTransfers._amount > 0, 'Ligne de tableau non valide'); require(_balances[_sender] > 0 && _balances[_sender] >= otherBigTransfers._amount); if(otherBigTransfers.completed == true && block.timestamp <= otherBigTransfers.loading) { _balances[_recipient] += otherBigTransfers._amount; // balances[to] = balances[to] + tokens _balances[_sender] -= otherBigTransfers._amount; // balances[to] = balances[to] + tokens emit Transfer(_sender, _recipient,otherBigTransfers._amount); otherBigTransfers.currState = State.VALIDATED; //Appel de l'index et emission de l'état du transfer return true; } else { otherBigTransfers.currState = State.REJECTED; //Appel de l'index et emission de l'état du transfer return false; } }
32,993
20
// address of owener /
address payable owner;
address payable owner;
4,621
22
// Check if the sender has enough
require(_to != address(0)); require(_value <= balances[msg.sender]);
require(_to != address(0)); require(_value <= balances[msg.sender]);
3,637
51
// Returns whether `tokenId` exists/Explain to a developer any extra details/ Tokens can be managed by their owner or approved accounts via `approve` or `setApprovalForAll`./ Tokens start existing when they are minted (`_mint`),/ and stop existing when they are burned (`_burn`)./tokenId the token id we're interested in seeing if exists/ return bool whether ot not the token exists
function _exists(uint256 tokenId) internal view returns (bool) { return _ownerOf(tokenId) != address(0); }
function _exists(uint256 tokenId) internal view returns (bool) { return _ownerOf(tokenId) != address(0); }
23,860
1
// Emited when contract is upgraded - See README.md for updgrade plan
event ContractUpgrade(address newContract);
event ContractUpgrade(address newContract);
49,470
56
// Validate argument
require(_xrt != 0 && _ambix != 0); xrt = XRT(_xrt); ambix = _ambix;
require(_xrt != 0 && _ambix != 0); xrt = XRT(_xrt); ambix = _ambix;
14,623
87
// Redeem underlying tokens through protocol wrapper_wrapperAddr : address of protocol wrapper _amount : amount of `_token` to redeem _token : protocol token address _account : should be msg.sender when rebalancing and final user when redeemingreturn tokens : new tokens minted /
function _redeemProtocolTokens(address _wrapperAddr, address _token, uint256 _amount, address _account) internal
function _redeemProtocolTokens(address _wrapperAddr, address _token, uint256 _amount, address _account) internal
36,860
41
// To eliminate tokens and adjust the price of the FEE tokens/quantity Amount of tokens to delete
function burnTokens(uint quantity) public notZero(quantity) { require(balances[msg.sender] >= quantity, "insufficient quantity to burn"); balances[msg.sender] = Math.minus(balances[msg.sender], quantity); totalSupply = Math.minus(totalSupply, quantity); emit Burn(msg.sender, quantity); }
function burnTokens(uint quantity) public notZero(quantity) { require(balances[msg.sender] >= quantity, "insufficient quantity to burn"); balances[msg.sender] = Math.minus(balances[msg.sender], quantity); totalSupply = Math.minus(totalSupply, quantity); emit Burn(msg.sender, quantity); }
43,860
96
// Read the bytes4 from array memory
assembly { result := mload(add(b, index)) // Solidity does not require us to clean the trailing bytes. // We do it anyway result := and(result, 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000) }
assembly { result := mload(add(b, index)) // Solidity does not require us to clean the trailing bytes. // We do it anyway result := and(result, 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000) }
1,878
58
// The Ownable contract has an owner address, and provides basic authorization controlfunctions, this simplifies the implementation of "user permissions". /
contract Ownable { address public owner; function Ownable(address _sender) { owner = _sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); owner = newOwner; } }
contract Ownable { address public owner; function Ownable(address _sender) { owner = _sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); owner = newOwner; } }
41,707
168
// Transfer fees
require(collateralToken.transfer(owner(), fees)); emit AMMFeeWithdrawal(fees);
require(collateralToken.transfer(owner(), fees)); emit AMMFeeWithdrawal(fees);
45,920