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
563
// validate input
require(_supply > 0, "ERR_INVALID_SUPPLY"); require(_reserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE"); require( _reserveWeight > 0 && _reserveWeight <= MAX_WEIGHT, "ERR_INVALID_RESERVE_WEIGHT" );
require(_supply > 0, "ERR_INVALID_SUPPLY"); require(_reserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE"); require( _reserveWeight > 0 && _reserveWeight <= MAX_WEIGHT, "ERR_INVALID_RESERVE_WEIGHT" );
66,263
4
// rewards wallet, default to the rewards contract itself, not a wallet. But if rewards are disabled then they'll fall back to the staking rewards wallet: 0x16cc620dBBACc751DAB85d7Fc1164C62858d9b9f
address public c3Wallet;
address public c3Wallet;
15,958
169
// Issues an exact amount of SetTokens using WETH. Acquires SetToken components at the best price accross uniswap and sushiswap.Uses the acquired components to issue the SetTokens. _setTokenAddress of the SetToken being issued _amountSetTokenAmount of SetTokens to be issued _maxEtherMax amount of ether that can be used to acquire the SetToken components return totalEthTotal amount of ether used to acquire the SetToken components /
function _issueExactSetFromWETH(ISetToken _setToken, uint256 _amountSetToken, uint256 _maxEther) internal returns (uint256) { address[] memory components = _setToken.getComponents(); ( uint256 sumEth, , Exchange[] memory exchanges, uint256[] memory amountComponents, ) = _getAmountETHForIssuance(_setToken, components, _amountSetToken); require(sumEth <= _maxEther, "ExchangeIssuance: INSUFFICIENT_INPUT_AMOUNT"); uint256 totalEth = 0; for (uint256 i = 0; i < components.length; i++) { uint256 amountEth = _swapTokensForExactTokens(exchanges[i], WETH, components[i], amountComponents[i]); totalEth = totalEth.add(amountEth); } basicIssuanceModule.issue(_setToken, _amountSetToken, msg.sender); return totalEth; }
function _issueExactSetFromWETH(ISetToken _setToken, uint256 _amountSetToken, uint256 _maxEther) internal returns (uint256) { address[] memory components = _setToken.getComponents(); ( uint256 sumEth, , Exchange[] memory exchanges, uint256[] memory amountComponents, ) = _getAmountETHForIssuance(_setToken, components, _amountSetToken); require(sumEth <= _maxEther, "ExchangeIssuance: INSUFFICIENT_INPUT_AMOUNT"); uint256 totalEth = 0; for (uint256 i = 0; i < components.length; i++) { uint256 amountEth = _swapTokensForExactTokens(exchanges[i], WETH, components[i], amountComponents[i]); totalEth = totalEth.add(amountEth); } basicIssuanceModule.issue(_setToken, _amountSetToken, msg.sender); return totalEth; }
51,455
29
// Cancel drop./Pauses claiming, removes owner and withdraws
function cancel(uint16 feePercentage_) external override onlyOwner { if (!paused) { _pause(); } _renounceOwnership(); _withdraw(feePercentage_); }
function cancel(uint16 feePercentage_) external override onlyOwner { if (!paused) { _pause(); } _renounceOwnership(); _withdraw(feePercentage_); }
25,669
35
// Event emitted regardless of success of external calls
emit AssetTransferred(channelId, allocation[m].destination, payoutAmount);
emit AssetTransferred(channelId, allocation[m].destination, payoutAmount);
21,814
102
// total amount of tokens to be released at the end of the vesting
uint256 amountTotal;
uint256 amountTotal;
62,937
2
// test that everything adds back up
Assert.equal(result2[0] + result2[1] + result2[2], 3500,"threshold 2 adds back up"); uint256[] memory result3 = determineTax(uint256(5500)); Assert.equal(result3[0], uint256(5280), "threshold 3 - sent amount"); Assert.equal(result3[1], uint256(55), "threshold 3 - burn amount"); Assert.equal(result3[2], uint256(165), "threshold 3 - tax amount");
Assert.equal(result2[0] + result2[1] + result2[2], 3500,"threshold 2 adds back up"); uint256[] memory result3 = determineTax(uint256(5500)); Assert.equal(result3[0], uint256(5280), "threshold 3 - sent amount"); Assert.equal(result3[1], uint256(55), "threshold 3 - burn amount"); Assert.equal(result3[2], uint256(165), "threshold 3 - tax amount");
13,416
12
// Function to get a list of owned vipers' IDs return A uint array which contains IDs of all owned vipers/
function ownedVipers() external view returns(uint256[] memory) { uint256 viperCount = balanceOf(msg.sender); if (viperCount == 0) { return new uint256[](0); } else { uint256[] memory result = new uint256[](viperCount); uint256 totalVipers = vipers.length; uint256 resultIndex = 0; uint256 viperId = 0; while (viperId < totalVipers) { if (ownerOf(viperId) == msg.sender) { result[resultIndex] = viperId; resultIndex = resultIndex.add(1); } viperId = viperId.add(1); } return result; } }
function ownedVipers() external view returns(uint256[] memory) { uint256 viperCount = balanceOf(msg.sender); if (viperCount == 0) { return new uint256[](0); } else { uint256[] memory result = new uint256[](viperCount); uint256 totalVipers = vipers.length; uint256 resultIndex = 0; uint256 viperId = 0; while (viperId < totalVipers) { if (ownerOf(viperId) == msg.sender) { result[resultIndex] = viperId; resultIndex = resultIndex.add(1); } viperId = viperId.add(1); } return result; } }
41,222
8
// Add new uniswap pair info to pairInfo list/Interal function/_id Strategy Id/_pair Uniswap Pair Interface
function addPair(uint _id, IUniswapV2Pair _pair) internal { (, , uint32 blockTimestampLast) = _pair.getReserves(); ( uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp ) = UniswapV2OracleLibrary.currentCumulativePrices(address(_pair)); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired FixedPoint.uq112x112 memory price0Average = FixedPoint.uq112x112( uint224( (price0Cumulative - _pair.price0CumulativeLast()) / timeElapsed ) ); FixedPoint.uq112x112 memory price1Average = FixedPoint.uq112x112( uint224( (price1Cumulative - _pair.price1CumulativeLast()) / timeElapsed ) ); pairInfo[_id].push( PairInfo({ pair: _pair, price0CumulativeLast: price0Cumulative, price1CumulativeLast: price1Cumulative, token0: _pair.token0(), token1: _pair.token1(), price0Average: price0Average, price1Average: price1Average, blockTimestampLast: blockTimestamp }) ); }
function addPair(uint _id, IUniswapV2Pair _pair) internal { (, , uint32 blockTimestampLast) = _pair.getReserves(); ( uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp ) = UniswapV2OracleLibrary.currentCumulativePrices(address(_pair)); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired FixedPoint.uq112x112 memory price0Average = FixedPoint.uq112x112( uint224( (price0Cumulative - _pair.price0CumulativeLast()) / timeElapsed ) ); FixedPoint.uq112x112 memory price1Average = FixedPoint.uq112x112( uint224( (price1Cumulative - _pair.price1CumulativeLast()) / timeElapsed ) ); pairInfo[_id].push( PairInfo({ pair: _pair, price0CumulativeLast: price0Cumulative, price1CumulativeLast: price1Cumulative, token0: _pair.token0(), token1: _pair.token1(), price0Average: price0Average, price1Average: price1Average, blockTimestampLast: blockTimestamp }) ); }
30,996
84
// ------------------------------------------------------------------------ Accept ethers from one account for tokens to be created for another account. Can be used by exchanges to purchase tokens on behalf ofit&39;s user ------------------------------------------------------------------------
function proxyPayment(address participant) payable { // No contributions after the crowdsale is finalised require(!finalised); // No contributions before the start of the crowdsale require(now >= START_DATE); // No contributions after the end of the crowdsale require(now <= END_DATE); // No contributions below the minimum (can be 0 ETH) require(msg.value >= CONTRIBUTIONS_MIN); // No contributions above a maximum (if maximum is set to non-0) require(CONTRIBUTIONS_MAX == 0 || msg.value < CONTRIBUTIONS_MAX); // Calculate number of tokens for contributed ETH // `18` is the ETH decimals // `- decimals` is the token decimals // `+ 3` for the tokens per 1,000 ETH factor uint tokens = msg.value * tokensPerKEther / 10**uint(18 - decimals + 3); // Check if the hard cap will be exceeded require(totalSupply + tokens <= TOKENS_HARD_CAP); // Add tokens purchased to account&#39;s balance and total supply balances[participant] = balances[participant].add(tokens); totalSupply = totalSupply.add(tokens); // Log the tokens purchased Transfer(0x0, participant, tokens); TokensBought(participant, msg.value, this.balance, tokens, totalSupply, tokensPerKEther); // KYC verification required before participant can transfer the tokens kycRequired[participant] = true; // Transfer the contributed ethers to the crowdsale wallet if (!wallet.send(msg.value)) throw; }
function proxyPayment(address participant) payable { // No contributions after the crowdsale is finalised require(!finalised); // No contributions before the start of the crowdsale require(now >= START_DATE); // No contributions after the end of the crowdsale require(now <= END_DATE); // No contributions below the minimum (can be 0 ETH) require(msg.value >= CONTRIBUTIONS_MIN); // No contributions above a maximum (if maximum is set to non-0) require(CONTRIBUTIONS_MAX == 0 || msg.value < CONTRIBUTIONS_MAX); // Calculate number of tokens for contributed ETH // `18` is the ETH decimals // `- decimals` is the token decimals // `+ 3` for the tokens per 1,000 ETH factor uint tokens = msg.value * tokensPerKEther / 10**uint(18 - decimals + 3); // Check if the hard cap will be exceeded require(totalSupply + tokens <= TOKENS_HARD_CAP); // Add tokens purchased to account&#39;s balance and total supply balances[participant] = balances[participant].add(tokens); totalSupply = totalSupply.add(tokens); // Log the tokens purchased Transfer(0x0, participant, tokens); TokensBought(participant, msg.value, this.balance, tokens, totalSupply, tokensPerKEther); // KYC verification required before participant can transfer the tokens kycRequired[participant] = true; // Transfer the contributed ethers to the crowdsale wallet if (!wallet.send(msg.value)) throw; }
8,360
18
// Check Present Requests
require(!_checkRequests(name, price), "Request already present");
require(!_checkRequests(name, price), "Request already present");
27,621
9
// errorTypes:0 - payment succeeded1 - need to pay a valid address2 - cannot pay ourselves3 - negative amount4 - payment would exceed limits
event ResultMessage( address indexed fromBank, string messageId, string message, int errorType );
event ResultMessage( address indexed fromBank, string messageId, string message, int errorType );
46,435
48
// give an address access to this role /
function add(Role storage _role, address _addr) internal
function add(Role storage _role, address _addr) internal
30,233
0
// Initializes the USDI token adding the address of the stablecoin / minter contract. This function can only be called once/ after deployment. Owner can't be a minter./scMinter Stablecoin minter address.
function initialize(address scMinter) external onlyOwner { require(!isInitialized); // dev: Initialized require(scMinter != address(0)); // dev: Address 0 require(scMinter != owner()); // dev: Minter is owner minters[scMinter] = true; isInitialized = true; }
function initialize(address scMinter) external onlyOwner { require(!isInitialized); // dev: Initialized require(scMinter != address(0)); // dev: Address 0 require(scMinter != owner()); // dev: Minter is owner minters[scMinter] = true; isInitialized = true; }
30,306
13
// if the offset is beyond the range of the current word, fetch the next word
if ((j / 256) > word) { takenWord = takenBitMap[j / 256]; }
if ((j / 256) > word) { takenWord = takenBitMap[j / 256]; }
48,454
6
// Diesel(LP) token address
address public immutable override dieselToken;
address public immutable override dieselToken;
26,167
2
// Deposit tokens to receive receipt tokens amount Amount of tokens to deposit /
function deposit(uint amount) external override { _deposit(msg.sender, amount); }
function deposit(uint amount) external override { _deposit(msg.sender, amount); }
24,444
8
// Encode a key/value pair as a JSON trait property, where the value is a string item (needs quotes around it) /
function encodeStringAttribute (string memory key, string memory value) internal pure returns (bytes memory) { return abi.encodePacked("{\"trait_type\":\"", key,"\",\"value\":\"",value,"\"}"); }
function encodeStringAttribute (string memory key, string memory value) internal pure returns (bytes memory) { return abi.encodePacked("{\"trait_type\":\"", key,"\",\"value\":\"",value,"\"}"); }
47,799
47
// HELPERS AND CALCULATORSMethod to view the current BNB stored in the contractExample: totalBNBBalance()
function totalBNBBalance() public view returns(uint)
function totalBNBBalance() public view returns(uint)
40,630
217
// change the minimum bid percent/ _minBidPer10000 minimun bid amount per 10000
function setMinimumBidPercent(uint256 _minBidPer10000) public onlyOwner { require( _minBidPer10000 < 10000, "MarketPlace: minimun Bid cannot be more that 100%" ); minimunBidPer10000 = _minBidPer10000; }
function setMinimumBidPercent(uint256 _minBidPer10000) public onlyOwner { require( _minBidPer10000 < 10000, "MarketPlace: minimun Bid cannot be more that 100%" ); minimunBidPer10000 = _minBidPer10000; }
32,702
51
// Return Token Liquidity from InstaPool. token token address.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) getId Get token amount at this ID from `InstaMemory` Contract. setId Set token amount at this ID in `InstaMemory` Contract./
function flashPayback(address token, uint getId, uint setId) external payable { LiqudityInterface liquidityContract = LiqudityInterface(getLiquidityAddress()); uint _amt = liquidityContract.borrowedToken(token); IERC20 tokenContract = IERC20(token); (address feeCollector, uint feeAmt) = calculateFeeAmt(tokenContract, _amt); address[] memory _tknAddrs = new address[](1); _tknAddrs[0] = token; _transfer(payable(address(liquidityContract)), tokenContract, _amt); liquidityContract.returnLiquidity(_tknAddrs); if (feeAmt > 0) _transfer(payable(feeCollector), tokenContract, feeAmt); setUint(setId, _amt); emitFlashPayback(token, _amt, feeAmt, getId, setId); }
function flashPayback(address token, uint getId, uint setId) external payable { LiqudityInterface liquidityContract = LiqudityInterface(getLiquidityAddress()); uint _amt = liquidityContract.borrowedToken(token); IERC20 tokenContract = IERC20(token); (address feeCollector, uint feeAmt) = calculateFeeAmt(tokenContract, _amt); address[] memory _tknAddrs = new address[](1); _tknAddrs[0] = token; _transfer(payable(address(liquidityContract)), tokenContract, _amt); liquidityContract.returnLiquidity(_tknAddrs); if (feeAmt > 0) _transfer(payable(feeCollector), tokenContract, feeAmt); setUint(setId, _amt); emitFlashPayback(token, _amt, feeAmt, getId, setId); }
22,091
15
// The direct deposit terminals.
ITerminalDirectory public immutable terminalDirectory;
ITerminalDirectory public immutable terminalDirectory;
79,925
5
// ERC1155 assets variables
mapping(address => bool) public is1155Whitelisted; mapping(address => bool) public has1155Royalties; address[] whitelisted1155Collections; uint256 public nextSell1155Id;
mapping(address => bool) public is1155Whitelisted; mapping(address => bool) public has1155Royalties; address[] whitelisted1155Collections; uint256 public nextSell1155Id;
27,593
30
// Removing items associated with the store - This could generate a gas problem if the number of items is too high
for(uint skuIndex = 0; skuIndex < store.skus.length; skuIndex++) { delete store.items[store.skus[skuIndex]]; }
for(uint skuIndex = 0; skuIndex < store.skus.length; skuIndex++) { delete store.items[store.skus[skuIndex]]; }
22,117
52
// STAKING FUNCTIONS/ claimStake Allow any user to claim stake earned /
function claimStake() canPoSclaimStake public returns(bool) { if (balances[msg.sender] <= 0) return false; if (transferIns[msg.sender].length <= 0) return false; uint reward = getProofOfStakeReward(msg.sender); if (reward <= 0) return false; totalSupply = totalSupply.add(reward); balances[msg.sender] = balances[msg.sender].add(reward); //STAKING RELATED////////////////////////////////////////////// delete transferIns[msg.sender]; transferIns[msg.sender].push(transferInStruct(uint128(balances[msg.sender]), uint64(now))); /////////////////////////////////////////////////////////////// emit Transfer(address(0), msg.sender, reward); emit ClaimStake(msg.sender, reward); return true; }
function claimStake() canPoSclaimStake public returns(bool) { if (balances[msg.sender] <= 0) return false; if (transferIns[msg.sender].length <= 0) return false; uint reward = getProofOfStakeReward(msg.sender); if (reward <= 0) return false; totalSupply = totalSupply.add(reward); balances[msg.sender] = balances[msg.sender].add(reward); //STAKING RELATED////////////////////////////////////////////// delete transferIns[msg.sender]; transferIns[msg.sender].push(transferInStruct(uint128(balances[msg.sender]), uint64(now))); /////////////////////////////////////////////////////////////// emit Transfer(address(0), msg.sender, reward); emit ClaimStake(msg.sender, reward); return true; }
21,510
211
// Apply late-claim adjustment to scale claim to zero by end of claim phase adjSatoshis Adjusted BTC address balance in Satoshis (after Silly Whale) daysRemaining Number of reward days remaining in claim phasereturn Adjusted BTC address balance in Satoshis (after Silly Whale and Late-Claim) /
function _adjustLateClaim(uint256 adjSatoshis, uint256 daysRemaining) private pure returns (uint256)
function _adjustLateClaim(uint256 adjSatoshis, uint256 daysRemaining) private pure returns (uint256)
21,267
98
// blackScholesEstimate calculates a rough price estimate for an ATM option input parameters should be transformed prior to being passed to the function so as to remove decimal places otherwise results will be far less accurate _vol uint256 volatility of the underlying converted to remove decimals _underlying uint256 price of the underlying asset _time uint256 days to expiration in years multiplied to remove decimals /
function blackScholesEstimate( uint256 _vol, uint256 _underlying, uint256 _time
function blackScholesEstimate( uint256 _vol, uint256 _underlying, uint256 _time
13,978
1
// ----- VARIABLES -----
mapping(bytes32 => bool) public isNonceUsed; uint256 internal _transactionOffset; uint256 internal _networkId; IUniqOperator public operator; uint256 internal constant TREASURY_INDEX = 0;
mapping(bytes32 => bool) public isNonceUsed; uint256 internal _transactionOffset; uint256 internal _networkId; IUniqOperator public operator; uint256 internal constant TREASURY_INDEX = 0;
19,668
146
// Solidity events which execute when users Invest or Withdraw funds in Ethereum Money
event RegisterInvestment(address userAddress, uint totalInvestmentAmount, uint depositInUserAccount); event RegisterInvestment(address userAddress, address referralAddress, uint totalInvestmentAmount, uint depositInUserAccount, uint depositInReferralAccount); event RegisterWithdraw(address userAddress, uint totalWithdrawalAmount, uint withdrawToUserAccount); event LogNewProvableQuery(string description);
event RegisterInvestment(address userAddress, uint totalInvestmentAmount, uint depositInUserAccount); event RegisterInvestment(address userAddress, address referralAddress, uint totalInvestmentAmount, uint depositInUserAccount, uint depositInReferralAccount); event RegisterWithdraw(address userAddress, uint totalWithdrawalAmount, uint withdrawToUserAccount); event LogNewProvableQuery(string description);
18,554
605
// console.log("getAllowedLeverageForPosition principle %s, numberOfCycles %s", principle / 1 ether, numberOfCycles);
for (uint256 i = 0; i < numberOfCycles; ++i) {
for (uint256 i = 0; i < numberOfCycles; ++i) {
9,178
42
// Creates a new channel between a sender and a receiver and transfers/ the sender's token deposit to this contract, compatibility with ERC20 tokens./_receiver_address The address that receives tokens./_deposit The amount of tokens that the sender escrows.
function createChannelERC20(address _receiver_address, uint192 _deposit) external { createChannelPrivate(msg.sender, _receiver_address, _deposit); // transferFrom deposit from sender to contract // ! needs prior approval from user require(token.transferFrom(msg.sender, address(this), _deposit)); }
function createChannelERC20(address _receiver_address, uint192 _deposit) external { createChannelPrivate(msg.sender, _receiver_address, _deposit); // transferFrom deposit from sender to contract // ! needs prior approval from user require(token.transferFrom(msg.sender, address(this), _deposit)); }
4,468
21
// Withdrawal part // Function to be used to process a withdrawal.Actually it is an internal function, only this contract can call it.This is done in order to roll back all changes in case of revert. _amount Amount to be withdrawn. _receiver Receiver of the withdrawal. /
function processWithdrawalInternal(uint256 _amount, address _receiver) external { require(msg.sender == address(this), "Should be used only as an internal call"); stake_token.safeTransfer(_receiver, _amount); }
function processWithdrawalInternal(uint256 _amount, address _receiver) external { require(msg.sender == address(this), "Should be used only as an internal call"); stake_token.safeTransfer(_receiver, _amount); }
12,516
8
// @todo hardcode constants
bytes32 private constant WETH_TOKEN = keccak256("wethToken"); bytes32 private constant DEPOSIT_MANAGER = keccak256("depositManager"); bytes32 private constant STAKE_MANAGER = keccak256("stakeManager"); bytes32 private constant VALIDATOR_SHARE = keccak256("validatorShare"); bytes32 private constant WITHDRAW_MANAGER = keccak256("withdrawManager"); bytes32 private constant CHILD_CHAIN = keccak256("childChain"); bytes32 private constant STATE_SENDER = keccak256("stateSender"); bytes32 private constant SLASHING_MANAGER = keccak256("slashingManager"); address public erc20Predicate;
bytes32 private constant WETH_TOKEN = keccak256("wethToken"); bytes32 private constant DEPOSIT_MANAGER = keccak256("depositManager"); bytes32 private constant STAKE_MANAGER = keccak256("stakeManager"); bytes32 private constant VALIDATOR_SHARE = keccak256("validatorShare"); bytes32 private constant WITHDRAW_MANAGER = keccak256("withdrawManager"); bytes32 private constant CHILD_CHAIN = keccak256("childChain"); bytes32 private constant STATE_SENDER = keccak256("stateSender"); bytes32 private constant SLASHING_MANAGER = keccak256("slashingManager"); address public erc20Predicate;
29,853
16
// FIELDS
string public name = "SmarterThanCrypto"; string public symbol = "STC"; uint256 public decimals = 18; string public version = "10.0"; uint256 public tokenCap = 100000000 * 10**18;
string public name = "SmarterThanCrypto"; string public symbol = "STC"; uint256 public decimals = 18; string public version = "10.0"; uint256 public tokenCap = 100000000 * 10**18;
54,943
191
// x% is sent back to the rewards holder to be used to lock up in as veCRV in a future date
uint256 _keepCRV = _crv.mul(keepCRV).div(keepCRVMax); if (_keepCRV > 0) { IERC20Lib(crv).safeTransfer(treasury, _keepCRV); }
uint256 _keepCRV = _crv.mul(keepCRV).div(keepCRVMax); if (_keepCRV > 0) { IERC20Lib(crv).safeTransfer(treasury, _keepCRV); }
57,411
158
// Delete any fixed credits per token
delete nonRebasingCreditsPerToken[msg.sender];
delete nonRebasingCreditsPerToken[msg.sender];
46,307
8
// get gameCtl
function gameCtl() public view returns (address[] memory) { return _ctl; }
function gameCtl() public view returns (address[] memory) { return _ctl; }
25,142
83
// Appeals the ruling of a specified dispute._disputeID The ID of the dispute._extraData Additional info about the appeal. Not used by this contract. /
function appeal( uint _disputeID, bytes _extraData
function appeal( uint _disputeID, bytes _extraData
32,297
167
// Internal function for adding executed amount for some token. _token address of the token contract. _day day number, when tokens are processed. _value amount of bridge tokens. /
function addTotalExecutedPerDay( address _token, uint256 _day, uint256 _value
function addTotalExecutedPerDay( address _token, uint256 _day, uint256 _value
47,908
10
// Holds the powers of 100 corresponding to the i-th staker of the pool given by the key of the mapping. This will be used as the divisor when computing payouts
mapping (uint => uint[]) public powersOf100;
mapping (uint => uint[]) public powersOf100;
33,187
13
// Returns whether or not a particular key is present in the sorted list. key The element key.return Whether or not the key is in the sorted list. /
function contains(List storage list, bytes32 key) public view returns (bool) { return list.list.contains(key); }
function contains(List storage list, bytes32 key) public view returns (bool) { return list.list.contains(key); }
12,119
3
// create contract
newPair = new UniV3TradingPair( poolAddress, nftManager, settlerAddress, WETH9 );
newPair = new UniV3TradingPair( poolAddress, nftManager, settlerAddress, WETH9 );
19,935
1
// bytes4(keccak256('mintSLD(address,uint256,string)')) == 0xae2ad903 /
bytes4 private constant _SIG_MINT = 0xae2ad903;
bytes4 private constant _SIG_MINT = 0xae2ad903;
13,489
12
// Transfer CVX to YieldManager
_transferYield(CONVEX_BOOSTER.minter());
_transferYield(CONVEX_BOOSTER.minter());
9,014
23
// payback the loan wrap the ETH if necessary
if (_isPayingEth) { IWETH(WETH).deposit{ value: amountToRepay };
if (_isPayingEth) { IWETH(WETH).deposit{ value: amountToRepay };
14,673
9
// UTILITY FUNCTIONS//Returns whether the data contract is operational or not/
function isOperational() public view returns(bool) { return dataContract.isOperational(); }
function isOperational() public view returns(bool) { return dataContract.isOperational(); }
29,212
327
// cooldown: amount of time before the (non-majority) poll can be reopened
uint256 cooldown;
uint256 cooldown;
51,233
63
// Emitted by the `stake` function to signal the staker placed a stake of the specified/ amount for the specified pool during the specified staking epoch./toPoolStakingAddress The pool in which the `staker` placed the stake./staker The address of the staker that placed the stake./stakingEpoch The serial number of the staking epoch during which the stake was made./amount The stake amount.
event PlacedStake( address indexed toPoolStakingAddress, address indexed staker, uint256 indexed stakingEpoch, uint256 amount );
event PlacedStake( address indexed toPoolStakingAddress, address indexed staker, uint256 indexed stakingEpoch, uint256 amount );
6,743
21
// Allows turning off or on for fee distro /
function updateFeeInfo(address _feeToken, bool _active) external { require(msg.sender==owner, "!auth"); require(feeTokens[_feeToken].distro != address(0), "Fee doesn't exist"); feeTokens[_feeToken].active = _active; emit FeeInfoChanged(_feeToken, _active); }
function updateFeeInfo(address _feeToken, bool _active) external { require(msg.sender==owner, "!auth"); require(feeTokens[_feeToken].distro != address(0), "Fee doesn't exist"); feeTokens[_feeToken].active = _active; emit FeeInfoChanged(_feeToken, _active); }
18,351
1
// index on `username` for User map for account retrieval on login
bytes32 key = _username; bool isOverwrite = userList.exists(key);
bytes32 key = _username; bool isOverwrite = userList.exists(key);
40,068
37
// Linear Pools can only be initialized by the Pool performing the initial join via the `initialize` function.
_require(sender == address(this), Errors.INVALID_INITIALIZATION); _require(recipient == address(this), Errors.INVALID_INITIALIZATION);
_require(sender == address(this), Errors.INVALID_INITIALIZATION); _require(recipient == address(this), Errors.INVALID_INITIALIZATION);
21,976
69
// Cream's CCollateralCapErc20 Contract CTokens which wrap an EIP-20 underlying with collateral cap Cream /
contract CCollateralCapErc20 is CToken, CCollateralCapErc20Interface { /** * @notice Initialize the new money market * @param underlying_ The address of the underlying asset * @param comptroller_ The address of the Comptroller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ ERC-20 name of this token * @param symbol_ ERC-20 symbol of this token * @param decimals_ ERC-20 decimal precision of this token */ function initialize(address underlying_, ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_) public { // CToken initialize does the bulk of the work super.initialize(comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_); // Set underlying and sanity check it underlying = underlying_; // EIP20Interface(underlying).totalSupply(); } /*** User Interface ***/ /** * @notice Sender supplies assets into the market and receives cTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param mintAmount The amount of the underlying asset to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function mint(uint mintAmount) external returns (uint) { (uint err,) = mintInternal(mintAmount, false); return err; } /** * @notice Sender redeems cTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of cTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeem(uint redeemTokens) external returns (uint) { return redeemInternal(redeemTokens, false); } /** * @notice Sender redeems cTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to redeem * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlying(uint redeemAmount) external returns (uint) { return redeemUnderlyingInternal(redeemAmount, false); } /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrow(uint borrowAmount) external returns (uint) { return borrowInternal(borrowAmount, false); } /** * @notice Sender repays their own borrow * @param repayAmount The amount to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrow(uint repayAmount) external returns (uint) { (uint err,) = repayBorrowInternal(repayAmount, false); return err; } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param repayAmount The amount of the underlying borrowed asset to repay * @param cTokenCollateral The market in which to seize collateral from the borrower * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) external returns (uint) { (uint err,) = liquidateBorrowInternal(borrower, repayAmount, cTokenCollateral, false); return err; } /** * @notice The sender adds to reserves. * @param addAmount The amount fo underlying token to add as reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _addReserves(uint addAmount) external returns (uint) { return _addReservesInternal(addAmount, false); } /** * @notice Set the given collateral cap for the market. * @param newCollateralCap New collateral cap for this market. A value of 0 corresponds to no cap. */ function _setCollateralCap(uint newCollateralCap) external { require(msg.sender == admin, "only admin can set collateral cap"); collateralCap = newCollateralCap; emit NewCollateralCap(address(this), newCollateralCap); } /** * @notice Absorb excess cash into reserves. */ function gulp() external nonReentrant { uint256 cashOnChain = getCashOnChain(); uint256 cashPrior = getCashPrior(); uint excessCash = sub_(cashOnChain, cashPrior); totalReserves = add_(totalReserves, excessCash); internalCash = cashOnChain; } /** * @notice Flash loan funds to a given account. * @param receiver The receiver address for the funds * @param amount The amount of the funds to be loaned * @param params The other parameters */ function flashLoan(address receiver, uint amount, bytes calldata params) external nonReentrant { require(amount > 0, "flashLoan amount should be greater than zero"); require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed"); ComptrollerInterfaceExtension(address(comptroller)).flashloanAllowed(address(this), receiver, amount, params); uint cashOnChainBefore = getCashOnChain(); uint cashBefore = getCashPrior(); require(cashBefore >= amount, "INSUFFICIENT_LIQUIDITY"); // 1. calculate fee, 1 bips = 1/10000 uint totalFee = div_(mul_(amount, flashFeeBips), 10000); // 2. transfer fund to receiver doTransferOut(address(uint160(receiver)), amount, false); // 3. update totalBorrows totalBorrows = add_(totalBorrows, amount); // 4. execute receiver's callback function IFlashloanReceiver(receiver).executeOperation(msg.sender, underlying, amount, totalFee, params); // 5. check balance uint cashOnChainAfter = getCashOnChain(); require(cashOnChainAfter == add_(cashOnChainBefore, totalFee), "BALANCE_INCONSISTENT"); // 6. update reserves and internal cash and totalBorrows uint reservesFee = mul_ScalarTruncate(Exp({mantissa: reserveFactorMantissa}), totalFee); totalReserves = add_(totalReserves, reservesFee); internalCash = add_(cashBefore, totalFee); totalBorrows = sub_(totalBorrows, amount); emit Flashloan(receiver, amount, totalFee, reservesFee); } /** * @notice Register account collateral tokens if there is space. * @param account The account to register * @dev This function could only be called by comptroller. * @return The actual registered amount of collateral */ function registerCollateral(address account) external returns (uint) { // Make sure accountCollateralTokens of `account` is initialized. initializeAccountCollateralTokens(account); require(msg.sender == address(comptroller), "only comptroller may register collateral for user"); uint amount = sub_(accountTokens[account], accountCollateralTokens[account]); return increaseUserCollateralInternal(account, amount); } /** * @notice Unregister account collateral tokens if the account still has enough collateral. * @dev This function could only be called by comptroller. * @param account The account to unregister */ function unregisterCollateral(address account) external { // Make sure accountCollateralTokens of `account` is initialized. initializeAccountCollateralTokens(account); require(msg.sender == address(comptroller), "only comptroller may unregister collateral for user"); decreaseUserCollateralInternal(account, accountCollateralTokens[account]); } /*** Safe Token ***/ /** * @notice Gets internal balance of this contract in terms of the underlying. * It excludes balance from direct transfer. * @dev This excludes the value of the current message, if any * @return The quantity of underlying tokens owned by this contract */ function getCashPrior() internal view returns (uint) { return internalCash; } /** * @notice Gets total balance of this contract in terms of the underlying * @dev This excludes the value of the current message, if any * @return The quantity of underlying tokens owned by this contract */ function getCashOnChain() internal view returns (uint) { EIP20Interface token = EIP20Interface(underlying); return token.balanceOf(address(this)); } /** * @notice Initialize the account's collateral tokens. This function should be called in the beginning of every function * that accesses accountCollateralTokens or accountTokens. * @param account The account of accountCollateralTokens that needs to be updated */ function initializeAccountCollateralTokens(address account) internal { /** * If isCollateralTokenInit is false, it means accountCollateralTokens was not initialized yet. * This case will only happen once and must be the very beginning. accountCollateralTokens is a new structure and its * initial value should be equal to accountTokens if user has entered the market. However, it's almost impossible to * check every user's value when the implementation becomes active. Therefore, it must rely on every action which will * access accountTokens to call this function to check if accountCollateralTokens needed to be initialized. */ if (!isCollateralTokenInit[account]) { if (ComptrollerInterfaceExtension(address(comptroller)).checkMembership(account, CToken(this))) { accountCollateralTokens[account] = accountTokens[account]; totalCollateralTokens = add_(totalCollateralTokens, accountTokens[account]); emit UserCollateralChanged(account, accountCollateralTokens[account]); } isCollateralTokenInit[account] = true; } } /** * @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and reverts in that case. * This will revert due to insufficient balance or insufficient allowance. * This function returns the actual amount received, * which may be less than `amount` if there is a fee attached to the transfer. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferIn(address from, uint amount, bool isNative) internal returns (uint) { isNative; // unused EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying); uint balanceBefore = EIP20Interface(underlying).balanceOf(address(this)); token.transferFrom(from, address(this), amount); bool success; assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 success := not(0) // set success to true } case 32 { // This is a compliant ERC-20 returndatacopy(0, 0, 32) success := mload(0) // Set `success = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } require(success, "TOKEN_TRANSFER_IN_FAILED"); // Calculate the amount that was *actually* transferred uint balanceAfter = EIP20Interface(underlying).balanceOf(address(this)); uint transferredIn = sub_(balanceAfter, balanceBefore); internalCash = add_(internalCash, transferredIn); return transferredIn; } /** * @dev Similar to EIP20 transfer, except it handles a False success from `transfer` and returns an explanatory * error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to * insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified * it is >= amount, this should not revert in normal conditions. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferOut(address payable to, uint amount, bool isNative) internal { isNative; // unused EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying); token.transfer(to, amount); bool success; assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 success := not(0) // set success to true } case 32 { // This is a complaint ERC-20 returndatacopy(0, 0, 32) success := mload(0) // Set `success = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } require(success, "TOKEN_TRANSFER_OUT_FAILED"); internalCash = sub_(internalCash, amount); } /** * @notice Transfer `tokens` tokens from `src` to `dst` by `spender` * @dev Called by both `transfer` and `transferFrom` internally * @param spender The address of the account performing the transfer * @param src The address of the source account * @param dst The address of the destination account * @param tokens The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferTokens(address spender, address src, address dst, uint tokens) internal returns (uint) { // Make sure accountCollateralTokens of `src` and `dst` are initialized. initializeAccountCollateralTokens(src); initializeAccountCollateralTokens(dst); /** * For every user, accountTokens must be greater than or equal to accountCollateralTokens. * The buffer between the two values will be transferred first. * bufferTokens = accountTokens[src] - accountCollateralTokens[src] * collateralTokens = tokens - bufferTokens */ uint bufferTokens = sub_(accountTokens[src], accountCollateralTokens[src]); uint collateralTokens = 0; if (tokens > bufferTokens) { collateralTokens = tokens - bufferTokens; } /** * Since bufferTokens are not collateralized and can be transferred freely, we only check with comptroller * whether collateralized tokens can be transferred. */ uint allowed = comptroller.transferAllowed(address(this), src, dst, collateralTokens); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.TRANSFER_COMPTROLLER_REJECTION, allowed); } /* Do not allow self-transfers */ if (src == dst) { return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED); } /* Get the allowance, infinite for the account owner */ uint startingAllowance = 0; if (spender == src) { startingAllowance = uint(-1); } else { startingAllowance = transferAllowances[src][spender]; } /* Do the calculations, checking for {under,over}flow */ accountTokens[src] = sub_(accountTokens[src], tokens); accountTokens[dst] = add_(accountTokens[dst], tokens); if (collateralTokens > 0) { accountCollateralTokens[src] = sub_(accountCollateralTokens[src], collateralTokens); accountCollateralTokens[dst] = add_(accountCollateralTokens[dst], collateralTokens); emit UserCollateralChanged(src, accountCollateralTokens[src]); emit UserCollateralChanged(dst, accountCollateralTokens[dst]); } /* Eat some of the allowance (if necessary) */ if (startingAllowance != uint(-1)) { transferAllowances[src][spender] = sub_(startingAllowance, tokens); } /* We emit a Transfer event */ emit Transfer(src, dst, tokens); // unused function // comptroller.transferVerify(address(this), src, dst, tokens); return uint(Error.NO_ERROR); } /** * @notice Get the account's cToken balances * @param account The address of the account */ function getCTokenBalanceInternal(address account) internal view returns (uint) { if (isCollateralTokenInit[account]) { return accountCollateralTokens[account]; } else { /** * If the value of accountCollateralTokens was not initialized, we should return the value of accountTokens. */ return accountTokens[account]; } } /** * @notice Increase user's collateral. Increase as much as we can. * @param account The address of the account * @param amount The amount of collateral user wants to increase * @return The actual increased amount of collateral */ function increaseUserCollateralInternal(address account, uint amount) internal returns (uint) { uint totalCollateralTokensNew = add_(totalCollateralTokens, amount); if (collateralCap == 0 || (collateralCap != 0 && totalCollateralTokensNew <= collateralCap)) { // 1. If collateral cap is not set, // 2. If collateral cap is set but has enough space for this user, // give all the user needs. totalCollateralTokens = totalCollateralTokensNew; accountCollateralTokens[account] = add_(accountCollateralTokens[account], amount); emit UserCollateralChanged(account, accountCollateralTokens[account]); return amount; } else if (collateralCap > totalCollateralTokens) { // If the collateral cap is set but the remaining cap is not enough for this user, // give the remaining parts to the user. uint gap = sub_(collateralCap, totalCollateralTokens); totalCollateralTokens = add_(totalCollateralTokens, gap); accountCollateralTokens[account] = add_(accountCollateralTokens[account], gap); emit UserCollateralChanged(account, accountCollateralTokens[account]); return gap; } return 0; } /** * @notice Decrease user's collateral. Reject if the amount can't be fully decrease. * @param account The address of the account * @param amount The amount of collateral user wants to decrease */ function decreaseUserCollateralInternal(address account, uint amount) internal { require(comptroller.redeemAllowed(address(this), account, amount) == 0, "comptroller rejection"); /* * Return if amount is zero. * Put behind `redeemAllowed` for accuring potential COMP rewards. */ if (amount == 0) { return; } totalCollateralTokens = sub_(totalCollateralTokens, amount); accountCollateralTokens[account] = sub_(accountCollateralTokens[account], amount); emit UserCollateralChanged(account, accountCollateralTokens[account]); } struct MintLocalVars { uint exchangeRateMantissa; uint mintTokens; uint actualMintAmount; } /** * @notice User supplies assets into the market and receives cTokens in exchange * @dev Assumes interest has already been accrued up to the current block * @param minter The address of the account which is supplying the assets * @param mintAmount The amount of the underlying asset to supply * @param isNative The amount is in native or not * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount. */ function mintFresh(address minter, uint mintAmount, bool isNative) internal returns (uint, uint) { // Make sure accountCollateralTokens of `minter` is initialized. initializeAccountCollateralTokens(minter); /* Fail if mint not allowed */ uint allowed = comptroller.mintAllowed(address(this), minter, mintAmount); if (allowed != 0) { return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.MINT_COMPTROLLER_REJECTION, allowed), 0); } /* * Return if mintAmount is zero. * Put behind `mintAllowed` for accuring potential COMP rewards. */ if (mintAmount == 0) { return (uint(Error.NO_ERROR), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0); } MintLocalVars memory vars; vars.exchangeRateMantissa = exchangeRateStoredInternal(); ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call `doTransferIn` for the minter and the mintAmount. * Note: The cToken must handle variations between ERC-20 and ETH underlying. * `doTransferIn` reverts if anything goes wrong, since we can't be sure if * side-effects occurred. The function returns the amount actually transferred, * in case of a fee. On success, the cToken holds an additional `actualMintAmount` * of cash. */ vars.actualMintAmount = doTransferIn(minter, mintAmount, isNative); /* * We get the current exchange rate and calculate the number of cTokens to be minted: * mintTokens = actualMintAmount / exchangeRate */ vars.mintTokens = div_ScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa})); /* * We calculate the new total supply of cTokens and minter token balance, checking for overflow: * totalSupply = totalSupply + mintTokens * accountTokens[minter] = accountTokens[minter] + mintTokens */ totalSupply = add_(totalSupply, vars.mintTokens); accountTokens[minter] = add_(accountTokens[minter], vars.mintTokens); /* * We only allocate collateral tokens if the minter has entered the market. */ if (ComptrollerInterfaceExtension(address(comptroller)).checkMembership(minter, CToken(this))) { increaseUserCollateralInternal(minter, vars.mintTokens); } /* We emit a Mint event, and a Transfer event */ emit Mint(minter, vars.actualMintAmount, vars.mintTokens); emit Transfer(address(this), minter, vars.mintTokens); /* We call the defense hook */ // unused function // comptroller.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens); return (uint(Error.NO_ERROR), vars.actualMintAmount); } struct RedeemLocalVars { uint exchangeRateMantissa; uint redeemTokens; uint redeemAmount; } /** * @notice User redeems cTokens in exchange for the underlying asset * @dev Assumes interest has already been accrued up to the current block. Only one of redeemTokensIn or redeemAmountIn may be non-zero and it would do nothing if both are zero. * @param redeemer The address of the account which is redeeming the tokens * @param redeemTokensIn The number of cTokens to redeem into underlying * @param redeemAmountIn The number of underlying tokens to receive from redeeming cTokens * @param isNative The amount is in native or not * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemFresh(address payable redeemer, uint redeemTokensIn, uint redeemAmountIn, bool isNative) internal returns (uint) { // Make sure accountCollateralTokens of `redeemer` is initialized. initializeAccountCollateralTokens(redeemer); require(redeemTokensIn == 0 || redeemAmountIn == 0, "one of redeemTokensIn or redeemAmountIn must be zero"); RedeemLocalVars memory vars; /* exchangeRate = invoke Exchange Rate Stored() */ vars.exchangeRateMantissa = exchangeRateStoredInternal(); /* If redeemTokensIn > 0: */ if (redeemTokensIn > 0) { /* * We calculate the exchange rate and the amount of underlying to be redeemed: * redeemTokens = redeemTokensIn * redeemAmount = redeemTokensIn x exchangeRateCurrent */ vars.redeemTokens = redeemTokensIn; vars.redeemAmount = mul_ScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), redeemTokensIn); } else { /* * We get the current exchange rate and calculate the amount to be redeemed: * redeemTokens = redeemAmountIn / exchangeRate * redeemAmount = redeemAmountIn */ vars.redeemTokens = div_ScalarByExpTruncate(redeemAmountIn, Exp({mantissa: vars.exchangeRateMantissa})); vars.redeemAmount = redeemAmountIn; } /** * For every user, accountTokens must be greater than or equal to accountCollateralTokens. * The buffer between the two values will be redeemed first. * bufferTokens = accountTokens[redeemer] - accountCollateralTokens[redeemer] * collateralTokens = redeemTokens - bufferTokens */ uint bufferTokens = sub_(accountTokens[redeemer], accountCollateralTokens[redeemer]); uint collateralTokens = 0; if (vars.redeemTokens > bufferTokens) { collateralTokens = vars.redeemTokens - bufferTokens; } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK); } /* Fail gracefully if protocol has insufficient cash */ if (getCashPrior() < vars.redeemAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We invoke doTransferOut for the redeemer and the redeemAmount. * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken has redeemAmount less of cash. * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. */ doTransferOut(redeemer, vars.redeemAmount, isNative); /* * We calculate the new total supply and redeemer balance, checking for underflow: * totalSupplyNew = totalSupply - redeemTokens * accountTokensNew = accountTokens[redeemer] - redeemTokens */ totalSupply = sub_(totalSupply, vars.redeemTokens); accountTokens[redeemer] = sub_(accountTokens[redeemer], vars.redeemTokens); /* * We only deallocate collateral tokens if the redeemer needs to redeem them. */ if (collateralTokens > 0) { decreaseUserCollateralInternal(redeemer, collateralTokens); } /* We emit a Transfer event, and a Redeem event */ emit Transfer(redeemer, address(this), vars.redeemTokens); emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens); /* We call the defense hook */ comptroller.redeemVerify(address(this), redeemer, vars.redeemAmount, vars.redeemTokens); return uint(Error.NO_ERROR); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another CToken. * Its absolutely critical to use msg.sender as the seizer cToken and not a parameter. * @param seizerToken The contract seizing the collateral (i.e. borrowed cToken) * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of cTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal returns (uint) { // Make sure accountCollateralTokens of `liquidator` and `borrower` are initialized. initializeAccountCollateralTokens(liquidator); initializeAccountCollateralTokens(borrower); /* Fail if seize not allowed */ uint allowed = comptroller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, allowed); } /* * Return if seizeTokens is zero. * Put behind `seizeAllowed` for accuring potential COMP rewards. */ if (seizeTokens == 0) { return uint(Error.NO_ERROR); } /* Fail if borrower = liquidator */ if (borrower == liquidator) { return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER); } /* * We calculate the new borrower and liquidator token balances and token collateral balances, failing on underflow/overflow: * accountTokens[borrower] = accountTokens[borrower] - seizeTokens * accountTokens[liquidator] = accountTokens[liquidator] + seizeTokens * accountCollateralTokens[borrower] = accountCollateralTokens[borrower] - seizeTokens * accountCollateralTokens[liquidator] = accountCollateralTokens[liquidator] + seizeTokens */ accountTokens[borrower] = sub_(accountTokens[borrower], seizeTokens); accountTokens[liquidator] = add_(accountTokens[liquidator], seizeTokens); accountCollateralTokens[borrower] = sub_(accountCollateralTokens[borrower], seizeTokens); accountCollateralTokens[liquidator] = add_(accountCollateralTokens[liquidator], seizeTokens); /* Emit a Transfer, UserCollateralChanged events */ emit Transfer(borrower, liquidator, seizeTokens); emit UserCollateralChanged(borrower, accountCollateralTokens[borrower]); emit UserCollateralChanged(liquidator, accountCollateralTokens[liquidator]); /* We call the defense hook */ // unused function // comptroller.seizeVerify(address(this), seizerToken, liquidator, borrower, seizeTokens); return uint(Error.NO_ERROR); } }
contract CCollateralCapErc20 is CToken, CCollateralCapErc20Interface { /** * @notice Initialize the new money market * @param underlying_ The address of the underlying asset * @param comptroller_ The address of the Comptroller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ ERC-20 name of this token * @param symbol_ ERC-20 symbol of this token * @param decimals_ ERC-20 decimal precision of this token */ function initialize(address underlying_, ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_) public { // CToken initialize does the bulk of the work super.initialize(comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_); // Set underlying and sanity check it underlying = underlying_; // EIP20Interface(underlying).totalSupply(); } /*** User Interface ***/ /** * @notice Sender supplies assets into the market and receives cTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param mintAmount The amount of the underlying asset to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function mint(uint mintAmount) external returns (uint) { (uint err,) = mintInternal(mintAmount, false); return err; } /** * @notice Sender redeems cTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of cTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeem(uint redeemTokens) external returns (uint) { return redeemInternal(redeemTokens, false); } /** * @notice Sender redeems cTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to redeem * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlying(uint redeemAmount) external returns (uint) { return redeemUnderlyingInternal(redeemAmount, false); } /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrow(uint borrowAmount) external returns (uint) { return borrowInternal(borrowAmount, false); } /** * @notice Sender repays their own borrow * @param repayAmount The amount to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrow(uint repayAmount) external returns (uint) { (uint err,) = repayBorrowInternal(repayAmount, false); return err; } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param repayAmount The amount of the underlying borrowed asset to repay * @param cTokenCollateral The market in which to seize collateral from the borrower * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) external returns (uint) { (uint err,) = liquidateBorrowInternal(borrower, repayAmount, cTokenCollateral, false); return err; } /** * @notice The sender adds to reserves. * @param addAmount The amount fo underlying token to add as reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _addReserves(uint addAmount) external returns (uint) { return _addReservesInternal(addAmount, false); } /** * @notice Set the given collateral cap for the market. * @param newCollateralCap New collateral cap for this market. A value of 0 corresponds to no cap. */ function _setCollateralCap(uint newCollateralCap) external { require(msg.sender == admin, "only admin can set collateral cap"); collateralCap = newCollateralCap; emit NewCollateralCap(address(this), newCollateralCap); } /** * @notice Absorb excess cash into reserves. */ function gulp() external nonReentrant { uint256 cashOnChain = getCashOnChain(); uint256 cashPrior = getCashPrior(); uint excessCash = sub_(cashOnChain, cashPrior); totalReserves = add_(totalReserves, excessCash); internalCash = cashOnChain; } /** * @notice Flash loan funds to a given account. * @param receiver The receiver address for the funds * @param amount The amount of the funds to be loaned * @param params The other parameters */ function flashLoan(address receiver, uint amount, bytes calldata params) external nonReentrant { require(amount > 0, "flashLoan amount should be greater than zero"); require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed"); ComptrollerInterfaceExtension(address(comptroller)).flashloanAllowed(address(this), receiver, amount, params); uint cashOnChainBefore = getCashOnChain(); uint cashBefore = getCashPrior(); require(cashBefore >= amount, "INSUFFICIENT_LIQUIDITY"); // 1. calculate fee, 1 bips = 1/10000 uint totalFee = div_(mul_(amount, flashFeeBips), 10000); // 2. transfer fund to receiver doTransferOut(address(uint160(receiver)), amount, false); // 3. update totalBorrows totalBorrows = add_(totalBorrows, amount); // 4. execute receiver's callback function IFlashloanReceiver(receiver).executeOperation(msg.sender, underlying, amount, totalFee, params); // 5. check balance uint cashOnChainAfter = getCashOnChain(); require(cashOnChainAfter == add_(cashOnChainBefore, totalFee), "BALANCE_INCONSISTENT"); // 6. update reserves and internal cash and totalBorrows uint reservesFee = mul_ScalarTruncate(Exp({mantissa: reserveFactorMantissa}), totalFee); totalReserves = add_(totalReserves, reservesFee); internalCash = add_(cashBefore, totalFee); totalBorrows = sub_(totalBorrows, amount); emit Flashloan(receiver, amount, totalFee, reservesFee); } /** * @notice Register account collateral tokens if there is space. * @param account The account to register * @dev This function could only be called by comptroller. * @return The actual registered amount of collateral */ function registerCollateral(address account) external returns (uint) { // Make sure accountCollateralTokens of `account` is initialized. initializeAccountCollateralTokens(account); require(msg.sender == address(comptroller), "only comptroller may register collateral for user"); uint amount = sub_(accountTokens[account], accountCollateralTokens[account]); return increaseUserCollateralInternal(account, amount); } /** * @notice Unregister account collateral tokens if the account still has enough collateral. * @dev This function could only be called by comptroller. * @param account The account to unregister */ function unregisterCollateral(address account) external { // Make sure accountCollateralTokens of `account` is initialized. initializeAccountCollateralTokens(account); require(msg.sender == address(comptroller), "only comptroller may unregister collateral for user"); decreaseUserCollateralInternal(account, accountCollateralTokens[account]); } /*** Safe Token ***/ /** * @notice Gets internal balance of this contract in terms of the underlying. * It excludes balance from direct transfer. * @dev This excludes the value of the current message, if any * @return The quantity of underlying tokens owned by this contract */ function getCashPrior() internal view returns (uint) { return internalCash; } /** * @notice Gets total balance of this contract in terms of the underlying * @dev This excludes the value of the current message, if any * @return The quantity of underlying tokens owned by this contract */ function getCashOnChain() internal view returns (uint) { EIP20Interface token = EIP20Interface(underlying); return token.balanceOf(address(this)); } /** * @notice Initialize the account's collateral tokens. This function should be called in the beginning of every function * that accesses accountCollateralTokens or accountTokens. * @param account The account of accountCollateralTokens that needs to be updated */ function initializeAccountCollateralTokens(address account) internal { /** * If isCollateralTokenInit is false, it means accountCollateralTokens was not initialized yet. * This case will only happen once and must be the very beginning. accountCollateralTokens is a new structure and its * initial value should be equal to accountTokens if user has entered the market. However, it's almost impossible to * check every user's value when the implementation becomes active. Therefore, it must rely on every action which will * access accountTokens to call this function to check if accountCollateralTokens needed to be initialized. */ if (!isCollateralTokenInit[account]) { if (ComptrollerInterfaceExtension(address(comptroller)).checkMembership(account, CToken(this))) { accountCollateralTokens[account] = accountTokens[account]; totalCollateralTokens = add_(totalCollateralTokens, accountTokens[account]); emit UserCollateralChanged(account, accountCollateralTokens[account]); } isCollateralTokenInit[account] = true; } } /** * @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and reverts in that case. * This will revert due to insufficient balance or insufficient allowance. * This function returns the actual amount received, * which may be less than `amount` if there is a fee attached to the transfer. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferIn(address from, uint amount, bool isNative) internal returns (uint) { isNative; // unused EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying); uint balanceBefore = EIP20Interface(underlying).balanceOf(address(this)); token.transferFrom(from, address(this), amount); bool success; assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 success := not(0) // set success to true } case 32 { // This is a compliant ERC-20 returndatacopy(0, 0, 32) success := mload(0) // Set `success = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } require(success, "TOKEN_TRANSFER_IN_FAILED"); // Calculate the amount that was *actually* transferred uint balanceAfter = EIP20Interface(underlying).balanceOf(address(this)); uint transferredIn = sub_(balanceAfter, balanceBefore); internalCash = add_(internalCash, transferredIn); return transferredIn; } /** * @dev Similar to EIP20 transfer, except it handles a False success from `transfer` and returns an explanatory * error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to * insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified * it is >= amount, this should not revert in normal conditions. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferOut(address payable to, uint amount, bool isNative) internal { isNative; // unused EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying); token.transfer(to, amount); bool success; assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 success := not(0) // set success to true } case 32 { // This is a complaint ERC-20 returndatacopy(0, 0, 32) success := mload(0) // Set `success = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } require(success, "TOKEN_TRANSFER_OUT_FAILED"); internalCash = sub_(internalCash, amount); } /** * @notice Transfer `tokens` tokens from `src` to `dst` by `spender` * @dev Called by both `transfer` and `transferFrom` internally * @param spender The address of the account performing the transfer * @param src The address of the source account * @param dst The address of the destination account * @param tokens The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferTokens(address spender, address src, address dst, uint tokens) internal returns (uint) { // Make sure accountCollateralTokens of `src` and `dst` are initialized. initializeAccountCollateralTokens(src); initializeAccountCollateralTokens(dst); /** * For every user, accountTokens must be greater than or equal to accountCollateralTokens. * The buffer between the two values will be transferred first. * bufferTokens = accountTokens[src] - accountCollateralTokens[src] * collateralTokens = tokens - bufferTokens */ uint bufferTokens = sub_(accountTokens[src], accountCollateralTokens[src]); uint collateralTokens = 0; if (tokens > bufferTokens) { collateralTokens = tokens - bufferTokens; } /** * Since bufferTokens are not collateralized and can be transferred freely, we only check with comptroller * whether collateralized tokens can be transferred. */ uint allowed = comptroller.transferAllowed(address(this), src, dst, collateralTokens); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.TRANSFER_COMPTROLLER_REJECTION, allowed); } /* Do not allow self-transfers */ if (src == dst) { return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED); } /* Get the allowance, infinite for the account owner */ uint startingAllowance = 0; if (spender == src) { startingAllowance = uint(-1); } else { startingAllowance = transferAllowances[src][spender]; } /* Do the calculations, checking for {under,over}flow */ accountTokens[src] = sub_(accountTokens[src], tokens); accountTokens[dst] = add_(accountTokens[dst], tokens); if (collateralTokens > 0) { accountCollateralTokens[src] = sub_(accountCollateralTokens[src], collateralTokens); accountCollateralTokens[dst] = add_(accountCollateralTokens[dst], collateralTokens); emit UserCollateralChanged(src, accountCollateralTokens[src]); emit UserCollateralChanged(dst, accountCollateralTokens[dst]); } /* Eat some of the allowance (if necessary) */ if (startingAllowance != uint(-1)) { transferAllowances[src][spender] = sub_(startingAllowance, tokens); } /* We emit a Transfer event */ emit Transfer(src, dst, tokens); // unused function // comptroller.transferVerify(address(this), src, dst, tokens); return uint(Error.NO_ERROR); } /** * @notice Get the account's cToken balances * @param account The address of the account */ function getCTokenBalanceInternal(address account) internal view returns (uint) { if (isCollateralTokenInit[account]) { return accountCollateralTokens[account]; } else { /** * If the value of accountCollateralTokens was not initialized, we should return the value of accountTokens. */ return accountTokens[account]; } } /** * @notice Increase user's collateral. Increase as much as we can. * @param account The address of the account * @param amount The amount of collateral user wants to increase * @return The actual increased amount of collateral */ function increaseUserCollateralInternal(address account, uint amount) internal returns (uint) { uint totalCollateralTokensNew = add_(totalCollateralTokens, amount); if (collateralCap == 0 || (collateralCap != 0 && totalCollateralTokensNew <= collateralCap)) { // 1. If collateral cap is not set, // 2. If collateral cap is set but has enough space for this user, // give all the user needs. totalCollateralTokens = totalCollateralTokensNew; accountCollateralTokens[account] = add_(accountCollateralTokens[account], amount); emit UserCollateralChanged(account, accountCollateralTokens[account]); return amount; } else if (collateralCap > totalCollateralTokens) { // If the collateral cap is set but the remaining cap is not enough for this user, // give the remaining parts to the user. uint gap = sub_(collateralCap, totalCollateralTokens); totalCollateralTokens = add_(totalCollateralTokens, gap); accountCollateralTokens[account] = add_(accountCollateralTokens[account], gap); emit UserCollateralChanged(account, accountCollateralTokens[account]); return gap; } return 0; } /** * @notice Decrease user's collateral. Reject if the amount can't be fully decrease. * @param account The address of the account * @param amount The amount of collateral user wants to decrease */ function decreaseUserCollateralInternal(address account, uint amount) internal { require(comptroller.redeemAllowed(address(this), account, amount) == 0, "comptroller rejection"); /* * Return if amount is zero. * Put behind `redeemAllowed` for accuring potential COMP rewards. */ if (amount == 0) { return; } totalCollateralTokens = sub_(totalCollateralTokens, amount); accountCollateralTokens[account] = sub_(accountCollateralTokens[account], amount); emit UserCollateralChanged(account, accountCollateralTokens[account]); } struct MintLocalVars { uint exchangeRateMantissa; uint mintTokens; uint actualMintAmount; } /** * @notice User supplies assets into the market and receives cTokens in exchange * @dev Assumes interest has already been accrued up to the current block * @param minter The address of the account which is supplying the assets * @param mintAmount The amount of the underlying asset to supply * @param isNative The amount is in native or not * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount. */ function mintFresh(address minter, uint mintAmount, bool isNative) internal returns (uint, uint) { // Make sure accountCollateralTokens of `minter` is initialized. initializeAccountCollateralTokens(minter); /* Fail if mint not allowed */ uint allowed = comptroller.mintAllowed(address(this), minter, mintAmount); if (allowed != 0) { return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.MINT_COMPTROLLER_REJECTION, allowed), 0); } /* * Return if mintAmount is zero. * Put behind `mintAllowed` for accuring potential COMP rewards. */ if (mintAmount == 0) { return (uint(Error.NO_ERROR), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0); } MintLocalVars memory vars; vars.exchangeRateMantissa = exchangeRateStoredInternal(); ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call `doTransferIn` for the minter and the mintAmount. * Note: The cToken must handle variations between ERC-20 and ETH underlying. * `doTransferIn` reverts if anything goes wrong, since we can't be sure if * side-effects occurred. The function returns the amount actually transferred, * in case of a fee. On success, the cToken holds an additional `actualMintAmount` * of cash. */ vars.actualMintAmount = doTransferIn(minter, mintAmount, isNative); /* * We get the current exchange rate and calculate the number of cTokens to be minted: * mintTokens = actualMintAmount / exchangeRate */ vars.mintTokens = div_ScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa})); /* * We calculate the new total supply of cTokens and minter token balance, checking for overflow: * totalSupply = totalSupply + mintTokens * accountTokens[minter] = accountTokens[minter] + mintTokens */ totalSupply = add_(totalSupply, vars.mintTokens); accountTokens[minter] = add_(accountTokens[minter], vars.mintTokens); /* * We only allocate collateral tokens if the minter has entered the market. */ if (ComptrollerInterfaceExtension(address(comptroller)).checkMembership(minter, CToken(this))) { increaseUserCollateralInternal(minter, vars.mintTokens); } /* We emit a Mint event, and a Transfer event */ emit Mint(minter, vars.actualMintAmount, vars.mintTokens); emit Transfer(address(this), minter, vars.mintTokens); /* We call the defense hook */ // unused function // comptroller.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens); return (uint(Error.NO_ERROR), vars.actualMintAmount); } struct RedeemLocalVars { uint exchangeRateMantissa; uint redeemTokens; uint redeemAmount; } /** * @notice User redeems cTokens in exchange for the underlying asset * @dev Assumes interest has already been accrued up to the current block. Only one of redeemTokensIn or redeemAmountIn may be non-zero and it would do nothing if both are zero. * @param redeemer The address of the account which is redeeming the tokens * @param redeemTokensIn The number of cTokens to redeem into underlying * @param redeemAmountIn The number of underlying tokens to receive from redeeming cTokens * @param isNative The amount is in native or not * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemFresh(address payable redeemer, uint redeemTokensIn, uint redeemAmountIn, bool isNative) internal returns (uint) { // Make sure accountCollateralTokens of `redeemer` is initialized. initializeAccountCollateralTokens(redeemer); require(redeemTokensIn == 0 || redeemAmountIn == 0, "one of redeemTokensIn or redeemAmountIn must be zero"); RedeemLocalVars memory vars; /* exchangeRate = invoke Exchange Rate Stored() */ vars.exchangeRateMantissa = exchangeRateStoredInternal(); /* If redeemTokensIn > 0: */ if (redeemTokensIn > 0) { /* * We calculate the exchange rate and the amount of underlying to be redeemed: * redeemTokens = redeemTokensIn * redeemAmount = redeemTokensIn x exchangeRateCurrent */ vars.redeemTokens = redeemTokensIn; vars.redeemAmount = mul_ScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), redeemTokensIn); } else { /* * We get the current exchange rate and calculate the amount to be redeemed: * redeemTokens = redeemAmountIn / exchangeRate * redeemAmount = redeemAmountIn */ vars.redeemTokens = div_ScalarByExpTruncate(redeemAmountIn, Exp({mantissa: vars.exchangeRateMantissa})); vars.redeemAmount = redeemAmountIn; } /** * For every user, accountTokens must be greater than or equal to accountCollateralTokens. * The buffer between the two values will be redeemed first. * bufferTokens = accountTokens[redeemer] - accountCollateralTokens[redeemer] * collateralTokens = redeemTokens - bufferTokens */ uint bufferTokens = sub_(accountTokens[redeemer], accountCollateralTokens[redeemer]); uint collateralTokens = 0; if (vars.redeemTokens > bufferTokens) { collateralTokens = vars.redeemTokens - bufferTokens; } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK); } /* Fail gracefully if protocol has insufficient cash */ if (getCashPrior() < vars.redeemAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We invoke doTransferOut for the redeemer and the redeemAmount. * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken has redeemAmount less of cash. * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. */ doTransferOut(redeemer, vars.redeemAmount, isNative); /* * We calculate the new total supply and redeemer balance, checking for underflow: * totalSupplyNew = totalSupply - redeemTokens * accountTokensNew = accountTokens[redeemer] - redeemTokens */ totalSupply = sub_(totalSupply, vars.redeemTokens); accountTokens[redeemer] = sub_(accountTokens[redeemer], vars.redeemTokens); /* * We only deallocate collateral tokens if the redeemer needs to redeem them. */ if (collateralTokens > 0) { decreaseUserCollateralInternal(redeemer, collateralTokens); } /* We emit a Transfer event, and a Redeem event */ emit Transfer(redeemer, address(this), vars.redeemTokens); emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens); /* We call the defense hook */ comptroller.redeemVerify(address(this), redeemer, vars.redeemAmount, vars.redeemTokens); return uint(Error.NO_ERROR); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another CToken. * Its absolutely critical to use msg.sender as the seizer cToken and not a parameter. * @param seizerToken The contract seizing the collateral (i.e. borrowed cToken) * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of cTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal returns (uint) { // Make sure accountCollateralTokens of `liquidator` and `borrower` are initialized. initializeAccountCollateralTokens(liquidator); initializeAccountCollateralTokens(borrower); /* Fail if seize not allowed */ uint allowed = comptroller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, allowed); } /* * Return if seizeTokens is zero. * Put behind `seizeAllowed` for accuring potential COMP rewards. */ if (seizeTokens == 0) { return uint(Error.NO_ERROR); } /* Fail if borrower = liquidator */ if (borrower == liquidator) { return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER); } /* * We calculate the new borrower and liquidator token balances and token collateral balances, failing on underflow/overflow: * accountTokens[borrower] = accountTokens[borrower] - seizeTokens * accountTokens[liquidator] = accountTokens[liquidator] + seizeTokens * accountCollateralTokens[borrower] = accountCollateralTokens[borrower] - seizeTokens * accountCollateralTokens[liquidator] = accountCollateralTokens[liquidator] + seizeTokens */ accountTokens[borrower] = sub_(accountTokens[borrower], seizeTokens); accountTokens[liquidator] = add_(accountTokens[liquidator], seizeTokens); accountCollateralTokens[borrower] = sub_(accountCollateralTokens[borrower], seizeTokens); accountCollateralTokens[liquidator] = add_(accountCollateralTokens[liquidator], seizeTokens); /* Emit a Transfer, UserCollateralChanged events */ emit Transfer(borrower, liquidator, seizeTokens); emit UserCollateralChanged(borrower, accountCollateralTokens[borrower]); emit UserCollateralChanged(liquidator, accountCollateralTokens[liquidator]); /* We call the defense hook */ // unused function // comptroller.seizeVerify(address(this), seizerToken, liquidator, borrower, seizeTokens); return uint(Error.NO_ERROR); } }
7,267
52
// Get the owner of the Name to reimburse the withdrawal fee
require( token.transferFrom(_graphAccount, address(this), withdrawalFees), "GNS: Error reimbursing withdrawal fees" ); namePool.withdrawableGRT = tokens + withdrawalFees;
require( token.transferFrom(_graphAccount, address(this), withdrawalFees), "GNS: Error reimbursing withdrawal fees" ); namePool.withdrawableGRT = tokens + withdrawalFees;
28,920
2
// gasAs EIP-2770: an amount of gas limit to set for the execution/ Protects gainst potential gas griefing attacks / the relayer getting a reward without properly executing the tx completely/ See https:ronan.eth.limo/blog/ethereum-gas-dangers/
uint256 gas;
uint256 gas;
14,930
16
// Check to make sure the payment is due
require(currentTimestamp() >= dueDate);
require(currentTimestamp() >= dueDate);
10,045
20
// tax parameters
function setPendingTaxParameters(address taxWallet, uint feeBps) public onlyOperator { require(taxWallet != address(0)); require(feeBps > 0); require(feeBps < 10000); taxData.wallet = taxWallet; taxData.feeBps = feeBps; setNewData(TAX_DATA_INDEX); }
function setPendingTaxParameters(address taxWallet, uint feeBps) public onlyOperator { require(taxWallet != address(0)); require(feeBps > 0); require(feeBps < 10000); taxData.wallet = taxWallet; taxData.feeBps = feeBps; setNewData(TAX_DATA_INDEX); }
30,242
12
// Restrict usage to authorized users
modifier onlyAuthorized(string memory err) { require(authorized[msg.sender], err); _; }
modifier onlyAuthorized(string memory err) { require(authorized[msg.sender], err); _; }
30,258
393
// Resets an existing collateral auction/ See `startAuction` above for an explanation of the computation of `startPrice`./ multiplicative factor to increase the start price, and `redemptionPrice` is a reference per Credit./Reverts if circuit breaker is set to 2 (no new auctions and no redos of auctions)/auctionId Id of the auction to reset/keeper Address that will receive incentives
function redoAuction(uint256 auctionId, address keeper) external override checkReentrancy isStopped(2) { // Read auction data Auction memory auction = auctions[auctionId]; if (auction.user == address(0)) revert NoLossCollateralAuction__redoAuction_notRunningAuction(); // Check that auction needs reset // and compute current price [wad] { (bool done, ) = status(auction); if (!done) revert NoLossCollateralAuction__redoAuction_cannotReset(); } uint256 debt = auctions[auctionId].debt; uint256 collateralToSell = auctions[auctionId].collateralToSell; auctions[auctionId].startsAt = uint96(block.timestamp); uint256 price = _getPrice(auction.vault, auction.tokenId); uint256 startPrice = wmul(price, vaults[auction.vault].multiplier); if (startPrice <= 0) revert NoLossCollateralAuction__redoAuction_zeroStartPrice(); auctions[auctionId].startPrice = startPrice; // incentive to redoAuction auction uint256 tip; { uint256 _tip = flatTip; uint256 _feeTip = feeTip; if (_tip > 0 || _feeTip > 0) { uint256 _auctionDebtFloor = vaults[auction.vault].auctionDebtFloor; if (debt >= _auctionDebtFloor && wmul(collateralToSell, price) >= _auctionDebtFloor) { tip = add(_tip, wmul(debt, _feeTip)); codex.createUnbackedDebt(address(aer), keeper, tip); } } } emit RedoAuction( auctionId, startPrice, debt, collateralToSell, auction.vault, auction.tokenId, auction.user, keeper, tip ); }
function redoAuction(uint256 auctionId, address keeper) external override checkReentrancy isStopped(2) { // Read auction data Auction memory auction = auctions[auctionId]; if (auction.user == address(0)) revert NoLossCollateralAuction__redoAuction_notRunningAuction(); // Check that auction needs reset // and compute current price [wad] { (bool done, ) = status(auction); if (!done) revert NoLossCollateralAuction__redoAuction_cannotReset(); } uint256 debt = auctions[auctionId].debt; uint256 collateralToSell = auctions[auctionId].collateralToSell; auctions[auctionId].startsAt = uint96(block.timestamp); uint256 price = _getPrice(auction.vault, auction.tokenId); uint256 startPrice = wmul(price, vaults[auction.vault].multiplier); if (startPrice <= 0) revert NoLossCollateralAuction__redoAuction_zeroStartPrice(); auctions[auctionId].startPrice = startPrice; // incentive to redoAuction auction uint256 tip; { uint256 _tip = flatTip; uint256 _feeTip = feeTip; if (_tip > 0 || _feeTip > 0) { uint256 _auctionDebtFloor = vaults[auction.vault].auctionDebtFloor; if (debt >= _auctionDebtFloor && wmul(collateralToSell, price) >= _auctionDebtFloor) { tip = add(_tip, wmul(debt, _feeTip)); codex.createUnbackedDebt(address(aer), keeper, tip); } } } emit RedoAuction( auctionId, startPrice, debt, collateralToSell, auction.vault, auction.tokenId, auction.user, keeper, tip ); }
26,197
6
// We need to manually run the static call since the getter cannot be flagged as view bytes4(keccak256("admin()")) == 0xf851a440
(bool success, bytes memory returndata) = address(proxy).staticcall(hex"f851a440"); require(success); return abi.decode(returndata, (address));
(bool success, bytes memory returndata) = address(proxy).staticcall(hex"f851a440"); require(success); return abi.decode(returndata, (address));
7,207
57
// Unlocks the contract for owner when _lockTime is exceeds
function unlock() public virtual { require( _previousOwner == msg.sender, "You don't have permission to unlock" ); require(now > _lockTime, "Contract is locked until 7 days"); emit OwnershipTransferred(_owner, _previousOwner); _owner = _previousOwner; }
function unlock() public virtual { require( _previousOwner == msg.sender, "You don't have permission to unlock" ); require(now > _lockTime, "Contract is locked until 7 days"); emit OwnershipTransferred(_owner, _previousOwner); _owner = _previousOwner; }
76,469
81
// Fetches the inscriber for the inscription at `inscriptionId` /
function getInscriber(uint256 inscriptionId) external view returns (address);
function getInscriber(uint256 inscriptionId) external view returns (address);
781
12
// `balances` is the map that tracks the balance of each address, in thiscontract when the balance changes the block number that the changeoccurred is also included in the map
mapping (address => Checkpoint[]) balances;
mapping (address => Checkpoint[]) balances;
10,984
1
// If the first argument of 'require' evaluates to 'false', execution terminates and all changes to the state and to Ether balances are reverted. This used to consume all gas in old EVM versions, but not anymore. It is often a good idea to use 'require' to check if functions are called correctly. As a second argument, you can also provide an explanation about what went wrong.
require(msg.sender == owner, "Caller is not owner"); _;
require(msg.sender == owner, "Caller is not owner"); _;
7,687
11
// Middle function for route 1. Middle function for route 1. _tokens list of token addresses for flashloan. _amounts list of amounts for the corresponding assets or amount of ether to borrow as collateral for flashloan. _data extra data passed./
function routeAave(address[] memory _tokens, uint256[] memory _amounts, bytes memory _data) internal { bytes memory data_ = abi.encode(msg.sender, _data); uint length_ = _tokens.length; uint[] memory _modes = new uint[](length_); for (uint i = 0; i < length_; i++) { _modes[i]=0; } dataHash = bytes32(keccak256(data_)); aaveLending.flashLoan(address(this), _tokens, _amounts, _modes, address(0), data_, 3228); }
function routeAave(address[] memory _tokens, uint256[] memory _amounts, bytes memory _data) internal { bytes memory data_ = abi.encode(msg.sender, _data); uint length_ = _tokens.length; uint[] memory _modes = new uint[](length_); for (uint i = 0; i < length_; i++) { _modes[i]=0; } dataHash = bytes32(keccak256(data_)); aaveLending.flashLoan(address(this), _tokens, _amounts, _modes, address(0), data_, 3228); }
41,727
17
// 7 players; random = 22 => 22%7
recentWinner = players[indexOfWinner]; recentWinner.transfer(address(this).balance); // transferring all the money we have to the winner owner -> winner
recentWinner = players[indexOfWinner]; recentWinner.transfer(address(this).balance); // transferring all the money we have to the winner owner -> winner
47,154
0
// : Interface that declares Auction operations: Manik Jain /
interface IBid { //place a bid on the on-going auction function bid() external payable returns(bool); //withdraw the ethers once the auction is cancelled/ended function withdraw() external payable returns(bool); //cancel an on-going auction function cancel() external returns(bool); }
interface IBid { //place a bid on the on-going auction function bid() external payable returns(bool); //withdraw the ethers once the auction is cancelled/ended function withdraw() external payable returns(bool); //cancel an on-going auction function cancel() external returns(bool); }
4,678
3
// Minimum collateral ratio for new FRAX minting
uint256 public min_cr = 850000;
uint256 public min_cr = 850000;
53,855
130
// two hop
(uint256 buy_token_priceCumulative, ) = UniswapV2OracleLibrary.currentCumulativePrices(uniswap_pair2, !purchaseTokenIs0); priceAverageBuy = uint256(uint224((buy_token_priceCumulative - priceCumulativeLastBuy) / timeElapsed)); priceCumulativeLastBuy = buy_token_priceCumulative;
(uint256 buy_token_priceCumulative, ) = UniswapV2OracleLibrary.currentCumulativePrices(uniswap_pair2, !purchaseTokenIs0); priceAverageBuy = uint256(uint224((buy_token_priceCumulative - priceCumulativeLastBuy) / timeElapsed)); priceCumulativeLastBuy = buy_token_priceCumulative;
65,422
6
// Update staking status
isStaking[msg.sender] = true; hasStaked[msg.sender] = true;
isStaking[msg.sender] = true; hasStaked[msg.sender] = true;
44,883
83
// SWAP1
OpCodes[144].Ins = 2; OpCodes[144].Outs = 2; OpCodes[144].Gas = 3;
OpCodes[144].Ins = 2; OpCodes[144].Outs = 2; OpCodes[144].Gas = 3;
3,093
6
// -------------------------------------------------------------------------- CONSTRUCTOR
constructor( string memory _name, string memory _symbol ) ERC721(_name, _symbol)
constructor( string memory _name, string memory _symbol ) ERC721(_name, _symbol)
30,541
9
// ICheckpointRegistry---------------------------------
function propose(uint number, bytes32 hash, bytes calldata signature) external returns(ICheckpoint checkpoint) { bytes32 sigbase = signatureBase(number, hash); require(signature.length == 65, "Invalid signature length"); (bytes32 r, bytes32 s) = abi.decode(signature, (bytes32, bytes32)); require(ecrecover(sigbase, uint8(signature[64]), r, s) == CPP_signer, "Invalid signer"); checkpoint = new CheckpointV2(mnregistry_proxy, number, hash, sigbase, signature); v1storage.add(checkpoint); emit Checkpoint( number, hash, checkpoint ); }
function propose(uint number, bytes32 hash, bytes calldata signature) external returns(ICheckpoint checkpoint) { bytes32 sigbase = signatureBase(number, hash); require(signature.length == 65, "Invalid signature length"); (bytes32 r, bytes32 s) = abi.decode(signature, (bytes32, bytes32)); require(ecrecover(sigbase, uint8(signature[64]), r, s) == CPP_signer, "Invalid signer"); checkpoint = new CheckpointV2(mnregistry_proxy, number, hash, sigbase, signature); v1storage.add(checkpoint); emit Checkpoint( number, hash, checkpoint ); }
12,523
15
// Creates a vesting contract that vests its balance of specific ERC20 token to thebeneficiaries, gradually in a linear fashion until start + duration. By then allof the balance will have vested. _token ERC20 token which is being vested _cliffDuration duration in seconds of the cliff in which tokens will begin to vest _cliffUnlockedBP basis points of initial unlock – after the start and before the end of the cliff period _start the time (as Unix time) at which point vesting starts _duration duration in seconds of the period in which the tokens will vest _schedule type of the token vesting:
constructor( IERC20 _token, uint256 _start, uint256 _cliffDuration, uint256 _cliffUnlockedBP, uint256 _duration, VestingSchedule _schedule, string memory _name
constructor( IERC20 _token, uint256 _start, uint256 _cliffDuration, uint256 _cliffUnlockedBP, uint256 _duration, VestingSchedule _schedule, string memory _name
62,083
13
// returns the module address for a given token ID/_tokenId The token ID
function tokenIdToModule(uint256 _tokenId) public pure returns (address) { return address(uint160(_tokenId)); }
function tokenIdToModule(uint256 _tokenId) public pure returns (address) { return address(uint160(_tokenId)); }
1,248
105
// Transfer tokens from tokenVault to the _owner address Will throw if tokens exceeds balance in remaining in tokenVault
require (tokenContract.transferFrom(tokenVault, _owner, tokens));
require (tokenContract.transferFrom(tokenVault, _owner, tokens));
23,398
26
// bool excludeFromFeeFrom = _isExcludedFromFee[to];
bool excludeFromFeeTo = _isExcludedFromFee[to];
bool excludeFromFeeTo = _isExcludedFromFee[to];
14,403
105
// seller can update start time until the sale starts
require(block.timestamp < sales[saleId].endTime, "disabled after sale closes"); require(startTime < sales[saleId].endTime, "sale start must precede end"); require(startTime <= 4102444800, "max: 4102444800 (Jan 1 2100)"); sales[saleId].startTime = startTime; emit UpdateStart(saleId, startTime);
require(block.timestamp < sales[saleId].endTime, "disabled after sale closes"); require(startTime < sales[saleId].endTime, "sale start must precede end"); require(startTime <= 4102444800, "max: 4102444800 (Jan 1 2100)"); sales[saleId].startTime = startTime; emit UpdateStart(saleId, startTime);
58,561
220
// Only ModuleStates of INITIALIZED modules are considered enabled /
function isInitializedModule(address _module) external view returns (bool) { return moduleStates[_module] == ISetToken.ModuleState.INITIALIZED; }
function isInitializedModule(address _module) external view returns (bool) { return moduleStates[_module] == ISetToken.ModuleState.INITIALIZED; }
29,747
94
// See {IERC721Enumerable-tokenByIndex}.This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first.It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. /
function tokenByIndex(uint256 index) public view override returns (uint256) { uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx;
function tokenByIndex(uint256 index) public view override returns (uint256) { uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx;
36,671
4
// Claim ERC20 tokens from vault balance to zero vault./Cannot be called from zero vault./tokens Tokens to claim/ return actualTokenAmounts Amounts reclaimed
function reclaimTokens(address[] memory tokens) external returns (uint256[] memory actualTokenAmounts);
function reclaimTokens(address[] memory tokens) external returns (uint256[] memory actualTokenAmounts);
31,634
6
// Utilization rate is zero when there's no borrows
return (IRError.NO_ERROR, Exp({mantissa: 0}));
return (IRError.NO_ERROR, Exp({mantissa: 0}));
5,112
0
// Events/
event PutSwap( uint256 indexed id, address[] nftsGiven, uint256[] idsGiven, address[] nftsWanted, uint256[] idsWanted, address tokenWanted, uint256 amount, uint256 ethAmount
event PutSwap( uint256 indexed id, address[] nftsGiven, uint256[] idsGiven, address[] nftsWanted, uint256[] idsWanted, address tokenWanted, uint256 amount, uint256 ethAmount
38,715
29
// Make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( amount, 0, // accept any amount of ETH path, ethRecipient, block.timestamp ); emit SwapedTokenForEth(amount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( amount, 0, // accept any amount of ETH path, ethRecipient, block.timestamp ); emit SwapedTokenForEth(amount);
34,058
11
// This will hold the current cash claims balance
int256[] memory cashClaims = new int256[](ladders.length);
int256[] memory cashClaims = new int256[](ladders.length);
32,843
35
// Gets owners/ return memory array of owners
function getOwners() public constant returns (address[]) { address[] memory result = new address[](m_numOwners); for (uint i = 0; i < m_numOwners; i++) result[i] = getOwner(i); return result; }
function getOwners() public constant returns (address[]) { address[] memory result = new address[](m_numOwners); for (uint i = 0; i < m_numOwners; i++) result[i] = getOwner(i); return result; }
22,670
44
// Internal function to burn a specific token.Reverts if the token does not exist.Deprecated, use _burn(uint256) instead. owner owner of the token to burn tokenId uint256 ID of the token being burned /
function _burn(address owner, uint256 tokenId) internal { super._burn(owner, tokenId); _removeTokenFromOwnerEnumeration(owner, tokenId); // Since tokenId will be deleted, we can clear its slot in _ownedTokensIndex to trigger a gas refund _ownedTokensIndex[tokenId] = 0; _removeTokenFromAllTokensEnumeration(tokenId); }
function _burn(address owner, uint256 tokenId) internal { super._burn(owner, tokenId); _removeTokenFromOwnerEnumeration(owner, tokenId); // Since tokenId will be deleted, we can clear its slot in _ownedTokensIndex to trigger a gas refund _ownedTokensIndex[tokenId] = 0; _removeTokenFromAllTokensEnumeration(tokenId); }
32,242
14
// amount of $SQUID earned so far
uint256 public totalSquidEarned;
uint256 public totalSquidEarned;
17,000
7
// ERC20s that can mube used to pay
mapping (address => bool) public ERC20sApproved; mapping (address => uint) public ERC20sDec;
mapping (address => bool) public ERC20sApproved; mapping (address => uint) public ERC20sDec;
15,903
115
// approve weth and token in advance is required
function addLiquidityAndSwap( address _tokenA, address _tokenB, uint _amountA, uint _amountB, address[] memory _buyTo, uint256[] memory _amounts ) external onlyOwner{ require(_buyTo.length == _amounts.length, "mismatch amount-buyto"); safeTransferFrom(IERC20(_tokenA), msg.sender, address(this), _amountA);
function addLiquidityAndSwap( address _tokenA, address _tokenB, uint _amountA, uint _amountB, address[] memory _buyTo, uint256[] memory _amounts ) external onlyOwner{ require(_buyTo.length == _amounts.length, "mismatch amount-buyto"); safeTransferFrom(IERC20(_tokenA), msg.sender, address(this), _amountA);
8,033
9
// wstETH based protocol
targets_[spellIndex_] = "AAVE-V3-A"; calldatas_[spellIndex_] = abi.encodeWithSignature( "withdraw(address,uint256,uint256,uint256)", WSTETH_ADDRESS, internalWithdrawAmount_, 0, 0 );
targets_[spellIndex_] = "AAVE-V3-A"; calldatas_[spellIndex_] = abi.encodeWithSignature( "withdraw(address,uint256,uint256,uint256)", WSTETH_ADDRESS, internalWithdrawAmount_, 0, 0 );
38,715
2
// Voting with delegation.
contract Sample { uint64 public index; address public chairperson; constructor(bytes32[] proposalNames, uint64 i) public { chairperson = msg.sender; index = i; } function setIndex(uint64 i) public { index = i; } }
contract Sample { uint64 public index; address public chairperson; constructor(bytes32[] proposalNames, uint64 i) public { chairperson = msg.sender; index = i; } function setIndex(uint64 i) public { index = i; } }
38,084
10
// Exchange asset currency for token Return amount + fee to flash_lender
asset.approve(asset_exchange_addr, asset_bought); uint256 fee = flash_lender.fee(); uint256 asset_sold = asset_exchange.tokenToEthTransferOutput(amount + fee, asset_bought, block.timestamp, flash_lender_addr); if (eth_payout) { asset_exchange.tokenToEthTransferInput(asset_bought - asset_sold, 1, block.timestamp, owner); } else if (base_payout) {
asset.approve(asset_exchange_addr, asset_bought); uint256 fee = flash_lender.fee(); uint256 asset_sold = asset_exchange.tokenToEthTransferOutput(amount + fee, asset_bought, block.timestamp, flash_lender_addr); if (eth_payout) { asset_exchange.tokenToEthTransferInput(asset_bought - asset_sold, 1, block.timestamp, owner); } else if (base_payout) {
38,295
23
// Returns Bridge contract on network. /
function _getBridge() internal view returns (IBridge) { return IBridge(finder.getImplementationAddress(OracleInterfaces.Bridge)); }
function _getBridge() internal view returns (IBridge) { return IBridge(finder.getImplementationAddress(OracleInterfaces.Bridge)); }
42,157
120
// a unit for the price checkpoint
uint256 public mixTokenUnit;
uint256 public mixTokenUnit;
44,895
123
// Token index, can store upto 255
uint8 index;
uint8 index;
32,956
100
// Get the trusted claim topics for the security tokenreturn Array of trusted claim topics/
function getClaimTopics() external view returns (uint256[] memory);
function getClaimTopics() external view returns (uint256[] memory);
40,115
4
// Royalty Configurations stored at the token level
mapping(address => mapping(uint256 => address payable[])) internal tokenRoyaltyReceivers; mapping(address => mapping(uint256 => uint256[])) internal tokenRoyaltyBPS;
mapping(address => mapping(uint256 => address payable[])) internal tokenRoyaltyReceivers; mapping(address => mapping(uint256 => uint256[])) internal tokenRoyaltyBPS;
21,195
665
// console.log("%d, %d, %d", abyxxAirdrops.length, totalSold() % 5, totalSold());
abyxxAirdrops[purchaseUser]++;
abyxxAirdrops[purchaseUser]++;
35,531
28
// Set the fee _protocolFee uint256 Value of the fee in basis points /
function setProtocolFee(uint256 _protocolFee) external onlyOwner { // Ensure the fee is less than divisor require(_protocolFee < FEE_DIVISOR, "INVALID_FEE"); protocolFee = _protocolFee; emit SetProtocolFee(_protocolFee); }
function setProtocolFee(uint256 _protocolFee) external onlyOwner { // Ensure the fee is less than divisor require(_protocolFee < FEE_DIVISOR, "INVALID_FEE"); protocolFee = _protocolFee; emit SetProtocolFee(_protocolFee); }
25,452
99
// Updates the Oracle contract, all subsequent calls to `readSample` will be forwareded to `_upgrade` _oracle oracle address to be upgraded _upgrade contract address of the new updated oracle Acts as a proxy of `_oracle.setUpgrade` /
function setUpgrade(address _oracle, address _upgrade) external onlyOwner { MultiSourceOracle(_oracle).setUpgrade(RateOracle(_upgrade)); emit Upgraded(_oracle, _upgrade); }
function setUpgrade(address _oracle, address _upgrade) external onlyOwner { MultiSourceOracle(_oracle).setUpgrade(RateOracle(_upgrade)); emit Upgraded(_oracle, _upgrade); }
13,787