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
111
// Finish crowdsale TLP1.2 period and open window1-5 crowdsale /
function finishCrowd() onlyOwner public {
function finishCrowd() onlyOwner public {
49,870
5
// Effects
emit OwnershipTransferred(owner, newOwner); owner = newOwner; pendingOwner = address(0);
emit OwnershipTransferred(owner, newOwner); owner = newOwner; pendingOwner = address(0);
10,667
2
// Keccak hash of the concatenation of two 32-byte words
function _efficientHash(bytes32 _lhs, bytes32 _rhs) private pure returns (bytes32 result) { assembly { mstore(0x00, _lhs) mstore(0x20, _rhs) result := keccak256(0x00, 0x40) } }
function _efficientHash(bytes32 _lhs, bytes32 _rhs) private pure returns (bytes32 result) { assembly { mstore(0x00, _lhs) mstore(0x20, _rhs) result := keccak256(0x00, 0x40) } }
27,841
81
// Enter xGamma. Pay some GAMMAs. Earn some shares.
function enter(uint256 _amount) public { uint256 totalGamma = gamma.balanceOf(address(this)); uint256 totalShares = totalSupply(); if (totalShares == 0 || totalGamma == 0) { _mint(msg.sender, _amount); } else { uint256 what = _amount.mul(totalShares).div(totalGamma); _mint(msg.sender, what); } gamma.transferFrom(msg.sender, address(this), _amount); }
function enter(uint256 _amount) public { uint256 totalGamma = gamma.balanceOf(address(this)); uint256 totalShares = totalSupply(); if (totalShares == 0 || totalGamma == 0) { _mint(msg.sender, _amount); } else { uint256 what = _amount.mul(totalShares).div(totalGamma); _mint(msg.sender, what); } gamma.transferFrom(msg.sender, address(this), _amount); }
31,724
7
// triggered when liquidity protection is updated /
event ProtectionUpdated(
event ProtectionUpdated(
43,688
4
// Send the rewards for a group of addresses receivers The addresses of the rewards receivers values The value in tokens to be sent to each receiver/
function sendRewards(address[] calldata receivers, uint256[] calldata values) external onlyOwner { require(receivers.length == values.length, "RewardsPool: Invalid length of receivers and values"); for (uint i = 0; i < receivers.length; i++) { require(tokenALN.transfer(receivers[i], values[i]), "Reward failed"); emit RewardComplete(receivers[i], values[i]); } }
function sendRewards(address[] calldata receivers, uint256[] calldata values) external onlyOwner { require(receivers.length == values.length, "RewardsPool: Invalid length of receivers and values"); for (uint i = 0; i < receivers.length; i++) { require(tokenALN.transfer(receivers[i], values[i]), "Reward failed"); emit RewardComplete(receivers[i], values[i]); } }
34,332
9
// Address of the DMG token
address dmg;
address dmg;
42,796
83
// Withdraw indexer tokens once the thawing period has passed. /
function withdraw() external override notPaused { _withdraw(msg.sender); }
function withdraw() external override notPaused { _withdraw(msg.sender); }
20,612
50
// handle the bookkeeping so trees don't share tokens, do it before transferring to create one more re-entrance gate
tree.tokenBalance -= currentWithdrawal;
tree.tokenBalance -= currentWithdrawal;
3,445
424
// Do external call (if data is defined) but to be extremely careful we don't allow to do it to the two contracts which the CollateralAuction needs to be authorized
ILimes limes_ = limes; if (data.length > 0 && recipient != address(codex) && recipient != address(limes_)) { CollateralAuctionCallee(recipient).collateralAuctionCall(msg.sender, owe, collateralSlice, data); }
ILimes limes_ = limes; if (data.length > 0 && recipient != address(codex) && recipient != address(limes_)) { CollateralAuctionCallee(recipient).collateralAuctionCall(msg.sender, owe, collateralSlice, data); }
26,652
9
// Update the burn rate.Can only be called by the current operator. /
function updateBurnRate(uint16 burnRate_) public onlyOwner { require( burnRate_ <= 100, "ERC20Govern::updateBurnRate: Burn rate must not exceed the maximum rate." ); burnRate = burnRate_; }
function updateBurnRate(uint16 burnRate_) public onlyOwner { require( burnRate_ <= 100, "ERC20Govern::updateBurnRate: Burn rate must not exceed the maximum rate." ); burnRate = burnRate_; }
49,717
6
// Internals /
function _mint(address to) internal { _safeMint(to, _tokenIdCounter.current()); _tokenIdCounter.increment(); }
function _mint(address to) internal { _safeMint(to, _tokenIdCounter.current()); _tokenIdCounter.increment(); }
25,202
14
// First initialisation
Invoice_Contract newInvoiceAddress = new Invoice_Contract(amount, currency, dueAt, issueAt, sellerAddress, buyerAddress, indexSeller, indexBuyer); buyer[buyerAddress].push(newInvoiceAddress); seller[sellerAddress].push(newInvoiceAddress);
Invoice_Contract newInvoiceAddress = new Invoice_Contract(amount, currency, dueAt, issueAt, sellerAddress, buyerAddress, indexSeller, indexBuyer); buyer[buyerAddress].push(newInvoiceAddress); seller[sellerAddress].push(newInvoiceAddress);
51,612
293
// Internally calculates a swap between two tokens.The caller is expected to transfer the actual amounts (dx and dy)using the token contracts.self Swap struct to read from tokenIndexFrom the token to sell tokenIndexTo the token to buy dx the number of tokens to sell. If the token charges a fee on transfers,use the amount that gets transferred after the fee.return dy the number of tokens the user will getreturn dyFee the associated fee /
function _calculateSwap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256[] memory balances
function _calculateSwap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256[] memory balances
17,234
24
// randSig is pseudorandomness supplied by verifier signiture so can't be influenced by miners
bytes memory _hashString = abi.encode(lotteryId, merkleRoot, prizePostition, "|claimReward|"); require(checkSigniture(_hashString, randSig), "Invalid sig"); bytes32 _hash = blockhash(_result.blockNumber); require(_hash != 0, "lottery expired"); uint256 winningTicketIndex = _getWinningTicket(randSig, _hash, ticketCount); return winningTicketIndex;
bytes memory _hashString = abi.encode(lotteryId, merkleRoot, prizePostition, "|claimReward|"); require(checkSigniture(_hashString, randSig), "Invalid sig"); bytes32 _hash = blockhash(_result.blockNumber); require(_hash != 0, "lottery expired"); uint256 winningTicketIndex = _getWinningTicket(randSig, _hash, ticketCount); return winningTicketIndex;
6,923
4
// Proxy Basic proxy that delegates all calls to a fixed implementing contract.The implementing contract cannot be upgraded. Julien Niset - <[email protected]> /
contract Proxy { address immutable public implementation; event Received(uint indexed value, address indexed sender, bytes data); constructor(address _implementation) { implementation = _implementation; } fallback() external payable { address target = implementation; // solhint-disable-next-line no-inline-assembly assembly { calldatacopy(0, 0, calldatasize()) let result := delegatecall(gas(), target, 0, calldatasize(), 0, 0) returndatacopy(0, 0, returndatasize()) switch result case 0 {revert(0, returndatasize())} default {return (0, returndatasize())} } } receive() external payable { emit Received(msg.value, msg.sender, ""); } }
contract Proxy { address immutable public implementation; event Received(uint indexed value, address indexed sender, bytes data); constructor(address _implementation) { implementation = _implementation; } fallback() external payable { address target = implementation; // solhint-disable-next-line no-inline-assembly assembly { calldatacopy(0, 0, calldatasize()) let result := delegatecall(gas(), target, 0, calldatasize(), 0, 0) returndatacopy(0, 0, returndatasize()) switch result case 0 {revert(0, returndatasize())} default {return (0, returndatasize())} } } receive() external payable { emit Received(msg.value, msg.sender, ""); } }
19,318
4
// The rewards rate is [_rewardPerHour] per 1 Hour.
uint256 public rewardPerHour;
uint256 public rewardPerHour;
2,427
109
// Ugly hack to work around rounding errors. Based on the idea that the furthest the amounts can stray from their "true" values is 1. Ergo the worst case has t_pay_amt and m_pay_amt at +1 away from their "correct" values and m_buy_amt and t_buy_amt at -1. Since (c - 1)(d - 1) > (a + 1)(b + 1) is equivalent to cd > ab + a + b + c + d, we write...
if (mul(m_buy_amt, t_buy_amt) > mul(t_pay_amt, m_pay_amt) + (rounding ? m_buy_amt + t_buy_amt + t_pay_amt + m_pay_amt : 0)) { break; }
if (mul(m_buy_amt, t_buy_amt) > mul(t_pay_amt, m_pay_amt) + (rounding ? m_buy_amt + t_buy_amt + t_pay_amt + m_pay_amt : 0)) { break; }
5,136
52
// Interface for PreSale and CrowdSale contracts with refund function
contract SaleInterface { function refund(address _to) public; }
contract SaleInterface { function refund(address _to) public; }
8,786
48
// as mentioned in the erc223 standard you need a function that checks whether an receiving wallet address is a contract
function isContract(address _addr) internal view returns(bool is_contract){ uint length; assembly { //retrieve the code length/size on target address length := extcodesize(_addr) } return (length>0); }
function isContract(address _addr) internal view returns(bool is_contract){ uint length; assembly { //retrieve the code length/size on target address length := extcodesize(_addr) } return (length>0); }
29,483
35
// keccak256("InterestValidator");
bytes32 internal constant KEY_INTEREST_VALIDATOR = 0xc10a28f028c7f7282a03c90608e38a4a646e136e614e4b07d119280c5f7f839f;
bytes32 internal constant KEY_INTEREST_VALIDATOR = 0xc10a28f028c7f7282a03c90608e38a4a646e136e614e4b07d119280c5f7f839f;
23,233
89
// collateral token address
function collateralToken() external view returns (address);
function collateralToken() external view returns (address);
18,456
125
// add liquidity fee to this contract.
_tokenBalances[address(this)] += values.tLiquifyFee; _reflectionBalances[address(this)] += values.rLiquifyFee; uint256 contractBalance = _tokenBalances[address(this)];
_tokenBalances[address(this)] += values.tLiquifyFee; _reflectionBalances[address(this)] += values.rLiquifyFee; uint256 contractBalance = _tokenBalances[address(this)];
27,254
13
// When the implementation calls pullAmountTo while in a swap, `amount` tokens of the `swap` amount will be sent from the swap`msg.sender` to the `to` address chosen by the implementation.This amount cannot exceed the amount set in the original swap transaction.Traditionally these funds would just be transferred to the implementation which then forwards them to the pairs.However, by using pull hooks, one avoids a transfer which is important for transfer-tax tokens.Can only be called by the implementation.to The address to send `amount` tokens of the swap to. This is presumably the first AMM pair in the route.amount The amount of tokens
function pullAmountTo(address to, uint256 amount) external override { require(msg.sender == address(implementation), "!implementation"); require(remaining >= amount + 1, "!overdraft"); unchecked { remaining -= amount; // Safeguard that the implementation cannot overdraft } pendingToken.safeTransferFrom(from, to, amount); }
function pullAmountTo(address to, uint256 amount) external override { require(msg.sender == address(implementation), "!implementation"); require(remaining >= amount + 1, "!overdraft"); unchecked { remaining -= amount; // Safeguard that the implementation cannot overdraft } pendingToken.safeTransferFrom(from, to, amount); }
15,901
197
// makes sure that the coupon is being processed by the correct chainand the nonce is not used before /
require(_chainId == toChain,"omLink:incorrect chain");
require(_chainId == toChain,"omLink:incorrect chain");
20,270
171
// determine position of given memeSBT ID in reverseBinding array
uint256 _index = reverseBindingIndex[tokenId_];
uint256 _index = reverseBindingIndex[tokenId_];
3,084
364
// Scoping for stack concerns
{
{
35,504
80
// Absorb any tokens that have been sent to this contract into the pool
function gulp(address token) external _logs_ _lock_ { require(_records[token].bound, "ERR_NOT_BOUND"); _records[token].balance = IERC20(token).balanceOf(address(this)); }
function gulp(address token) external _logs_ _lock_ { require(_records[token].bound, "ERR_NOT_BOUND"); _records[token].balance = IERC20(token).balanceOf(address(this)); }
29,051
15
// Precision 1e18 for compatibility with ERC20 token
function getRewardForDuration() external view returns (uint256) { return stakingRewardsDistribution.getRewardRatePerSecond(address(this)) * rewardsDurationSeconds; }
function getRewardForDuration() external view returns (uint256) { return stakingRewardsDistribution.getRewardRatePerSecond(address(this)) * rewardsDurationSeconds; }
35,607
240
// Internal view function that, given an action type and arguments,will return the action ID or message hash that will need to be prefixed(according to EIP-191 0x45), hashed, and signed by the key designated bythe Dharma Key Registry in order to construct a valid signature for thecorresponding action. The current nonce will be supplied to this functionwhen reconstructing an action ID during protected function execution basedon the supplied parameters. action uint8 The type of action, designated by it's index. Validactions in V8 include Cancel (0), SetUserSigningKey (1), Generic (2),GenericAtomicBatch (3), DAIWithdrawal (10), USDCWithdrawal (5),ETHWithdrawal (6), SetEscapeHatch (7), RemoveEscapeHatch (8), andDisableEscapeHatch (9).
function _getActionID( ActionType action, bytes memory arguments, uint256 nonce, uint256 minimumActionGas, address userSigningKey, address dharmaSigningKey
function _getActionID( ActionType action, bytes memory arguments, uint256 nonce, uint256 minimumActionGas, address userSigningKey, address dharmaSigningKey
43,623
108
// OpenseaERC721Upgradeable ERC721 contract that whitelists a trading address, and has minting functionality. /
contract OpenseaERC721Upgradeable is ERC721Upgradeable, EIP712MetaTxUpgradeable { address public proxyRegistryAddress; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ function __OpenseaERC721_init_unchained( string memory _name, string memory _symbol, address _proxyRegistryAddress ) internal initializer { __ERC721_init(_name, _symbol); __EIP712MetaTx_init_unchained(_name, "1"); proxyRegistryAddress = _proxyRegistryAddress; } /** * Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings. */ function isApprovedForAll(address tokenOwner, address operator) override public view returns (bool) { // Whitelist OpenSea proxy contract for easy trading. if (proxyRegistryAddress != address(0)) { OpenseaProxyRegistry proxyRegistry = OpenseaProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(tokenOwner)) == operator) { return true; } } return super.isApprovedForAll(tokenOwner, operator); } uint256[49] private __gap; }
contract OpenseaERC721Upgradeable is ERC721Upgradeable, EIP712MetaTxUpgradeable { address public proxyRegistryAddress; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ function __OpenseaERC721_init_unchained( string memory _name, string memory _symbol, address _proxyRegistryAddress ) internal initializer { __ERC721_init(_name, _symbol); __EIP712MetaTx_init_unchained(_name, "1"); proxyRegistryAddress = _proxyRegistryAddress; } /** * Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings. */ function isApprovedForAll(address tokenOwner, address operator) override public view returns (bool) { // Whitelist OpenSea proxy contract for easy trading. if (proxyRegistryAddress != address(0)) { OpenseaProxyRegistry proxyRegistry = OpenseaProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(tokenOwner)) == operator) { return true; } } return super.isApprovedForAll(tokenOwner, operator); } uint256[49] private __gap; }
43,785
289
// Mints some Bit Monsters.count The number of Bit Monsters to mint. Must be >= 1 and <= 10. You must send 0.06 ETH for each Bit Monster you want to mint. /
function mint(uint count) external payable { require(count >= 1 && count <= 10, "Count must be >=1 and <=10"); require(!Address.isContract(msg.sender), "Contracts cannot mint"); require(mintingState != MintingState.NotAllowed, "Minting is not allowed atm"); if (mintingState == MintingState.WhitelistOnly) { require(whitelist[msg.sender] >= 1000 + count, "Not enough whitelisted mints"); whitelist[msg.sender] -= count; } require(msg.value == count * 0.06 ether, "Send exactly 0.06 ETH for each mint"); Rng memory rn = rng; bool[9] memory ms = mintedSpecials; for (uint i = 0; i < count; ++i) { bitMonsters.createBitMonster(generateBitMonster(rn, ms), msg.sender); } rng = rn; mintedSpecials = ms; Address.sendValue(payHere, msg.value); }
function mint(uint count) external payable { require(count >= 1 && count <= 10, "Count must be >=1 and <=10"); require(!Address.isContract(msg.sender), "Contracts cannot mint"); require(mintingState != MintingState.NotAllowed, "Minting is not allowed atm"); if (mintingState == MintingState.WhitelistOnly) { require(whitelist[msg.sender] >= 1000 + count, "Not enough whitelisted mints"); whitelist[msg.sender] -= count; } require(msg.value == count * 0.06 ether, "Send exactly 0.06 ETH for each mint"); Rng memory rn = rng; bool[9] memory ms = mintedSpecials; for (uint i = 0; i < count; ++i) { bitMonsters.createBitMonster(generateBitMonster(rn, ms), msg.sender); } rng = rn; mintedSpecials = ms; Address.sendValue(payHere, msg.value); }
22,040
7
// Unfreeze adapter at `index` in `frozenAdapters`.Market for the adapter must not be frozen by the protocol. /
function unfreezeAdapter(uint256 index) external virtual { address adapter = frozenAdapters[index]; require(!isAdapterMarketFrozen(adapter), "Market still frozen"); frozenAdapters.remove(index); registry.addTokenAdapter(adapter); emit AdapterUnfrozen(adapter); }
function unfreezeAdapter(uint256 index) external virtual { address adapter = frozenAdapters[index]; require(!isAdapterMarketFrozen(adapter), "Market still frozen"); frozenAdapters.remove(index); registry.addTokenAdapter(adapter); emit AdapterUnfrozen(adapter); }
28,787
15
// user to redeem share for input or output token input token when ride has not been departed, otherwise, output token /
function redeemShare(uint256 _rideId, uint256 _redeemAmount) external { uint256 amount = ridesShares[_rideId]; require(amount > 0, "no shares to redeem"); RideInfo memory rideInfo = rideInfos[_rideId]; //amount > 0 implies that the rideAssetsInfo already registered IERC20(rideInfo.share).safeTransferFrom(msg.sender, address(this), _redeemAmount); IOnchainVaults ocv = IOnchainVaults(onchainVaults); bool departed = rideDeparted[_rideId]; if (departed) { //swap to output token uint256 boughtAmt = _redeemAmount * actualPrices[_rideId] / PRICE_DECIMALS; ocv.withdrawFromVault(rideInfo.tokenIdOutput, _rideId, boughtAmt / rideInfo.quantumOutput); IERC20(rideInfo.outputToken).safeTransfer(msg.sender, boughtAmt); } else { //swap to input token ocv.withdrawFromVault(rideInfo.tokenIdInput, _rideId, _redeemAmount / rideInfo.quantumInput); if (rideInfo.inputToken == address(0) /*ETH*/) { (bool success, ) = msg.sender.call{value: _redeemAmount}(""); require(success, "ETH_TRANSFER_FAILED"); } else { IERC20(rideInfo.inputToken).safeTransfer(msg.sender, _redeemAmount); } } ridesShares[_rideId] -= _redeemAmount; IShareToken(rideInfo.share).burn(address(this), _redeemAmount); emit SharesRedeemed(_rideId, _redeemAmount); }
function redeemShare(uint256 _rideId, uint256 _redeemAmount) external { uint256 amount = ridesShares[_rideId]; require(amount > 0, "no shares to redeem"); RideInfo memory rideInfo = rideInfos[_rideId]; //amount > 0 implies that the rideAssetsInfo already registered IERC20(rideInfo.share).safeTransferFrom(msg.sender, address(this), _redeemAmount); IOnchainVaults ocv = IOnchainVaults(onchainVaults); bool departed = rideDeparted[_rideId]; if (departed) { //swap to output token uint256 boughtAmt = _redeemAmount * actualPrices[_rideId] / PRICE_DECIMALS; ocv.withdrawFromVault(rideInfo.tokenIdOutput, _rideId, boughtAmt / rideInfo.quantumOutput); IERC20(rideInfo.outputToken).safeTransfer(msg.sender, boughtAmt); } else { //swap to input token ocv.withdrawFromVault(rideInfo.tokenIdInput, _rideId, _redeemAmount / rideInfo.quantumInput); if (rideInfo.inputToken == address(0) /*ETH*/) { (bool success, ) = msg.sender.call{value: _redeemAmount}(""); require(success, "ETH_TRANSFER_FAILED"); } else { IERC20(rideInfo.inputToken).safeTransfer(msg.sender, _redeemAmount); } } ridesShares[_rideId] -= _redeemAmount; IShareToken(rideInfo.share).burn(address(this), _redeemAmount); emit SharesRedeemed(_rideId, _redeemAmount); }
13,098
244
// actively transfer amount of asset from msg.sender to lock_proxy contract
require(_transferERC20ToContract(fromAssetHash, _msgSender(), address(this), amount), "transfer erc20 asset to lock_proxy contract failed!");
require(_transferERC20ToContract(fromAssetHash, _msgSender(), address(this), amount), "transfer erc20 asset to lock_proxy contract failed!");
33,713
24
// if `ownership.addr != address(0)`. The `addr` already has it's upper 96 bits clearned, since it is written to memory with regular Solidity.
if mload(ownership) { currOwnershipAddr := mload(ownership) }
if mload(ownership) { currOwnershipAddr := mload(ownership) }
33,568
62
// additional code to rescue erc20 tokens/
function tokenRescue(IERC20 token) public { require(shares(msg.sender) > 0, "not a shareholder"); uint256 amount = token.balanceOf(address(this)); require(amount > 0, "no tokens to rescue"); uint i; for (i = 0; i < _payees.length; i++) { tokenTransfer(token, payee(i),shares(payee(i)) * amount / totalShares()); } }
function tokenRescue(IERC20 token) public { require(shares(msg.sender) > 0, "not a shareholder"); uint256 amount = token.balanceOf(address(this)); require(amount > 0, "no tokens to rescue"); uint i; for (i = 0; i < _payees.length; i++) { tokenTransfer(token, payee(i),shares(payee(i)) * amount / totalShares()); } }
28,764
27
// This function is used when neither the _tokenBorrow nor the _tokenPay is WETHSince it is unlikely that the _tokenBorrow/_tokenPay pair has more liquidaity than the _tokenBorrow/WETH and _tokenPay/WETH pairs, we do a triangular swap here. That is, we flash borrow WETH from the _tokenPay/WETH pair, Then we swap that borrowed WETH for the desired _tokenBorrow via the _tokenBorrow/WETH pair. And finally, we pay back the original flash-borrow using _tokenPay.This initiates the flash borrow. See `traingularFlashSwapExecute` for the code that executes after the borrow.
function traingularFlashSwap(address _tokenBorrow, uint _amount, address _tokenPay, bytes memory _userData) private { address borrowPairAddress = uniswapV2Factory.getPair(_tokenBorrow, WETH); // is it cheaper to compute this locally? require(borrowPairAddress != address(0), "Requested borrow token is not available."); permissionedPairAddress = uniswapV2Factory.getPair(_tokenPay, WETH); // is it cheaper to compute this locally? address payPairAddress = permissionedPairAddress; // gas efficiency require(payPairAddress != address(0), "Requested pay token is not available."); // STEP 1: Compute how much WETH will be needed to get _amount of _tokenBorrow out of the _tokenBorrow/WETH pool uint pairBalanceTokenBorrowBefore = IERC20(_tokenBorrow).balanceOf(borrowPairAddress); require(pairBalanceTokenBorrowBefore >= _amount, "_amount is too big"); uint pairBalanceTokenBorrowAfter = pairBalanceTokenBorrowBefore - _amount; uint pairBalanceWeth = IERC20(WETH).balanceOf(borrowPairAddress); uint amountOfWeth = ((1000 * pairBalanceWeth * _amount) / (997 * pairBalanceTokenBorrowAfter)) + 1; // using a helper function here to avoid "stack too deep" :( traingularFlashSwapHelper(_tokenBorrow, _amount, _tokenPay, borrowPairAddress, payPairAddress, amountOfWeth, _userData); }
function traingularFlashSwap(address _tokenBorrow, uint _amount, address _tokenPay, bytes memory _userData) private { address borrowPairAddress = uniswapV2Factory.getPair(_tokenBorrow, WETH); // is it cheaper to compute this locally? require(borrowPairAddress != address(0), "Requested borrow token is not available."); permissionedPairAddress = uniswapV2Factory.getPair(_tokenPay, WETH); // is it cheaper to compute this locally? address payPairAddress = permissionedPairAddress; // gas efficiency require(payPairAddress != address(0), "Requested pay token is not available."); // STEP 1: Compute how much WETH will be needed to get _amount of _tokenBorrow out of the _tokenBorrow/WETH pool uint pairBalanceTokenBorrowBefore = IERC20(_tokenBorrow).balanceOf(borrowPairAddress); require(pairBalanceTokenBorrowBefore >= _amount, "_amount is too big"); uint pairBalanceTokenBorrowAfter = pairBalanceTokenBorrowBefore - _amount; uint pairBalanceWeth = IERC20(WETH).balanceOf(borrowPairAddress); uint amountOfWeth = ((1000 * pairBalanceWeth * _amount) / (997 * pairBalanceTokenBorrowAfter)) + 1; // using a helper function here to avoid "stack too deep" :( traingularFlashSwapHelper(_tokenBorrow, _amount, _tokenPay, borrowPairAddress, payPairAddress, amountOfWeth, _userData); }
46,963
133
// Stores a new beacon in the EIP1967 beacon slot. /
function _setBeacon(address newBeacon) private { require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract"); require( AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon; }
function _setBeacon(address newBeacon) private { require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract"); require( AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon; }
19,280
8
// Internal value storing the local universe identifier.
bytes32 internal localUniverse;
bytes32 internal localUniverse;
2,948
1
// Recorded epochs
mapping(uint256 => bytes32) public epochMerkleRoots; mapping(uint256 => mapping(uint256 => mapping(address => bool))) public claimed; uint256 public version;
mapping(uint256 => bytes32) public epochMerkleRoots; mapping(uint256 => mapping(uint256 => mapping(address => bool))) public claimed; uint256 public version;
51,104
3
// check if donation period has ended/
modifier onlyAfter(uint256 _time) { require(block.timestamp > _time); _; }
modifier onlyAfter(uint256 _time) { require(block.timestamp > _time); _; }
6,604
55
// If this transaction is not in the allowed period of time
return 4;
return 4;
40,950
28
// If dispute fails: - Proposer earns back their bonds: proposal bond + final fee bond - Proposer earns as reward: the dispute bond
FixedPoint.Unsigned memory proposerRebate = fundingRateDispute.proposal.proposalBond.add(fundingRateDispute.proposal.finalFee); FixedPoint.Unsigned memory proposerReward = fundingRateDispute.proposal.proposalBond; collateralCurrency.safeTransfer(fundingRateDispute.proposal.proposer, proposerReward.add(proposerRebate).rawValue);
FixedPoint.Unsigned memory proposerRebate = fundingRateDispute.proposal.proposalBond.add(fundingRateDispute.proposal.finalFee); FixedPoint.Unsigned memory proposerReward = fundingRateDispute.proposal.proposalBond; collateralCurrency.safeTransfer(fundingRateDispute.proposal.proposer, proposerReward.add(proposerRebate).rawValue);
28,813
7
// increment listing id after each function call
_listingId++; _listings[_listingId] = listing;
_listingId++; _listings[_listingId] = listing;
41,573
2
// `transfer`. {sendValue} removes this limitation.IMPORTANT: because control is transferred to `recipient`, care must betaken to not create reentrancy vulnerabilities. Consider using{ReentrancyGuard} or the /
function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}("");
function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}("");
24,186
211
// Disable the staker's set proxy if it was the toggler and is currently on
if (staker_designated_proxies[staker_address] == msg.sender){ staker_designated_proxies[staker_address] = address(0); }
if (staker_designated_proxies[staker_address] == msg.sender){ staker_designated_proxies[staker_address] = address(0); }
34,924
58
// proof
);
);
19,639
13
// performs chained getAmountIn calculations on any number of pairs
function getAmountsIn( address factory, uint256 amountOut, address[] memory path
function getAmountsIn( address factory, uint256 amountOut, address[] memory path
1,046
17
// used to calculate the earned rewards for a user/_user the address of the user to calculate available rewards for/ return _rewards the amount of tokens available as rewards for the passed address
function calculateRewards(address _user) public view returns (uint256 _rewards)
function calculateRewards(address _user) public view returns (uint256 _rewards)
12,536
131
// Recalculate and update PIE speeds for all PIE markets /
function refreshPieSpeedsInternal() internal { address[] memory allMarkets_ = allMarkets; for (uint i = 0; i < allMarkets_.length; i++) { address pToken = allMarkets_[i]; Exp memory borrowIndex = Exp({mantissa: PTokenInterface(pToken).borrowIndex()}); updatePieSupplyIndex(pToken); updatePieBorrowIndex(pToken, borrowIndex); } Exp memory totalUtility = Exp({mantissa: 0}); Exp[] memory utilities = new Exp[](allMarkets_.length); for (uint i = 0; i < allMarkets_.length; i++) { address pToken = allMarkets_[i]; if (markets[pToken].isPied) { oracle.updateUnderlyingPrice(pToken); Exp memory assetPrice = Exp({mantissa: oracle.getUnderlyingPrice(pToken)}); Exp memory interestPerBlock = mul_(Exp({mantissa: PTokenInterface(pToken).borrowRatePerBlock()}), PTokenInterface(pToken).totalBorrows()); Exp memory utility = mul_(interestPerBlock, assetPrice); utilities[i] = utility; totalUtility = add_(totalUtility, utility); } } for (uint i = 0; i < allMarkets_.length; i++) { address pToken = allMarkets[i]; uint newSpeed = totalUtility.mantissa > 0 ? mul_(pieRate, div_(utilities[i], totalUtility)) : 0; pieSpeeds[pToken] = newSpeed; emit PieSpeedUpdated(pToken, newSpeed); } }
function refreshPieSpeedsInternal() internal { address[] memory allMarkets_ = allMarkets; for (uint i = 0; i < allMarkets_.length; i++) { address pToken = allMarkets_[i]; Exp memory borrowIndex = Exp({mantissa: PTokenInterface(pToken).borrowIndex()}); updatePieSupplyIndex(pToken); updatePieBorrowIndex(pToken, borrowIndex); } Exp memory totalUtility = Exp({mantissa: 0}); Exp[] memory utilities = new Exp[](allMarkets_.length); for (uint i = 0; i < allMarkets_.length; i++) { address pToken = allMarkets_[i]; if (markets[pToken].isPied) { oracle.updateUnderlyingPrice(pToken); Exp memory assetPrice = Exp({mantissa: oracle.getUnderlyingPrice(pToken)}); Exp memory interestPerBlock = mul_(Exp({mantissa: PTokenInterface(pToken).borrowRatePerBlock()}), PTokenInterface(pToken).totalBorrows()); Exp memory utility = mul_(interestPerBlock, assetPrice); utilities[i] = utility; totalUtility = add_(totalUtility, utility); } } for (uint i = 0; i < allMarkets_.length; i++) { address pToken = allMarkets[i]; uint newSpeed = totalUtility.mantissa > 0 ? mul_(pieRate, div_(utilities[i], totalUtility)) : 0; pieSpeeds[pToken] = newSpeed; emit PieSpeedUpdated(pToken, newSpeed); } }
7,256
91
// Changing the Stake address (zero address)
MockProposalChangeGovernanceManagerStorageStake logic2 = new MockProposalChangeGovernanceManagerStorageStake(); uint256 proposalID2 = governanceManager.propose(address(logic2)); setBlockNumber(block.number +10); assertTrue(!governanceManager.isProposalExecuted(proposalID2)); user1.voteAsStaker(proposalID2, tokenID); governanceManager.execute(proposalID2); assertEq(governanceManager.getStakeTokenAddress(), address(0x0));
MockProposalChangeGovernanceManagerStorageStake logic2 = new MockProposalChangeGovernanceManagerStorageStake(); uint256 proposalID2 = governanceManager.propose(address(logic2)); setBlockNumber(block.number +10); assertTrue(!governanceManager.isProposalExecuted(proposalID2)); user1.voteAsStaker(proposalID2, tokenID); governanceManager.execute(proposalID2); assertEq(governanceManager.getStakeTokenAddress(), address(0x0));
913
50
// Returns the max transfer amount./
function maxTransferAmount() public view returns (uint256) { return totalSupply().mul(maxTransferAmountRate).div(10000); }
function maxTransferAmount() public view returns (uint256) { return totalSupply().mul(maxTransferAmountRate).div(10000); }
35,225
7
// Sets the length of the `value` to 43, such that it only contains the CID.
mstore(value, 43)
mstore(value, 43)
43,250
27
// ------------------------------------------------------------------------ If you consider yourself rich, donate for world peace ------------------------------------------------------------------------
function philanthropise(string name) payable { // Sending something real? require(msg.value > 0); // Calculate the number of tokens uint tokens = msg.value * ONEPERCENT_TOKENS_PER_ETH; // Assign tokens to account and inflate total supply balances[msg.sender] += tokens; totalSupply += tokens; // Calculate and forward taxes to the treasury uint taxAmount = msg.value * TAXRATE / 100; if (taxAmount > 0) { totalTaxed += taxAmount; uint taxPerOfficial = taxAmount / treasuryOfficials.length; for (uint i = 0; i < treasuryOfficials.length; i++) { treasuryOfficials[i].transfer(taxPerOfficial); } } Philanthropy(msg.sender, name, tokens, totalSupply, msg.value, this.balance, totalTaxed); Transfer(0x0, msg.sender, tokens); }
function philanthropise(string name) payable { // Sending something real? require(msg.value > 0); // Calculate the number of tokens uint tokens = msg.value * ONEPERCENT_TOKENS_PER_ETH; // Assign tokens to account and inflate total supply balances[msg.sender] += tokens; totalSupply += tokens; // Calculate and forward taxes to the treasury uint taxAmount = msg.value * TAXRATE / 100; if (taxAmount > 0) { totalTaxed += taxAmount; uint taxPerOfficial = taxAmount / treasuryOfficials.length; for (uint i = 0; i < treasuryOfficials.length; i++) { treasuryOfficials[i].transfer(taxPerOfficial); } } Philanthropy(msg.sender, name, tokens, totalSupply, msg.value, this.balance, totalTaxed); Transfer(0x0, msg.sender, tokens); }
10,987
55
// used for transfer bonus tokens after stopping ICO _recipients list of recipients _amount list of no. tokens/
function bonusToken(address[] _recipients, uint[] _amount) public onlyOwnerOrCoOwner onlyStopping { uint len = _recipients.length; uint len1 = _amount.length; require(len == len1); require(len <= MAX_TRANSFER); uint i; uint total = 0; for (i = 0; i < len; i++) { if (bonus_transferred_recipients[_recipients[i]] == false) { bonus_transferred_recipients[_recipients[i]] = transfer(_recipients[i], _amount[i]); total = total.add(_amount[i]); } } totalBonusToken = totalBonusToken.add(total); noBonusTokenRecipients = noBonusTokenRecipients.add(len); }
function bonusToken(address[] _recipients, uint[] _amount) public onlyOwnerOrCoOwner onlyStopping { uint len = _recipients.length; uint len1 = _amount.length; require(len == len1); require(len <= MAX_TRANSFER); uint i; uint total = 0; for (i = 0; i < len; i++) { if (bonus_transferred_recipients[_recipients[i]] == false) { bonus_transferred_recipients[_recipients[i]] = transfer(_recipients[i], _amount[i]); total = total.add(_amount[i]); } } totalBonusToken = totalBonusToken.add(total); noBonusTokenRecipients = noBonusTokenRecipients.add(len); }
43,890
38
// Presale merkle root
bytes32 presaleMerkleRoot;
bytes32 presaleMerkleRoot;
3,349
1
// This function can be called only by owner _epochLength – value of epochLength param /
function setEpochLength(uint _epochLength) public onlyOwner { epochLength = _epochLength; }
function setEpochLength(uint _epochLength) public onlyOwner { epochLength = _epochLength; }
29,876
158
// only sell for minTokenNumberToSell, decouple from _maxTxAmount
contractTokenBalance = minTokenNumberToSell;
contractTokenBalance = minTokenNumberToSell;
9,785
82
// require user to set to zero before resetting to nonzero
if ((_value != 0) && (allowance[_owner][_spender] != 0)) { return false; }
if ((_value != 0) && (allowance[_owner][_spender] != 0)) { return false; }
40,711
53
// Checks the validity of a Bitcoin signed request & the expiration date. requestData bytes containing all the data packed : payeesPaymentAddress array of payees payment addresses (the index 0 will be the payee the others are subPayees) expirationDate timestamp after that the signed request cannot be broadcasted signature ECDSA signature containing v, r and s as bytes return Validity of order signature. /
function checkBtcRequestSignature( bytes requestData, bytes payeesPaymentAddress, uint256 expirationDate, bytes signature) internal view returns (bool)
function checkBtcRequestSignature( bytes requestData, bytes payeesPaymentAddress, uint256 expirationDate, bytes signature) internal view returns (bool)
5,004
100
// GIVEAWAY
uint256 private constant _giveawayAmount = 100100 * (10 ** _decimals); // 1001 tokens to be given away uint256 private constant _giveawayAmountPerAddress = 200200 * (10 ** _decimals); // 200.2 tokens per address uint256 private constant _giveawayFrequency = 1 days; // Giveaway everyday uint256 private constant _giveawayDuration = 888 days; // Total giveaway duration uint256 private constant _maxgiveawayPercentofLiquidity = 1; // 1.0% of liquidity uint256 private constant _maxgiveawayPercentofBuyback= 3; // 3% of PF buyback amount uint256 private constant _minPF1amountinUniswapWallet = 30000 *(10 ** _decimals); // 3% of buyback amount uint256 private constant _reflectionsPercentage = 4; // 4% reflections for pepe & floki wallets mapping(uint256 => address[]) private giveawayAddresses;
uint256 private constant _giveawayAmount = 100100 * (10 ** _decimals); // 1001 tokens to be given away uint256 private constant _giveawayAmountPerAddress = 200200 * (10 ** _decimals); // 200.2 tokens per address uint256 private constant _giveawayFrequency = 1 days; // Giveaway everyday uint256 private constant _giveawayDuration = 888 days; // Total giveaway duration uint256 private constant _maxgiveawayPercentofLiquidity = 1; // 1.0% of liquidity uint256 private constant _maxgiveawayPercentofBuyback= 3; // 3% of PF buyback amount uint256 private constant _minPF1amountinUniswapWallet = 30000 *(10 ** _decimals); // 3% of buyback amount uint256 private constant _reflectionsPercentage = 4; // 4% reflections for pepe & floki wallets mapping(uint256 => address[]) private giveawayAddresses;
4,929
44
// The rate at which comp is distributed to the corresponding borrow market (per block)
mapping(address => uint) public compBorrowSpeeds;
mapping(address => uint) public compBorrowSpeeds;
17,061
8
// Adding 99% royalty on sales via Rariable and 2981;
function _setRoyalties(address payable _royaltyRecipient) internal nonReentrant { LibPart.Part[] memory _royalties = new LibPart.Part[](1); _royalties[0].value = royaltyBasisPoints; _royalties[0].account = _royaltyRecipient; _saveRoyalties(GoodKarmaTokenID, _royalties); }
function _setRoyalties(address payable _royaltyRecipient) internal nonReentrant { LibPart.Part[] memory _royalties = new LibPart.Part[](1); _royalties[0].value = royaltyBasisPoints; _royalties[0].account = _royaltyRecipient; _saveRoyalties(GoodKarmaTokenID, _royalties); }
61,917
34
// Function to remove a token template. Should have operator access. _templateId Refers to template that is to be deleted./
function removeTokenTemplate(uint256 _templateId) external { require( accessControls.hasAdminRole(msg.sender) || accessControls.hasOperatorRole(msg.sender), "MISOTokenFactory: Sender must be operator" ); require(tokenTemplates[_templateId] != address(0)); address template = tokenTemplates[_templateId]; uint256 templateType = IMisoToken(tokenTemplates[_templateId]).tokenTemplate(); if (currentTemplateId[templateType] == _templateId) { delete currentTemplateId[templateType]; } tokenTemplates[_templateId] = address(0); delete tokenTemplateToId[template]; emit TokenTemplateRemoved(template, _templateId); }
function removeTokenTemplate(uint256 _templateId) external { require( accessControls.hasAdminRole(msg.sender) || accessControls.hasOperatorRole(msg.sender), "MISOTokenFactory: Sender must be operator" ); require(tokenTemplates[_templateId] != address(0)); address template = tokenTemplates[_templateId]; uint256 templateType = IMisoToken(tokenTemplates[_templateId]).tokenTemplate(); if (currentTemplateId[templateType] == _templateId) { delete currentTemplateId[templateType]; } tokenTemplates[_templateId] = address(0); delete tokenTemplateToId[template]; emit TokenTemplateRemoved(template, _templateId); }
40,109
109
// Drain tokens that are sent here for donation Requirements Can only be called by the owner.Ensure requested tokens aren't SWAMPWOLF tokens. /
function drainTokensExceptOurTokens(address _token) public onlyOwner { require(_token != address(presaleSwampWolfToken) && _token != address(swampWolfToken), "Cannot recover SWAMPWOLF tokens"); uint256 amount = IBEP20(_token).balanceOf(address(this)); IBEP20(_token).transfer(msg.sender, amount); }
function drainTokensExceptOurTokens(address _token) public onlyOwner { require(_token != address(presaleSwampWolfToken) && _token != address(swampWolfToken), "Cannot recover SWAMPWOLF tokens"); uint256 amount = IBEP20(_token).balanceOf(address(this)); IBEP20(_token).transfer(msg.sender, amount); }
8,178
6
// Mints tokens according to the provided mint request. req The payload / mint request.signature The signature produced by an account signing the mint request.returns (signer) the recovered address. /
function bonfireBurn(BurnRequest calldata req, bytes calldata signature)
function bonfireBurn(BurnRequest calldata req, bytes calldata signature)
9,131
12
// Events//Variables//Public Functions//Changes the address associated with a particular name. _name String name to associate an address with. _address Address to associate with the name. /
function setAddress( string memory _name, address _address ) external onlyOwner { bytes32 nameHash = _getNameHash(_name); address oldAddress = addresses[nameHash]; addresses[nameHash] = _address;
function setAddress( string memory _name, address _address ) external onlyOwner { bytes32 nameHash = _getNameHash(_name); address oldAddress = addresses[nameHash]; addresses[nameHash] = _address;
11,583
6
// logged when company bylaws are amended
event LogTokenholderRightsAmended( bytes32 indexed resolutionId, Gov.TokenType tokenType, IControlledToken token, ITokenholderRights tokenholderRights );
event LogTokenholderRightsAmended( bytes32 indexed resolutionId, Gov.TokenType tokenType, IControlledToken token, ITokenholderRights tokenholderRights );
19,470
103
// Method that allows a contest creator to cancel his/her contest./ Throws if we try to cancel a contest not owned by the msg.sender/ or by contract's scoring oracle. Also throws if we try to cancel a contest that/ is not int the ContestStatus.Active state.
function cancelContest(uint32 _contestId) public { require(_contestId > 0); Contest storage _toCancel = contests[_contestId]; // The a contest can only be canceled if it is in the active state. require (_toCancel.status == ContestStatus.Active); // Now make sure the calling entity is authorized to cancel the contest // based on the state of the contest. if (_toCancel.startTime > uint64(now)) { // This is a contest that starts in the future. The creator of // the contest or the scoringOracle can cancel it. require((msg.sender == _toCancel.creator) || (msg.sender == _toCancel.scoringOracleAddress)); } else { // This is a contest that has passed its lock time (i.e. started). if (_toCancel.teamIds.length >= uint32(_toCancel.maxMinEntries & 0x00000000FFFFFFFF)) { // A contest that has met its minimum entry count can only be canceled // by the scoringOracle. require(msg.sender == _toCancel.scoringOracleAddress); } } // Note: Contests that have not met their minimum entry requirement // can be canceled by anyone since they cannot be scored or paid out. Once canceled, // anyone can release the teams back to their owners and refund any entry // fees. Otherwise, it would require the contests' ending time to pass // before anyone could release and refund as implemented in the // releaseTeams(...) method. // Return the creator's prizeAmount if (_toCancel.prizeAmount > 0) { _authorizePayment(_toCancel.creator, _toCancel.prizeAmount); _toCancel.remainingPrizeAmount = 0; } // Mark the contest as canceled, which then will allow anyone to // release the teams (and refund the entryFees if any) for this contest. // Generally, this is automatically done by the scoring oracle. _toCancel.status = ContestStatus.Canceled; // Fire event emit ContestCanceled(_contestId); }
function cancelContest(uint32 _contestId) public { require(_contestId > 0); Contest storage _toCancel = contests[_contestId]; // The a contest can only be canceled if it is in the active state. require (_toCancel.status == ContestStatus.Active); // Now make sure the calling entity is authorized to cancel the contest // based on the state of the contest. if (_toCancel.startTime > uint64(now)) { // This is a contest that starts in the future. The creator of // the contest or the scoringOracle can cancel it. require((msg.sender == _toCancel.creator) || (msg.sender == _toCancel.scoringOracleAddress)); } else { // This is a contest that has passed its lock time (i.e. started). if (_toCancel.teamIds.length >= uint32(_toCancel.maxMinEntries & 0x00000000FFFFFFFF)) { // A contest that has met its minimum entry count can only be canceled // by the scoringOracle. require(msg.sender == _toCancel.scoringOracleAddress); } } // Note: Contests that have not met their minimum entry requirement // can be canceled by anyone since they cannot be scored or paid out. Once canceled, // anyone can release the teams back to their owners and refund any entry // fees. Otherwise, it would require the contests' ending time to pass // before anyone could release and refund as implemented in the // releaseTeams(...) method. // Return the creator's prizeAmount if (_toCancel.prizeAmount > 0) { _authorizePayment(_toCancel.creator, _toCancel.prizeAmount); _toCancel.remainingPrizeAmount = 0; } // Mark the contest as canceled, which then will allow anyone to // release the teams (and refund the entryFees if any) for this contest. // Generally, this is automatically done by the scoring oracle. _toCancel.status = ContestStatus.Canceled; // Fire event emit ContestCanceled(_contestId); }
17,903
357
// Getter for premium in underlying tokens that can be redeemed at the end of the period of the deposit _amount the amount of underlying depositedreturn the number of underlying of the ibt deposited that will be redeemable /
function getPremiumPerUnderlyingDeposited(uint256 _amount) external view returns (uint256);
function getPremiumPerUnderlyingDeposited(uint256 _amount) external view returns (uint256);
20,565
7
// Variable que dice si el torneo esta abierto a inscripciones
bool public isOpen = true;
bool public isOpen = true;
31,359
99
// Internal execution mechanism. Can be overriden to implement different execution mechanism /
function _execute( uint256, /* proposalId */ address[] memory targets, uint256[] memory values, bytes[] memory calldatas, bytes32 /*descriptionHash*/
function _execute( uint256, /* proposalId */ address[] memory targets, uint256[] memory values, bytes[] memory calldatas, bytes32 /*descriptionHash*/
38,604
109
// nifty registry contract
address public niftyRegistryContract = 0x6e53130dDfF21E3BC963Ee902005223b9A202106;
address public niftyRegistryContract = 0x6e53130dDfF21E3BC963Ee902005223b9A202106;
14,888
19
// modifyBurnAddress modify address burnt tokens should be sent to _burnAddress burn address /
function modifyBurnAddress(address _burnAddress) public onlyOwner { burnAddress = _burnAddress; emit ModifyBurnAddress(_burnAddress); }
function modifyBurnAddress(address _burnAddress) public onlyOwner { burnAddress = _burnAddress; emit ModifyBurnAddress(_burnAddress); }
20,081
14
// perhaps have mongodb or something to store the actual file data?
event AddedObligation(bytes32 id, bytes32 state, address solver);
event AddedObligation(bytes32 id, bytes32 state, address solver);
41,061
15
// calculates XEN Stake Reward /
function _calculateStakeReward( uint256 amount, uint256 term, uint256 maturityTs, uint256 apy
function _calculateStakeReward( uint256 amount, uint256 term, uint256 maturityTs, uint256 apy
13,804
170
// We update their last balance before updating their emission multiple to avoid overpaying them by retroactively applying their new (higher) emission multiple.
getUserData[to].lastBalance = uint128(gooBalance(to)); getUserData[to].lastTimestamp = uint64(block.timestamp); getUserData[to].emissionMultiple += emissionMultiple; getUserData[to].gobblersOwned += 1;
getUserData[to].lastBalance = uint128(gooBalance(to)); getUserData[to].lastTimestamp = uint64(block.timestamp); getUserData[to].emissionMultiple += emissionMultiple; getUserData[to].gobblersOwned += 1;
37,587
424
// res += valcoefficients[86].
res := addmod(res, mulmod(val, /*coefficients[86]*/ mload(0x1000), PRIME), PRIME)
res := addmod(res, mulmod(val, /*coefficients[86]*/ mload(0x1000), PRIME), PRIME)
33,887
179
// METADATA
string public baseURI; string public baseExtension = ".json"; string public notRevealedUri;
string public baseURI; string public baseExtension = ".json"; string public notRevealedUri;
56,538
8
// require( PRICEamount <= msg.value, "There was not enough/extra ETH transferred to mint an NFT." );
require( cost * amount <= msg.value, "There was not enough/extra ETH transferred to mint an NFT." );
require( cost * amount <= msg.value, "There was not enough/extra ETH transferred to mint an NFT." );
7,413
74
// Return channel's migratedTo address _c the channel to be viewedreturn channel's migratedTo address /
function getMigratedTo(LedgerStruct.Channel storage _c) external view returns(address) {
function getMigratedTo(LedgerStruct.Channel storage _c) external view returns(address) {
41,346
21
// Indicates that the contract is in the process of being initialized./
bool private initializing;
bool private initializing;
6,249
13
// line 2 -proof of cheating the line Whale
mapping(uint256 => address) public cheatLineWhale; mapping(address => bool) public isInLineWhale; mapping(address => uint256) public lineNumberWhale; uint256 public cheatLinePotWhale; uint256 public nextInLineWhale; uint256 public lastInLineWhale;
mapping(uint256 => address) public cheatLineWhale; mapping(address => bool) public isInLineWhale; mapping(address => uint256) public lineNumberWhale; uint256 public cheatLinePotWhale; uint256 public nextInLineWhale; uint256 public lastInLineWhale;
16,414
75
// Contract Constructorowner defaults to msg.sender if delegateContractOwner is provided as address(0)delegateSwap address Swap contract the delegate will deploy withdelegateIndexer address Indexer contract the delegate will deploy withdelegateContractOwner address Owner of the delegatedelegateTradeWallet address Wallet the delegate will trade fromdelegateProtocol bytes2 The protocol identifier for Delegate contracts/
constructor( ISwap delegateSwap, IIndexer delegateIndexer, address delegateContractOwner, address delegateTradeWallet, bytes2 delegateProtocol
constructor( ISwap delegateSwap, IIndexer delegateIndexer, address delegateContractOwner, address delegateTradeWallet, bytes2 delegateProtocol
35,727
186
// Gets the unlockable tokens of a specified address_of The address to query the the unlockable token count of/
function getUnlockableTokens(address _of) public view returns (uint256 unlockableTokens)
function getUnlockableTokens(address _of) public view returns (uint256 unlockableTokens)
28,503
22
// The delay before voting on a proposal may take place, once proposed, in blocks
uint256 public votingDelay;
uint256 public votingDelay;
16,280
10
// We can now derive what percentage of the Pool's total value each invariant delta represents by dividing by the total growth invariant. These values, multiplied by the protocol fee percentage for each growth type, represent the percentage of Pool ownership the protocol should have due to each source.
uint256 protocolSwapFeePercentage = swapFeeGrowthInvariantDelta.divDown(totalGrowthInvariant).mulDown( getProtocolFeePercentageCache(ProtocolFeeType.SWAP) ); uint256 protocolYieldPercentage = nonExemptYieldGrowthInvariantDelta.divDown(totalGrowthInvariant).mulDown( getProtocolFeePercentageCache(ProtocolFeeType.YIELD) );
uint256 protocolSwapFeePercentage = swapFeeGrowthInvariantDelta.divDown(totalGrowthInvariant).mulDown( getProtocolFeePercentageCache(ProtocolFeeType.SWAP) ); uint256 protocolYieldPercentage = nonExemptYieldGrowthInvariantDelta.divDown(totalGrowthInvariant).mulDown( getProtocolFeePercentageCache(ProtocolFeeType.YIELD) );
21,633
10
// emit dbgBytes("message rebuilt", messageStr);emit dbgAddress("signee", signee);emit dbgAddress("bitcodeAddress", bitcodeAddress);
require(signee == bitcodeAddress); //bitcodeaddress could be stored in AdmgrCampaignManager or AdmgrCampaign
require(signee == bitcodeAddress); //bitcodeaddress could be stored in AdmgrCampaignManager or AdmgrCampaign
44,935
22
// Returns the multiplication of two unsigned integers, reverting onoverflow. Counterpart to Solidity's `` operator. Requirements:- Multiplication cannot overflow. /
function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; }
function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; }
1,785
273
// these variables are immutable after initialization
pool = IUniswapV3Pool(_pool); token0 = IERC20(pool.token0()); token1 = IERC20(pool.token1()); managerFeeBPS = _managerFeeBPS; // if set to 0 here manager can still initialize later
pool = IUniswapV3Pool(_pool); token0 = IERC20(pool.token0()); token1 = IERC20(pool.token1()); managerFeeBPS = _managerFeeBPS; // if set to 0 here manager can still initialize later
63,200
70
// send ETH from the contract to a given address
function sendEth(address _receiver, uint _amount) public onlyOwner { _receiver.transfer(_amount); }
function sendEth(address _receiver, uint _amount) public onlyOwner { _receiver.transfer(_amount); }
32,827
98
// Constructor that initializes the sale conditions./_fundingRecipient address The address of the funding recipient./_startTime uint256 The start time of the token sale.
function KinTokenSale(address _fundingRecipient, uint256 _startTime) { require(_fundingRecipient != address(0)); require(_startTime > now); // Deploy new KinToken contract. kin = new KinToken(); // Deploy new VestingTrustee contract. trustee = new VestingTrustee(kin); fundingRecipient = _fundingRecipient; startTime = _startTime; endTime = startTime + SALE_DURATION; // Initialize special vesting grants. initTokenGrants(); }
function KinTokenSale(address _fundingRecipient, uint256 _startTime) { require(_fundingRecipient != address(0)); require(_startTime > now); // Deploy new KinToken contract. kin = new KinToken(); // Deploy new VestingTrustee contract. trustee = new VestingTrustee(kin); fundingRecipient = _fundingRecipient; startTime = _startTime; endTime = startTime + SALE_DURATION; // Initialize special vesting grants. initTokenGrants(); }
16,897
227
// check if a uint is in an array /
{ for (uint256 i = 0; i < array.length; i++) { if (array[i] == value) { return true; } } return false; }
{ for (uint256 i = 0; i < array.length; i++) { if (array[i] == value) { return true; } } return false; }
72,030
107
// 10% of total reward goes to community
uint256 communityReward = amount.div(10); alpa.mint(communityAddr, communityReward);
uint256 communityReward = amount.div(10); alpa.mint(communityAddr, communityReward);
51,894
176
// Transfer principal-plus-interest-minus-fees from borrower to lender
IERC20(loan.loanERC20Denomination).transferFrom(loan.borrower, lender, payoffAmount);
IERC20(loan.loanERC20Denomination).transferFrom(loan.borrower, lender, payoffAmount);
10,251
18
// calculates the next token ID based on value of currentTokenId return uint256 for the next token ID/
function _getNextTokenId() public view returns (uint256) { return currentTokenId.add(1); }
function _getNextTokenId() public view returns (uint256) { return currentTokenId.add(1); }
24,727
203
// Side Token Crossing
ISideToken(tokenToUse).burn(amountMinusFees, userData);
ISideToken(tokenToUse).burn(amountMinusFees, userData);
62,377
42
// return how many shares you can get if you deposit {_amount} sdecrv _amount amount of token depositing /
function getSharesByDepositAmount(uint256 _amount) external view returns (uint256) { return _getSharesByDepositAmount(_amount, totalStakedaoAsset()); }
function getSharesByDepositAmount(uint256 _amount) external view returns (uint256) { return _getSharesByDepositAmount(_amount, totalStakedaoAsset()); }
18,924
372
// Contract-level variables
uint public updateId; // Update counter for this pricefeed; used as a check during investment CanonicalRegistrar public registrar; CanonicalPriceFeed public superFeed;
uint public updateId; // Update counter for this pricefeed; used as a check during investment CanonicalRegistrar public registrar; CanonicalPriceFeed public superFeed;
25,090