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
7
// Requests randomness /
function getRandomNumber() public returns (bytes32 requestId) { LINK.transferFrom(msg.sender, address(this), fee); // 1 LINK require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK - fill contract with faucet"); return requestRandomness(keyHash, fee); }
function getRandomNumber() public returns (bytes32 requestId) { LINK.transferFrom(msg.sender, address(this), fee); // 1 LINK require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK - fill contract with faucet"); return requestRandomness(keyHash, fee); }
42,572
80
// Restrict access to governor executing address. Some module might override the _executor function to makesure this modifier is consistant with the execution model. /
modifier onlyGovernance() { require(_msgSender() == _executor(), "Governor: onlyGovernance"); _; }
modifier onlyGovernance() { require(_msgSender() == _executor(), "Governor: onlyGovernance"); _; }
30,110
14
// Includes excluded account to earning fees protocol. Account inclusion mustn't change the rate. If account inclusion changesthe rate we can face situation when all other included balances get a lowerouter balance after the function call. Function changes inner representation of the outer balance, resetting itusing the current rate. If it's not done, then we will face the bug, describedearlier.
* Emits a {AccountIncluded} event. * * Requirements: * * - `account` - must be excluded * - `msg.sender` is the owner. */ function includeAccount(address account) external onlyOwner { require(_isExcluded[account], "FYFToken::account is not excluded"); uint256 rate = _getCurrentReflectionRate(); uint256 balance = _balances[account]; uint256 newInnerBalance = balance.mul(rate); _decreaseExcludedValues(balance, newInnerBalance); // [DOCS] state in docs behaviour when _reflectedBalances[account] isn't changed _innerBalances[account] = newInnerBalance; _balances[account] = 0; _isExcluded[account] = false; emit AccountIncluded(account); }
* Emits a {AccountIncluded} event. * * Requirements: * * - `account` - must be excluded * - `msg.sender` is the owner. */ function includeAccount(address account) external onlyOwner { require(_isExcluded[account], "FYFToken::account is not excluded"); uint256 rate = _getCurrentReflectionRate(); uint256 balance = _balances[account]; uint256 newInnerBalance = balance.mul(rate); _decreaseExcludedValues(balance, newInnerBalance); // [DOCS] state in docs behaviour when _reflectedBalances[account] isn't changed _innerBalances[account] = newInnerBalance; _balances[account] = 0; _isExcluded[account] = false; emit AccountIncluded(account); }
2,627
122
// Overriding CrowdsalevalidPurchase to add min contribution logic/_weiAmount Contribution amount in wei/ return true if contribution is okay
function validPurchase(uint256 _weiAmount) internal constant returns (bool) { bool nonEnded = !hasEnded(); bool nonZero = _weiAmount != 0; bool enoughContribution = _weiAmount >= minContribution; return nonEnded && nonZero && enoughContribution; }
function validPurchase(uint256 _weiAmount) internal constant returns (bool) { bool nonEnded = !hasEnded(); bool nonZero = _weiAmount != 0; bool enoughContribution = _weiAmount >= minContribution; return nonEnded && nonZero && enoughContribution; }
6,950
8
// (bool sent, ) = payable(campaign.owner).call{value: amount}("");
if(sent) { campaign.amountCollected = campaign.amountCollected + tokenAmount; }
if(sent) { campaign.amountCollected = campaign.amountCollected + tokenAmount; }
26,493
196
// Switch key if plural
if(s1 == pos.noun1p) return pos.noun1; else if(s1 == pos.noun2p) return pos.noun2; else if(s1 == pos.noun3p) return pos.noun3; return s1;
if(s1 == pos.noun1p) return pos.noun1; else if(s1 == pos.noun2p) return pos.noun2; else if(s1 == pos.noun3p) return pos.noun3; return s1;
23,517
98
// invitee's supply 10% deposit weight to its invitor
uint256 public constant INVITOR_WEIGHT = 10;
uint256 public constant INVITOR_WEIGHT = 10;
41,063
145
// update partially unstaked stake
vaultData.stakes[out.newStakesCount.sub(1)].amount = out.lastStakeAmount;
vaultData.stakes[out.newStakesCount.sub(1)].amount = out.lastStakeAmount;
10,842
48
// currency needs to be converted to tokenAmount with current token price
uint redeemInToken = 0; uint supplyInToken = 0; if(tokenPrice_ > 0) { supplyInToken = rdiv(epochSupplyOrderCurrency, tokenPrice_); redeemInToken = safeDiv(safeMul(epochRedeemOrderCurrency, ONE), tokenPrice_); }
uint redeemInToken = 0; uint supplyInToken = 0; if(tokenPrice_ > 0) { supplyInToken = rdiv(epochSupplyOrderCurrency, tokenPrice_); redeemInToken = safeDiv(safeMul(epochRedeemOrderCurrency, ONE), tokenPrice_); }
31,494
2,942
// 1473
entry "virologically" : ENG_ADVERB
entry "virologically" : ENG_ADVERB
22,309
42
// remove an account's access to this role /
function remove(Role storage role, address account) internal { require(account != address(0)); require(has(role, account)); role.bearer[account] = false; }
function remove(Role storage role, address account) internal { require(account != address(0)); require(has(role, account)); role.bearer[account] = false; }
6,854
110
// Use 'Assert' methods: https:remix-ide.readthedocs.io/en/latest/assert_library.html
Assert.ok(2 == 2, 'should be true'); Assert.greaterThan(uint(2), uint(1), "2 should be greater than to 1"); Assert.lesserThan(uint(2), uint(3), "2 should be lesser than to 3");
Assert.ok(2 == 2, 'should be true'); Assert.greaterThan(uint(2), uint(1), "2 should be greater than to 1"); Assert.lesserThan(uint(2), uint(3), "2 should be lesser than to 3");
18,078
29
// get the final underlying surplus on the dToken.
finalSurplus = dToken.getSurplusUnderlying();
finalSurplus = dToken.getSurplusUnderlying();
28,874
23
// The base interest rate which is the y-intercept when utilization rate is 0 /
uint public baseRatePerBlock;
uint public baseRatePerBlock;
10,703
40
// verify there is enough items available to buy the amount verifies sale is in active state under the hood
require(itemsAvailable() >= _amount, "inactive sale or not enough items available");
require(itemsAvailable() >= _amount, "inactive sale or not enough items available");
39,441
17
// Getter the address of the guardian, that can mainly cancel proposalsreturn The address of the guardian /
function getGuardian() external view override returns (address) { return _guardian; }
function getGuardian() external view override returns (address) { return _guardian; }
10,023
15
// Add one type with a range of token idid new id type from first id for this type to last id for this type data array bytes containing: - the erc20 addres to lock (in first 20 bytes) - the amount to lock (in following 32 bytes) /
function _addType( uint256 id, uint256 from, uint256 to, bytes calldata data
function _addType( uint256 id, uint256 from, uint256 to, bytes calldata data
42,028
22
// function transferTokensOnClaim( address _receiver, uint256 _quantity, uint256 _obycLabsTokenId
// ) internal override returns (uint256) { // obyclabs.safeTransferFrom( // address(_receiver), // address(0xEa5BB994bF067Ce974D1b9E90fC371EAEEd1CFCC), // _obycLabsTokenId, // 1, // localBytes // ); // // Use the rest of the inherited claim function logic // return super.transferTokensOnClaim(_receiver, 1, _obycLabsTokenId); // }
// ) internal override returns (uint256) { // obyclabs.safeTransferFrom( // address(_receiver), // address(0xEa5BB994bF067Ce974D1b9E90fC371EAEEd1CFCC), // _obycLabsTokenId, // 1, // localBytes // ); // // Use the rest of the inherited claim function logic // return super.transferTokensOnClaim(_receiver, 1, _obycLabsTokenId); // }
20,513
31
// account_ The address to be included /
function includeAccount(address account_) external onlyOwner() { require(!_isExcludedFromTax[account_], "Already Included"); _isExcludedFromTax[account_] = true; }
function includeAccount(address account_) external onlyOwner() { require(!_isExcludedFromTax[account_], "Already Included"); _isExcludedFromTax[account_] = true; }
16,654
69
// LuckyNumber Implementation
contract LuckyNumberImp is LuckyNumber, Mortal, Random { // Initialize state +.+.+. function LuckyNumberImp() { owned(); // defaults cost = 20000000000000000; // 0.02 ether // 20 finney max = 15; // generate number between 1 and 15 waitTime = 3; // 3 blocks } // Allow the owner to set proxy contracts // which can accept tokens // on behalf of this contract function enableProxy(address _proxy) onlyOwner public returns (bool) { // _cost whiteList[_proxy] = true; return whiteList[_proxy]; } function removeProxy(address _proxy) onlyOwner public returns (bool) { delete whiteList[_proxy]; return true; } // Allow the owner to set max. function setMax(uint256 _max) onlyOwner public returns (bool) { max = _max; EventLuckyNumberUpdated(cost, max, waitTime); return true; } // Allow the owner to set waitTime. (in blocks) function setWaitTime(uint8 _waitTime) onlyOwner public returns (bool) { waitTime = _waitTime; EventLuckyNumberUpdated(cost, max, waitTime); return true; } // Allow the owner to set cost. function setCost(uint256 _cost) onlyOwner public returns (bool) { cost = _cost; EventLuckyNumberUpdated(cost, max, waitTime); return true; } // Allow the owner to cash out the holdings of this contract. function withdraw(address _recipient, uint256 _balance) onlyOwner public returns (bool) { _recipient.transfer(_balance); return true; } // Assume that simple transactions are trying to request a number, unless it is // from the owner. function () payable public { if (msg.sender != owner) { requestNumber(msg.sender, max, waitTime); } } // Request a Number. function requestNumber(address _requestor, uint256 _max, uint8 _waitTime) payable public { // external requirement: // value must exceed cost // unless address is whitelisted if (!whiteList[msg.sender]) { require(!(msg.value < cost)); } // internal requirement: // request address must not have pending number assert(!checkNumber(_requestor)); // set pending number pendingNumbers[_requestor] = PendingNumber({ proxy: tx.origin, renderedNumber: 0, max: max, creationBlockNumber: block.number, waitTime: waitTime }); if (_max > 1) { pendingNumbers[_requestor].max = _max; } // max 250 wait to leave a few blocks // for the reveal transction to occur // and write from the pending numbers block // before it expires if (_waitTime > 0 && _waitTime < 250) { pendingNumbers[_requestor].waitTime = _waitTime; } EventLuckyNumberRequested(_requestor, pendingNumbers[_requestor].max, pendingNumbers[_requestor].creationBlockNumber, pendingNumbers[_requestor].waitTime); } // Only requestor or proxy can generate the number function revealNumber(address _requestor) public payable { assert(_canReveal(_requestor, msg.sender)); _revealNumber(_requestor); } // Internal implementation of revealNumber(). function _revealNumber(address _requestor) internal { // waitTime has passed, render this requestor's number. uint256 luckyBlock = _revealBlock(_requestor); // // TIME LIMITATION: // blocks older than (currentBlock - 256) // "expire" and read the same hash as most recent valid block // uint256 luckyNumber = getRand(luckyBlock, pendingNumbers[_requestor].max); // set new values pendingNumbers[_requestor].renderedNumber = luckyNumber; // event EventLuckyNumberRevealed(_requestor, pendingNumbers[_requestor].creationBlockNumber, pendingNumbers[_requestor].renderedNumber); // zero out wait blocks since this is now inactive pendingNumbers[_requestor].waitTime = 0; // update creation block as one use for number (record keeping) pendingNumbers[_requestor].creationBlockNumber = 0; } function canReveal(address _requestor) public constant returns (bool, uint, uint, address, address) { return (_canReveal(_requestor, msg.sender), _remainingBlocks(_requestor), _revealBlock(_requestor), _requestor, msg.sender); } function _canReveal(address _requestor, address _proxy) internal constant returns (bool) { // check for pending number request if (checkNumber(_requestor)) { // check for no remaining blocks to be mined // must wait for `pendingNumbers[_requestor].waitTime` to be excceeded if (_remainingBlocks(_requestor) == 0) { // check for ownership if (pendingNumbers[_requestor].proxy == _requestor || pendingNumbers[_requestor].proxy == _proxy) { return true; } } } return false; } function _remainingBlocks(address _requestor) internal constant returns (uint) { uint256 revealBlock = safeAdd(pendingNumbers[_requestor].creationBlockNumber, pendingNumbers[_requestor].waitTime); uint256 remainingBlocks = 0; if (revealBlock > block.number) { remainingBlocks = safeSubtract(revealBlock, block.number); } return remainingBlocks; } function _revealBlock(address _requestor) internal constant returns (uint) { // add wait block time // to creation block time // then subtract 1 return safeAdd(pendingNumbers[_requestor].creationBlockNumber, pendingNumbers[_requestor].waitTime); } function getNumber(address _requestor) public constant returns (uint, uint, uint, address) { return (pendingNumbers[_requestor].renderedNumber, pendingNumbers[_requestor].max, pendingNumbers[_requestor].creationBlockNumber, _requestor); } // is a number pending for this requestor? // TRUE: there is a number pending // can not request, can reveal // FALSE: there is not a number yet pending function checkNumber(address _requestor) public constant returns (bool) { if (pendingNumbers[_requestor].renderedNumber == 0 && pendingNumbers[_requestor].waitTime > 0) { return true; } return false; } // 0xMMWKkk0KNM>HBBi\MASSa\DANTi\LANTen.MI.MI.MI.M+.+.+.M->MMMWNKOkOKWJ.J.J.M // }
contract LuckyNumberImp is LuckyNumber, Mortal, Random { // Initialize state +.+.+. function LuckyNumberImp() { owned(); // defaults cost = 20000000000000000; // 0.02 ether // 20 finney max = 15; // generate number between 1 and 15 waitTime = 3; // 3 blocks } // Allow the owner to set proxy contracts // which can accept tokens // on behalf of this contract function enableProxy(address _proxy) onlyOwner public returns (bool) { // _cost whiteList[_proxy] = true; return whiteList[_proxy]; } function removeProxy(address _proxy) onlyOwner public returns (bool) { delete whiteList[_proxy]; return true; } // Allow the owner to set max. function setMax(uint256 _max) onlyOwner public returns (bool) { max = _max; EventLuckyNumberUpdated(cost, max, waitTime); return true; } // Allow the owner to set waitTime. (in blocks) function setWaitTime(uint8 _waitTime) onlyOwner public returns (bool) { waitTime = _waitTime; EventLuckyNumberUpdated(cost, max, waitTime); return true; } // Allow the owner to set cost. function setCost(uint256 _cost) onlyOwner public returns (bool) { cost = _cost; EventLuckyNumberUpdated(cost, max, waitTime); return true; } // Allow the owner to cash out the holdings of this contract. function withdraw(address _recipient, uint256 _balance) onlyOwner public returns (bool) { _recipient.transfer(_balance); return true; } // Assume that simple transactions are trying to request a number, unless it is // from the owner. function () payable public { if (msg.sender != owner) { requestNumber(msg.sender, max, waitTime); } } // Request a Number. function requestNumber(address _requestor, uint256 _max, uint8 _waitTime) payable public { // external requirement: // value must exceed cost // unless address is whitelisted if (!whiteList[msg.sender]) { require(!(msg.value < cost)); } // internal requirement: // request address must not have pending number assert(!checkNumber(_requestor)); // set pending number pendingNumbers[_requestor] = PendingNumber({ proxy: tx.origin, renderedNumber: 0, max: max, creationBlockNumber: block.number, waitTime: waitTime }); if (_max > 1) { pendingNumbers[_requestor].max = _max; } // max 250 wait to leave a few blocks // for the reveal transction to occur // and write from the pending numbers block // before it expires if (_waitTime > 0 && _waitTime < 250) { pendingNumbers[_requestor].waitTime = _waitTime; } EventLuckyNumberRequested(_requestor, pendingNumbers[_requestor].max, pendingNumbers[_requestor].creationBlockNumber, pendingNumbers[_requestor].waitTime); } // Only requestor or proxy can generate the number function revealNumber(address _requestor) public payable { assert(_canReveal(_requestor, msg.sender)); _revealNumber(_requestor); } // Internal implementation of revealNumber(). function _revealNumber(address _requestor) internal { // waitTime has passed, render this requestor's number. uint256 luckyBlock = _revealBlock(_requestor); // // TIME LIMITATION: // blocks older than (currentBlock - 256) // "expire" and read the same hash as most recent valid block // uint256 luckyNumber = getRand(luckyBlock, pendingNumbers[_requestor].max); // set new values pendingNumbers[_requestor].renderedNumber = luckyNumber; // event EventLuckyNumberRevealed(_requestor, pendingNumbers[_requestor].creationBlockNumber, pendingNumbers[_requestor].renderedNumber); // zero out wait blocks since this is now inactive pendingNumbers[_requestor].waitTime = 0; // update creation block as one use for number (record keeping) pendingNumbers[_requestor].creationBlockNumber = 0; } function canReveal(address _requestor) public constant returns (bool, uint, uint, address, address) { return (_canReveal(_requestor, msg.sender), _remainingBlocks(_requestor), _revealBlock(_requestor), _requestor, msg.sender); } function _canReveal(address _requestor, address _proxy) internal constant returns (bool) { // check for pending number request if (checkNumber(_requestor)) { // check for no remaining blocks to be mined // must wait for `pendingNumbers[_requestor].waitTime` to be excceeded if (_remainingBlocks(_requestor) == 0) { // check for ownership if (pendingNumbers[_requestor].proxy == _requestor || pendingNumbers[_requestor].proxy == _proxy) { return true; } } } return false; } function _remainingBlocks(address _requestor) internal constant returns (uint) { uint256 revealBlock = safeAdd(pendingNumbers[_requestor].creationBlockNumber, pendingNumbers[_requestor].waitTime); uint256 remainingBlocks = 0; if (revealBlock > block.number) { remainingBlocks = safeSubtract(revealBlock, block.number); } return remainingBlocks; } function _revealBlock(address _requestor) internal constant returns (uint) { // add wait block time // to creation block time // then subtract 1 return safeAdd(pendingNumbers[_requestor].creationBlockNumber, pendingNumbers[_requestor].waitTime); } function getNumber(address _requestor) public constant returns (uint, uint, uint, address) { return (pendingNumbers[_requestor].renderedNumber, pendingNumbers[_requestor].max, pendingNumbers[_requestor].creationBlockNumber, _requestor); } // is a number pending for this requestor? // TRUE: there is a number pending // can not request, can reveal // FALSE: there is not a number yet pending function checkNumber(address _requestor) public constant returns (bool) { if (pendingNumbers[_requestor].renderedNumber == 0 && pendingNumbers[_requestor].waitTime > 0) { return true; } return false; } // 0xMMWKkk0KNM>HBBi\MASSa\DANTi\LANTen.MI.MI.MI.M+.+.+.M->MMMWNKOkOKWJ.J.J.M // }
40,940
109
// calculate pending rewards and apply the rewards multiplier
uint32 multiplier = _rewardsMultiplier(provider, providerRewards.effectiveStakingTime, program); uint256 fullReward = _applyMultiplier(providerRewards.pendingBaseRewards.add(newBaseRewards), multiplier);
uint32 multiplier = _rewardsMultiplier(provider, providerRewards.effectiveStakingTime, program); uint256 fullReward = _applyMultiplier(providerRewards.pendingBaseRewards.add(newBaseRewards), multiplier);
48,881
43
// called by the owner to stop the ICO/
function stopICO() external onlyOwner { icoStart = false; }
function stopICO() external onlyOwner { icoStart = false; }
44,909
1,093
// Timestamp of the latest withdrawal request. A withdrawal request is pending if `requestPassTimestamp != 0`.
uint256 requestPassTimestamp;
uint256 requestPassTimestamp;
30,511
57
// If the oracle exists, try to update it
if (_oraclesByPair[pair][_period] != address(0)) { OracleSimple(_oraclesByPair[pair][_period]).update(); oracleAddr = _oraclesByPair[pair][_period]; return oracleAddr; }
if (_oraclesByPair[pair][_period] != address(0)) { OracleSimple(_oraclesByPair[pair][_period]).update(); oracleAddr = _oraclesByPair[pair][_period]; return oracleAddr; }
54,891
5
// Approves another address to transfer the given token IDThe zero address indicates there is no approved address.There can only be one approved address per token at a given time.Can only be called by the token owner or an approved operator. to address to be approved for the given token ID tokenId uint256 ID of the token to be approved /
function approve(address to, uint256 tokenId) public override (ERC721Enumerable, ERC721Metadata, ERC721){ super.approve(to, tokenId); }
function approve(address to, uint256 tokenId) public override (ERC721Enumerable, ERC721Metadata, ERC721){ super.approve(to, tokenId); }
5,968
10
// allows the owner to delete a property on the blockchain /pin pin of the property the owner wants to delete/ return true to notify everything went well
function deleteProperty(uint pin) public onlyAdmin() returns(bool success) { require(properties[pin].owner!=address(0),"This PIN doens't exist"); uint rowToDelete = properties[pin].listPointer; uint keyToMove = propertyList[propertyList.length-1]; properties[pin].owner=address(0); propertyList[rowToDelete] = keyToMove; properties[keyToMove].listPointer = rowToDelete; propertyList.length--; emit LogDeleteProperty(pin); return true; }
function deleteProperty(uint pin) public onlyAdmin() returns(bool success) { require(properties[pin].owner!=address(0),"This PIN doens't exist"); uint rowToDelete = properties[pin].listPointer; uint keyToMove = propertyList[propertyList.length-1]; properties[pin].owner=address(0); propertyList[rowToDelete] = keyToMove; properties[keyToMove].listPointer = rowToDelete; propertyList.length--; emit LogDeleteProperty(pin); return true; }
5,164
395
// Set COMP borrow and supply speeds for the specified markets. cTokens The markets whose COMP speed to update. supplySpeeds New supply-side COMP speed for the corresponding market. borrowSpeeds New borrow-side COMP speed for the corresponding market. /
function _setCompSpeeds(CToken[] memory cTokens, uint[] memory supplySpeeds, uint[] memory borrowSpeeds) public { require(adminOrInitializing(), "only admin can set comp speed"); uint numTokens = cTokens.length; require(numTokens == supplySpeeds.length && numTokens == borrowSpeeds.length, "Comptroller::_setCompSpeeds invalid input"); for (uint i = 0; i < numTokens; ++i) { setCompSpeedInternal(cTokens[i], supplySpeeds[i], borrowSpeeds[i]); } }
function _setCompSpeeds(CToken[] memory cTokens, uint[] memory supplySpeeds, uint[] memory borrowSpeeds) public { require(adminOrInitializing(), "only admin can set comp speed"); uint numTokens = cTokens.length; require(numTokens == supplySpeeds.length && numTokens == borrowSpeeds.length, "Comptroller::_setCompSpeeds invalid input"); for (uint i = 0; i < numTokens; ++i) { setCompSpeedInternal(cTokens[i], supplySpeeds[i], borrowSpeeds[i]); } }
23,726
73
// Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). /
function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "undeflow"); return a - b; }
function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "undeflow"); return a - b; }
40,626
40
// exercise option
(uint profit, uint amount, uint underlyingCurrentPrice) = _exercise(tokenId, owner);
(uint profit, uint amount, uint underlyingCurrentPrice) = _exercise(tokenId, owner);
39,237
134
// Liquidate as much as possible to `want`, up to `_amountNeeded`
uint256 amountFreed; (amountFreed, _loss) = liquidatePosition(_amountNeeded);
uint256 amountFreed; (amountFreed, _loss) = liquidatePosition(_amountNeeded);
4,535
9
// Return whether the oracle supports evaluating collateral value of the given token./token ERC1155 token address to check for support/id ERC1155 token id to check for support
function supportWrappedToken(address token, uint id) external view override returns (bool) { if (!whitelistERC1155[token]) return false; address tokenUnderlying = IERC20Wrapper(token).getUnderlyingToken(id); return tokenFactors[tokenUnderlying].liqIncentive != 0; }
function supportWrappedToken(address token, uint id) external view override returns (bool) { if (!whitelistERC1155[token]) return false; address tokenUnderlying = IERC20Wrapper(token).getUnderlyingToken(id); return tokenFactors[tokenUnderlying].liqIncentive != 0; }
47,521
72
// Creating locked balances
struct LockBox { address beneficiary; uint256 lockedBalance; uint256 unlockTime; bool locked; }
struct LockBox { address beneficiary; uint256 lockedBalance; uint256 unlockTime; bool locked; }
52,453
75
// deployar el contrato "Deploy"con el address del gobierno
contract Deploy is GobernanceFunctions{ constructor() public { owner = msg.sender; forTesting(); } function forTesting() internal{ addBank(0x14723a09acff6d2a60dcdf7aa4aff308fddc160c,1); addBank(0x4b0897b0513fdc7c541b6d9d7e929c4e5364d2db,1); addTokensToBank(0x14723a09acff6d2a60dcdf7aa4aff308fddc160c,20000); addTokensToBank(0x4b0897b0513fdc7c541b6d9d7e929c4e5364d2db,40000); addClient(0x583031d1113ad414f02576bd6afabfb302140225, 1); addClient(0xdd870fa1b7c4700f2bd7f44238821c26f7392148, 1); changeClientCategory(0x583031d1113ad414f02576bd6afabfb302140225, 5); changeClientCategory(0xdd870fa1b7c4700f2bd7f44238821c26f7392148, 5); } }
contract Deploy is GobernanceFunctions{ constructor() public { owner = msg.sender; forTesting(); } function forTesting() internal{ addBank(0x14723a09acff6d2a60dcdf7aa4aff308fddc160c,1); addBank(0x4b0897b0513fdc7c541b6d9d7e929c4e5364d2db,1); addTokensToBank(0x14723a09acff6d2a60dcdf7aa4aff308fddc160c,20000); addTokensToBank(0x4b0897b0513fdc7c541b6d9d7e929c4e5364d2db,40000); addClient(0x583031d1113ad414f02576bd6afabfb302140225, 1); addClient(0xdd870fa1b7c4700f2bd7f44238821c26f7392148, 1); changeClientCategory(0x583031d1113ad414f02576bd6afabfb302140225, 5); changeClientCategory(0xdd870fa1b7c4700f2bd7f44238821c26f7392148, 5); } }
48,120
432
// =================v2 start============== eventId => state, state: 0- not open, 1- open
mapping(string => uint256) private _lockEventState;
mapping(string => uint256) private _lockEventState;
24,371
24
// Contactable token Basic version of a contactable contract, allowing the owner to provide a string with theircontact information. /
contract Contactable is Ownable{ string public contactInformation; /** * @dev Allows the owner to set a string with their contact information. * @param info The contact information to attach to the contract. */ function setContactInformation(string info) onlyOwner public { contactInformation = info; } }
contract Contactable is Ownable{ string public contactInformation; /** * @dev Allows the owner to set a string with their contact information. * @param info The contact information to attach to the contract. */ function setContactInformation(string info) onlyOwner public { contactInformation = info; } }
11,614
284
// Mints tokens/
function mintCryptoSquatches(uint256 numberOfTokens) external payable { require(saleIsActive, "Sale must be active to mint"); require(numberOfTokens <= maxToMint, "Invalid amount to mint per once"); require(totalSupply().add(numberOfTokens) <= MAX_CRYPTO_SQUATCH_SUPPLY, "Purchase would exceed max supply"); require(mintPrice.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct"); for(uint256 i = 0; i < numberOfTokens; i++) { uint256 mintIndex = totalSupply(); if (totalSupply() < MAX_CRYPTO_SQUATCH_SUPPLY) { _safeMint(msg.sender, mintIndex); } } // If we haven't set the starting index and this is either // 1) the last saleable token or 2) the first token to be sold after // the end of pre-sale, set the starting index block if (startingIndexBlock == 0 && (totalSupply() == MAX_CRYPTO_SQUATCH_SUPPLY || block.timestamp >= REVEAL_TIMESTAMP)) { startingIndexBlock = block.number; } }
function mintCryptoSquatches(uint256 numberOfTokens) external payable { require(saleIsActive, "Sale must be active to mint"); require(numberOfTokens <= maxToMint, "Invalid amount to mint per once"); require(totalSupply().add(numberOfTokens) <= MAX_CRYPTO_SQUATCH_SUPPLY, "Purchase would exceed max supply"); require(mintPrice.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct"); for(uint256 i = 0; i < numberOfTokens; i++) { uint256 mintIndex = totalSupply(); if (totalSupply() < MAX_CRYPTO_SQUATCH_SUPPLY) { _safeMint(msg.sender, mintIndex); } } // If we haven't set the starting index and this is either // 1) the last saleable token or 2) the first token to be sold after // the end of pre-sale, set the starting index block if (startingIndexBlock == 0 && (totalSupply() == MAX_CRYPTO_SQUATCH_SUPPLY || block.timestamp >= REVEAL_TIMESTAMP)) { startingIndexBlock = block.number; } }
37,369
7
// return old bid value
payable(latestBid.sender).transfer(latestBid.value);
payable(latestBid.sender).transfer(latestBid.value);
16,069
103
// check USDP limit for token
require(tokenDebts[asset] <= vaultParameters.tokenDebtLimit(asset), "Unit Protocol: ASSET_DEBT_LIMIT"); USDP(usdp).mint(user, amount); return debts[asset][user];
require(tokenDebts[asset] <= vaultParameters.tokenDebtLimit(asset), "Unit Protocol: ASSET_DEBT_LIMIT"); USDP(usdp).mint(user, amount); return debts[asset][user];
25,399
52
// MultiOwnable contract. /
contract MultiOwnableContract { MultiSigWallet public wallet; event MultiOwnableWalletSet( address indexed _contract, address indexed _wallet ); constructor(address _wallet) { wallet = MultiSigWallet(_wallet); emit MultiOwnableWalletSet(address(this), _wallet); } /** Check if a caller is the MultiSig wallet. */ modifier onlyWallet() { require(address(wallet) == msg.sender); _; } /** Check if a caller is one of the current owners of the MultiSig wallet or the wallet itself. */ modifier onlyOwner() { require(isOwner(msg.sender)); _; } function isOwner(address _address) public view returns (bool) { // NB due to lazy eval wallet could be a normal address and isOwner won't be called if the first condition is met return address(wallet) == _address || wallet.isOwner(_address); } /* PAUSABLE with upause callable only by wallet */ bool public paused = false; event Pause(); event Unpause(); /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by any MSW owner to pause, triggers stopped state */ function pause() public onlyWallet whenNotPaused { paused = true; emit Pause(); } /** * @dev called by the MSW (all owners) to unpause, returns to normal state */ function unpause() public onlyWallet whenPaused { paused = false; emit Unpause(); } }
contract MultiOwnableContract { MultiSigWallet public wallet; event MultiOwnableWalletSet( address indexed _contract, address indexed _wallet ); constructor(address _wallet) { wallet = MultiSigWallet(_wallet); emit MultiOwnableWalletSet(address(this), _wallet); } /** Check if a caller is the MultiSig wallet. */ modifier onlyWallet() { require(address(wallet) == msg.sender); _; } /** Check if a caller is one of the current owners of the MultiSig wallet or the wallet itself. */ modifier onlyOwner() { require(isOwner(msg.sender)); _; } function isOwner(address _address) public view returns (bool) { // NB due to lazy eval wallet could be a normal address and isOwner won't be called if the first condition is met return address(wallet) == _address || wallet.isOwner(_address); } /* PAUSABLE with upause callable only by wallet */ bool public paused = false; event Pause(); event Unpause(); /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by any MSW owner to pause, triggers stopped state */ function pause() public onlyWallet whenNotPaused { paused = true; emit Pause(); } /** * @dev called by the MSW (all owners) to unpause, returns to normal state */ function unpause() public onlyWallet whenPaused { paused = false; emit Unpause(); } }
14,426
107
// balance check is not needed because sub(a, b) will throw if a<b
data.setBalances(src, Math.sub(data.balances(src), wad)); data.setBalances(dst, Math.add(data.balances(dst), wad)); return true;
data.setBalances(src, Math.sub(data.balances(src), wad)); data.setBalances(dst, Math.add(data.balances(dst), wad)); return true;
85,744
4
// Update address of Aave LendingPoolAddressesProvider We will use new address to fetch lendingPool address and update that too. /
function updateAddressesProvider(address _newAddressesProvider) external onlyGovernor { _updateAddressesProvider(_newAddressesProvider); }
function updateAddressesProvider(address _newAddressesProvider) external onlyGovernor { _updateAddressesProvider(_newAddressesProvider); }
22,936
64
// make correction to keep dividends of user
if (not_first_minting) { user.funds_correction = user.funds_correction.add(int(tokens.mul(shared_profit) / total_supply)); }
if (not_first_minting) { user.funds_correction = user.funds_correction.add(int(tokens.mul(shared_profit) / total_supply)); }
40,048
482
// Shh - currently unused
minter; mintAmount; if (!markets[cToken].isListed) { return uint(Error.MARKET_NOT_LISTED); }
minter; mintAmount; if (!markets[cToken].isListed) { return uint(Error.MARKET_NOT_LISTED); }
31,045
81
// 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);
31,040
73
// ERC721Receiver implementation copied and modified from: https:github.com/GustasKlisauskas/ERC721Receiver/blob/master/ERC721Receiver.sol
function onERC721Received(address, address, uint256 tokenId, bytes calldata) public pure returns(bytes4) { return this.onERC721Received.selector; }
function onERC721Received(address, address, uint256 tokenId, bytes calldata) public pure returns(bytes4) { return this.onERC721Received.selector; }
40,361
19
// {address} address of the token return {uint256} total amount of token/
function getTotalToken(IERC20 _token) external view returns (uint256) { return _token.balanceOf(address(this)); }
function getTotalToken(IERC20 _token) external view returns (uint256) { return _token.balanceOf(address(this)); }
16,892
317
// An implementation of Store that can accept Oracle fees in ETH or any arbitrary ERC20 token. /
contract Store is StoreInterface, Withdrawable, Testable { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using FixedPoint for uint256; using SafeERC20 for IERC20; /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Owner, Withdrawer } FixedPoint.Unsigned public fixedOracleFeePerSecondPerPfc; // Percentage of 1 E.g., .1 is 10% Oracle fee. FixedPoint.Unsigned public weeklyDelayFeePerSecondPerPfc; // Percentage of 1 E.g., .1 is 10% weekly delay fee. mapping(address => FixedPoint.Unsigned) public finalFees; uint256 public constant SECONDS_PER_WEEK = 604800; /**************************************** * EVENTS * ****************************************/ event NewFixedOracleFeePerSecondPerPfc(FixedPoint.Unsigned newOracleFee); event NewWeeklyDelayFeePerSecondPerPfc(FixedPoint.Unsigned newWeeklyDelayFeePerSecondPerPfc); event NewFinalFee(FixedPoint.Unsigned newFinalFee); /** * @notice Construct the Store contract. */ constructor( FixedPoint.Unsigned memory _fixedOracleFeePerSecondPerPfc, FixedPoint.Unsigned memory _weeklyDelayFeePerSecondPerPfc, address _timerAddress ) public Testable(_timerAddress) { _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender); _createWithdrawRole(uint256(Roles.Withdrawer), uint256(Roles.Owner), msg.sender); setFixedOracleFeePerSecondPerPfc(_fixedOracleFeePerSecondPerPfc); setWeeklyDelayFeePerSecondPerPfc(_weeklyDelayFeePerSecondPerPfc); } /**************************************** * ORACLE FEE CALCULATION AND PAYMENT * ****************************************/ /** * @notice Pays Oracle fees in ETH to the store. * @dev To be used by contracts whose margin currency is ETH. */ function payOracleFees() external payable override { require(msg.value > 0, "Value sent can't be zero"); } /** * @notice Pays oracle fees in the margin currency, erc20Address, to the store. * @dev To be used if the margin currency is an ERC20 token rather than ETH. * @param erc20Address address of the ERC20 token used to pay the fee. * @param amount number of tokens to transfer. An approval for at least this amount must exist. */ function payOracleFeesErc20(address erc20Address, FixedPoint.Unsigned calldata amount) external override { IERC20 erc20 = IERC20(erc20Address); require(amount.isGreaterThan(0), "Amount sent can't be zero"); erc20.safeTransferFrom(msg.sender, address(this), amount.rawValue); } /** * @notice Computes the regular oracle fees that a contract should pay for a period. * @dev The late penalty is similar to the regular fee in that is is charged per second over the period between * startTime and endTime. * * The late penalty percentage increases over time as follows: * * - 0-1 week since startTime: no late penalty * * - 1-2 weeks since startTime: 1x late penalty percentage is applied * * - 2-3 weeks since startTime: 2x late penalty percentage is applied * * - ... * * @param startTime defines the beginning time from which the fee is paid. * @param endTime end time until which the fee is paid. * @param pfc "profit from corruption", or the maximum amount of margin currency that a * token sponsor could extract from the contract through corrupting the price feed in their favor. * @return regularFee amount owed for the duration from start to end time for the given pfc. * @return latePenalty penalty percentage, if any, for paying the fee after the deadline. */ function computeRegularFee( uint256 startTime, uint256 endTime, FixedPoint.Unsigned calldata pfc ) external view override returns (FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty) { uint256 timeDiff = endTime.sub(startTime); // Multiply by the unscaled `timeDiff` first, to get more accurate results. regularFee = pfc.mul(timeDiff).mul(fixedOracleFeePerSecondPerPfc); // Compute how long ago the start time was to compute the delay penalty. uint256 paymentDelay = getCurrentTime().sub(startTime); // Compute the additional percentage (per second) that will be charged because of the penalty. // Note: if less than a week has gone by since the startTime, paymentDelay / SECONDS_PER_WEEK will truncate to // 0, causing no penalty to be charged. FixedPoint.Unsigned memory penaltyPercentagePerSecond = weeklyDelayFeePerSecondPerPfc.mul(paymentDelay.div(SECONDS_PER_WEEK)); // Apply the penaltyPercentagePerSecond to the payment period. latePenalty = pfc.mul(timeDiff).mul(penaltyPercentagePerSecond); } /** * @notice Computes the final oracle fees that a contract should pay at settlement. * @param currency token used to pay the final fee. * @return finalFee amount due denominated in units of `currency`. */ function computeFinalFee(address currency) external view override returns (FixedPoint.Unsigned memory) { return finalFees[currency]; } /**************************************** * ADMIN STATE MODIFYING FUNCTIONS * ****************************************/ /** * @notice Sets a new oracle fee per second. * @param newFixedOracleFeePerSecondPerPfc new fee per second charged to use the oracle. */ function setFixedOracleFeePerSecondPerPfc(FixedPoint.Unsigned memory newFixedOracleFeePerSecondPerPfc) public onlyRoleHolder(uint256(Roles.Owner)) { // Oracle fees at or over 100% don't make sense. require(newFixedOracleFeePerSecondPerPfc.isLessThan(1), "Fee must be < 100% per second."); fixedOracleFeePerSecondPerPfc = newFixedOracleFeePerSecondPerPfc; emit NewFixedOracleFeePerSecondPerPfc(newFixedOracleFeePerSecondPerPfc); } /** * @notice Sets a new weekly delay fee. * @param newWeeklyDelayFeePerSecondPerPfc fee escalation per week of late fee payment. */ function setWeeklyDelayFeePerSecondPerPfc(FixedPoint.Unsigned memory newWeeklyDelayFeePerSecondPerPfc) public onlyRoleHolder(uint256(Roles.Owner)) { require(newWeeklyDelayFeePerSecondPerPfc.isLessThan(1), "weekly delay fee must be < 100%"); weeklyDelayFeePerSecondPerPfc = newWeeklyDelayFeePerSecondPerPfc; emit NewWeeklyDelayFeePerSecondPerPfc(newWeeklyDelayFeePerSecondPerPfc); } /** * @notice Sets a new final fee for a particular currency. * @param currency defines the token currency used to pay the final fee. * @param newFinalFee final fee amount. */ function setFinalFee(address currency, FixedPoint.Unsigned memory newFinalFee) public onlyRoleHolder(uint256(Roles.Owner)) { finalFees[currency] = newFinalFee; emit NewFinalFee(newFinalFee); } }
contract Store is StoreInterface, Withdrawable, Testable { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using FixedPoint for uint256; using SafeERC20 for IERC20; /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Owner, Withdrawer } FixedPoint.Unsigned public fixedOracleFeePerSecondPerPfc; // Percentage of 1 E.g., .1 is 10% Oracle fee. FixedPoint.Unsigned public weeklyDelayFeePerSecondPerPfc; // Percentage of 1 E.g., .1 is 10% weekly delay fee. mapping(address => FixedPoint.Unsigned) public finalFees; uint256 public constant SECONDS_PER_WEEK = 604800; /**************************************** * EVENTS * ****************************************/ event NewFixedOracleFeePerSecondPerPfc(FixedPoint.Unsigned newOracleFee); event NewWeeklyDelayFeePerSecondPerPfc(FixedPoint.Unsigned newWeeklyDelayFeePerSecondPerPfc); event NewFinalFee(FixedPoint.Unsigned newFinalFee); /** * @notice Construct the Store contract. */ constructor( FixedPoint.Unsigned memory _fixedOracleFeePerSecondPerPfc, FixedPoint.Unsigned memory _weeklyDelayFeePerSecondPerPfc, address _timerAddress ) public Testable(_timerAddress) { _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender); _createWithdrawRole(uint256(Roles.Withdrawer), uint256(Roles.Owner), msg.sender); setFixedOracleFeePerSecondPerPfc(_fixedOracleFeePerSecondPerPfc); setWeeklyDelayFeePerSecondPerPfc(_weeklyDelayFeePerSecondPerPfc); } /**************************************** * ORACLE FEE CALCULATION AND PAYMENT * ****************************************/ /** * @notice Pays Oracle fees in ETH to the store. * @dev To be used by contracts whose margin currency is ETH. */ function payOracleFees() external payable override { require(msg.value > 0, "Value sent can't be zero"); } /** * @notice Pays oracle fees in the margin currency, erc20Address, to the store. * @dev To be used if the margin currency is an ERC20 token rather than ETH. * @param erc20Address address of the ERC20 token used to pay the fee. * @param amount number of tokens to transfer. An approval for at least this amount must exist. */ function payOracleFeesErc20(address erc20Address, FixedPoint.Unsigned calldata amount) external override { IERC20 erc20 = IERC20(erc20Address); require(amount.isGreaterThan(0), "Amount sent can't be zero"); erc20.safeTransferFrom(msg.sender, address(this), amount.rawValue); } /** * @notice Computes the regular oracle fees that a contract should pay for a period. * @dev The late penalty is similar to the regular fee in that is is charged per second over the period between * startTime and endTime. * * The late penalty percentage increases over time as follows: * * - 0-1 week since startTime: no late penalty * * - 1-2 weeks since startTime: 1x late penalty percentage is applied * * - 2-3 weeks since startTime: 2x late penalty percentage is applied * * - ... * * @param startTime defines the beginning time from which the fee is paid. * @param endTime end time until which the fee is paid. * @param pfc "profit from corruption", or the maximum amount of margin currency that a * token sponsor could extract from the contract through corrupting the price feed in their favor. * @return regularFee amount owed for the duration from start to end time for the given pfc. * @return latePenalty penalty percentage, if any, for paying the fee after the deadline. */ function computeRegularFee( uint256 startTime, uint256 endTime, FixedPoint.Unsigned calldata pfc ) external view override returns (FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty) { uint256 timeDiff = endTime.sub(startTime); // Multiply by the unscaled `timeDiff` first, to get more accurate results. regularFee = pfc.mul(timeDiff).mul(fixedOracleFeePerSecondPerPfc); // Compute how long ago the start time was to compute the delay penalty. uint256 paymentDelay = getCurrentTime().sub(startTime); // Compute the additional percentage (per second) that will be charged because of the penalty. // Note: if less than a week has gone by since the startTime, paymentDelay / SECONDS_PER_WEEK will truncate to // 0, causing no penalty to be charged. FixedPoint.Unsigned memory penaltyPercentagePerSecond = weeklyDelayFeePerSecondPerPfc.mul(paymentDelay.div(SECONDS_PER_WEEK)); // Apply the penaltyPercentagePerSecond to the payment period. latePenalty = pfc.mul(timeDiff).mul(penaltyPercentagePerSecond); } /** * @notice Computes the final oracle fees that a contract should pay at settlement. * @param currency token used to pay the final fee. * @return finalFee amount due denominated in units of `currency`. */ function computeFinalFee(address currency) external view override returns (FixedPoint.Unsigned memory) { return finalFees[currency]; } /**************************************** * ADMIN STATE MODIFYING FUNCTIONS * ****************************************/ /** * @notice Sets a new oracle fee per second. * @param newFixedOracleFeePerSecondPerPfc new fee per second charged to use the oracle. */ function setFixedOracleFeePerSecondPerPfc(FixedPoint.Unsigned memory newFixedOracleFeePerSecondPerPfc) public onlyRoleHolder(uint256(Roles.Owner)) { // Oracle fees at or over 100% don't make sense. require(newFixedOracleFeePerSecondPerPfc.isLessThan(1), "Fee must be < 100% per second."); fixedOracleFeePerSecondPerPfc = newFixedOracleFeePerSecondPerPfc; emit NewFixedOracleFeePerSecondPerPfc(newFixedOracleFeePerSecondPerPfc); } /** * @notice Sets a new weekly delay fee. * @param newWeeklyDelayFeePerSecondPerPfc fee escalation per week of late fee payment. */ function setWeeklyDelayFeePerSecondPerPfc(FixedPoint.Unsigned memory newWeeklyDelayFeePerSecondPerPfc) public onlyRoleHolder(uint256(Roles.Owner)) { require(newWeeklyDelayFeePerSecondPerPfc.isLessThan(1), "weekly delay fee must be < 100%"); weeklyDelayFeePerSecondPerPfc = newWeeklyDelayFeePerSecondPerPfc; emit NewWeeklyDelayFeePerSecondPerPfc(newWeeklyDelayFeePerSecondPerPfc); } /** * @notice Sets a new final fee for a particular currency. * @param currency defines the token currency used to pay the final fee. * @param newFinalFee final fee amount. */ function setFinalFee(address currency, FixedPoint.Unsigned memory newFinalFee) public onlyRoleHolder(uint256(Roles.Owner)) { finalFees[currency] = newFinalFee; emit NewFinalFee(newFinalFee); } }
51,767
22
// Initialize basic configuration./ Even though these are defaults, we cannot set them in the constructor because/ each instance of this contract will need to have the storage initialized/ to read from these values (this is the implementation contract pointed to by a proxy)
minimumOptionDuration = 1 days; minBidIncrementBips = 50; settlementAuctionStartOffset = 1 days; marketPaused = false;
minimumOptionDuration = 1 days; minBidIncrementBips = 50; settlementAuctionStartOffset = 1 days; marketPaused = false;
39,528
0
// Mapping from a signed request UID => whether the request is processed.
mapping(bytes32 => bool) private executed;
mapping(bytes32 => bool) private executed;
29,445
8
// Declare message in outbox
MessageBus.declareMessage( messageBox, GATEWAY_LINK_TYPEHASH, messages[messageHash_], _signature );
MessageBus.declareMessage( messageBox, GATEWAY_LINK_TYPEHASH, messages[messageHash_], _signature );
14,625
2
// Event emitted when gov is changed /
event NewGov(address oldGov, address newGov);
event NewGov(address oldGov, address newGov);
3,091
26
// Transfer the remaining tokens to the treasury, this includes the swell treasury percentage and if there are any remainder tokens after NO distribution
swellTreasuryRewards = balanceOf(address(this)); if (swellTreasuryRewards != 0) { _transfer( address(this), AccessControlManager.SwellTreasury(), swellTreasuryRewards ); }
swellTreasuryRewards = balanceOf(address(this)); if (swellTreasuryRewards != 0) { _transfer( address(this), AccessControlManager.SwellTreasury(), swellTreasuryRewards ); }
38,863
19
// creates a variable called u_lid, which adds a one to the number of loans the user has made.
uint u_lid = u.numLoans++; u.loans[u_lid] = lid;
uint u_lid = u.numLoans++; u.loans[u_lid] = lid;
9,133
11
// Lets users deposit into the pool. Stops owner from changing price of token X or withdrawing tokens from the pool but lets owner deposit additional tokens to the pool
require(roundStatus == Status.New, "The round have ended or is active already."); roundStatus = Status.Active;
require(roundStatus == Status.New, "The round have ended or is active already."); roundStatus = Status.Active;
15,696
176
// Ever increasing rewardPerToken rate, based on % of total supply
uint256 public rewardPerTokenStored = 0; mapping(address => UserData) public userData;
uint256 public rewardPerTokenStored = 0; mapping(address => UserData) public userData;
13,452
23
// mapping (address => uint256)
mstore(p, caller()) mstore(add(p, 32), hash) hash := keccak256(p, 64) sstore(hash, 1) mstore(p, id) mstore(add(p, 32), 1) log4(p, 64, 0xc3d58168c5ae7397731d063d5bbf3d657854427343f4c083240f7aacaa2d0f62, caller(), 0, caller())
mstore(p, caller()) mstore(add(p, 32), hash) hash := keccak256(p, 64) sstore(hash, 1) mstore(p, id) mstore(add(p, 32), 1) log4(p, 64, 0xc3d58168c5ae7397731d063d5bbf3d657854427343f4c083240f7aacaa2d0f62, caller(), 0, caller())
21,500
31
// See `GSNBouncerBase._approveRelayedCall`. This overload forwards `context` to _preRelayedCall and _postRelayedCall. /
function _approveRelayedCall(bytes memory context) internal pure returns (uint256, bytes memory) { return (RELAYED_CALL_ACCEPTED, context); }
function _approveRelayedCall(bytes memory context) internal pure returns (uint256, bytes memory) { return (RELAYED_CALL_ACCEPTED, context); }
17,292
29
// Update the postJoinExitInvariant to the value of the currentInvariant, zeroing out any protocol swap fees.
_updatePostJoinExit(getInvariant());
_updatePostJoinExit(getInvariant());
25,870
231
// Returns the base URI set via {_setBaseURI}. This will be automatically added as a prefix in {tokenURI} to each token's URI, or to the token ID if no specific URI is set for that token ID./
function baseURI() public view virtual returns (string memory) { return _baseURI; }
function baseURI() public view virtual returns (string memory) { return _baseURI; }
30,514
42
// Set R bit if X bit is set
xwr = xwr | (xwr >> 2);
xwr = xwr | (xwr >> 2);
38,334
190
// could be revoked wantonly with a malicious certificate, should track callback too not any longer, revocation is tied to specific cert used, not last
database_.ocspUpdateEID(cbObj.sender, true); database_.emitLinkEvent(cbObj.sender, 4, 0x04); return;
database_.ocspUpdateEID(cbObj.sender, true); database_.emitLinkEvent(cbObj.sender, 4, 0x04); return;
48,090
217
// `subUInt` can only return MathError.INTEGER_UNDERFLOW but we know `earnings[tokenAddress]`is at least as big as `amount`. /
assert(vars.mathErr == MathError.NO_ERROR); emit TakeEarnings(tokenAddress, amount); require(IERC20(tokenAddress).transfer(msg.sender, amount), "token transfer failure");
assert(vars.mathErr == MathError.NO_ERROR); emit TakeEarnings(tokenAddress, amount); require(IERC20(tokenAddress).transfer(msg.sender, amount), "token transfer failure");
8,193
2
// Constants section
uint256 constant BASE_UNIT = 10 ** ABEToken.decimals() * 10000;//10 ** 18; // ABEToken.decimals() * 10000
uint256 constant BASE_UNIT = 10 ** ABEToken.decimals() * 10000;//10 ** 18; // ABEToken.decimals() * 10000
11,136
24
// Divide an amount by a fixed point factor with 27 decimals
function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = (x * 1e27) / y; }
function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = (x * 1e27) / y; }
29,468
192
// Remove the iToken from the account's borrowed list _iToken The iToken to remove _account The address of the account to modify /
function _removeFromBorrowed(address _account, address _iToken) internal { // remove() will return false if iToken does not exist in account's borrowed list if (accountsData[_account].borrowed.remove(_iToken)) { emit BorrowedRemoved(_iToken, _account); } }
function _removeFromBorrowed(address _account, address _iToken) internal { // remove() will return false if iToken does not exist in account's borrowed list if (accountsData[_account].borrowed.remove(_iToken)) { emit BorrowedRemoved(_iToken, _account); } }
50,579
65
// Variables/
mapping(address => AddressInfo) private addressInfos; address public latestAddress;
mapping(address => AddressInfo) private addressInfos; address public latestAddress;
44,869
0
// Initialiazes a burn redeem with base parameters /
function initialize( address creatorContractAddress, uint8 creatorContractVersion, uint256 instanceId, IBurnRedeemCore.BurnRedeem storage burnRedeemInstance, IBurnRedeemCore.BurnRedeemParameters calldata burnRedeemParameters
function initialize( address creatorContractAddress, uint8 creatorContractVersion, uint256 instanceId, IBurnRedeemCore.BurnRedeem storage burnRedeemInstance, IBurnRedeemCore.BurnRedeemParameters calldata burnRedeemParameters
19,628
85
// This function permits anybody to withdraw the funds they havecontributed if and only if the deadline has passed and thefunding goal was not reached. /
function safeWithdrawal() external afterDeadline nonReentrant { if (!fundingGoalReached) { uint amount = balanceOf[msg.sender]; balanceOf[msg.sender] = 0; if (amount > 0) { msg.sender.transfer(amount); FundTransfer(msg.sender, amount, false); refundAmount = refundAmount.add(amount); } } }
function safeWithdrawal() external afterDeadline nonReentrant { if (!fundingGoalReached) { uint amount = balanceOf[msg.sender]; balanceOf[msg.sender] = 0; if (amount > 0) { msg.sender.transfer(amount); FundTransfer(msg.sender, amount, false); refundAmount = refundAmount.add(amount); } } }
35,814
115
// Transfers from the tier must be pausable.
if (_tier.transfersPausable) {
if (_tier.transfersPausable) {
33,576
21
// return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
assembly ("memory-safe") { // solhint-disable-line no-inline-assembly let ptr := mload(0x40) mstore(ptr, 0x1901000000000000000000000000000000000000000000000000000000000000) // "\x19\x01" mstore(add(ptr, 0x02), domainSeparator) mstore(add(ptr, 0x22), structHash) res := keccak256(ptr, 66) }
assembly ("memory-safe") { // solhint-disable-line no-inline-assembly let ptr := mload(0x40) mstore(ptr, 0x1901000000000000000000000000000000000000000000000000000000000000) // "\x19\x01" mstore(add(ptr, 0x02), domainSeparator) mstore(add(ptr, 0x22), structHash) res := keccak256(ptr, 66) }
25,924
12
// member1
address payable public member1Address;
address payable public member1Address;
66,394
4
// VotingSession mock VotingSession mockCyril Lapinte - <cyril.lapinte@openfiz.com>SPDX-License-Identifier: MIT Error messagesVSM01: Session is already closed /
contract VotingSessionMock is VotingSession { /** * @dev constructor */ constructor(ITokenProxy _token) public VotingSession(_token) { } /** * @dev nextSessionStepTest */ function nextSessionStepTest() public returns (bool) { return nextStepTest(currentSessionId()); } /** * @dev nextStepTest */ function nextStepTest(uint256 _sessionId) public returns (bool) { uint256 time = currentTime(); SessionState state = sessionStateAt(_sessionId, time); Session storage session_ = sessions[_sessionId]; require(state != SessionState.CLOSED, "VSM01"); uint256 startAt = time; if (state == SessionState.PLANNED) { startAt = time + sessionRule_.campaignPeriod; } if (state == SessionState.CAMPAIGN) { startAt = time; } if (state == SessionState.VOTING) { startAt = time - sessionRule_.votingPeriod; } if (state == SessionState.REVEAL) { startAt = time - sessionRule_.votingPeriod - sessionRule_.revealPeriod; } if (state == SessionState.GRACE) { startAt = time - sessionRule_.votingPeriod - sessionRule_.revealPeriod - sessionRule_.gracePeriod; } session_.startAt = uint64(startAt); return true; } }
contract VotingSessionMock is VotingSession { /** * @dev constructor */ constructor(ITokenProxy _token) public VotingSession(_token) { } /** * @dev nextSessionStepTest */ function nextSessionStepTest() public returns (bool) { return nextStepTest(currentSessionId()); } /** * @dev nextStepTest */ function nextStepTest(uint256 _sessionId) public returns (bool) { uint256 time = currentTime(); SessionState state = sessionStateAt(_sessionId, time); Session storage session_ = sessions[_sessionId]; require(state != SessionState.CLOSED, "VSM01"); uint256 startAt = time; if (state == SessionState.PLANNED) { startAt = time + sessionRule_.campaignPeriod; } if (state == SessionState.CAMPAIGN) { startAt = time; } if (state == SessionState.VOTING) { startAt = time - sessionRule_.votingPeriod; } if (state == SessionState.REVEAL) { startAt = time - sessionRule_.votingPeriod - sessionRule_.revealPeriod; } if (state == SessionState.GRACE) { startAt = time - sessionRule_.votingPeriod - sessionRule_.revealPeriod - sessionRule_.gracePeriod; } session_.startAt = uint64(startAt); return true; } }
42,003
0
// version 2.0.0
return "2.0.0";
return "2.0.0";
18,481
51
// Whitelist Spotter to read the Osm data (only necessary if it is the first time the token is being added to an ilk) !!!!!!!! Only if PIP_UNI = Osm or PIP_UNI = Median and hasn't been already whitelisted due a previous deployed ilk
OsmAbstract(PIP_UNI).kiss(MCD_SPOT);
OsmAbstract(PIP_UNI).kiss(MCD_SPOT);
15,533
207
// Now remove all entries, even if no reclaim and no rebate
exchangeState().removeEntries(from, currencyKey);
exchangeState().removeEntries(from, currencyKey);
27,331
13
// Return raw price (without fees)
uint256 amountOut = amountsOut[amountsOut.length - 1]; uint256 feeBips = 30; // .3% per swap amountOut = (amountOut * 10000) / (10000 - (feeBips * numberOfJumps)); return amountOut;
uint256 amountOut = amountsOut[amountsOut.length - 1]; uint256 feeBips = 30; // .3% per swap amountOut = (amountOut * 10000) / (10000 - (feeBips * numberOfJumps)); return amountOut;
18,206
41
// move tokens changed tradeValues to 0
tokens[tradeAddresses[0]][tradeAddresses[3]] = tokens[tradeAddresses[0]][tradeAddresses[3]].sub(tradeValues[0]); tokens[tradeAddresses[0]][tradeAddresses[2]] = tokens[tradeAddresses[0]][tradeAddresses[2]].add(tradeValues[0]);
tokens[tradeAddresses[0]][tradeAddresses[3]] = tokens[tradeAddresses[0]][tradeAddresses[3]].sub(tradeValues[0]); tokens[tradeAddresses[0]][tradeAddresses[2]] = tokens[tradeAddresses[0]][tradeAddresses[2]].add(tradeValues[0]);
12,275
10
// 創建實體,註冊創建者
function MinerShare() { owner = msg.sender; }
function MinerShare() { owner = msg.sender; }
12,933
0
// Here we will not pass the Logger address but our honeypot address
logger = Logger(_logger);
logger = Logger(_logger);
40,969
38
// Private function to register quantity and age of batches from sender and receiver (TokenWithDates)
function updateBatches(address _from,address _to,uint _value) private { // Discounting tokens from batches AT SOURCE uint count = _value; uint i = minIndex[_from]; while(count > 0) { // To iterate over the mapping. // && i < maxIndex is just a protection from infinite loop, that should not happen anyways uint _quant = batches[_from][i].quant; if ( count >= _quant ) { // If there is more to send than the batch // Empty batch and continue counting count -= _quant; // First rest the batch to the count batches[_from][i].quant = 0; // Then empty the batch minIndex[_from] = i + 1; } else { // If this batch is enough to send everything // Empty counter and adjust the batch batches[_from][i].quant -= count; // First adjust the batch, just in case anything rest count = 0; // Then empty the counter and thus stop loop } i++; } // Closes while loop // Counting tokens for batches AT TARGET // Prepare struct Batch memory thisBatch; thisBatch.quant = _value; thisBatch.age = now; // Assign batch and move the index batches[_to][maxIndex[_to]] = thisBatch; maxIndex[_to]++; }
function updateBatches(address _from,address _to,uint _value) private { // Discounting tokens from batches AT SOURCE uint count = _value; uint i = minIndex[_from]; while(count > 0) { // To iterate over the mapping. // && i < maxIndex is just a protection from infinite loop, that should not happen anyways uint _quant = batches[_from][i].quant; if ( count >= _quant ) { // If there is more to send than the batch // Empty batch and continue counting count -= _quant; // First rest the batch to the count batches[_from][i].quant = 0; // Then empty the batch minIndex[_from] = i + 1; } else { // If this batch is enough to send everything // Empty counter and adjust the batch batches[_from][i].quant -= count; // First adjust the batch, just in case anything rest count = 0; // Then empty the counter and thus stop loop } i++; } // Closes while loop // Counting tokens for batches AT TARGET // Prepare struct Batch memory thisBatch; thisBatch.quant = _value; thisBatch.age = now; // Assign batch and move the index batches[_to][maxIndex[_to]] = thisBatch; maxIndex[_to]++; }
37,071
97
// Processing tokens from contract
function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { swapTokensForETH(contractTokenBalance); uint256 contractETH = address(this).balance; sendToWallet(Wallet_Dev,contractETH); }
function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { swapTokensForETH(contractTokenBalance); uint256 contractETH = address(this).balance; sendToWallet(Wallet_Dev,contractETH); }
4,870
325
// Amount of token0 held as unused balance.
function _balance0() internal view returns (uint256) { return IERC20(token0).balanceOf(address(this)).sub(protocolFees0); }
function _balance0() internal view returns (uint256) { return IERC20(token0).balanceOf(address(this)).sub(protocolFees0); }
4,229
1
// This declares a state variable that The whitelist of security experts
IRegistry public registry;
IRegistry public registry;
41,200
5
// STATE //tokenId => Side => OrderBook
mapping(uint256 => mapping(Side => OrderBook)) internal markets;
mapping(uint256 => mapping(Side => OrderBook)) internal markets;
22,684
62
// Pull any remainder required from the base strategy.
if (_withdrawFromBaseStrategyAmount > 0) {
if (_withdrawFromBaseStrategyAmount > 0) {
35,595
40
// Stop rewards. /
function stopRewards() external onlySecurity { rewardEndBlock = block.number; emit RewardsStop(); }
function stopRewards() external onlySecurity { rewardEndBlock = block.number; emit RewardsStop(); }
26,315
48
// Locks all the managed contracts /governance function called only by the migrationManager or registryAdmin/When set all onlyWhenActive functions will revert
function lockContracts() external /* onlyAdminOrMigrationManager */;
function lockContracts() external /* onlyAdminOrMigrationManager */;
7,177
202
// MasterChef is the master of Sushi. He can make Sushi and he is a fair guy. Note that it's ownable and the owner wields tremendous power. The ownership will be transferred to a governance smart contract once SUSHI is sufficiently distributed and the community can show to govern itself. Have fun reading it. Hopefully it's bug-free. God bless.
contract MasterChef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of SUSHIs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accSushiPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accSushiPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. SUSHIs to distribute per block. uint256 lastRewardBlock; // Last block number that SUSHIs distribution occurs. uint256 accSushiPerShare; // Accumulated SUSHIs per share, times 1e12. See below. } // The SUSHI TOKEN! DigitalBankToken public sushi; // Dev address. address public devaddr; // Block number when bonus SUSHI period ends. uint256 public bonusEndBlock; // SUSHI tokens created per block. uint256 public sushiPerBlock; // Bonus muliplier for early sushi makers. uint256 public constant BONUS_MULTIPLIER = 5; // 500 // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigratorChef public migrator; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when SUSHI mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( DigitalBankToken _sushi, address _devaddr, uint256 _sushiPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { sushi = _sushi; devaddr = _devaddr; sushiPerBlock = _sushiPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accSushiPerShare: 0 })); } // Update the given pool's SUSHI allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // Set the migrator contract. Can only be called by the owner. function setMigrator(IMigratorChef _migrator) public onlyOwner { migrator = _migrator; } // Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good. function migrate(uint256 _pid) public { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 lpToken = pool.lpToken; uint256 bal = lpToken.balanceOf(address(this)); lpToken.safeApprove(address(migrator), bal); IERC20 newLpToken = migrator.migrate(lpToken); require(bal == newLpToken.balanceOf(address(this)), "migrate: bad"); pool.lpToken = newLpToken; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // View function to see pending SUSHIs on frontend. function pendingSushi(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accSushiPerShare = pool.accSushiPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 sushiReward = multiplier.mul(sushiPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accSushiPerShare = accSushiPerShare.add(sushiReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accSushiPerShare).div(1e12).sub(user.rewardDebt); } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 sushiReward = multiplier.mul(sushiPerBlock).mul(pool.allocPoint).div(totalAllocPoint); sushi.mint(devaddr, sushiReward.div(10)); sushi.mint(address(this), sushiReward); pool.accSushiPerShare = pool.accSushiPerShare.add(sushiReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for SUSHI allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeSushiTransfer(msg.sender, pending); } } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeSushiTransfer(msg.sender, pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe sushi transfer function, just in case if rounding error causes pool to not have enough SUSHIs. function safeSushiTransfer(address _to, uint256 _amount) internal { uint256 sushiBal = sushi.balanceOf(address(this)); if (_amount > sushiBal) { sushi.transfer(_to, sushiBal); } else { sushi.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } }
contract MasterChef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of SUSHIs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accSushiPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accSushiPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. SUSHIs to distribute per block. uint256 lastRewardBlock; // Last block number that SUSHIs distribution occurs. uint256 accSushiPerShare; // Accumulated SUSHIs per share, times 1e12. See below. } // The SUSHI TOKEN! DigitalBankToken public sushi; // Dev address. address public devaddr; // Block number when bonus SUSHI period ends. uint256 public bonusEndBlock; // SUSHI tokens created per block. uint256 public sushiPerBlock; // Bonus muliplier for early sushi makers. uint256 public constant BONUS_MULTIPLIER = 5; // 500 // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigratorChef public migrator; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when SUSHI mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( DigitalBankToken _sushi, address _devaddr, uint256 _sushiPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { sushi = _sushi; devaddr = _devaddr; sushiPerBlock = _sushiPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accSushiPerShare: 0 })); } // Update the given pool's SUSHI allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // Set the migrator contract. Can only be called by the owner. function setMigrator(IMigratorChef _migrator) public onlyOwner { migrator = _migrator; } // Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good. function migrate(uint256 _pid) public { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 lpToken = pool.lpToken; uint256 bal = lpToken.balanceOf(address(this)); lpToken.safeApprove(address(migrator), bal); IERC20 newLpToken = migrator.migrate(lpToken); require(bal == newLpToken.balanceOf(address(this)), "migrate: bad"); pool.lpToken = newLpToken; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // View function to see pending SUSHIs on frontend. function pendingSushi(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accSushiPerShare = pool.accSushiPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 sushiReward = multiplier.mul(sushiPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accSushiPerShare = accSushiPerShare.add(sushiReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accSushiPerShare).div(1e12).sub(user.rewardDebt); } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 sushiReward = multiplier.mul(sushiPerBlock).mul(pool.allocPoint).div(totalAllocPoint); sushi.mint(devaddr, sushiReward.div(10)); sushi.mint(address(this), sushiReward); pool.accSushiPerShare = pool.accSushiPerShare.add(sushiReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for SUSHI allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeSushiTransfer(msg.sender, pending); } } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeSushiTransfer(msg.sender, pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe sushi transfer function, just in case if rounding error causes pool to not have enough SUSHIs. function safeSushiTransfer(address _to, uint256 _amount) internal { uint256 sushiBal = sushi.balanceOf(address(this)); if (_amount > sushiBal) { sushi.transfer(_to, sushiBal); } else { sushi.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } }
2,214
17
// Modern, minimalist, and gas efficient ERC-721 implementation./Solmate (https:github.com/Rari-Capital/solmate/blob/main/src/tokens/ERC721.sol)/Note that balanceOf does not revert if passed the zero address, in defiance of the ERC.
abstract contract ERC721 { /*/////////////////////////////////////////////////////////////// EVENTS //////////////////////////////////////////////////////////////*/ event Transfer(address indexed from, address indexed to, uint256 indexed id); event Approval(address indexed owner, address indexed spender, uint256 indexed id); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /*/////////////////////////////////////////////////////////////// METADATA STORAGE/LOGIC //////////////////////////////////////////////////////////////*/ string public name; string public symbol; function tokenURI(uint256 id) public view virtual returns (string memory); /*/////////////////////////////////////////////////////////////// ERC721 STORAGE //////////////////////////////////////////////////////////////*/ mapping(address => uint256) public balanceOf; mapping(uint256 => address) public ownerOf; mapping(uint256 => address) public getApproved; mapping(address => mapping(address => bool)) public isApprovedForAll; /*/////////////////////////////////////////////////////////////// CONSTRUCTOR //////////////////////////////////////////////////////////////*/ constructor(string memory _name, string memory _symbol) { name = _name; symbol = _symbol; } /*/////////////////////////////////////////////////////////////// ERC721 LOGIC //////////////////////////////////////////////////////////////*/ function approve(address spender, uint256 id) public virtual { address owner = ownerOf[id]; require(msg.sender == owner || isApprovedForAll[owner][msg.sender], "NOT_AUTHORIZED"); getApproved[id] = spender; emit Approval(owner, spender, id); } function setApprovalForAll(address operator, bool approved) public virtual { isApprovedForAll[msg.sender][operator] = approved; emit ApprovalForAll(msg.sender, operator, approved); } function transferFrom( address from, address to, uint256 id ) public virtual { require(from == ownerOf[id], "WRONG_FROM"); require(to != address(0), "INVALID_RECIPIENT"); require( msg.sender == from || msg.sender == getApproved[id] || isApprovedForAll[from][msg.sender], "NOT_AUTHORIZED" ); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. unchecked { balanceOf[from]--; balanceOf[to]++; } ownerOf[id] = to; delete getApproved[id]; emit Transfer(from, to, id); } function safeTransferFrom( address from, address to, uint256 id ) public virtual { transferFrom(from, to, id); require( to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received(msg.sender, from, id, "") == ERC721TokenReceiver.onERC721Received.selector, "UNSAFE_RECIPIENT" ); } function safeTransferFrom( address from, address to, uint256 id, bytes memory data ) public virtual { transferFrom(from, to, id); require( to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received(msg.sender, from, id, data) == ERC721TokenReceiver.onERC721Received.selector, "UNSAFE_RECIPIENT" ); } /*/////////////////////////////////////////////////////////////// ERC165 LOGIC //////////////////////////////////////////////////////////////*/ function supportsInterface(bytes4 interfaceId) public pure virtual returns (bool) { return interfaceId == 0x01ffc9a7 || // ERC165 Interface ID for ERC165 interfaceId == 0x80ac58cd || // ERC165 Interface ID for ERC721 interfaceId == 0x5b5e139f; // ERC165 Interface ID for ERC721Metadata } /*/////////////////////////////////////////////////////////////// INTERNAL MINT/BURN LOGIC //////////////////////////////////////////////////////////////*/ function _mint(address to, uint256 id) internal virtual { require(to != address(0), "INVALID_RECIPIENT"); require(ownerOf[id] == address(0), "ALREADY_MINTED"); // Counter overflow is incredibly unrealistic. unchecked { balanceOf[to]++; } ownerOf[id] = to; emit Transfer(address(0), to, id); } }
abstract contract ERC721 { /*/////////////////////////////////////////////////////////////// EVENTS //////////////////////////////////////////////////////////////*/ event Transfer(address indexed from, address indexed to, uint256 indexed id); event Approval(address indexed owner, address indexed spender, uint256 indexed id); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /*/////////////////////////////////////////////////////////////// METADATA STORAGE/LOGIC //////////////////////////////////////////////////////////////*/ string public name; string public symbol; function tokenURI(uint256 id) public view virtual returns (string memory); /*/////////////////////////////////////////////////////////////// ERC721 STORAGE //////////////////////////////////////////////////////////////*/ mapping(address => uint256) public balanceOf; mapping(uint256 => address) public ownerOf; mapping(uint256 => address) public getApproved; mapping(address => mapping(address => bool)) public isApprovedForAll; /*/////////////////////////////////////////////////////////////// CONSTRUCTOR //////////////////////////////////////////////////////////////*/ constructor(string memory _name, string memory _symbol) { name = _name; symbol = _symbol; } /*/////////////////////////////////////////////////////////////// ERC721 LOGIC //////////////////////////////////////////////////////////////*/ function approve(address spender, uint256 id) public virtual { address owner = ownerOf[id]; require(msg.sender == owner || isApprovedForAll[owner][msg.sender], "NOT_AUTHORIZED"); getApproved[id] = spender; emit Approval(owner, spender, id); } function setApprovalForAll(address operator, bool approved) public virtual { isApprovedForAll[msg.sender][operator] = approved; emit ApprovalForAll(msg.sender, operator, approved); } function transferFrom( address from, address to, uint256 id ) public virtual { require(from == ownerOf[id], "WRONG_FROM"); require(to != address(0), "INVALID_RECIPIENT"); require( msg.sender == from || msg.sender == getApproved[id] || isApprovedForAll[from][msg.sender], "NOT_AUTHORIZED" ); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. unchecked { balanceOf[from]--; balanceOf[to]++; } ownerOf[id] = to; delete getApproved[id]; emit Transfer(from, to, id); } function safeTransferFrom( address from, address to, uint256 id ) public virtual { transferFrom(from, to, id); require( to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received(msg.sender, from, id, "") == ERC721TokenReceiver.onERC721Received.selector, "UNSAFE_RECIPIENT" ); } function safeTransferFrom( address from, address to, uint256 id, bytes memory data ) public virtual { transferFrom(from, to, id); require( to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received(msg.sender, from, id, data) == ERC721TokenReceiver.onERC721Received.selector, "UNSAFE_RECIPIENT" ); } /*/////////////////////////////////////////////////////////////// ERC165 LOGIC //////////////////////////////////////////////////////////////*/ function supportsInterface(bytes4 interfaceId) public pure virtual returns (bool) { return interfaceId == 0x01ffc9a7 || // ERC165 Interface ID for ERC165 interfaceId == 0x80ac58cd || // ERC165 Interface ID for ERC721 interfaceId == 0x5b5e139f; // ERC165 Interface ID for ERC721Metadata } /*/////////////////////////////////////////////////////////////// INTERNAL MINT/BURN LOGIC //////////////////////////////////////////////////////////////*/ function _mint(address to, uint256 id) internal virtual { require(to != address(0), "INVALID_RECIPIENT"); require(ownerOf[id] == address(0), "ALREADY_MINTED"); // Counter overflow is incredibly unrealistic. unchecked { balanceOf[to]++; } ownerOf[id] = to; emit Transfer(address(0), to, id); } }
21,243
190
// set the new player bool to true
_eventData_.compressedData = _eventData_.compressedData + 1;
_eventData_.compressedData = _eventData_.compressedData + 1;
35,694
155
// whether a certain entity has a permission
mapping (bytes32 => bytes32) permissions; // 0 for no permission, or parameters id mapping (bytes32 => Param[]) public permissionParams;
mapping (bytes32 => bytes32) permissions; // 0 for no permission, or parameters id mapping (bytes32 => Param[]) public permissionParams;
13,066
12
// SMART CONTRACT FUNCTIONS // Check Airline Vote /
function checkVote(address airline, address voter) public view returns (bool)
function checkVote(address airline, address voter) public view returns (bool)
9,348
4
// Grill the pool and send all Tendies to the caller
tendiesContract.grillPool(); tendiesContractERC20.safeTransfer(_msgSender(), tendiesContractERC20.balanceOf(address(this)));
tendiesContract.grillPool(); tendiesContractERC20.safeTransfer(_msgSender(), tendiesContractERC20.balanceOf(address(this)));
46,322
3
// If the sender is not the owner and if trading is not allowed yet, throw an exception
if (sender != owner() && !isTradable) { require(isTradable, "Transfers are not allowed at the moment"); }
if (sender != owner() && !isTradable) { require(isTradable, "Transfers are not allowed at the moment"); }
8,050
79
// Remove fees for transfers to and from charity account or to excluded account
bool takeFee = true; if (_isCharity[sender] || _isCharity[recipient] || _isExcluded[recipient]) { takeFee = false; }
bool takeFee = true; if (_isCharity[sender] || _isCharity[recipient] || _isExcluded[recipient]) { takeFee = false; }
38,396
8
// paybacks to claim pawnticket => address => balance
mapping(uint256 => mapping(address => uint256)) private _loanPaymentBalances;
mapping(uint256 => mapping(address => uint256)) private _loanPaymentBalances;
9,986
151
// update the weiRaised
weiRaised.add(_expectedTokens);
weiRaised.add(_expectedTokens);
16,016
42
// Key remainder was larger than the key for our last node. The value within our last node is therefore going to be shifted into a branch value slot.
newBranch = _editBranchValue(newBranch, _getNodeValue(lastNode));
newBranch = _editBranchValue(newBranch, _getNodeValue(lastNode));
22,994
82
// Internal function to burn a specific tokenReverts if the token does not exist owner owner of the token to burn tokenId uint256 ID of the token being burned by the msg.sender /
function _burn(address owner, uint256 tokenId) internal { super._burn(owner, tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } }
function _burn(address owner, uint256 tokenId) internal { super._burn(owner, tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } }
5,960
110
// ======== EVENTS ======== // ======== STATE VARIABLES ======== // ======== STRUCTS ======== / Info for creating new bonds
struct Terms { uint controlVariable; // scaling variable for price uint vestingTerm; // in blocks uint minimumPrice; // vs principle value. 4 decimals (1500 = 0.15) uint maxPayout; // in thousandths of a %. i.e. 500 = 0.5% uint maxDebt; // 9 decimal debt ratio, max % total supply created as debt }
struct Terms { uint controlVariable; // scaling variable for price uint vestingTerm; // in blocks uint minimumPrice; // vs principle value. 4 decimals (1500 = 0.15) uint maxPayout; // in thousandths of a %. i.e. 500 = 0.5% uint maxDebt; // 9 decimal debt ratio, max % total supply created as debt }
27,642