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
139
// res += val(coefficients[0] + coefficients[1]adjustments[0]).
res := addmod(res, mulmod(val, add(/*coefficients[0]*/ mload(0x440), mulmod(/*coefficients[1]*/ mload(0x460),
res := addmod(res, mulmod(val, add(/*coefficients[0]*/ mload(0x440), mulmod(/*coefficients[1]*/ mload(0x460),
56,625
62
// cannot have been invoked before
require(!isFinalized);
require(!isFinalized);
4,437
27
// returns the number of pools
function poolLength() external returns (uint256);
function poolLength() external returns (uint256);
27,322
57
// % more for the referrer
uint16 affiliate_get;
uint16 affiliate_get;
4,841
35
// TODO: finalize auction
_activeAuctions = _activeAuctions.sub(1);
_activeAuctions = _activeAuctions.sub(1);
45,421
306
// Mints the vault shares to the msg.sender amount is the amount of `asset` deposited /
function _deposit(uint256 amount) private { uint256 totalWithDepositedAmount = totalBalance(); require(totalWithDepositedAmount < cap, "Cap exceeded"); require( totalWithDepositedAmount >= MINIMUM_SUPPLY, "Insufficient asset balance" ); // amount needs to be subtracted from totalBalance because it has already been // added to it from either IWETH.deposit and IERC20.safeTransferFrom uint256 total = totalWithDepositedAmount.sub(amount); uint256 shareSupply = totalSupply(); // Following the pool share calculation from Alpha Homora: // solhint-disable-next-line // https://github.com/AlphaFinanceLab/alphahomora/blob/340653c8ac1e9b4f23d5b81e61307bf7d02a26e8/contracts/5/Bank.sol#L104 uint256 share = shareSupply == 0 ? amount : amount.mul(shareSupply).div(total); require( shareSupply.add(share) >= MINIMUM_SUPPLY, "Insufficient share supply" ); emit Deposit(msg.sender, amount, share); _mint(msg.sender, share); }
function _deposit(uint256 amount) private { uint256 totalWithDepositedAmount = totalBalance(); require(totalWithDepositedAmount < cap, "Cap exceeded"); require( totalWithDepositedAmount >= MINIMUM_SUPPLY, "Insufficient asset balance" ); // amount needs to be subtracted from totalBalance because it has already been // added to it from either IWETH.deposit and IERC20.safeTransferFrom uint256 total = totalWithDepositedAmount.sub(amount); uint256 shareSupply = totalSupply(); // Following the pool share calculation from Alpha Homora: // solhint-disable-next-line // https://github.com/AlphaFinanceLab/alphahomora/blob/340653c8ac1e9b4f23d5b81e61307bf7d02a26e8/contracts/5/Bank.sol#L104 uint256 share = shareSupply == 0 ? amount : amount.mul(shareSupply).div(total); require( shareSupply.add(share) >= MINIMUM_SUPPLY, "Insufficient share supply" ); emit Deposit(msg.sender, amount, share); _mint(msg.sender, share); }
48,935
117
// constructor/_mmLib address for the deployed elipse market maker contract/_clnAddress address for the deployed CLN ERC20 token
function IssuanceFactory(address _mmLib, address _clnAddress) public CurrencyFactory(_mmLib, _clnAddress) { CLNTotalSupply = ERC20(_clnAddress).totalSupply(); PRECISION = IEllipseMarketMaker(_mmLib).PRECISION(); }
function IssuanceFactory(address _mmLib, address _clnAddress) public CurrencyFactory(_mmLib, _clnAddress) { CLNTotalSupply = ERC20(_clnAddress).totalSupply(); PRECISION = IEllipseMarketMaker(_mmLib).PRECISION(); }
32,968
171
// update funding rate = premiumFraction / twapIndexPrice
updateFundingRate(premiumFraction, underlyingPrice);
updateFundingRate(premiumFraction, underlyingPrice);
29,830
16
// Make sure token balance > 0
uint256 vnetBalance = vnetToken.balanceOf(address(this)); require(vnetBalance > 0); require(vnetSold < vnetSupply);
uint256 vnetBalance = vnetToken.balanceOf(address(this)); require(vnetBalance > 0); require(vnetSold < vnetSupply);
62,998
229
// 1. Check amount
require(amountETH == 0, "CoFiXAnchorPool: invalid asset ratio");
require(amountETH == 0, "CoFiXAnchorPool: invalid asset ratio");
40,706
16
// Emitted when a function is invocated by unauthorized addresses.
event InvalidCaller(address caller);
event InvalidCaller(address caller);
19,739
0
// Throws if called by any account other than the blacklister /
modifier onlyBlacklister() { require( msg.sender == blacklister, "Blacklistable: caller is not the blacklister" ); _; }
modifier onlyBlacklister() { require( msg.sender == blacklister, "Blacklistable: caller is not the blacklister" ); _; }
15,084
261
// always fits 160 bits
return uint160(sqrtPX96 - quotient);
return uint160(sqrtPX96 - quotient);
13,150
6
// See {IERC20-totalSupply}. /
function totalSupply() public view virtual override returns (uint256) { return _totalSupply; }
function totalSupply() public view virtual override returns (uint256) { return _totalSupply; }
813
41
// Leaves the contract without owner. It will not be possible to call`onlyOwner` functions anymore. Can only be called by the current owner. NOTE: Renouncing ownership will leave the contract without an owner,thereby removing any functionality that is only available to the owner. /
function renounceOwnership() public virtual onlyOwner {
function renounceOwnership() public virtual onlyOwner {
354
95
// ERC20 behaviour but revert if paused/_from address The address which you want to send tokens from./_to address The address which you want to transfer to./_value uint256 the amount of tokens to be transferred.
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { // "transfers" to address(0) should only be by the burn() function require(_to != address(0)); // special case: _from is the Mint // note: within the current D1 Coin design, should never encounter this case if (_from == theCoin) { // ensure Mint is not exceeding its balance less protected supply require(_value <= balances[theCoin].sub(protectedSupply)); } return super.transferFrom(_from, _to, _value); }
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { // "transfers" to address(0) should only be by the burn() function require(_to != address(0)); // special case: _from is the Mint // note: within the current D1 Coin design, should never encounter this case if (_from == theCoin) { // ensure Mint is not exceeding its balance less protected supply require(_value <= balances[theCoin].sub(protectedSupply)); } return super.transferFrom(_from, _to, _value); }
6,907
7
// SafeMath Math operations with safety checks that throw on error /
library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function ceil(uint a, uint m) internal pure returns (uint r) { return (a + m - 1) / m * m; } }
library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function ceil(uint a, uint m) internal pure returns (uint r) { return (a + m - 1) / m * m; } }
41,459
19
// Calculates the amount of fees from MATIC rewards that haven't yet been turned into shares./ return The amount of fees from rewards that haven't yet been turned into shares.
function getDust() external view returns (uint256) { return (totalRewards() * phi) / PHI_PRECISION; }
function getDust() external view returns (uint256) { return (totalRewards() * phi) / PHI_PRECISION; }
10,986
33
// stakes all pending rewards into another participating pool /
function stakeRewards(uint256 maxAmount, IDSToken newPoolToken) external override returns (uint256, uint256) { return _stakeRewards(msg.sender, maxAmount, newPoolToken, _liquidityProtectionStats()); }
function stakeRewards(uint256 maxAmount, IDSToken newPoolToken) external override returns (uint256, uint256) { return _stakeRewards(msg.sender, maxAmount, newPoolToken, _liquidityProtectionStats()); }
23,569
10
// pragma solidity ^0.8.15; // import "../utils/Context.sol"; /
abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() { _transferOwnership(_msgSender()); } function owner() public view virtual returns (address) { return _owner; } modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } }
abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() { _transferOwnership(_msgSender()); } function owner() public view virtual returns (address) { return _owner; } modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } }
51,053
17
// Return the current unlock-phase. Won't work until after the contract/ has `finalise()` called.
function currentPhase() public constant returns (uint)
function currentPhase() public constant returns (uint)
24,644
284
// Holds account level context information used to determine settlement and/ free collateral actions. Total storage is 28 bytes
struct AccountContext { // Used to check when settlement must be triggered on an account uint40 nextSettleTime; // For lenders that never incur debt, we use this flag to skip the free collateral check. bytes1 hasDebt; // Length of the account\'s asset array uint8 assetArrayLength; // If this account has bitmaps set, this is the corresponding currency id uint16 bitmapCurrencyId; // 9 total active currencies possible (2 bytes each) bytes18 activeCurrencies; }
struct AccountContext { // Used to check when settlement must be triggered on an account uint40 nextSettleTime; // For lenders that never incur debt, we use this flag to skip the free collateral check. bytes1 hasDebt; // Length of the account\'s asset array uint8 assetArrayLength; // If this account has bitmaps set, this is the corresponding currency id uint16 bitmapCurrencyId; // 9 total active currencies possible (2 bytes each) bytes18 activeCurrencies; }
6,984
277
// The total amount of funds that the prize pool can hold.
uint256 internal liquidityCap;
uint256 internal liquidityCap;
69,881
156
// Calculate collateral rate in 18 decimals
collateralUsdRate = rmul(mat, spot) / 10**9;
collateralUsdRate = rmul(mat, spot) / 10**9;
48,407
30
// return free Tokens
function freeBalance() public view returns (uint tokens) { return _released.sub(_allocated); }
function freeBalance() public view returns (uint tokens) { return _released.sub(_allocated); }
36,655
14
// DSMath add /
function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, "math-not-safe"); }
function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, "math-not-safe"); }
40,626
6
// FSM_WRAPPER_ETH, INCREASING_TREASURY_REIMBURSEMENT_OVERLAY
AuthLike(0x105b857583346E250FBD04a57ce0E491EB204BA3).addAuthorization(0x1dCeE093a7C952260f591D9B8401318f2d2d72Ac);
AuthLike(0x105b857583346E250FBD04a57ce0E491EB204BA3).addAuthorization(0x1dCeE093a7C952260f591D9B8401318f2d2d72Ac);
26,691
255
// Same as `_prepare(bytes32,uint256,uint256)` but uses a default delay /
function _prepare(bytes32 key, uint256 value) internal returns (bool) { return _prepare(key, value, _MIN_DELAY); }
function _prepare(bytes32 key, uint256 value) internal returns (bool) { return _prepare(key, value, _MIN_DELAY); }
9,665
20
// Resolves an assertion. If the assertion has not been disputed, the assertion is resolved as true and theasserter receives the bond. If the assertion has been disputed, the assertion is resolved depending on the oracleresult. Based on the result, the asserter or disputer receives the bond. If the assertion was disputed then anamount of the bond is sent to the UMA Store as an oracle fee based on the burnedBondPercentage. The remainder ofthe bond is returned to the asserter or disputer. assertionId unique identifier for the assertion to resolve. /
function settleAssertion(bytes32 assertionId) public nonReentrant { Assertion storage assertion = assertions[assertionId]; require(assertion.asserter != address(0), "Assertion does not exist"); // Revert if assertion does not exist. require(!assertion.settled, "Assertion already settled"); // Revert if assertion already settled. assertion.settled = true; if (assertion.disputer == address(0)) { // No dispute, settle with the asserter require(assertion.expirationTime <= getCurrentTime(), "Assertion not expired"); // Revert if not expired. assertion.settlementResolution = true; assertion.currency.safeTransfer(assertion.asserter, assertion.bond); _callbackOnAssertionResolve(assertionId, true); emit AssertionSettled(assertionId, assertion.asserter, false, true, msg.sender); } else { // Dispute, settle with the disputer. Reverts if price not resolved. int256 resolvedPrice = _oracleGetPrice(assertionId, assertion.identifier, assertion.assertionTime); // If set to discard settlement resolution then false. Else, use oracle value to find resolution. if (assertion.escalationManagerSettings.discardOracle) assertion.settlementResolution = false; else assertion.settlementResolution = resolvedPrice == numericalTrue; address bondRecipient = resolvedPrice == numericalTrue ? assertion.asserter : assertion.disputer; // Calculate oracle fee and the remaining amount of bonds to send to the correct party (asserter or disputer). uint256 oracleFee = (burnedBondPercentage * assertion.bond) / 1e18; uint256 bondRecipientAmount = assertion.bond * 2 - oracleFee; // Pay out the oracle fee and remaining bonds to the correct party. Note: the oracle fee is sent to the // Store contract, even if the escalation manager is used to arbitrate disputes. assertion.currency.safeTransfer(address(_getStore()), oracleFee); assertion.currency.safeTransfer(bondRecipient, bondRecipientAmount); if (!assertion.escalationManagerSettings.discardOracle) _callbackOnAssertionResolve(assertionId, assertion.settlementResolution); emit AssertionSettled(assertionId, bondRecipient, true, assertion.settlementResolution, msg.sender); } }
function settleAssertion(bytes32 assertionId) public nonReentrant { Assertion storage assertion = assertions[assertionId]; require(assertion.asserter != address(0), "Assertion does not exist"); // Revert if assertion does not exist. require(!assertion.settled, "Assertion already settled"); // Revert if assertion already settled. assertion.settled = true; if (assertion.disputer == address(0)) { // No dispute, settle with the asserter require(assertion.expirationTime <= getCurrentTime(), "Assertion not expired"); // Revert if not expired. assertion.settlementResolution = true; assertion.currency.safeTransfer(assertion.asserter, assertion.bond); _callbackOnAssertionResolve(assertionId, true); emit AssertionSettled(assertionId, assertion.asserter, false, true, msg.sender); } else { // Dispute, settle with the disputer. Reverts if price not resolved. int256 resolvedPrice = _oracleGetPrice(assertionId, assertion.identifier, assertion.assertionTime); // If set to discard settlement resolution then false. Else, use oracle value to find resolution. if (assertion.escalationManagerSettings.discardOracle) assertion.settlementResolution = false; else assertion.settlementResolution = resolvedPrice == numericalTrue; address bondRecipient = resolvedPrice == numericalTrue ? assertion.asserter : assertion.disputer; // Calculate oracle fee and the remaining amount of bonds to send to the correct party (asserter or disputer). uint256 oracleFee = (burnedBondPercentage * assertion.bond) / 1e18; uint256 bondRecipientAmount = assertion.bond * 2 - oracleFee; // Pay out the oracle fee and remaining bonds to the correct party. Note: the oracle fee is sent to the // Store contract, even if the escalation manager is used to arbitrate disputes. assertion.currency.safeTransfer(address(_getStore()), oracleFee); assertion.currency.safeTransfer(bondRecipient, bondRecipientAmount); if (!assertion.escalationManagerSettings.discardOracle) _callbackOnAssertionResolve(assertionId, assertion.settlementResolution); emit AssertionSettled(assertionId, bondRecipient, true, assertion.settlementResolution, msg.sender); } }
30,304
180
// Updates: - 'address' to the last owner. - 'startTimestamp' to the timestamp of burning. - 'burned' to 'true'. - 'nextInitialized' to 'true'.
_packedOwnerships[tokenId] = _packOwnershipData( from, (_BITMASK_BURNED | _BITMASK_NEXT_INITIALIZED) | _nextExtraData(from, address(0), prevOwnershipPacked) );
_packedOwnerships[tokenId] = _packOwnershipData( from, (_BITMASK_BURNED | _BITMASK_NEXT_INITIALIZED) | _nextExtraData(from, address(0), prevOwnershipPacked) );
44,305
236
// Mint for multiple assets in the same call. _assets Addresses of assets being deposited _amounts Amount of each asset at the same index in the _assetsto deposit. _minimumOusdAmount Minimum OUSD to mint /
function mintMultiple( address[] calldata _assets, uint256[] calldata _amounts, uint256 _minimumOusdAmount
function mintMultiple( address[] calldata _assets, uint256[] calldata _amounts, uint256 _minimumOusdAmount
24,355
210
// Begins creating a storage buffer - destinations entered will be forwarded wei before the end of execution
function paying() conditions(validPayBuff, isPaying) internal pure { bytes4 action_req = PAYS; assembly { // Get pointer to buffer length - let ptr := add(0x20, mload(0xc0)) // Push requestor to the end of buffer, as well as to the 'current action' slot - mstore(add(0x20, add(ptr, mload(ptr))), action_req) // Push '0' to the end of the 4 bytes just pushed - this will be the length of the PAYS action mstore(add(0x24, add(ptr, mload(ptr))), 0) // Increment buffer length - 0x24 plus the previous length mstore(ptr, add(0x24, mload(ptr))) // Set the current action being executed (PAYS) - mstore(0xe0, action_req) // Set the expected next function - PAY_AMT mstore(0x100, 8) // Set a pointer to the length of the current request within the buffer mstore(sub(ptr, 0x20), add(ptr, mload(ptr))) } // Update free memory pointer setFreeMem(); }
function paying() conditions(validPayBuff, isPaying) internal pure { bytes4 action_req = PAYS; assembly { // Get pointer to buffer length - let ptr := add(0x20, mload(0xc0)) // Push requestor to the end of buffer, as well as to the 'current action' slot - mstore(add(0x20, add(ptr, mload(ptr))), action_req) // Push '0' to the end of the 4 bytes just pushed - this will be the length of the PAYS action mstore(add(0x24, add(ptr, mload(ptr))), 0) // Increment buffer length - 0x24 plus the previous length mstore(ptr, add(0x24, mload(ptr))) // Set the current action being executed (PAYS) - mstore(0xe0, action_req) // Set the expected next function - PAY_AMT mstore(0x100, 8) // Set a pointer to the length of the current request within the buffer mstore(sub(ptr, 0x20), add(ptr, mload(ptr))) } // Update free memory pointer setFreeMem(); }
30,915
7
// Allows Linker to connect mainnet contracts with their receivers on schain.Requirements:- Numbers of mainnet contracts and schain contracts must be equal.- Mainnet contract must implement method `addSchainContract`. /
function connectSchain( string calldata schainName, address[] calldata schainContracts ) external override onlyLinker
function connectSchain( string calldata schainName, address[] calldata schainContracts ) external override onlyLinker
59,572
14
// Increment total M-Bill share capital
base.incrementMShareCap(shareCapital);
base.incrementMShareCap(shareCapital);
39,508
16
// increment used count/tokenId_ the token id
function incrementUsedCount(uint tokenId_) external onlyQuestFactory { discounts[tokenId_].usedCount++; }
function incrementUsedCount(uint tokenId_) external onlyQuestFactory { discounts[tokenId_].usedCount++; }
30,832
152
// ========== PARAMS
uint256 public cashPriceOne; uint256 public cashPriceCeiling; uint256 public bondDepletionFloor; uint256 private accumulatedSeigniorage = 0; uint256 public fundAllocationRate = 2; // %
uint256 public cashPriceOne; uint256 public cashPriceCeiling; uint256 public bondDepletionFloor; uint256 private accumulatedSeigniorage = 0; uint256 public fundAllocationRate = 2; // %
20,682
30
// ´:°•.°+.•´.:˚.°.˚•´.°:°•.°•.•´.:˚.°.˚•´.°:°•.°+.•´.://PUBLIC UPDATE FUNCTIONS //.•°:°.´+˚.°.˚:.´•.+°.•°:´.´•.•°.•°:°.´:•˚°.°.˚:.´+°.•//Allows the owner to grant `user` `roles`./ If the `user` already has a role, then it will be an no-op for the role.
function grantRoles(address user, uint256 roles) public payable virtual onlyOwner { _grantRoles(user, roles); }
function grantRoles(address user, uint256 roles) public payable virtual onlyOwner { _grantRoles(user, roles); }
20,374
30
// Implementation of a whitelist which filters a eligible uint32. /
library whiteListUint32 { /** * @dev add uint32 into white list. * @param whiteList the storage whiteList. * @param temp input value */ function addWhiteListUint32(uint32[] storage whiteList,uint32 temp) internal{ if (!isEligibleUint32(whiteList,temp)){ whiteList.push(temp); } } /** * @dev remove uint32 from whitelist. */ function removeWhiteListUint32(uint32[] storage whiteList,uint32 temp)internal returns (bool) { uint256 len = whiteList.length; uint256 i=0; for (;i<len;i++){ if (whiteList[i] == temp) break; } if (i<len){ if (i!=len-1) { whiteList[i] = whiteList[len-1]; } whiteList.length--; return true; } return false; } function isEligibleUint32(uint32[] memory whiteList,uint32 temp) internal pure returns (bool){ uint256 len = whiteList.length; for (uint256 i=0;i<len;i++){ if (whiteList[i] == temp) return true; } return false; } function _getEligibleIndexUint32(uint32[] memory whiteList,uint32 temp) internal pure returns (uint256){ uint256 len = whiteList.length; uint256 i=0; for (;i<len;i++){ if (whiteList[i] == temp) break; } return i; } }
library whiteListUint32 { /** * @dev add uint32 into white list. * @param whiteList the storage whiteList. * @param temp input value */ function addWhiteListUint32(uint32[] storage whiteList,uint32 temp) internal{ if (!isEligibleUint32(whiteList,temp)){ whiteList.push(temp); } } /** * @dev remove uint32 from whitelist. */ function removeWhiteListUint32(uint32[] storage whiteList,uint32 temp)internal returns (bool) { uint256 len = whiteList.length; uint256 i=0; for (;i<len;i++){ if (whiteList[i] == temp) break; } if (i<len){ if (i!=len-1) { whiteList[i] = whiteList[len-1]; } whiteList.length--; return true; } return false; } function isEligibleUint32(uint32[] memory whiteList,uint32 temp) internal pure returns (bool){ uint256 len = whiteList.length; for (uint256 i=0;i<len;i++){ if (whiteList[i] == temp) return true; } return false; } function _getEligibleIndexUint32(uint32[] memory whiteList,uint32 temp) internal pure returns (uint256){ uint256 len = whiteList.length; uint256 i=0; for (;i<len;i++){ if (whiteList[i] == temp) break; } return i; } }
6,000
26
// Art Blocks gives each project a token space of 1 million IDs. Most IDs/ in this space are not actually used, but a token's ID floor-divided by/ this stride gives the project ID, and the token ID modulo this stride/ gives the token index within the project.
uint256 constant PROJECT_STRIDE = 10**6; address public oracleSigner; mapping(bytes32 => ProjectInfo) public projectTraitInfo; mapping(bytes32 => FeatureInfo) public featureTraitInfo;
uint256 constant PROJECT_STRIDE = 10**6; address public oracleSigner; mapping(bytes32 => ProjectInfo) public projectTraitInfo; mapping(bytes32 => FeatureInfo) public featureTraitInfo;
27,788
228
// Require a 0.1 buffer between market collateral factor and strategy's collateral factor when leveraging
uint256 colFactorLeverageBuffer = 100; uint256 colFactorLeverageBufferMax = 1000;
uint256 colFactorLeverageBuffer = 100; uint256 colFactorLeverageBufferMax = 1000;
51,083
509
// This is how rewards are calculated
lastBlockUpdate = block.number + 300; // 300 is for deposits to roll in before rewards start
lastBlockUpdate = block.number + 300; // 300 is for deposits to roll in before rewards start
36,211
55
// See {IERC721Metadata-symbol}. /
function symbol() public view virtual override returns (string memory) {
function symbol() public view virtual override returns (string memory) {
3,132
41
// check if sell
if ( to == uniswapV2Pair && from != address(uniswapV2Router) && !_isExcludedFromFee[from] ) { _taxFee = 5; _teamFee = 9;
if ( to == uniswapV2Pair && from != address(uniswapV2Router) && !_isExcludedFromFee[from] ) { _taxFee = 5; _teamFee = 9;
38,915
51
// Outstanding normalised debt
uint256 ire;
uint256 ire;
18,270
88
// Approves a spender [ERC20].Note that using the approve/transferFrom presents a possiblesecurity vulnerability described in:Use transferAndCall to mitigate. db Token storage to operate on. caller Address of the caller passed through the frontend. spender The address of the future spender. amount The allowance of the spender. /
function approve(TokenStorage db, address caller, address spender, uint amount) public returns (bool success)
function approve(TokenStorage db, address caller, address spender, uint amount) public returns (bool success)
3,367
27
// allow sender to reclaim (if public == true)
if(nextRegisterTimestamp[msg.sender] > block.timestamp && msg.sender != owner()){ nextRegisterTimestamp[msg.sender] = block.timestamp + (60 * 30); //30 minute cooldown }
if(nextRegisterTimestamp[msg.sender] > block.timestamp && msg.sender != owner()){ nextRegisterTimestamp[msg.sender] = block.timestamp + (60 * 30); //30 minute cooldown }
56,983
37
// Factories
SmartFundETHFactoryInterface public smartFundETHFactory; SmartFundERC20FactoryInterface public smartFundERC20Factory; SmartFundETHLightFactoryInterface public smartFundETHLightFactory; SmartFundERC20LightFactoryInterface public smartFundERC20LightFactory;
SmartFundETHFactoryInterface public smartFundETHFactory; SmartFundERC20FactoryInterface public smartFundERC20Factory; SmartFundETHLightFactoryInterface public smartFundETHLightFactory; SmartFundERC20LightFactoryInterface public smartFundERC20LightFactory;
22,292
13
// Set metadata config _name string _symbol string /
function setMetaData(string memory _name, string memory _symbol) external onlyOwner
function setMetaData(string memory _name, string memory _symbol) external onlyOwner
32,122
78
// Internal Functions //Extend parent behavior to check if current stage should close. Must call super to ensure the enforcement of the whitelist./_beneficiary Token purchaser/_weiAmount Amount of wei contributed
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal whenNotPaused whenNotFinalized
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal whenNotPaused whenNotFinalized
32,872
12
// shows the init state of the contract
bool public _inited;
bool public _inited;
9,757
20
// Returns true if this contract implements the interface defined by`interfaceId`. See the correspondingto learn more about how these ids are created. This function call must use less than 30 000 gas. /
function supportsInterface(bytes4 interfaceId) external view returns (bool);
function supportsInterface(bytes4 interfaceId) external view returns (bool);
13,130
46
// Treasury vesting smart contract. Vesting period is over 36 months.Tokens are locked for 6 months. After that releasing the tokens over 30 months with a linear function. /
contract VestingTreasury { using SafeMath for uint256; uint256 constant public sixMonths = 182 days; uint256 constant public thirtyMonths = 912 days; ERC20Basic public erc20Contract; struct Locking { uint256 startDate; // date when the release process of the vesting will start. uint256 initialized; // initialized amount of tokens uint256 released; // already released tokens } mapping(address => Locking) public lockingMap; event ReleaseVestingEvent(address indexed to, uint256 value); /** * @dev Constructor. With the reference to the ERC20 contract */ constructor(address _erc20) public { require(AddressUtils.isContract(_erc20), "Address is not a smart contract"); erc20Contract = ERC20Basic(_erc20); } /** * @dev Adds vested tokens to this contract. ERC20 contract has assigned the tokens. * @param _tokenHolder The token holder. * @param _value The amount of tokens to protect. * @return True if accepted. */ function addVested( address _tokenHolder, uint256 _value ) public returns (bool) { require(msg.sender == address(erc20Contract), "ERC20 contract required"); require(lockingMap[_tokenHolder].startDate == 0, "Address is already vested"); lockingMap[_tokenHolder].startDate = block.timestamp + sixMonths; lockingMap[_tokenHolder].initialized = _value; lockingMap[_tokenHolder].released = 0; return true; } /** * @dev Calculates the amount of the total currently vested and available tokens. * @param _tokenHolder The address to query the balance of. * @return The total amount of owned tokens (vested + available). */ function balanceOf( address _tokenHolder ) public view returns (uint256) { return lockingMap[_tokenHolder].initialized.sub(lockingMap[_tokenHolder].released); } /** * @dev Calculates the amount of currently available (unlocked) tokens. This amount can be unlocked. * @param _tokenHolder The address to query the balance of. * @return The total amount of owned and available tokens. */ function availableBalanceOf( address _tokenHolder ) public view returns (uint256) { uint256 startDate = lockingMap[_tokenHolder].startDate; if (block.timestamp <= startDate) { return 0; } uint256 tmpAvailableTokens = 0; if (block.timestamp >= startDate + thirtyMonths) { tmpAvailableTokens = lockingMap[_tokenHolder].initialized; } else { uint256 timeDiff = block.timestamp - startDate; uint256 totalBalance = lockingMap[_tokenHolder].initialized; tmpAvailableTokens = totalBalance.mul(timeDiff).div(thirtyMonths); } uint256 availableTokens = tmpAvailableTokens.sub(lockingMap[_tokenHolder].released); require(availableTokens <= lockingMap[_tokenHolder].initialized, "Max value exceeded"); return availableTokens; } /** * @dev Releases unlocked tokens of the transaction sender. * @dev This function will transfer unlocked tokens to the owner. * @return The total amount of released tokens. */ function releaseTokens() public returns (uint256) { require(lockingMap[msg.sender].startDate != 0, "Sender is not a vested address"); uint256 tokens = availableBalanceOf(msg.sender); lockingMap[msg.sender].released = lockingMap[msg.sender].released.add(tokens); require(lockingMap[msg.sender].released <= lockingMap[msg.sender].initialized, "Max value exceeded"); require(erc20Contract.transfer(msg.sender, tokens), "Transfer failed"); emit ReleaseVestingEvent(msg.sender, tokens); return tokens; } }
contract VestingTreasury { using SafeMath for uint256; uint256 constant public sixMonths = 182 days; uint256 constant public thirtyMonths = 912 days; ERC20Basic public erc20Contract; struct Locking { uint256 startDate; // date when the release process of the vesting will start. uint256 initialized; // initialized amount of tokens uint256 released; // already released tokens } mapping(address => Locking) public lockingMap; event ReleaseVestingEvent(address indexed to, uint256 value); /** * @dev Constructor. With the reference to the ERC20 contract */ constructor(address _erc20) public { require(AddressUtils.isContract(_erc20), "Address is not a smart contract"); erc20Contract = ERC20Basic(_erc20); } /** * @dev Adds vested tokens to this contract. ERC20 contract has assigned the tokens. * @param _tokenHolder The token holder. * @param _value The amount of tokens to protect. * @return True if accepted. */ function addVested( address _tokenHolder, uint256 _value ) public returns (bool) { require(msg.sender == address(erc20Contract), "ERC20 contract required"); require(lockingMap[_tokenHolder].startDate == 0, "Address is already vested"); lockingMap[_tokenHolder].startDate = block.timestamp + sixMonths; lockingMap[_tokenHolder].initialized = _value; lockingMap[_tokenHolder].released = 0; return true; } /** * @dev Calculates the amount of the total currently vested and available tokens. * @param _tokenHolder The address to query the balance of. * @return The total amount of owned tokens (vested + available). */ function balanceOf( address _tokenHolder ) public view returns (uint256) { return lockingMap[_tokenHolder].initialized.sub(lockingMap[_tokenHolder].released); } /** * @dev Calculates the amount of currently available (unlocked) tokens. This amount can be unlocked. * @param _tokenHolder The address to query the balance of. * @return The total amount of owned and available tokens. */ function availableBalanceOf( address _tokenHolder ) public view returns (uint256) { uint256 startDate = lockingMap[_tokenHolder].startDate; if (block.timestamp <= startDate) { return 0; } uint256 tmpAvailableTokens = 0; if (block.timestamp >= startDate + thirtyMonths) { tmpAvailableTokens = lockingMap[_tokenHolder].initialized; } else { uint256 timeDiff = block.timestamp - startDate; uint256 totalBalance = lockingMap[_tokenHolder].initialized; tmpAvailableTokens = totalBalance.mul(timeDiff).div(thirtyMonths); } uint256 availableTokens = tmpAvailableTokens.sub(lockingMap[_tokenHolder].released); require(availableTokens <= lockingMap[_tokenHolder].initialized, "Max value exceeded"); return availableTokens; } /** * @dev Releases unlocked tokens of the transaction sender. * @dev This function will transfer unlocked tokens to the owner. * @return The total amount of released tokens. */ function releaseTokens() public returns (uint256) { require(lockingMap[msg.sender].startDate != 0, "Sender is not a vested address"); uint256 tokens = availableBalanceOf(msg.sender); lockingMap[msg.sender].released = lockingMap[msg.sender].released.add(tokens); require(lockingMap[msg.sender].released <= lockingMap[msg.sender].initialized, "Max value exceeded"); require(erc20Contract.transfer(msg.sender, tokens), "Transfer failed"); emit ReleaseVestingEvent(msg.sender, tokens); return tokens; } }
31,062
31
// Add the taylor series for log(1 + z), where z = x - 1
z = y = x - FIXED_1; w = y * y / FIXED_1; r += z * (0x100000000000000000000000000000000 - y) / 0x100000000000000000000000000000000; z = z * w / FIXED_1; // add y^01 / 01 - y^02 / 02 r += z * (0x0aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - y) / 0x200000000000000000000000000000000; z = z * w / FIXED_1; // add y^03 / 03 - y^04 / 04 r += z * (0x099999999999999999999999999999999 - y) / 0x300000000000000000000000000000000; z = z * w / FIXED_1; // add y^05 / 05 - y^06 / 06 r += z * (0x092492492492492492492492492492492 - y) / 0x400000000000000000000000000000000; z = z * w / FIXED_1; // add y^07 / 07 - y^08 / 08 r += z * (0x08e38e38e38e38e38e38e38e38e38e38e - y) / 0x500000000000000000000000000000000; z = z * w / FIXED_1; // add y^09 / 09 - y^10 / 10 r += z * (0x08ba2e8ba2e8ba2e8ba2e8ba2e8ba2e8b - y) / 0x600000000000000000000000000000000; z = z * w / FIXED_1; // add y^11 / 11 - y^12 / 12 r += z * (0x089d89d89d89d89d89d89d89d89d89d89 - y) / 0x700000000000000000000000000000000; z = z * w / FIXED_1; // add y^13 / 13 - y^14 / 14 r += z * (0x088888888888888888888888888888888 - y) / 0x800000000000000000000000000000000; // add y^15 / 15 - y^16 / 16
z = y = x - FIXED_1; w = y * y / FIXED_1; r += z * (0x100000000000000000000000000000000 - y) / 0x100000000000000000000000000000000; z = z * w / FIXED_1; // add y^01 / 01 - y^02 / 02 r += z * (0x0aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - y) / 0x200000000000000000000000000000000; z = z * w / FIXED_1; // add y^03 / 03 - y^04 / 04 r += z * (0x099999999999999999999999999999999 - y) / 0x300000000000000000000000000000000; z = z * w / FIXED_1; // add y^05 / 05 - y^06 / 06 r += z * (0x092492492492492492492492492492492 - y) / 0x400000000000000000000000000000000; z = z * w / FIXED_1; // add y^07 / 07 - y^08 / 08 r += z * (0x08e38e38e38e38e38e38e38e38e38e38e - y) / 0x500000000000000000000000000000000; z = z * w / FIXED_1; // add y^09 / 09 - y^10 / 10 r += z * (0x08ba2e8ba2e8ba2e8ba2e8ba2e8ba2e8b - y) / 0x600000000000000000000000000000000; z = z * w / FIXED_1; // add y^11 / 11 - y^12 / 12 r += z * (0x089d89d89d89d89d89d89d89d89d89d89 - y) / 0x700000000000000000000000000000000; z = z * w / FIXED_1; // add y^13 / 13 - y^14 / 14 r += z * (0x088888888888888888888888888888888 - y) / 0x800000000000000000000000000000000; // add y^15 / 15 - y^16 / 16
24,946
3
// token settings
uint256 fixed_tokens; uint8 price_addition_percentage; // uint8 token_share_percentage; uint8 index;
uint256 fixed_tokens; uint8 price_addition_percentage; // uint8 token_share_percentage; uint8 index;
5,883
20
// Allows users to self-register in the marketplace
function register() public payable { require( msg.value >= minimumDeposit, "User must deposit funds greater than minimum deposit" ); if (users[msg.sender].exists == true) revert("User is already registered"); users[msg.sender] = User(msg.value, true, 0, 0); emit UserEvent(msg.sender, UserStatus.Registered); }
function register() public payable { require( msg.value >= minimumDeposit, "User must deposit funds greater than minimum deposit" ); if (users[msg.sender].exists == true) revert("User is already registered"); users[msg.sender] = User(msg.value, true, 0, 0); emit UserEvent(msg.sender, UserStatus.Registered); }
24,262
466
// Returns the index of the oracle's latest sample. /
function oracleIndex(bytes32 data) internal pure returns (uint256) { return data.decodeUint10(_ORACLE_INDEX_OFFSET); }
function oracleIndex(bytes32 data) internal pure returns (uint256) { return data.decodeUint10(_ORACLE_INDEX_OFFSET); }
3,205
65
// function
function Do_Unstacking(uint stacking_amount) public OnlyRegistered returns(bool) { //check balance require( m_User_Map[msg.sender].Stacking_Amount>=stacking_amount); Update_Global_Data(); Update_User(msg.sender,false); uint256 old_stacking_amount=m_User_Map[msg.sender].Stacking_Amount; bool res=false; res=ERC20Interface(m_Stacking_Address).transfer(msg.sender,stacking_amount); if(res ==false) { revert(); } m_User_Map[msg.sender].Stacking_Amount= m_User_Map[msg.sender].Stacking_Amount.sub(stacking_amount); m_Total_Stacking=m_Total_Stacking.sub(stacking_amount); //------------------------------------------------------------ // delete contribute //------------------------------------------------------------ address referer_address=GetRefererAddress(msg.sender); //Update_User(referer_address,false); m_User_Map[referer_address].Contribution_Amount= m_User_Map[referer_address].Contribution_Amount.sub(stacking_amount/5); //------------------------------------------------------------ // delete contribute //------------------------------------------------------------ referer_address=GetRefererAddress(referer_address); //Update_User(referer_address,false); m_User_Map[referer_address].Contribution_Amount= m_User_Map[referer_address].Contribution_Amount.sub(stacking_amount/10); if(old_stacking_amount>=15e16 && m_User_Map[msg.sender].Stacking_Amount<15e16 ) { m_User_Count=m_User_Count-1; } emit EVENT_UNSTACK(msg.sender,stacking_amount); return true; }
function Do_Unstacking(uint stacking_amount) public OnlyRegistered returns(bool) { //check balance require( m_User_Map[msg.sender].Stacking_Amount>=stacking_amount); Update_Global_Data(); Update_User(msg.sender,false); uint256 old_stacking_amount=m_User_Map[msg.sender].Stacking_Amount; bool res=false; res=ERC20Interface(m_Stacking_Address).transfer(msg.sender,stacking_amount); if(res ==false) { revert(); } m_User_Map[msg.sender].Stacking_Amount= m_User_Map[msg.sender].Stacking_Amount.sub(stacking_amount); m_Total_Stacking=m_Total_Stacking.sub(stacking_amount); //------------------------------------------------------------ // delete contribute //------------------------------------------------------------ address referer_address=GetRefererAddress(msg.sender); //Update_User(referer_address,false); m_User_Map[referer_address].Contribution_Amount= m_User_Map[referer_address].Contribution_Amount.sub(stacking_amount/5); //------------------------------------------------------------ // delete contribute //------------------------------------------------------------ referer_address=GetRefererAddress(referer_address); //Update_User(referer_address,false); m_User_Map[referer_address].Contribution_Amount= m_User_Map[referer_address].Contribution_Amount.sub(stacking_amount/10); if(old_stacking_amount>=15e16 && m_User_Map[msg.sender].Stacking_Amount<15e16 ) { m_User_Count=m_User_Count-1; } emit EVENT_UNSTACK(msg.sender,stacking_amount); return true; }
13,897
17
// Emits when a 3rd-party contract is forbidden
event ContractForbidden(address indexed protocol);
event ContractForbidden(address indexed protocol);
20,072
185
// If gas price is increased, then check if new rewards cover gas costs
if (tx.gasprice > requests[_id].gasPrice) {
if (tx.gasprice > requests[_id].gasPrice) {
59,851
26
// spell to swap clerk contract in the ns2 koan deployment
contract TinlakeSpell { bool public done; string constant public description = "Tinlake NS2 migration kovan Spell"; address constant public ROOT = 0x25dF507570c8285E9c8E7FFabC87db7836850dCd; address constant public SENIOR_TOKEN = 0x352Fee834a14800739DC72B219572d18618D9846; address constant public SENIOR_TRANCHE = 0xDF0c780Ae58cD067ce10E0D7cdB49e92EEe716d9; address constant public SENIOR_MEMBERLIST = 0xD927F069faf59eD83A1072624Eeb794235bBA652; address constant public COORDINATOR = 0xB51D3cbaa5CCeEf896B96091E69be48bCbDE8367; address constant public ASSESSOR = 0x49527a20904aF41d1cbFc0ba77576B9FBd8ec9E5; address constant public RESERVE = 0xc264eCc07728d43cdA564154c2638D3da110D4DD; address constant public TINLAKE_CURRENCY = 0x4F96Fe3b7A6Cf9725f59d353F723c1bDb64CA6Aa; // DAI // adapter contracts -> to be integrated address constant public CLERK_OLD = 0xE3F80411CD0Dd02Def6AF3041DA4c6f9b87BA1D8; address constant public CLERK_NEW = 0x892251594cD8Fb367218a95b136a624d95F8A92F; address constant public MGR = 0x65242F75e6cCBF973b15d483dD5F555d13955A1e; // mkr kovan contracts from release 1.2.2 https://changelog.makerdao.com/releases/kovan/1.2.2/contracts.json address constant public SPOTTER = 0x3a042de6413eDB15F2784f2f97cC68C7E9750b2D; address constant public VAT = 0xbA987bDB501d131f766fEe8180Da5d81b34b69d9; address constant public JUG = 0xcbB7718c9F39d05aEEDE1c472ca8Bf804b2f1EaD; uint constant public CLERK_BUFFER = 0.01 * 10**27; address self; // permissions to be set function cast() public { require(!done, "spell-already-cast"); done = true; execute(); } function execute() internal { SpellTinlakeRootLike root = SpellTinlakeRootLike(ROOT); self = address(this); // set spell as ward on the core contract to be able to wire the new contracts correctly root.relyContract(SENIOR_TRANCHE, self); root.relyContract(SENIOR_MEMBERLIST, self); root.relyContract(CLERK_OLD, self); root.relyContract(CLERK_NEW, self); root.relyContract(ASSESSOR, self); root.relyContract(COORDINATOR, self); root.relyContract(RESERVE, self); // contract migration --> assumption: root contract is already ward on the new contracts migrateClerk(); } function migrateClerk() internal { // dependencies DependLike(CLERK_NEW).depend("assessor", ASSESSOR); DependLike(CLERK_NEW).depend("mgr", MGR); DependLike(CLERK_NEW).depend("coordinator", COORDINATOR); DependLike(CLERK_NEW).depend("reserve", RESERVE); DependLike(CLERK_NEW).depend("tranche", SENIOR_TRANCHE); DependLike(CLERK_NEW).depend("collateral", SENIOR_TOKEN); DependLike(CLERK_NEW).depend("spotter", SPOTTER); DependLike(CLERK_NEW).depend("vat", VAT); DependLike(CLERK_NEW).depend("jug", JUG); DependLike(ASSESSOR).depend("clerk", CLERK_NEW); DependLike(RESERVE).depend("lending", CLERK_NEW); // permissions AuthLike(CLERK_NEW).rely(COORDINATOR); AuthLike(CLERK_NEW).rely(RESERVE); // rely new clerk AuthLike(SENIOR_TRANCHE).rely(CLERK_NEW); AuthLike(RESERVE).rely(CLERK_NEW); AuthLike(ASSESSOR).rely(CLERK_NEW); // deny old clerk AuthLike(SENIOR_TRANCHE).deny(CLERK_OLD); AuthLike(RESERVE).deny(CLERK_OLD); AuthLike(ASSESSOR).deny(CLERK_OLD); // currency SpellMemberlistLike(SENIOR_MEMBERLIST).updateMember(CLERK_NEW, uint(-1)); // state FileLike(CLERK_NEW).file("buffer", CLERK_BUFFER); // swap mgr ownership SpellClerkLike(CLERK_OLD).changeOwnerMgr(CLERK_NEW); } }
contract TinlakeSpell { bool public done; string constant public description = "Tinlake NS2 migration kovan Spell"; address constant public ROOT = 0x25dF507570c8285E9c8E7FFabC87db7836850dCd; address constant public SENIOR_TOKEN = 0x352Fee834a14800739DC72B219572d18618D9846; address constant public SENIOR_TRANCHE = 0xDF0c780Ae58cD067ce10E0D7cdB49e92EEe716d9; address constant public SENIOR_MEMBERLIST = 0xD927F069faf59eD83A1072624Eeb794235bBA652; address constant public COORDINATOR = 0xB51D3cbaa5CCeEf896B96091E69be48bCbDE8367; address constant public ASSESSOR = 0x49527a20904aF41d1cbFc0ba77576B9FBd8ec9E5; address constant public RESERVE = 0xc264eCc07728d43cdA564154c2638D3da110D4DD; address constant public TINLAKE_CURRENCY = 0x4F96Fe3b7A6Cf9725f59d353F723c1bDb64CA6Aa; // DAI // adapter contracts -> to be integrated address constant public CLERK_OLD = 0xE3F80411CD0Dd02Def6AF3041DA4c6f9b87BA1D8; address constant public CLERK_NEW = 0x892251594cD8Fb367218a95b136a624d95F8A92F; address constant public MGR = 0x65242F75e6cCBF973b15d483dD5F555d13955A1e; // mkr kovan contracts from release 1.2.2 https://changelog.makerdao.com/releases/kovan/1.2.2/contracts.json address constant public SPOTTER = 0x3a042de6413eDB15F2784f2f97cC68C7E9750b2D; address constant public VAT = 0xbA987bDB501d131f766fEe8180Da5d81b34b69d9; address constant public JUG = 0xcbB7718c9F39d05aEEDE1c472ca8Bf804b2f1EaD; uint constant public CLERK_BUFFER = 0.01 * 10**27; address self; // permissions to be set function cast() public { require(!done, "spell-already-cast"); done = true; execute(); } function execute() internal { SpellTinlakeRootLike root = SpellTinlakeRootLike(ROOT); self = address(this); // set spell as ward on the core contract to be able to wire the new contracts correctly root.relyContract(SENIOR_TRANCHE, self); root.relyContract(SENIOR_MEMBERLIST, self); root.relyContract(CLERK_OLD, self); root.relyContract(CLERK_NEW, self); root.relyContract(ASSESSOR, self); root.relyContract(COORDINATOR, self); root.relyContract(RESERVE, self); // contract migration --> assumption: root contract is already ward on the new contracts migrateClerk(); } function migrateClerk() internal { // dependencies DependLike(CLERK_NEW).depend("assessor", ASSESSOR); DependLike(CLERK_NEW).depend("mgr", MGR); DependLike(CLERK_NEW).depend("coordinator", COORDINATOR); DependLike(CLERK_NEW).depend("reserve", RESERVE); DependLike(CLERK_NEW).depend("tranche", SENIOR_TRANCHE); DependLike(CLERK_NEW).depend("collateral", SENIOR_TOKEN); DependLike(CLERK_NEW).depend("spotter", SPOTTER); DependLike(CLERK_NEW).depend("vat", VAT); DependLike(CLERK_NEW).depend("jug", JUG); DependLike(ASSESSOR).depend("clerk", CLERK_NEW); DependLike(RESERVE).depend("lending", CLERK_NEW); // permissions AuthLike(CLERK_NEW).rely(COORDINATOR); AuthLike(CLERK_NEW).rely(RESERVE); // rely new clerk AuthLike(SENIOR_TRANCHE).rely(CLERK_NEW); AuthLike(RESERVE).rely(CLERK_NEW); AuthLike(ASSESSOR).rely(CLERK_NEW); // deny old clerk AuthLike(SENIOR_TRANCHE).deny(CLERK_OLD); AuthLike(RESERVE).deny(CLERK_OLD); AuthLike(ASSESSOR).deny(CLERK_OLD); // currency SpellMemberlistLike(SENIOR_MEMBERLIST).updateMember(CLERK_NEW, uint(-1)); // state FileLike(CLERK_NEW).file("buffer", CLERK_BUFFER); // swap mgr ownership SpellClerkLike(CLERK_OLD).changeOwnerMgr(CLERK_NEW); } }
6,875
297
// round 56
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 9799099446406796696742256539758943483211846559715874347178722060519817626047) t0, t1, t2, t3, t4 := sbox_full(t0, t1, t2, t3, t4, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 9799099446406796696742256539758943483211846559715874347178722060519817626047) t0, t1, t2, t3, t4 := sbox_full(t0, t1, t2, t3, t4, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
31,578
0
// DepositWalletInterface// Defines an interface for a wallet that can be deposited/withdrawn by 3rd contract
contract DepositWalletInterface { function deposit(address _asset, address _from, uint256 amount) public returns (uint); function withdraw(address _asset, address _to, uint256 amount) public returns (uint); }
contract DepositWalletInterface { function deposit(address _asset, address _from, uint256 amount) public returns (uint); function withdraw(address _asset, address _to, uint256 amount) public returns (uint); }
68,895
420
// ReplaceablePaymentSplitter ps = new ReplaceablePaymentSplitter();
ps_address = Clones.clone(_splitterTemplate); ReplaceablePaymentSplitter ps = ReplaceablePaymentSplitter( payable(ps_address) ); splitters[tokenId] = ps; ps.initialize(address(this), payees_, shares_);
ps_address = Clones.clone(_splitterTemplate); ReplaceablePaymentSplitter ps = ReplaceablePaymentSplitter( payable(ps_address) ); splitters[tokenId] = ps; ps.initialize(address(this), payees_, shares_);
70,361
73
// Update the total amount of funds for which tokens have been claimed
fundsClaimed += bids[receiverAddress];
fundsClaimed += bids[receiverAddress];
24,746
12
// Final `_invTotalWeightIntegral` before each rebalance./These values are accessed in a loop in `_userCheckpoint()` with bounds checking./So we store them in a fixed-length array, in order to make compiler-generated/bounds checking on every access cheaper. The actual length of this array is stored in/`_historicalIntegralSize` and should be explicitly checked when necessary.
uint256[65535] private _historicalIntegrals;
uint256[65535] private _historicalIntegrals;
28,488
11
// Wrapper around OpenZeppelin's Initializable contract.Exposes initialized state management to ensure logic contract functions cannot be called before initialization.This is needed because OZ's Initializable contract no longer exposes initialized state variable. /
contract InitializableV2 is Initializable { bool private isInitialized; string private constant ERROR_NOT_INITIALIZED = "InitializableV2: Not initialized"; /** * @notice wrapper function around parent contract Initializable's `initializable` modifier * initializable modifier ensures this function can only be called once by each deployed child contract * sets isInitialized flag to true to which is used by _requireIsInitialized() */ function initialize() public initializer { isInitialized = true; } /** * @notice Reverts transaction if isInitialized is false. Used by child contracts to ensure * contract is initialized before functions can be called. */ function _requireIsInitialized() internal view { require(isInitialized == true, ERROR_NOT_INITIALIZED); } /** * @notice Exposes isInitialized bool var to child contracts with read-only access */ function _isInitialized() internal view returns (bool) { return isInitialized; } }
contract InitializableV2 is Initializable { bool private isInitialized; string private constant ERROR_NOT_INITIALIZED = "InitializableV2: Not initialized"; /** * @notice wrapper function around parent contract Initializable's `initializable` modifier * initializable modifier ensures this function can only be called once by each deployed child contract * sets isInitialized flag to true to which is used by _requireIsInitialized() */ function initialize() public initializer { isInitialized = true; } /** * @notice Reverts transaction if isInitialized is false. Used by child contracts to ensure * contract is initialized before functions can be called. */ function _requireIsInitialized() internal view { require(isInitialized == true, ERROR_NOT_INITIALIZED); } /** * @notice Exposes isInitialized bool var to child contracts with read-only access */ function _isInitialized() internal view returns (bool) { return isInitialized; } }
26,363
198
// owner/treasury address only functions/
function () payable onlyTreasury
function () payable onlyTreasury
34,573
91
// Forward error from Pool contract
if (!success) assembly { revert(add(result, 32), result) }
if (!success) assembly { revert(add(result, 32), result) }
8,533
111
// Set the token, beneficiary, start timestamp and vesting duration of the vesting wallet. /
constructor( address _token, address _beneficiary, uint64 _startTimestamp, uint64 _durationSeconds
constructor( address _token, address _beneficiary, uint64 _startTimestamp, uint64 _durationSeconds
74,197
31
// Make sure the new addresses are not address(0)
require(custodian_address != address(0) && timelock_address != address(0), "Invalid custodian or timelock");
require(custodian_address != address(0) && timelock_address != address(0), "Invalid custodian or timelock");
48,014
56
// Alerts the token controller of the approve function call
if (isContract(controller)) { require(TokenController(controller).onApprove(msg.sender, _spender, _amount)); }
if (isContract(controller)) { require(TokenController(controller).onApprove(msg.sender, _spender, _amount)); }
43,981
37
// Check all items are burned
for (uint256 i = 0; i < list.length; i++) { assertEq(items.ownerOf(list[i]), address(0)); }
for (uint256 i = 0; i < list.length; i++) { assertEq(items.ownerOf(list[i]), address(0)); }
3,415
167
// Add Chunky Chickens URI here
string private URI = "";
string private URI = "";
29,384
139
// Library for managing an enumerable variant of Solidity'stype. Maps have the following properties: - Entries are added, removed, and checked for existence in constant time(O(1)).- Entries are enumerated in O(n). No guarantees are made on the ordering. ```
* contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * }
* contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * }
1,348
23
// Sets `amount` as the allowance of `spender` over the caller's tokens. Returns a boolean value indicating whether the operation succeeded. IMPORTANT: Beware that changing an allowance with this method brings the riskthat someone may use both the old and the new allowance by unfortunatetransaction ordering. One possible solution to mitigate this racecondition is to first reduce the spender's allowance to 0 and set thedesired value afterwards: Emits an {Approval} event. /
function approve(address spender, uint256 amount) external returns (bool);
function approve(address spender, uint256 amount) external returns (bool);
13,340
169
// Sets the contract's biggest withdraw nonce if current withdraw nonce is the known biggest onethis is for information purposes only /
if(nonce > _tracker[token]._biggestWithdrawNonce) { _tracker[token]._biggestWithdrawNonce = nonce; }
if(nonce > _tracker[token]._biggestWithdrawNonce) { _tracker[token]._biggestWithdrawNonce = nonce; }
8,880
74
// Version of the contract
uint8 public version;
uint8 public version;
16,345
55
// We return early if the creditor values were not signed correctly.
return false;
return false;
10,533
193
// only allow Oraclize to call this function
require(msg.sender == oraclize_cbAddress());
require(msg.sender == oraclize_cbAddress());
36,949
32
// getNumberOfExchanges gets the total number of registered exchangesreturn total number of registered exchange IDs /
function getNumberOfExchanges() external view returns (uint256) { return exchangeIds.length; }
function getNumberOfExchanges() external view returns (uint256) { return exchangeIds.length; }
484
22
// Sets the implementation address of the proxy. newImplementation Address of the new implementation. /
function _setImplementation(address newImplementation) internal { require( Address.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address" ); bytes32 slot = IMPLEMENTATION_SLOT; assembly { sstore(slot, newImplementation) } }
function _setImplementation(address newImplementation) internal { require( Address.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address" ); bytes32 slot = IMPLEMENTATION_SLOT; assembly { sstore(slot, newImplementation) } }
27,261
30
// referrer ON
referrerOn[msg.sender] = 1;
referrerOn[msg.sender] = 1;
38,175
26
// buyer wants more than is available
success = false;
success = false;
35,529
20
// Update rebasingCredits by subtracting the deducted amount
rebasingCredits = rebasingCredits.sub(creditsDeducted);
rebasingCredits = rebasingCredits.sub(creditsDeducted);
36,219
0
// okt 1个币开始分红 bsc 0.1 eth 0.01
uint256 public DividendBeginNum = 10**18;
uint256 public DividendBeginNum = 10**18;
51,371
13
// Functions:/ return total amount of tokens
function totalSupply() constant returns (uint256 supply) {} /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance) {} /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success) {} /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success) {} /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} // Events: event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
function totalSupply() constant returns (uint256 supply) {} /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance) {} /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success) {} /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success) {} /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} // Events: event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
35,116
71
// make sure that we are in mode 1
require(mode[_stack]==1);
require(mode[_stack]==1);
65,306
6
// Wenn der ersteller des smart contracts in der transaktion einen Beg&252;nstigten angegeben hat, soll ihmder zuvor als Startguthaben definierte Wert als Guthaben gutgeschrieben werden. Das mitgesendete Ether wird dabei dem smart contract gutgeschrieben, er war der Empf&228;nger der Transaktion.
if (_sparer != 0x0) guthaben[_sparer] = startGuthaben; else guthaben[msg.sender] = startGuthaben;
if (_sparer != 0x0) guthaben[_sparer] = startGuthaben; else guthaben[msg.sender] = startGuthaben;
41,129
86
// fixed window oracle that recomputes the average price for the entire epochPeriod once every epochPeriod note that the price average is only guaranteed to be over at least 1 epochPeriod, but may be over a longer epochPeriodThis version 2 supports querying twap with shorted period (ie 2hrs for BSDB reference price)
contract OracleMultiPairV2 is Ownable { using FixedPoint for *; using SafeMath for uint256; using UQ112x112 for uint224; /* ========= CONSTANT VARIABLES ======== */ uint256 public constant BPOOL_BONE = 10**18; uint256 public constant ORACLE_RESERVE_MINIMUM = 10000 ether; // $10,000 /* ========== STATE VARIABLES ========== */ // governance address public operator; // epoch uint256 public startTime; uint256 public lastEpochTime; uint256 public epoch; // for display only uint256 public epochPeriod; // 2-hours update uint256 public lastUpdateHour; uint256 public updatePeriod; mapping(uint256 => uint112) public epochPrice; // BPool address public mainToken; address[] public sideTokens; uint256[] public sideTokenDecimals; IBPool[] public pools; // Pool price for update in cumulative epochPeriod uint32 public blockTimestampCumulativeLast; uint public priceCumulative; // oracle uint32 public blockTimestampLast; uint256 public priceCumulativeLast; FixedPoint.uq112x112 public priceAverage; event Updated(uint256 priceCumulativeLast); /* ========== CONSTRUCTOR ========== */ constructor( address[] memory _pools, address _mainToken, address[] memory _sideTokens, uint256 _epoch, uint256 _epochPeriod, uint256 _lastEpochTime, uint256 _updatePeriod, uint256 _lastUpdateHour ) public { require(_pools.length == _sideTokens.length, "ERR_LENGTH_MISMATCH"); mainToken = _mainToken; for (uint256 i = 0; i < _pools.length; i++) { IBPool pool = IBPool(_pools[i]); require(pool.isBound(_mainToken) && pool.isBound(_sideTokens[i]), "!bound"); require(pool.getBalance(_mainToken) != 0 && pool.getBalance(_sideTokens[i]) != 0, "OracleMultiPair: NO_RESERVES"); // ensure that there's liquidity in the pool pools.push(pool); sideTokens.push(_sideTokens[i]); sideTokenDecimals.push(IDecimals(_sideTokens[i]).decimals()); } epoch = _epoch; epochPeriod = _epochPeriod; lastEpochTime = _lastEpochTime; lastUpdateHour = _lastUpdateHour; updatePeriod = _updatePeriod; operator = msg.sender; } /* ========== GOVERNANCE ========== */ function setOperator(address _operator) external onlyOperator { operator = _operator; } function setEpoch(uint256 _epoch) external onlyOperator { epoch = _epoch; } function setEpochPeriod(uint256 _epochPeriod) external onlyOperator { require(_epochPeriod >= 1 hours && _epochPeriod <= 48 hours, '_epochPeriod out of range'); epochPeriod = _epochPeriod; } function setLastUpdateHour(uint256 _lastUpdateHour) external onlyOperator { require(_lastUpdateHour % 3600 == 0, '_lastUpdateHour is not valid'); lastUpdateHour = _lastUpdateHour; } function setUpdatePeriod(uint256 _updatePeriod) external onlyOperator { require(_updatePeriod >= 1 hours && _updatePeriod <= epochPeriod, '_updatePeriod out of range'); updatePeriod = _updatePeriod; } function addPool(address _pool, address _sideToken) public onlyOperator { IBPool pool = IBPool(_pool); require(pool.isBound(mainToken) && pool.isBound(_sideToken), "!bound"); require(pool.getBalance(mainToken) != 0 && pool.getBalance(_sideToken) != 0, "OracleMultiPair: NO_RESERVES"); // ensure that there's liquidity in the pool pools.push(pool); sideTokens.push(_sideToken); sideTokenDecimals.push(IDecimals(_sideToken).decimals()); } function removePool(address _pool, address _sideToken) public onlyOperator { uint last = pools.length - 1; for (uint256 i = 0; i < pools.length; i++) { if (address(pools[i]) == _pool && sideTokens[i] == _sideToken) { pools[i] = pools[last]; sideTokens[i] = sideTokens[last]; sideTokenDecimals[i] = sideTokenDecimals[last]; pools.pop(); sideTokens.pop(); sideTokenDecimals.pop(); break; } } } /* =================== Modifier =================== */ modifier checkEpoch { uint256 _nextEpochPoint = nextEpochPoint(); require(now >= _nextEpochPoint, "OracleMultiPair: not opened yet"); _; for (;;) { lastEpochTime = _nextEpochPoint; ++epoch; _nextEpochPoint = nextEpochPoint(); if (now < _nextEpochPoint) break; } } modifier onlyOperator() { require(operator == msg.sender, "OracleMultiPair: caller is not the operator"); _; } /* ========== VIEW FUNCTIONS ========== */ function nextEpochPoint() public view returns (uint256) { return lastEpochTime.add(epochPeriod); } function nextUpdateHour() public view returns (uint256) { return lastUpdateHour.add(updatePeriod); } /* ========== MUTABLE FUNCTIONS ========== */ // update reserves and, on the first call per block, price accumulators function updateCumulative() public { uint256 _nextUpdateHour = lastUpdateHour.add(updatePeriod); if (now >= _nextUpdateHour) { uint totalMainPriceWeight; uint totalMainPoolBal; for (uint256 i = 0; i < pools.length; i++) { uint _decimalFactor = 10 ** (uint256(18).sub(sideTokenDecimals[i])); uint tokenMainPrice = pools[i].getSpotPrice(sideTokens[i], mainToken).mul(_decimalFactor); require(tokenMainPrice != 0, "!price"); uint reserveBal = pools[i].getBalance(sideTokens[i]).mul(_decimalFactor); require(reserveBal >= ORACLE_RESERVE_MINIMUM, "!min reserve"); uint tokenBal = pools[i].getBalance(mainToken); totalMainPriceWeight = totalMainPriceWeight.add(tokenMainPrice.mul(tokenBal).div(BPOOL_BONE)); totalMainPoolBal = totalMainPoolBal.add(tokenBal); } require(totalMainPriceWeight <= uint112(- 1) && totalMainPoolBal <= uint112(- 1), 'BPool: OVERFLOW'); uint32 blockTimestamp = uint32(block.timestamp % 2 ** 32); uint32 timeElapsed = blockTimestamp - blockTimestampCumulativeLast; // overflow is desired if (timeElapsed > 0 && totalMainPoolBal != 0) { // * never overflows, and + overflow is desired priceCumulative += uint(UQ112x112.encode(uint112(totalMainPriceWeight)).uqdiv(uint112(totalMainPoolBal))) * timeElapsed; blockTimestampCumulativeLast = blockTimestamp; } lastUpdateHour = _nextUpdateHour; } } /** @dev Updates 1-day EMA price. */ function update() external checkEpoch { updateCumulative(); uint32 timeElapsed = blockTimestampCumulativeLast - blockTimestampLast; // overflow is desired if (timeElapsed == 0) { // prevent divided by zero return; } // overflow is desired, casting never truncates // cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed priceAverage = FixedPoint.uq112x112(uint224((priceCumulative - priceCumulativeLast) / timeElapsed)); priceCumulativeLast = priceCumulative; blockTimestampLast = blockTimestampCumulativeLast; epochPrice[epoch] = priceAverage.decode(); emit Updated(priceCumulative); } // note this will always return 0 before update has been called successfully for the first time. function consult(address token, uint256 amountIn) external view returns (uint144 amountOut) { require(token == mainToken, "OracleMultiPair: INVALID_TOKEN"); require(now.sub(blockTimestampLast) <= epochPeriod, "OracleMultiPair: Price out-of-date"); amountOut = priceAverage.mul(amountIn).decode144(); } function twap(uint256 _amountIn) external view returns (uint144) { uint32 timeElapsed = blockTimestampCumulativeLast - blockTimestampLast; return (timeElapsed == 0) ? priceAverage.mul(_amountIn).decode144() : FixedPoint.uq112x112(uint224((priceCumulative - priceCumulativeLast) / timeElapsed)).mul(_amountIn).decode144(); } function governanceRecoverUnsupported(IERC20 _token, uint256 _amount, address _to) external onlyOperator { _token.transfer(_to, _amount); } }
contract OracleMultiPairV2 is Ownable { using FixedPoint for *; using SafeMath for uint256; using UQ112x112 for uint224; /* ========= CONSTANT VARIABLES ======== */ uint256 public constant BPOOL_BONE = 10**18; uint256 public constant ORACLE_RESERVE_MINIMUM = 10000 ether; // $10,000 /* ========== STATE VARIABLES ========== */ // governance address public operator; // epoch uint256 public startTime; uint256 public lastEpochTime; uint256 public epoch; // for display only uint256 public epochPeriod; // 2-hours update uint256 public lastUpdateHour; uint256 public updatePeriod; mapping(uint256 => uint112) public epochPrice; // BPool address public mainToken; address[] public sideTokens; uint256[] public sideTokenDecimals; IBPool[] public pools; // Pool price for update in cumulative epochPeriod uint32 public blockTimestampCumulativeLast; uint public priceCumulative; // oracle uint32 public blockTimestampLast; uint256 public priceCumulativeLast; FixedPoint.uq112x112 public priceAverage; event Updated(uint256 priceCumulativeLast); /* ========== CONSTRUCTOR ========== */ constructor( address[] memory _pools, address _mainToken, address[] memory _sideTokens, uint256 _epoch, uint256 _epochPeriod, uint256 _lastEpochTime, uint256 _updatePeriod, uint256 _lastUpdateHour ) public { require(_pools.length == _sideTokens.length, "ERR_LENGTH_MISMATCH"); mainToken = _mainToken; for (uint256 i = 0; i < _pools.length; i++) { IBPool pool = IBPool(_pools[i]); require(pool.isBound(_mainToken) && pool.isBound(_sideTokens[i]), "!bound"); require(pool.getBalance(_mainToken) != 0 && pool.getBalance(_sideTokens[i]) != 0, "OracleMultiPair: NO_RESERVES"); // ensure that there's liquidity in the pool pools.push(pool); sideTokens.push(_sideTokens[i]); sideTokenDecimals.push(IDecimals(_sideTokens[i]).decimals()); } epoch = _epoch; epochPeriod = _epochPeriod; lastEpochTime = _lastEpochTime; lastUpdateHour = _lastUpdateHour; updatePeriod = _updatePeriod; operator = msg.sender; } /* ========== GOVERNANCE ========== */ function setOperator(address _operator) external onlyOperator { operator = _operator; } function setEpoch(uint256 _epoch) external onlyOperator { epoch = _epoch; } function setEpochPeriod(uint256 _epochPeriod) external onlyOperator { require(_epochPeriod >= 1 hours && _epochPeriod <= 48 hours, '_epochPeriod out of range'); epochPeriod = _epochPeriod; } function setLastUpdateHour(uint256 _lastUpdateHour) external onlyOperator { require(_lastUpdateHour % 3600 == 0, '_lastUpdateHour is not valid'); lastUpdateHour = _lastUpdateHour; } function setUpdatePeriod(uint256 _updatePeriod) external onlyOperator { require(_updatePeriod >= 1 hours && _updatePeriod <= epochPeriod, '_updatePeriod out of range'); updatePeriod = _updatePeriod; } function addPool(address _pool, address _sideToken) public onlyOperator { IBPool pool = IBPool(_pool); require(pool.isBound(mainToken) && pool.isBound(_sideToken), "!bound"); require(pool.getBalance(mainToken) != 0 && pool.getBalance(_sideToken) != 0, "OracleMultiPair: NO_RESERVES"); // ensure that there's liquidity in the pool pools.push(pool); sideTokens.push(_sideToken); sideTokenDecimals.push(IDecimals(_sideToken).decimals()); } function removePool(address _pool, address _sideToken) public onlyOperator { uint last = pools.length - 1; for (uint256 i = 0; i < pools.length; i++) { if (address(pools[i]) == _pool && sideTokens[i] == _sideToken) { pools[i] = pools[last]; sideTokens[i] = sideTokens[last]; sideTokenDecimals[i] = sideTokenDecimals[last]; pools.pop(); sideTokens.pop(); sideTokenDecimals.pop(); break; } } } /* =================== Modifier =================== */ modifier checkEpoch { uint256 _nextEpochPoint = nextEpochPoint(); require(now >= _nextEpochPoint, "OracleMultiPair: not opened yet"); _; for (;;) { lastEpochTime = _nextEpochPoint; ++epoch; _nextEpochPoint = nextEpochPoint(); if (now < _nextEpochPoint) break; } } modifier onlyOperator() { require(operator == msg.sender, "OracleMultiPair: caller is not the operator"); _; } /* ========== VIEW FUNCTIONS ========== */ function nextEpochPoint() public view returns (uint256) { return lastEpochTime.add(epochPeriod); } function nextUpdateHour() public view returns (uint256) { return lastUpdateHour.add(updatePeriod); } /* ========== MUTABLE FUNCTIONS ========== */ // update reserves and, on the first call per block, price accumulators function updateCumulative() public { uint256 _nextUpdateHour = lastUpdateHour.add(updatePeriod); if (now >= _nextUpdateHour) { uint totalMainPriceWeight; uint totalMainPoolBal; for (uint256 i = 0; i < pools.length; i++) { uint _decimalFactor = 10 ** (uint256(18).sub(sideTokenDecimals[i])); uint tokenMainPrice = pools[i].getSpotPrice(sideTokens[i], mainToken).mul(_decimalFactor); require(tokenMainPrice != 0, "!price"); uint reserveBal = pools[i].getBalance(sideTokens[i]).mul(_decimalFactor); require(reserveBal >= ORACLE_RESERVE_MINIMUM, "!min reserve"); uint tokenBal = pools[i].getBalance(mainToken); totalMainPriceWeight = totalMainPriceWeight.add(tokenMainPrice.mul(tokenBal).div(BPOOL_BONE)); totalMainPoolBal = totalMainPoolBal.add(tokenBal); } require(totalMainPriceWeight <= uint112(- 1) && totalMainPoolBal <= uint112(- 1), 'BPool: OVERFLOW'); uint32 blockTimestamp = uint32(block.timestamp % 2 ** 32); uint32 timeElapsed = blockTimestamp - blockTimestampCumulativeLast; // overflow is desired if (timeElapsed > 0 && totalMainPoolBal != 0) { // * never overflows, and + overflow is desired priceCumulative += uint(UQ112x112.encode(uint112(totalMainPriceWeight)).uqdiv(uint112(totalMainPoolBal))) * timeElapsed; blockTimestampCumulativeLast = blockTimestamp; } lastUpdateHour = _nextUpdateHour; } } /** @dev Updates 1-day EMA price. */ function update() external checkEpoch { updateCumulative(); uint32 timeElapsed = blockTimestampCumulativeLast - blockTimestampLast; // overflow is desired if (timeElapsed == 0) { // prevent divided by zero return; } // overflow is desired, casting never truncates // cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed priceAverage = FixedPoint.uq112x112(uint224((priceCumulative - priceCumulativeLast) / timeElapsed)); priceCumulativeLast = priceCumulative; blockTimestampLast = blockTimestampCumulativeLast; epochPrice[epoch] = priceAverage.decode(); emit Updated(priceCumulative); } // note this will always return 0 before update has been called successfully for the first time. function consult(address token, uint256 amountIn) external view returns (uint144 amountOut) { require(token == mainToken, "OracleMultiPair: INVALID_TOKEN"); require(now.sub(blockTimestampLast) <= epochPeriod, "OracleMultiPair: Price out-of-date"); amountOut = priceAverage.mul(amountIn).decode144(); } function twap(uint256 _amountIn) external view returns (uint144) { uint32 timeElapsed = blockTimestampCumulativeLast - blockTimestampLast; return (timeElapsed == 0) ? priceAverage.mul(_amountIn).decode144() : FixedPoint.uq112x112(uint224((priceCumulative - priceCumulativeLast) / timeElapsed)).mul(_amountIn).decode144(); } function governanceRecoverUnsupported(IERC20 _token, uint256 _amount, address _to) external onlyOperator { _token.transfer(_to, _amount); } }
48,494
0
// --- Structs and enums ---
struct Intent {
struct Intent {
29,370
17
// global pseudo-randomization seed
PRNG.Data seed;
PRNG.Data seed;
22,291
100
// Validates a fill (signature and instance identifier) fill the approval signed by the OperatorBlockchain sig the signature on the fill /
function checkFillSig( Fill memory fill, bytes memory sig ) public view returns (bool)
function checkFillSig( Fill memory fill, bytes memory sig ) public view returns (bool)
2,391
90
// Pass if Token check if not locked or stopped delegation
if (Validator(node.validatorAddress).locked() || !Validator(node.validatorAddress).delegation()) continue; uint256 toStakeNode; { uint256 targetNode = (targetStake * node.points) / totalPoints_; toStakeNode = _min(toStake, _positiveSub(targetNode, node.staked)); }
if (Validator(node.validatorAddress).locked() || !Validator(node.validatorAddress).delegation()) continue; uint256 toStakeNode; { uint256 targetNode = (targetStake * node.points) / totalPoints_; toStakeNode = _min(toStake, _positiveSub(targetNode, node.staked)); }
34,093
232
// Address of Collybus
Collybus public immutable collybus; constructor( address senatus, address guardian, uint256 delay, address collybus_
Collybus public immutable collybus; constructor( address senatus, address guardian, uint256 delay, address collybus_
4,813
47
// farm token collection
address public _farmTokenCollection;
address public _farmTokenCollection;
57,064
30
// given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut
function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut
17,140
4
// BioX Token
library SafeMath{ function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
library SafeMath{ function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
4,606
252
// CKToken must be in a pending state and module must be in pending state /
function _validateOnlyValidAndPendingCK(ICKToken _ckToken) internal view { require(controller.isCK(address(_ckToken)), "Must be controller-enabled CKToken"); require(isCKPendingInitialization(_ckToken), "Must be pending initialization"); }
function _validateOnlyValidAndPendingCK(ICKToken _ckToken) internal view { require(controller.isCK(address(_ckToken)), "Must be controller-enabled CKToken"); require(isCKPendingInitialization(_ckToken), "Must be pending initialization"); }
19,338
86
// View function to check whether the supply has been capped.
function isSupplyCapped() public view returns (bool) { return _supplycapped; }
function isSupplyCapped() public view returns (bool) { return _supplycapped; }
28,128
3
// Returns the address of the current fee wallet. /
function getFeeWallet() external view returns (address) { return _feeWallet; }
function getFeeWallet() external view returns (address) { return _feeWallet; }
20,883