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
76
// Divides one `Unsigned` by an unscaled uint256, reverting on overflow or division by 0. This will "floor" the quotient. a a FixedPoint numerator. b a uint256 denominator.return the quotient of `a` divided by `b`. /
function div(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.div(b)); }
function div(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.div(b)); }
7,958
1
// Fallback function returns funds to the sender
function() external payable { revert("not payable fallback"); }
function() external payable { revert("not payable fallback"); }
36,368
3
// `transferFrom` will be called with the following parameters: assetData Encoded byte array. from Address to transfer asset from. to Address to transfer asset to. amount Amount of asset to transfer. bytes4(keccak256("transferFrom(bytes,address,address,uint256)")) = 0xa85e59e4
if eq(selector, 0xa85e59e400000000000000000000000000000000000000000000000000000000) {
if eq(selector, 0xa85e59e400000000000000000000000000000000000000000000000000000000) {
33,336
56
// totalKwhを修正(prevTotalWh使用)
totalKwh = totalKwh - prevTotalWh + _totalWh;
totalKwh = totalKwh - prevTotalWh + _totalWh;
15,590
73
// Returns all allowed contracts
function allowedContracts() external view returns (address[] memory);
function allowedContracts() external view returns (address[] memory);
20,123
4
// Confirmations required to confirm semi approved superblocks
uint public superblockConfirmations;
uint public superblockConfirmations;
36,581
756
// Transfer wad amount of any type of collateral (ilk) from the cdp address to a dst address. This function has the purpose to take away collateral from the system that doesn't correspond to the cdp but was sent there wrongly.
function flux( bytes32 ilk, uint cdp, address dst, uint wad ) public cdpAllowed(cdp) { VatLike(vat).flux(ilk, urns[cdp], dst, wad); }
function flux( bytes32 ilk, uint cdp, address dst, uint wad ) public cdpAllowed(cdp) { VatLike(vat).flux(ilk, urns[cdp], dst, wad); }
78,487
99
// Withdraw reward. EMERGENCY ONLY.
function emergencyRewardWithdraw(uint256 _amount) public onlyOwner { uint256 totalBalance = rewardToken.balanceOf(address(this)); uint256 availableRewards = totalBalance.sub(totalStaked); require(_amount < availableRewards, 'not enough rewards'); rewardToken.safeTransfer(address(msg.sender), _amount); }
function emergencyRewardWithdraw(uint256 _amount) public onlyOwner { uint256 totalBalance = rewardToken.balanceOf(address(this)); uint256 availableRewards = totalBalance.sub(totalStaked); require(_amount < availableRewards, 'not enough rewards'); rewardToken.safeTransfer(address(msg.sender), _amount); }
29,280
92
// Taxes for Universe owner
if (tokenIndexToOwner[UNIVERSE_TOKEN_ID]!=address(0)) tokenIndexToOwner[UNIVERSE_TOKEN_ID].transfer(feeOnce); if (_tokenId > MAX_WORLD_INDEX) {
if (tokenIndexToOwner[UNIVERSE_TOKEN_ID]!=address(0)) tokenIndexToOwner[UNIVERSE_TOKEN_ID].transfer(feeOnce); if (_tokenId > MAX_WORLD_INDEX) {
24,541
172
// Constructor - Fill the details while deploying the contract
constructor( string memory _name, // Name of the project (can be anything) string memory _symbol, // Symbol of the project (can be anything) string memory _initNFT_URI, // URI of the metadata (ipfs://CID/) Fill this column in the same way. CID is the ID you get from IPFS string memory _inithidden_URI // URI of hidden metadata (ipfs://CID/name.json) Fill this colum with CID of hidden data from IPFS along with the filename.json
constructor( string memory _name, // Name of the project (can be anything) string memory _symbol, // Symbol of the project (can be anything) string memory _initNFT_URI, // URI of the metadata (ipfs://CID/) Fill this column in the same way. CID is the ID you get from IPFS string memory _inithidden_URI // URI of hidden metadata (ipfs://CID/name.json) Fill this colum with CID of hidden data from IPFS along with the filename.json
45,517
64
// .add(extraTheoryWithdrawRequested);
; totalWithdrawRequestedInTheory = 0;
; totalWithdrawRequestedInTheory = 0;
50,407
4
// Proxy initializer
function initialize( IDione _dione, uint256 _reimbursementFee, address _burnAddress
function initialize( IDione _dione, uint256 _reimbursementFee, address _burnAddress
14,169
1
// Getter for the keeper address. /
function keeper() public view virtual returns (address) { return _keeper; }
function keeper() public view virtual returns (address) { return _keeper; }
69,284
80
// owner : the address to check return the number of tokens controlled by owner/
function balanceOf(address owner) public view returns (uint) { return ownedTokens[owner].length; }
function balanceOf(address owner) public view returns (uint) { return ownedTokens[owner].length; }
57,443
100
// Whether `a` is greater than `b`. a a FixedPoint.Signed. b an int256.return True if `a > b`, or False. /
function isGreaterThan(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue > fromUnscaledInt(b).rawValue; }
function isGreaterThan(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue > fromUnscaledInt(b).rawValue; }
31,650
112
// Allows a referral tree to claim all the dividends./_referral Address of user that claims his dividends.
function claimAllDividends(address _referral) public { require( msg.sender == address(referralTree), "claimAllDividends: bad role" ); claimUserDividends(_referral); }
function claimAllDividends(address _referral) public { require( msg.sender == address(referralTree), "claimAllDividends: bad role" ); claimUserDividends(_referral); }
21,175
221
// Check that price update was requested/more than 1 update interval ago/NOTE: m_leeway seconds added to offset possible timestamp inaccuracy
function updateRequestExpired() public view returns (bool) { return ( (getTime() + m_leeway) >= (m_ETHPriceLastUpdateRequest + m_ETHPriceUpdateInterval) ); }
function updateRequestExpired() public view returns (bool) { return ( (getTime() + m_leeway) >= (m_ETHPriceLastUpdateRequest + m_ETHPriceUpdateInterval) ); }
40,275
195
// Deposit tokens to SafeInterest for SUSHI allocation.
function deposit(uint256 safeId, uint256 _amount) public { SafeInfo storage safe = safeInfo[safeId]; UserInfo storage user = userInfo[safeId][msg.sender]; updateSafe(safeId); if (user.amount > 0) { uint256 pending = user.amount.mul(safe.accSushiPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeSushiTransfer(msg.sender, pending); } } if(_amount > 0) { safe.token.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(safe.accSushiPerShare).div(1e12); emit Deposit(msg.sender, safeId, _amount); }
function deposit(uint256 safeId, uint256 _amount) public { SafeInfo storage safe = safeInfo[safeId]; UserInfo storage user = userInfo[safeId][msg.sender]; updateSafe(safeId); if (user.amount > 0) { uint256 pending = user.amount.mul(safe.accSushiPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeSushiTransfer(msg.sender, pending); } } if(_amount > 0) { safe.token.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(safe.accSushiPerShare).div(1e12); emit Deposit(msg.sender, safeId, _amount); }
13,376
4
// Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,non-reverting calls are assumed to be successful. Compatible with tokens that require the approval to be set to0 before setting it to a non-zero value. /
function forceApprove(IERC20 token, address spender, uint256 value) internal { bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value); if (!_callOptionalReturnBool(token, approvalCall)) { _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0)); _callOptionalReturn(token, approvalCall); } }
function forceApprove(IERC20 token, address spender, uint256 value) internal { bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value); if (!_callOptionalReturnBool(token, approvalCall)) { _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0)); _callOptionalReturn(token, approvalCall); } }
9,909
463
// Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} iscalled. NOTE: This information is only used for _display_ purposes: it inno way affects any of the arithmetic of the contract, including{IERC20-balanceOf} and {IERC20-transfer}. /
function decimals() public view virtual returns (uint8) { return _decimals; }
function decimals() public view virtual returns (uint8) { return _decimals; }
3,983
3
// manage ownership
mapping(uint => address) public polliwogIdToOwner; // polliwogId -> owner mapping(address => uint) ownerPolliwogCount; PolliwogTrait[] public polliwogTraits; // all polliwog traits
mapping(uint => address) public polliwogIdToOwner; // polliwogId -> owner mapping(address => uint) ownerPolliwogCount; PolliwogTrait[] public polliwogTraits; // all polliwog traits
25,374
33
// Return the result of subtracting y from x, throwing an exception in case of overflow. /
{ require(y <= x); return x - y; }
{ require(y <= x); return x - y; }
35,693
140
// A record of each accounts delegate
mapping (address => address) internal _delegates;
mapping (address => address) internal _delegates;
1,851
155
// Required for ERC721 safe token transfers from smart contracts./operator The address that acts on behalf of the owner/from The current owner of the NFT/tokenId The NFT to transfer/data Additional data with no specified format, sent in call to `_to`.
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external override returns (bytes4){ return IERC721ReceiverUpgradeable.onERC721Received.selector; }
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external override returns (bytes4){ return IERC721ReceiverUpgradeable.onERC721Received.selector; }
41,077
4
// Contract version
uint256 public constant version = 1; modifier onlyAllowedAdapter() { require(fundFilter.protocolAdapter() == msg.sender, Errors.NotAllowedAdapter); _; }
uint256 public constant version = 1; modifier onlyAllowedAdapter() { require(fundFilter.protocolAdapter() == msg.sender, Errors.NotAllowedAdapter); _; }
25,867
259
// Keccak gas cost is 30 + numWords6. This is a cheap way to compare. We early exit on unequal lengths, but keccak would also correctly handle this.
return lhs.length == rhs.length && keccak256(lhs) == keccak256(rhs);
return lhs.length == rhs.length && keccak256(lhs) == keccak256(rhs);
42,218
18
// This function is always restricted to hosts.
_assertIsHost(msg.sender, governanceOpts, hostIndex); return _buy( nftContract, tokenId, callTarget, callValue, callData, governanceOpts,
_assertIsHost(msg.sender, governanceOpts, hostIndex); return _buy( nftContract, tokenId, callTarget, callValue, callData, governanceOpts,
31,355
32
// Function to increment count by 1
function inc() public { count += 1; }
function inc() public { count += 1; }
15,162
6
// Handle the end of the auction Refund the difference between the first price and second price
function finalize() public creatorOnly { require(getBlockNumber() > revealTimeEndBlock, "Auction can be finalized after the reveal phase is over."); winner.transfer(winningBid - runnerUpBid + bidders[winner].depositAmount); selfdestruct(address(0)); }
function finalize() public creatorOnly { require(getBlockNumber() > revealTimeEndBlock, "Auction can be finalized after the reveal phase is over."); winner.transfer(winningBid - runnerUpBid + bidders[winner].depositAmount); selfdestruct(address(0)); }
7,842
57
// Implementation of the {IERC20} interface.that a supply mechanism has to be added in a derived contract using {_mint}.For a generic mechanism see {ERC20PresetMinterPauser}.Additionally, an {Approval} event is emitted on calls to {transferFrom}.Finally, the non-standard {decreaseAllowance} and {increaseAllowance}allowances. See {IERC20-approve}./ Initializes the contract setting the deployer as the initial owner. /
constructor () public { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), _owner); }
constructor () public { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), _owner); }
40,275
92
// Decreases internal data structure which tracks free bond perarchaeologist data the system's data struct instance archAddress the archaeologist's address to operate on amount the amount to decrease free bond by /
function decreaseFreeBond( Datas.Data storage data, address archAddress, uint256 amount
function decreaseFreeBond( Datas.Data storage data, address archAddress, uint256 amount
57,693
271
// Set maximum count to mint per once. /
function setMaxToMint(uint256 _maxValue) external onlyOwner { maxToMint = _maxValue; }
function setMaxToMint(uint256 _maxValue) external onlyOwner { maxToMint = _maxValue; }
3,406
64
// sets recipient of transfer fee only callable by owner _newBeneficiary new beneficiary /
function setBeneficiary(address _newBeneficiary) public onlyOwner { setExcludeFromFee(_newBeneficiary, true); emit BeneficiaryUpdated(beneficiary, _newBeneficiary); beneficiary = _newBeneficiary; }
function setBeneficiary(address _newBeneficiary) public onlyOwner { setExcludeFromFee(_newBeneficiary, true); emit BeneficiaryUpdated(beneficiary, _newBeneficiary); beneficiary = _newBeneficiary; }
12,854
221
// 0x fee
COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value); uint loanAmount = (_exData.srcAmount - maxColl); if (loanAmount > availableLiquidity) loanAmount = availableLiquidity; bytes memory encoded = packExchangeData(_exData); bytes memory paramsData = abi.encode(encoded, _cAddresses, _gasCost, true, address(this)); givePermission(COMPOUND_SAVER_FLASH_LOAN); lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[0]), loanAmount, paramsData);
COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value); uint loanAmount = (_exData.srcAmount - maxColl); if (loanAmount > availableLiquidity) loanAmount = availableLiquidity; bytes memory encoded = packExchangeData(_exData); bytes memory paramsData = abi.encode(encoded, _cAddresses, _gasCost, true, address(this)); givePermission(COMPOUND_SAVER_FLASH_LOAN); lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[0]), loanAmount, paramsData);
17,698
222
// dogeAssets
struct DogeAsset { uint256 ratio; string[] assets; }
struct DogeAsset { uint256 ratio; string[] assets; }
31,054
60
// swap hope to wMatic
{ uint256 hopeBalance = IERC20(hopeToken).balanceOf(address(this));
{ uint256 hopeBalance = IERC20(hopeToken).balanceOf(address(this));
16,323
92
// Executes transferAllowed() function from the Controller.
modifier isAllowed(address _from, address _to) { require(controller.transferAllowed(_from, _to), "controller must allow the transfer"); _; }
modifier isAllowed(address _from, address _to) { require(controller.transferAllowed(_from, _to), "controller must allow the transfer"); _; }
45,562
111
// Get the new price that would be stored if updated right now. /
function getBoundedTargetPrice() public view returns (Monetary.Price memory)
function getBoundedTargetPrice() public view returns (Monetary.Price memory)
39,870
116
// Gives people balances based on core units, if Core is contributed then we just append it to it without special logic
unitsContributed[msg.sender] = unitsContributed[msg.sender].add(unitsChange); totalUnitsContributed = totalUnitsContributed.add(unitsChange); emit Contibution(totalCredit, msg.sender);
unitsContributed[msg.sender] = unitsContributed[msg.sender].add(unitsChange); totalUnitsContributed = totalUnitsContributed.add(unitsChange); emit Contibution(totalCredit, msg.sender);
11,269
448
// Upgrade a lock to a specific versiononly available for publicLockVersion > 10 (proxyAdmin /required)lockAddress the existing lock addressversion the version number you are targeting Likely implemented with OpenZeppelin TransparentProxy contract/
function upgradeLock(
function upgradeLock(
27,015
8
// Write PLTE
bytes memory plte = formatPalette(palette, force8bit);
bytes memory plte = formatPalette(palette, force8bit);
14,623
63
// Validates that a setup ID can be applied for `applyInstallation`, `applyUpdate`, or `applyUninstallation`./pluginInstallationId The plugin installation ID obtained from the hash of `abi.encode(daoAddress, pluginAddress)`./preparedSetupId The prepared setup ID to be validated./If the block number stored in `states[pluginInstallationId].blockNumber` exceeds the one stored in `pluginState.preparedSetupIdToBlockNumber[preparedSetupId]`, the prepared setup with `preparedSetupId` is outdated and not applicable anymore.
function validatePreparedSetupId( bytes32 pluginInstallationId, bytes32 preparedSetupId
function validatePreparedSetupId( bytes32 pluginInstallationId, bytes32 preparedSetupId
8,159
137
// Gets the current price in WEI for 1 USDT
uint256 usdtVsWeiCurrentPrice = uint256(priceConsumerUSDT.getLatestPrice());
uint256 usdtVsWeiCurrentPrice = uint256(priceConsumerUSDT.getLatestPrice());
22,105
96
// IPriceOracle Set Protocol Interface for interacting with PriceOracle /
interface IPriceOracle { /* ============ Functions ============ */ function getPrice(address _assetOne, address _assetTwo) external view returns (uint256); function masterQuoteAsset() external view returns (address); }
interface IPriceOracle { /* ============ Functions ============ */ function getPrice(address _assetOne, address _assetTwo) external view returns (uint256); function masterQuoteAsset() external view returns (address); }
66,377
5
// ============================================================================== _ ___|. |`. __ _.| | |(_)(_||~|~|(/_| _\.(these are safety checks)==============================================================================/ prevents contracts from interacting with fomo3d/
modifier isHuman() { address _addr = msg.sender; uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)}
modifier isHuman() { address _addr = msg.sender; uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)}
15,196
19
// Unassign task `taskId` from who it is currently assigned to./taskId The task identifier.
function unassign(uint256 taskId) external exists(taskId) { Task storage task = tasks[taskId]; if (!task.open) { revert Closed(taskId); } if (task.issuer != msg.sender && task.assignedTo != msg.sender && owner() != msg.sender) { revert Unauthorized(); } task.status = TaskState.Todo; emit Unassigned(taskId, task.assignedTo, msg.sender); delete task.assignedTo; }
function unassign(uint256 taskId) external exists(taskId) { Task storage task = tasks[taskId]; if (!task.open) { revert Closed(taskId); } if (task.issuer != msg.sender && task.assignedTo != msg.sender && owner() != msg.sender) { revert Unauthorized(); } task.status = TaskState.Todo; emit Unassigned(taskId, task.assignedTo, msg.sender); delete task.assignedTo; }
18,407
5
// add a role to an address addr address roleName the name of the role /
function adminAddRole(address addr, string roleName) onlyAdmin public
function adminAddRole(address addr, string roleName) onlyAdmin public
43,356
9
// print_if
assembly { if 2 { pop(mload(0)) }}
assembly { if 2 { pop(mload(0)) }}
32,773
116
// Mapping holds user address => reward amount
mapping(address => uint256) public rewards; event RewardAdded(uint256 reward); event Staked(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); uint256 private _totalSupply;
mapping(address => uint256) public rewards; event RewardAdded(uint256 reward); event Staked(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); uint256 private _totalSupply;
1,818
11
// /
function balanceOf() external view returns(uint){ return address(this).balance; }
function balanceOf() external view returns(uint){ return address(this).balance; }
8,578
374
// round 32
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 10716307389353583413755237303156291454109852751296156900963208377067748518748) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 10716307389353583413755237303156291454109852751296156900963208377067748518748) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
32,653
367
// 2. Convert 3CRV -> cvxCRV via USDC
uint256 threeCrvBalance = threeCrvToken.balanceOf(address(this)); if (threeCrvBalance > 0) { _remove_liquidity_one_coin(threeCrvSwap, threeCrvBalance, 1, 0); _swapExactTokensForTokens(sushiswap, usdc, usdcToken.balanceOf(address(this)), getTokenSwapPath(usdc, cvxCrv)); }
uint256 threeCrvBalance = threeCrvToken.balanceOf(address(this)); if (threeCrvBalance > 0) { _remove_liquidity_one_coin(threeCrvSwap, threeCrvBalance, 1, 0); _swapExactTokensForTokens(sushiswap, usdc, usdcToken.balanceOf(address(this)), getTokenSwapPath(usdc, cvxCrv)); }
24,013
21
// delete country[index_of_country];
remove(index_of_country); votes[topic]=0;
remove(index_of_country); votes[topic]=0;
27,473
198
// assigns delegate to self only
_delegate(nonvotingContract, nonvotingContract);
_delegate(nonvotingContract, nonvotingContract);
87,493
16
// gets the collectionAddress variablereturn address of the collection /
function getCollectionAddress() external view returns (address) { return collectionAddress; }
function getCollectionAddress() external view returns (address) { return collectionAddress; }
11,294
121
// View function to see deposited LP for a user.
function deposited(uint256 _pid, address _user) external view returns (uint256) { UserInfo storage user = userInfo[_pid][_user]; return user.amount; }
function deposited(uint256 _pid, address _user) external view returns (uint256) { UserInfo storage user = userInfo[_pid][_user]; return user.amount; }
12,166
3
// Emitted when the `gateway` for `token` is updated./token The address of token updated./oldGateway The corresponding address of the old gateway./newGateway The corresponding address of the new gateway.
event SetERC20Gateway(address indexed token, address indexed oldGateway, address indexed newGateway);
event SetERC20Gateway(address indexed token, address indexed oldGateway, address indexed newGateway);
14,161
0
// constructor(<other arguments>, address _vrfCoordinator, address _link)
* @dev VRFConsumerBase(_vrfCoordinator, _link) public { * @dev <initialization with other arguments goes here> * @dev }
* @dev VRFConsumerBase(_vrfCoordinator, _link) public { * @dev <initialization with other arguments goes here> * @dev }
4,268
43
// Abstract token contract - Functions to be implemented by token contracts
contract Token { /* * Events */ event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); /* * Public functions */ function transfer(address to, uint value) public returns (bool); function transferFrom(address from, address to, uint value) public returns (bool); function approve(address spender, uint value) public returns (bool); function balanceOf(address owner) public constant returns (uint); function allowance(address owner, address spender) public constant returns (uint); function totalSupply() public constant returns (uint); }
contract Token { /* * Events */ event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); /* * Public functions */ function transfer(address to, uint value) public returns (bool); function transferFrom(address from, address to, uint value) public returns (bool); function approve(address spender, uint value) public returns (bool); function balanceOf(address owner) public constant returns (uint); function allowance(address owner, address spender) public constant returns (uint); function totalSupply() public constant returns (uint); }
16,003
51
// if swapOut, swapIn, balance = 3, 2, 0; mk.amount = 1; then amountB = 0, amountA = 1;
uint dust = amountA.SUB798(mp.balance); ADDFEE570(!left, dust, 0); mp.swapOut = mp.swapOut.SUB798(dust); amountA = mp.balance;
uint dust = amountA.SUB798(mp.balance); ADDFEE570(!left, dust, 0); mp.swapOut = mp.swapOut.SUB798(dust); amountA = mp.balance;
51,137
296
// This contains the last token id that was created
uint256 public lastTokenId; bool internal _mintingOpenToAll;
uint256 public lastTokenId; bool internal _mintingOpenToAll;
13,871
29
// PAUSABLE EVENTS
event Pause(); event Unpause();
event Pause(); event Unpause();
27,985
100
// The whitelist of contracts that can be vaulted. //How many tokens are currently in the vault for a given contract. //The index of a given contract, 1-based. We use 0 for the existance check. / The tokens stored in the vault and their contracts' address.
address[] private _tokenContracts; uint256[] private _tokenIds; uint256[] private _tokenCounts;
address[] private _tokenContracts; uint256[] private _tokenIds; uint256[] private _tokenCounts;
30,440
8
// fund portfolio with msg value
address(portfolio).call{value: msg.value}("");
address(portfolio).call{value: msg.value}("");
32,507
35
// actual balances of the 2 pool and amount accumulated
mapping (uint8 => uint256) public pool;
mapping (uint8 => uint256) public pool;
21,021
28
// -- Static & Default Variables --- The Kp and Ki values used in this calculator
ControllerGains internal controllerGains;
ControllerGains internal controllerGains;
5,682
130
// Implementation of a vault to deposit funds for yield optimizing.This is the contract that receives funds and that users interface with.The yield optimizing strategy itself is implemented in a separate 'Strategy.sol' contract. /
contract ToshaVaultV2 is ERC20, Ownable { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; struct StratCandidate { address implementation; uint proposedTime; } // The last proposed strategy to switch to. StratCandidate public stratCandidate; // The strategy currently in use by the vault. // address public strategy; // The token the vault accepts and looks to maximize. IERC20 public token; // The minimum time it has to pass before a strat cantidate can be approved. uint256 public immutable approvalDelay; event NewStratCandidate(address implementation); event UpgradeStrat(address implementation); /** * @dev Sets the value of {token} to the token that the vault will * hold as underlying value. It initializes the vault's own 'moo' token. * This token is minted when someone does a deposit. It is burned in order * to withdraw the corresponding portion of the underlying assets. * @param _token the token to maximize. * @param _name the name of the vault token. * @param _symbol the symbol of the vault token. * @param _approvalDelay the delay before a new strat can be approved. */ constructor ( address _token, // address _strategy, string memory _name, string memory _symbol, uint256 _approvalDelay ) public ERC20( string(abi.encodePacked(_name)), string(abi.encodePacked(_symbol)) ) { token = IERC20(_token); // strategy = _strategy; approvalDelay = _approvalDelay; } /** * @dev It calculates the total underlying value of {token} held by the system. * It takes into account the vault contract balance, the strategy contract balance * and the balance deployed in other contracts as part of the strategy. */ function balance() public view returns (uint) { // return token.balanceOf(address(this)).add(IStrategy(strategy).balanceOf()); return token.balanceOf(address(this)); } /** * @dev Custom logic in here for how much the vault allows to be borrowed. * We return 100% of tokens for now. Under certain conditions we might * want to keep some of the system funds at hand in the vault, instead * of putting them to work. */ function available() public view returns (uint256) { return token.balanceOf(address(this)); } /** * @dev Function for various UIs to display the current value of one of our yield tokens. * Returns an uint256 with 18 decimals of how much underlying asset one vault share represents. */ function getPricePerFullShare() public view returns (uint256) { return balance().mul(1e18).div(totalSupply()); } /** * @dev A helper function to call deposit() with all the sender's funds. */ function depositAll() external { deposit(token.balanceOf(msg.sender)); } /** * @dev The entrypoint of funds into the system. People deposit with this function * into the vault. The vault is then in charge of sending funds into the strategy. */ function deposit(uint _amount) public { // uint256 _pool = balance(); // uint256 _before = token.balanceOf(address(this)); // token.safeTransferFrom(msg.sender, address(this), _amount); // uint256 _after = token.balanceOf(address(this)); // _amount = _after.sub(_before); // Additional check for deflationary tokens // uint256 shares = 0; // if (totalSupply() == 0) { // shares = _amount; // } else { // shares = (_amount.mul(totalSupply())).div(_pool); // } // _mint(msg.sender, shares); _mint(msg.sender, _amount); // earn(); } /** * @dev Function to send funds into the strategy and put them to work. It's primarily called * by the vault's deposit() function. */ function earn() public { // uint _bal = available(); // token.safeTransfer(strategy, _bal); // IStrategy(strategy).deposit(); } /** * @dev A helper function to call withdraw() with all the sender's funds. */ function withdrawAll() external { withdraw(balanceOf(msg.sender)); } /** * @dev Function to exit the system. The vault will withdraw the required tokens * from the strategy and pay up the token holder. A proportional number of IOU * tokens are burned in the process. */ function withdraw(uint256 _shares) public { // uint256 r = (balance().mul(_shares)).div(totalSupply()); // _burn(msg.sender, _shares); _burn(msg.sender, _shares); // uint b = token.balanceOf(address(this)); // if (b < r) { // uint _withdraw = r.sub(b); // IStrategy(strategy).withdraw(_withdraw); // uint _after = token.balanceOf(address(this)); // uint _diff = _after.sub(b); // if (_diff < _withdraw) { // r = b.add(_diff); // } // } // token.safeTransfer(msg.sender, r); } /** * @dev Sets the candidate for the new strat to use with this vault. * @param _implementation The address of the candidate strategy. */ function proposeStrat(address _implementation) public onlyOwner { stratCandidate = StratCandidate({ implementation: _implementation, proposedTime: block.timestamp }); emit NewStratCandidate(_implementation); } /** * @dev It switches the active strat for the strat candidate. You have to call 'retireStrat' * in the strategy contract before. This pauses the old strat and makes sure that all the old * strategy funds are sent back to this vault before switching strats. When upgrading, the * candidate implementation is set to the 0x00 address, and proposedTime to a time happening in +100 years for safety. */ function upgradeStrat() public onlyOwner { require(stratCandidate.implementation != address(0), "There is no candidate"); require(stratCandidate.proposedTime.add(approvalDelay) < block.timestamp, "Delay has not passed"); emit UpgradeStrat(stratCandidate.implementation); // strategy = stratCandidate.implementation; stratCandidate.implementation = address(0); stratCandidate.proposedTime = 5000000000; earn(); } }
contract ToshaVaultV2 is ERC20, Ownable { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; struct StratCandidate { address implementation; uint proposedTime; } // The last proposed strategy to switch to. StratCandidate public stratCandidate; // The strategy currently in use by the vault. // address public strategy; // The token the vault accepts and looks to maximize. IERC20 public token; // The minimum time it has to pass before a strat cantidate can be approved. uint256 public immutable approvalDelay; event NewStratCandidate(address implementation); event UpgradeStrat(address implementation); /** * @dev Sets the value of {token} to the token that the vault will * hold as underlying value. It initializes the vault's own 'moo' token. * This token is minted when someone does a deposit. It is burned in order * to withdraw the corresponding portion of the underlying assets. * @param _token the token to maximize. * @param _name the name of the vault token. * @param _symbol the symbol of the vault token. * @param _approvalDelay the delay before a new strat can be approved. */ constructor ( address _token, // address _strategy, string memory _name, string memory _symbol, uint256 _approvalDelay ) public ERC20( string(abi.encodePacked(_name)), string(abi.encodePacked(_symbol)) ) { token = IERC20(_token); // strategy = _strategy; approvalDelay = _approvalDelay; } /** * @dev It calculates the total underlying value of {token} held by the system. * It takes into account the vault contract balance, the strategy contract balance * and the balance deployed in other contracts as part of the strategy. */ function balance() public view returns (uint) { // return token.balanceOf(address(this)).add(IStrategy(strategy).balanceOf()); return token.balanceOf(address(this)); } /** * @dev Custom logic in here for how much the vault allows to be borrowed. * We return 100% of tokens for now. Under certain conditions we might * want to keep some of the system funds at hand in the vault, instead * of putting them to work. */ function available() public view returns (uint256) { return token.balanceOf(address(this)); } /** * @dev Function for various UIs to display the current value of one of our yield tokens. * Returns an uint256 with 18 decimals of how much underlying asset one vault share represents. */ function getPricePerFullShare() public view returns (uint256) { return balance().mul(1e18).div(totalSupply()); } /** * @dev A helper function to call deposit() with all the sender's funds. */ function depositAll() external { deposit(token.balanceOf(msg.sender)); } /** * @dev The entrypoint of funds into the system. People deposit with this function * into the vault. The vault is then in charge of sending funds into the strategy. */ function deposit(uint _amount) public { // uint256 _pool = balance(); // uint256 _before = token.balanceOf(address(this)); // token.safeTransferFrom(msg.sender, address(this), _amount); // uint256 _after = token.balanceOf(address(this)); // _amount = _after.sub(_before); // Additional check for deflationary tokens // uint256 shares = 0; // if (totalSupply() == 0) { // shares = _amount; // } else { // shares = (_amount.mul(totalSupply())).div(_pool); // } // _mint(msg.sender, shares); _mint(msg.sender, _amount); // earn(); } /** * @dev Function to send funds into the strategy and put them to work. It's primarily called * by the vault's deposit() function. */ function earn() public { // uint _bal = available(); // token.safeTransfer(strategy, _bal); // IStrategy(strategy).deposit(); } /** * @dev A helper function to call withdraw() with all the sender's funds. */ function withdrawAll() external { withdraw(balanceOf(msg.sender)); } /** * @dev Function to exit the system. The vault will withdraw the required tokens * from the strategy and pay up the token holder. A proportional number of IOU * tokens are burned in the process. */ function withdraw(uint256 _shares) public { // uint256 r = (balance().mul(_shares)).div(totalSupply()); // _burn(msg.sender, _shares); _burn(msg.sender, _shares); // uint b = token.balanceOf(address(this)); // if (b < r) { // uint _withdraw = r.sub(b); // IStrategy(strategy).withdraw(_withdraw); // uint _after = token.balanceOf(address(this)); // uint _diff = _after.sub(b); // if (_diff < _withdraw) { // r = b.add(_diff); // } // } // token.safeTransfer(msg.sender, r); } /** * @dev Sets the candidate for the new strat to use with this vault. * @param _implementation The address of the candidate strategy. */ function proposeStrat(address _implementation) public onlyOwner { stratCandidate = StratCandidate({ implementation: _implementation, proposedTime: block.timestamp }); emit NewStratCandidate(_implementation); } /** * @dev It switches the active strat for the strat candidate. You have to call 'retireStrat' * in the strategy contract before. This pauses the old strat and makes sure that all the old * strategy funds are sent back to this vault before switching strats. When upgrading, the * candidate implementation is set to the 0x00 address, and proposedTime to a time happening in +100 years for safety. */ function upgradeStrat() public onlyOwner { require(stratCandidate.implementation != address(0), "There is no candidate"); require(stratCandidate.proposedTime.add(approvalDelay) < block.timestamp, "Delay has not passed"); emit UpgradeStrat(stratCandidate.implementation); // strategy = stratCandidate.implementation; stratCandidate.implementation = address(0); stratCandidate.proposedTime = 5000000000; earn(); } }
22,330
28
// restrict the royalties to 4.5% at the most
require(_MAX_ROYALTY_VALUE >= basis, "Royalty basis too high"); _;
require(_MAX_ROYALTY_VALUE >= basis, "Royalty basis too high"); _;
64,534
503
// if we reached this point, we can transfer
core.transferToUser(_reserve, msg.sender, _amount); emit Borrow( _reserve, msg.sender, _amount, _interestRateMode, vars.finalUserBorrowRate, vars.borrowFee, vars.borrowBalanceIncrease,
core.transferToUser(_reserve, msg.sender, _amount); emit Borrow( _reserve, msg.sender, _amount, _interestRateMode, vars.finalUserBorrowRate, vars.borrowFee, vars.borrowBalanceIncrease,
32,203
13
// update price
priceCumulativeLast = pair.latestIsSlotA ? pair.priceCumulativeSlotA : pair.priceCumulativeSlotB; if (pair.latestIsSlotA) { pairStorage.priceCumulativeSlotB = priceCumulativeCurrent; pairStorage.lastUpdateSlotB = blockTimestamp; } else {
priceCumulativeLast = pair.latestIsSlotA ? pair.priceCumulativeSlotA : pair.priceCumulativeSlotB; if (pair.latestIsSlotA) { pairStorage.priceCumulativeSlotB = priceCumulativeCurrent; pairStorage.lastUpdateSlotB = blockTimestamp; } else {
35,367
356
// Emitted when a proposal has been queued
event ProposalQueued(uint128 indexed id, uint256 eta);
event ProposalQueued(uint128 indexed id, uint256 eta);
23,851
71
// The main contract managing Ramp Swaps escrows lifecycle: create, release or return.Uses an abstract AssetAdapter to carry out the transfers and handle the particular asset data.With a corresponding off-chain oracle protocol allows for atomic-swap-like transfer betweenfiat currencies and crypto assets.an active swap is represented by a hash of its details, mapped to its escrow expirationtimestamp. When the swap is created, its end time is set a given amount of time in the future
* (but within {MIN,MAX}_SWAP_LOCK_TIME_S). * The hashed swap details are: * * address pool: the `RampInstantPool` contract that sells the crypto asset; * * address receiver: the user that buys the crypto asset; * * address oracle: address of the oracle that handles this particular swap; * * bytes assetData: description of the crypto asset, handled by an AssetAdapter; * * bytes32 paymentDetailsHash: hash of the fiat payment details: account numbers, fiat value * and currency, and the transfer reference (title), that can be verified off-chain. * * @author Ramp Network sp. z o.o. */ contract RampInstantEscrows is Ownable, WithStatus, WithOracles, WithSwapsCreator, AssetAdapterWithFees { /// @dev contract version, defined in semver string public constant VERSION = "0.5.1"; uint32 internal constant MIN_ACTUAL_TIMESTAMP = 1000000000; /// @notice lock time limits for pool's assets, after which unreleased escrows can be returned uint32 internal constant MIN_SWAP_LOCK_TIME_S = 24 hours; uint32 internal constant MAX_SWAP_LOCK_TIME_S = 30 days; event Created(bytes32 indexed swapHash); event Released(bytes32 indexed swapHash); event PoolReleased(bytes32 indexed swapHash); event Returned(bytes32 indexed swapHash); event PoolReturned(bytes32 indexed swapHash); /** * @notice Mapping from swap details hash to its end time (as a unix timestamp). * After the end time the swap can be cancelled, and the funds will be returned to the pool. */ mapping (bytes32 => uint32) internal swaps; /** * Swap creation, called by the Ramp Network. Checks swap parameters and ensures the crypto * asset is locked on this contract. * * Emits a `Created` event with the swap hash. */ function create( address payable _pool, address _receiver, address _oracle, bytes calldata _assetData, bytes32 _paymentDetailsHash, uint32 lockTimeS ) external statusAtLeast(Status.ACTIVE) onlySwapCreator() isOracle(_oracle) checkAssetTypeAndData(_assetData, _pool) returns (bool success) { require( lockTimeS >= MIN_SWAP_LOCK_TIME_S && lockTimeS <= MAX_SWAP_LOCK_TIME_S, "lock time outside limits" ); bytes32 swapHash = getSwapHash( _pool, _receiver, _oracle, keccak256(_assetData), _paymentDetailsHash ); requireSwapNotExists(swapHash); // Set up swap status before transfer, to avoid reentrancy attacks. // Even if a malicious token is somehow passed to this function (despite the oracle // signature of its details), the state of this contract is already fully updated, // so it will behave correctly (as it would be a separate call). // solium-disable-next-line security/no-block-members swaps[swapHash] = uint32(block.timestamp) + lockTimeS; require( lockAssetWithFee(_assetData, _pool), "escrow lock failed" ); emit Created(swapHash); return true; } /** * Swap release, which transfers the crypto asset to the receiver and removes the swap from * the active swap mapping. Normally called by the swap's oracle after it confirms a matching * wire transfer on pool's bank account. Can be also called by the pool, for example in case * of a dispute, when the parties reach an agreement off-chain. * * Emits a `Released` or `PoolReleased` event with the swap's hash. */ function release( address _pool, address payable _receiver, address _oracle, bytes calldata _assetData, bytes32 _paymentDetailsHash ) external statusAtLeast(Status.FINALIZE_ONLY) onlyOracleOrPool(_pool, _oracle) { bytes32 swapHash = getSwapHash( _pool, _receiver, _oracle, keccak256(_assetData), _paymentDetailsHash ); requireSwapCreated(swapHash); // Delete the swap status before transfer, to avoid reentrancy attacks. swaps[swapHash] = 0; require( sendAssetKeepingFee(_assetData, _receiver), "asset release failed" ); if (msg.sender == _pool) { emit PoolReleased(swapHash); } else { emit Released(swapHash); } } /** * Swap return, which transfers the crypto asset back to the pool and removes the swap from * the active swap mapping. Can be called by the pool or the swap's oracle, but only if the * escrow lock time expired. * * Emits a `Returned` or `PoolReturned` event with the swap's hash. */ function returnFunds( address payable _pool, address _receiver, address _oracle, bytes calldata _assetData, bytes32 _paymentDetailsHash ) external statusAtLeast(Status.RETURN_ONLY) onlyOracleOrPool(_pool, _oracle) { bytes32 swapHash = getSwapHash( _pool, _receiver, _oracle, keccak256(_assetData), _paymentDetailsHash ); requireSwapExpired(swapHash); // Delete the swap status before transfer, to avoid reentrancy attacks. swaps[swapHash] = 0; require( sendAssetWithFee(_assetData, _pool), "asset return failed" ); if (msg.sender == _pool) { emit PoolReturned(swapHash); } else { emit Returned(swapHash); } } /** * Given all valid swap details, returns its status. The return can be: * 0: the swap details are invalid, swap doesn't exist, or was already released/returned. * >1: the swap was created, and the value is a timestamp indicating end of its lock time. */ function getSwapStatus( address _pool, address _receiver, address _oracle, bytes calldata _assetData, bytes32 _paymentDetailsHash ) external view returns (uint32 status) { bytes32 swapHash = getSwapHash( _pool, _receiver, _oracle, keccak256(_assetData), _paymentDetailsHash ); return swaps[swapHash]; } /** * Calculates the swap hash used to reference the swap in this contract's storage. */ function getSwapHash( address _pool, address _receiver, address _oracle, bytes32 assetHash, bytes32 _paymentDetailsHash ) internal pure returns (bytes32) { return keccak256( abi.encodePacked( _pool, _receiver, _oracle, assetHash, _paymentDetailsHash ) ); } function requireSwapNotExists(bytes32 swapHash) internal view { require( swaps[swapHash] == 0, "swap already exists" ); } function requireSwapCreated(bytes32 swapHash) internal view { require( swaps[swapHash] > MIN_ACTUAL_TIMESTAMP, "swap invalid" ); } function requireSwapExpired(bytes32 swapHash) internal view { require( // solium-disable-next-line security/no-block-members swaps[swapHash] > MIN_ACTUAL_TIMESTAMP && block.timestamp > swaps[swapHash], "swap not expired or invalid" ); } }
* (but within {MIN,MAX}_SWAP_LOCK_TIME_S). * The hashed swap details are: * * address pool: the `RampInstantPool` contract that sells the crypto asset; * * address receiver: the user that buys the crypto asset; * * address oracle: address of the oracle that handles this particular swap; * * bytes assetData: description of the crypto asset, handled by an AssetAdapter; * * bytes32 paymentDetailsHash: hash of the fiat payment details: account numbers, fiat value * and currency, and the transfer reference (title), that can be verified off-chain. * * @author Ramp Network sp. z o.o. */ contract RampInstantEscrows is Ownable, WithStatus, WithOracles, WithSwapsCreator, AssetAdapterWithFees { /// @dev contract version, defined in semver string public constant VERSION = "0.5.1"; uint32 internal constant MIN_ACTUAL_TIMESTAMP = 1000000000; /// @notice lock time limits for pool's assets, after which unreleased escrows can be returned uint32 internal constant MIN_SWAP_LOCK_TIME_S = 24 hours; uint32 internal constant MAX_SWAP_LOCK_TIME_S = 30 days; event Created(bytes32 indexed swapHash); event Released(bytes32 indexed swapHash); event PoolReleased(bytes32 indexed swapHash); event Returned(bytes32 indexed swapHash); event PoolReturned(bytes32 indexed swapHash); /** * @notice Mapping from swap details hash to its end time (as a unix timestamp). * After the end time the swap can be cancelled, and the funds will be returned to the pool. */ mapping (bytes32 => uint32) internal swaps; /** * Swap creation, called by the Ramp Network. Checks swap parameters and ensures the crypto * asset is locked on this contract. * * Emits a `Created` event with the swap hash. */ function create( address payable _pool, address _receiver, address _oracle, bytes calldata _assetData, bytes32 _paymentDetailsHash, uint32 lockTimeS ) external statusAtLeast(Status.ACTIVE) onlySwapCreator() isOracle(_oracle) checkAssetTypeAndData(_assetData, _pool) returns (bool success) { require( lockTimeS >= MIN_SWAP_LOCK_TIME_S && lockTimeS <= MAX_SWAP_LOCK_TIME_S, "lock time outside limits" ); bytes32 swapHash = getSwapHash( _pool, _receiver, _oracle, keccak256(_assetData), _paymentDetailsHash ); requireSwapNotExists(swapHash); // Set up swap status before transfer, to avoid reentrancy attacks. // Even if a malicious token is somehow passed to this function (despite the oracle // signature of its details), the state of this contract is already fully updated, // so it will behave correctly (as it would be a separate call). // solium-disable-next-line security/no-block-members swaps[swapHash] = uint32(block.timestamp) + lockTimeS; require( lockAssetWithFee(_assetData, _pool), "escrow lock failed" ); emit Created(swapHash); return true; } /** * Swap release, which transfers the crypto asset to the receiver and removes the swap from * the active swap mapping. Normally called by the swap's oracle after it confirms a matching * wire transfer on pool's bank account. Can be also called by the pool, for example in case * of a dispute, when the parties reach an agreement off-chain. * * Emits a `Released` or `PoolReleased` event with the swap's hash. */ function release( address _pool, address payable _receiver, address _oracle, bytes calldata _assetData, bytes32 _paymentDetailsHash ) external statusAtLeast(Status.FINALIZE_ONLY) onlyOracleOrPool(_pool, _oracle) { bytes32 swapHash = getSwapHash( _pool, _receiver, _oracle, keccak256(_assetData), _paymentDetailsHash ); requireSwapCreated(swapHash); // Delete the swap status before transfer, to avoid reentrancy attacks. swaps[swapHash] = 0; require( sendAssetKeepingFee(_assetData, _receiver), "asset release failed" ); if (msg.sender == _pool) { emit PoolReleased(swapHash); } else { emit Released(swapHash); } } /** * Swap return, which transfers the crypto asset back to the pool and removes the swap from * the active swap mapping. Can be called by the pool or the swap's oracle, but only if the * escrow lock time expired. * * Emits a `Returned` or `PoolReturned` event with the swap's hash. */ function returnFunds( address payable _pool, address _receiver, address _oracle, bytes calldata _assetData, bytes32 _paymentDetailsHash ) external statusAtLeast(Status.RETURN_ONLY) onlyOracleOrPool(_pool, _oracle) { bytes32 swapHash = getSwapHash( _pool, _receiver, _oracle, keccak256(_assetData), _paymentDetailsHash ); requireSwapExpired(swapHash); // Delete the swap status before transfer, to avoid reentrancy attacks. swaps[swapHash] = 0; require( sendAssetWithFee(_assetData, _pool), "asset return failed" ); if (msg.sender == _pool) { emit PoolReturned(swapHash); } else { emit Returned(swapHash); } } /** * Given all valid swap details, returns its status. The return can be: * 0: the swap details are invalid, swap doesn't exist, or was already released/returned. * >1: the swap was created, and the value is a timestamp indicating end of its lock time. */ function getSwapStatus( address _pool, address _receiver, address _oracle, bytes calldata _assetData, bytes32 _paymentDetailsHash ) external view returns (uint32 status) { bytes32 swapHash = getSwapHash( _pool, _receiver, _oracle, keccak256(_assetData), _paymentDetailsHash ); return swaps[swapHash]; } /** * Calculates the swap hash used to reference the swap in this contract's storage. */ function getSwapHash( address _pool, address _receiver, address _oracle, bytes32 assetHash, bytes32 _paymentDetailsHash ) internal pure returns (bytes32) { return keccak256( abi.encodePacked( _pool, _receiver, _oracle, assetHash, _paymentDetailsHash ) ); } function requireSwapNotExists(bytes32 swapHash) internal view { require( swaps[swapHash] == 0, "swap already exists" ); } function requireSwapCreated(bytes32 swapHash) internal view { require( swaps[swapHash] > MIN_ACTUAL_TIMESTAMP, "swap invalid" ); } function requireSwapExpired(bytes32 swapHash) internal view { require( // solium-disable-next-line security/no-block-members swaps[swapHash] > MIN_ACTUAL_TIMESTAMP && block.timestamp > swaps[swapHash], "swap not expired or invalid" ); } }
38,829
141
// default tax is 8% of every transfer
uint256 taxAmount = amount.mul(transferTaxRate).div(10000); uint256 burnAmount = taxAmount.mul(burnRate).div(100); uint256 liquidityAmount = taxAmount.sub(burnAmount); require(taxAmount == burnAmount + liquidityAmount, "transfer: Burn value invalid");
uint256 taxAmount = amount.mul(transferTaxRate).div(10000); uint256 burnAmount = taxAmount.mul(burnRate).div(100); uint256 liquidityAmount = taxAmount.sub(burnAmount); require(taxAmount == burnAmount + liquidityAmount, "transfer: Burn value invalid");
7,879
0
// Lib_PredeployAddresses /
library Lib_PredeployAddresses { // solhint-disable max-line-length address internal constant L2_TO_L1_MESSAGE_PASSER = 0x4200000000000000000000000000000000000000; address internal constant L1_MESSAGE_SENDER = 0x4200000000000000000000000000000000000001; address internal constant DEPLOYER_WHITELIST = 0x4200000000000000000000000000000000000002; address payable internal constant OVM_ETH = payable(0x4200000000000000000000000000000000000006); // solhint-disable-next-line max-line-length address internal constant L2_CROSS_DOMAIN_MESSENGER = 0x4200000000000000000000000000000000000007; address internal constant LIB_ADDRESS_MANAGER = 0x4200000000000000000000000000000000000008; address internal constant PROXY_EOA = 0x4200000000000000000000000000000000000009; address internal constant L2_STANDARD_BRIDGE = 0x4200000000000000000000000000000000000010; address internal constant SEQUENCER_FEE_WALLET = 0x4200000000000000000000000000000000000011; address internal constant L2_STANDARD_TOKEN_FACTORY = 0x4200000000000000000000000000000000000012; address internal constant L1_BLOCK_NUMBER = 0x4200000000000000000000000000000000000013; address internal constant OVM_GAS_PRICE_ORACLE = 0x420000000000000000000000000000000000000F; address internal constant PROXY__BOBA_TURING_PREPAY = 0x4200000000000000000000000000000000000020; address internal constant BOBA_TURING_PREPAY = 0x4200000000000000000000000000000000000021; address internal constant BOBA_TURING_HELPER = 0x4200000000000000000000000000000000000022; address internal constant L2_BOBA = 0x4200000000000000000000000000000000000023; address internal constant PROXY__BOBA_GAS_PRICE_ORACLE = 0x4200000000000000000000000000000000000024; address internal constant BOBA_GAS_PRICE_ORACLE = 0x4200000000000000000000000000000000000025; }
library Lib_PredeployAddresses { // solhint-disable max-line-length address internal constant L2_TO_L1_MESSAGE_PASSER = 0x4200000000000000000000000000000000000000; address internal constant L1_MESSAGE_SENDER = 0x4200000000000000000000000000000000000001; address internal constant DEPLOYER_WHITELIST = 0x4200000000000000000000000000000000000002; address payable internal constant OVM_ETH = payable(0x4200000000000000000000000000000000000006); // solhint-disable-next-line max-line-length address internal constant L2_CROSS_DOMAIN_MESSENGER = 0x4200000000000000000000000000000000000007; address internal constant LIB_ADDRESS_MANAGER = 0x4200000000000000000000000000000000000008; address internal constant PROXY_EOA = 0x4200000000000000000000000000000000000009; address internal constant L2_STANDARD_BRIDGE = 0x4200000000000000000000000000000000000010; address internal constant SEQUENCER_FEE_WALLET = 0x4200000000000000000000000000000000000011; address internal constant L2_STANDARD_TOKEN_FACTORY = 0x4200000000000000000000000000000000000012; address internal constant L1_BLOCK_NUMBER = 0x4200000000000000000000000000000000000013; address internal constant OVM_GAS_PRICE_ORACLE = 0x420000000000000000000000000000000000000F; address internal constant PROXY__BOBA_TURING_PREPAY = 0x4200000000000000000000000000000000000020; address internal constant BOBA_TURING_PREPAY = 0x4200000000000000000000000000000000000021; address internal constant BOBA_TURING_HELPER = 0x4200000000000000000000000000000000000022; address internal constant L2_BOBA = 0x4200000000000000000000000000000000000023; address internal constant PROXY__BOBA_GAS_PRICE_ORACLE = 0x4200000000000000000000000000000000000024; address internal constant BOBA_GAS_PRICE_ORACLE = 0x4200000000000000000000000000000000000025; }
29,370
31
// no need to require value <= totalSupply, since that would imply the sender's balance is greater than the totalSupply, which should be an assertion failure
address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); Burn(burner, _value);
address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); Burn(burner, _value);
9,798
64
// constructor () public ERC20Detailed("Indigo.Loans", "INDIGO", 18) { }
string private _name; string private _symbol; uint8 private _decimals;
string private _name; string private _symbol; uint8 private _decimals;
6,883
24
// constructure /
function StandardToken() public payable {} /* Send coins */ function transfer( address to_, uint256 amount_ ) public returns(bool success) { if(balances[msg.sender] >= amount_ && amount_ > 0) { balances[msg.sender] = safeSub(balances[msg.sender], amount_); balances[to_] = safeAdd(balances[to_], amount_); emit Transfer(msg.sender, to_, amount_); return true; } else { return false; } }
function StandardToken() public payable {} /* Send coins */ function transfer( address to_, uint256 amount_ ) public returns(bool success) { if(balances[msg.sender] >= amount_ && amount_ > 0) { balances[msg.sender] = safeSub(balances[msg.sender], amount_); balances[to_] = safeAdd(balances[to_], amount_); emit Transfer(msg.sender, to_, amount_); return true; } else { return false; } }
8,830
113
// Emitted when a pool is created /
event PoolAdded(uint256 poolIndex, Pool pool);
event PoolAdded(uint256 poolIndex, Pool pool);
33,737
117
// Calculate natural logarithm of x.Revert if x <= 0.x signed 64.64-bit fixed point numberreturn signed 64.64-bit fixed point number /
function ln (int128 x) internal pure returns (int128) { unchecked { require (x > 0); return int128 (int256 ( uint256 (int256 (log_2 (x))) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128)); } }
function ln (int128 x) internal pure returns (int128) { unchecked { require (x > 0); return int128 (int256 ( uint256 (int256 (log_2 (x))) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128)); } }
24,076
7
// sell ETH in sushiswap for DAI with high price and buy ETH from uniswap with lower price
uint256 amountOut = _swap( amountIn, sushiswapRouterAddress, wethAddress, daiAddress ); uint256 amountFinal = _swap( amountOut, uniswapRouterAddress, daiAddress,
uint256 amountOut = _swap( amountIn, sushiswapRouterAddress, wethAddress, daiAddress ); uint256 amountFinal = _swap( amountOut, uniswapRouterAddress, daiAddress,
41,119
32
// Transfers ownership of the contract to a new account (`newOwner`).Can only be called by the current owner. /
function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); }
function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); }
6,362
28
// usdc fei pool, swap fei out
v3pool(address(0x8c54aA2A32a779e6f6fBea568aD85a19E0109C26)).swap(address(this), false, int256(-feiout), 1461446703485210103287273052203988822378723970342 - 1, data);
v3pool(address(0x8c54aA2A32a779e6f6fBea568aD85a19E0109C26)).swap(address(this), false, int256(-feiout), 1461446703485210103287273052203988822378723970342 - 1, data);
6,563
5
// Used to initialize a new UBIController contract_cUSDToken token used for cUSD /
constructor( address _cUSDToken, address _cUBIAuthToken, address _factory, address _custodian
constructor( address _cUSDToken, address _cUBIAuthToken, address _factory, address _custodian
17,645
28
// add the ambassadors here - Tokens will be distributed to these addresses from main premine
ambassadors_[0x8721a7477c697fE56Cba5Bfb769cA24a697CFB16] = true;
ambassadors_[0x8721a7477c697fE56Cba5Bfb769cA24a697CFB16] = true;
61,249
154
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, andthen delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId];
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId];
44,223
7
// Store the childId.
itemChildIds[itemId][i] = childId;
itemChildIds[itemId][i] = childId;
6,305
11
// Incase any usdc has been sent from OTC or otherwise, report that as gained this amount.
uint256 amountLiquified = totalTokenBalance - usdcRewardBalance; usdcRewardBalance = totalTokenBalance; return amountLiquified;
uint256 amountLiquified = totalTokenBalance - usdcRewardBalance; usdcRewardBalance = totalTokenBalance; return amountLiquified;
17,520
109
// returns a dynamic array of the ids of all tokens which are owned by (_owner) Looping through every possible part and checking it against the owner is actually much more efficient than storing a mapping or something, because it won't be executed as a transaction
function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) { uint256 totalParts = totalSupply(); return tokensOfOwnerWithinRange(_owner, 0, totalParts); }
function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) { uint256 totalParts = totalSupply(); return tokensOfOwnerWithinRange(_owner, 0, totalParts); }
52,593
57
// rate data. base and changes according to quantity and reserve balance. generally speaking. Sell rate is 1 / buy rate i.e. the buy in the other direction.
uint baseBuyRate; // in PRECISION units. see KyberConstants uint baseSellRate; // PRECISION units. without (sell / buy) spread it is 1 / baseBuyRate StepFunction buyRateQtyStepFunction; // in bps. higher quantity - bigger the rate. StepFunction sellRateQtyStepFunction;// in bps. higher the qua StepFunction buyRateImbalanceStepFunction; // in BPS. higher reserve imbalance - bigger the rate. StepFunction sellRateImbalanceStepFunction;
uint baseBuyRate; // in PRECISION units. see KyberConstants uint baseSellRate; // PRECISION units. without (sell / buy) spread it is 1 / baseBuyRate StepFunction buyRateQtyStepFunction; // in bps. higher quantity - bigger the rate. StepFunction sellRateQtyStepFunction;// in bps. higher the qua StepFunction buyRateImbalanceStepFunction; // in BPS. higher reserve imbalance - bigger the rate. StepFunction sellRateImbalanceStepFunction;
38,304
23
// Moves the median pointer right or left of its current value. action Which direction to move the median pointer. /
function updateMedian(List storage list, MedianAction action) private { LinkedList.Element storage previousMedian = list.list.list.elements[list.median]; if (action == MedianAction.Lesser) { list.relation[list.median] = MedianRelation.Greater; list.median = previousMedian.previousKey; } else if (action == MedianAction.Greater) { list.relation[list.median] = MedianRelation.Lesser; list.median = previousMedian.nextKey; } list.relation[list.median] = MedianRelation.Equal; }
function updateMedian(List storage list, MedianAction action) private { LinkedList.Element storage previousMedian = list.list.list.elements[list.median]; if (action == MedianAction.Lesser) { list.relation[list.median] = MedianRelation.Greater; list.median = previousMedian.previousKey; } else if (action == MedianAction.Greater) { list.relation[list.median] = MedianRelation.Lesser; list.median = previousMedian.nextKey; } list.relation[list.median] = MedianRelation.Equal; }
12,128
0
// Initial contribution from the owner
contributions[msg.sender] = 1000 * (1 ether);
contributions[msg.sender] = 1000 * (1 ether);
47,575
11
// Total allocation points. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
uint256 public totalAllocPoint = 0;
6,091
90
// cant take staked asset
require(_token != dai, "dai");
require(_token != dai, "dai");
81,245
327
// Transfer ETH to the beneficiary
if (currency.ct == address(0)) AccrualBeneficiary(beneficiaryAddress).receiveEthersTo.value(uint256(transferable))(address(0), "");
if (currency.ct == address(0)) AccrualBeneficiary(beneficiaryAddress).receiveEthersTo.value(uint256(transferable))(address(0), "");
37,137
5
// Sets the content hash associated with an PNS node.May only be called by the owner of that node in the PNS registry.Note that this resource type is not standardized, and will likely changein future to a resource type based on multihash. node The node to update. hash The content hash to set /
function setContent(bytes32 node, bytes32 hash) public only_owner(node) { records[node].content = hash; ContentChanged(node, hash); }
function setContent(bytes32 node, bytes32 hash) public only_owner(node) { records[node].content = hash; ContentChanged(node, hash); }
7,205
8
// Set the resolver for the TLD this registrar manages.
function setResolver(address resolver) external virtual;
function setResolver(address resolver) external virtual;
20,082
6
// Adds two numbers, reverts on overflow. /
function add(uint256 a, uint256 b) internal pure returns(uint256) { uint256 c = a + b; require(c >= a); return c; }
function add(uint256 a, uint256 b) internal pure returns(uint256) { uint256 c = a + b; require(c >= a); return c; }
47,599
1
// Modifiers /
modifier onlyActive { require(!ended); _; }
modifier onlyActive { require(!ended); _; }
10,527
309
// ============ Public Implementation Functions ============
function closePositionImpl( MarginState.State storage state, bytes32 positionId, uint256 requestedCloseAmount, address payoutRecipient, address exchangeWrapper, bool payoutInHeldToken, bytes memory orderData )
function closePositionImpl( MarginState.State storage state, bytes32 positionId, uint256 requestedCloseAmount, address payoutRecipient, address exchangeWrapper, bool payoutInHeldToken, bytes memory orderData )
46,001
4
// Destroy contract and scrub a data Only owner can call it /
function destroy() onlyContractOwner { suicide(msg.sender); }
function destroy() onlyContractOwner { suicide(msg.sender); }
23,076