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
28
// Returns payout for a user which can be withdrawn or claimed. _forAddress Address of ClaimsToken holder /
function _calcUnprocessedFunds(address _forAddress) internal view returns (uint256)
function _calcUnprocessedFunds(address _forAddress) internal view returns (uint256)
38,897
3
// Mints `tokenId` and transfers it to `to`. Requirements: - `tokenSupplyCap() - totalSupply()` must be greater than zero.- `tokenId` must not exist.- `to` cannot be the zero address.
* Emits a {Transfer} event. */ function _mint( address to, bytes32 tokenId, bool force, bytes memory data ) internal virtual override(LSP8IdentifiableDigitalAssetCore, LSP8CappedSupplyCore) { super._mint(to, tokenId, force, data); }
* Emits a {Transfer} event. */ function _mint( address to, bytes32 tokenId, bool force, bytes memory data ) internal virtual override(LSP8IdentifiableDigitalAssetCore, LSP8CappedSupplyCore) { super._mint(to, tokenId, force, data); }
16,726
10
// all good
tokenIdToLinkedNFT[_tokenId] = LinkedNFT( _collection, _linkedNFTTokenId ); emit NewContraCard(_collection, _linkedNFTTokenId, _tokenId);
tokenIdToLinkedNFT[_tokenId] = LinkedNFT( _collection, _linkedNFTTokenId ); emit NewContraCard(_collection, _linkedNFTTokenId, _tokenId);
24,093
177
// Initializer for RariFundToken. /
function initialize() public initializer { ERC20Detailed.initialize("Rari Stable Pool Token", "RSPT", 18); ERC20Mintable.initialize(msg.sender); }
function initialize() public initializer { ERC20Detailed.initialize("Rari Stable Pool Token", "RSPT", 18); ERC20Mintable.initialize(msg.sender); }
2,231
3
// update user timestamps if it is first user invest
if (userInvested[msg.sender] == 0) { userLastOperationTime[msg.sender] = now; userLastWithdrawTime[msg.sender] = now;
if (userInvested[msg.sender] == 0) { userLastOperationTime[msg.sender] = now; userLastWithdrawTime[msg.sender] = now;
28,952
63
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){ return tokenPriceInitial_ - tokenPriceIncremental_; } else {
if(tokenSupply_ == 0){ return tokenPriceInitial_ - tokenPriceIncremental_; } else {
44,037
2
// result check
result := and ( eq(callResult, 1), or(eq(returndatasize, 0), and(eq(returndatasize, 32), gt(returnValue, 0))) )
result := and ( eq(callResult, 1), or(eq(returndatasize, 0), and(eq(returndatasize, 32), gt(returnValue, 0))) )
11,774
36
// In the case where a buyer sent in too much ether, or there weren&39;t enough tokens available, the remaining ether is sent back to the buyer.
if (remainder > 0) { msg.sender.transfer(remainder); }
if (remainder > 0) { msg.sender.transfer(remainder); }
23,324
235
// Note! This function assumes the price obtained from the onchain oracle in getCurrentCollateralPrice is a valid market price in units of collateralToken/paymentToken. If the onchain price oracle's value were to drift from the true market price, then the bToken price we calculate here would also drift, and will result in undefined behavior for any functions which call getPriceForMarket
calcPrice( market.expirationDate().sub(now), market.priceRatio(), getCurrentCollateralPrice(), volatilityFactor );
calcPrice( market.expirationDate().sub(now), market.priceRatio(), getCurrentCollateralPrice(), volatilityFactor );
7,100
10
// Use transfer to send the funds and throw an exception if the transfer fails
campaign.owner.transfer(msg.value);
campaign.owner.transfer(msg.value);
11,313
41
// Internal Functions//Returns the BatchContext located at a particular index. _index The index of the BatchContextreturn The BatchContext at the specified index. /
function _getBatchContext(uint256 _index) internal pure returns (BatchContext memory) { uint256 contextPtr = 15 + _index * BATCH_CONTEXT_SIZE; // slither-disable-next-line similar-names uint256 numSequencedTransactions; uint256 numSubsequentQueueTransactions; uint256 ctxTimestamp; uint256 ctxBlockNumber; assembly { numSequencedTransactions := shr(232, calldataload(contextPtr)) numSubsequentQueueTransactions := shr(232, calldataload(add(contextPtr, 3))) ctxTimestamp := shr(216, calldataload(add(contextPtr, 6))) ctxBlockNumber := shr(216, calldataload(add(contextPtr, 11))) } return BatchContext({ numSequencedTransactions: numSequencedTransactions, numSubsequentQueueTransactions: numSubsequentQueueTransactions, timestamp: ctxTimestamp, blockNumber: ctxBlockNumber }); }
function _getBatchContext(uint256 _index) internal pure returns (BatchContext memory) { uint256 contextPtr = 15 + _index * BATCH_CONTEXT_SIZE; // slither-disable-next-line similar-names uint256 numSequencedTransactions; uint256 numSubsequentQueueTransactions; uint256 ctxTimestamp; uint256 ctxBlockNumber; assembly { numSequencedTransactions := shr(232, calldataload(contextPtr)) numSubsequentQueueTransactions := shr(232, calldataload(add(contextPtr, 3))) ctxTimestamp := shr(216, calldataload(add(contextPtr, 6))) ctxBlockNumber := shr(216, calldataload(add(contextPtr, 11))) } return BatchContext({ numSequencedTransactions: numSequencedTransactions, numSubsequentQueueTransactions: numSubsequentQueueTransactions, timestamp: ctxTimestamp, blockNumber: ctxBlockNumber }); }
2,258
5
// 저는 7년 동안 한국에서 살았어요 한국어능력시험대한민국
function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value);
function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value);
3,756
11
// fee values are actually in DAI, ether is just a keyword
uint public flatFee = 7 ether; uint public contractFee = 1 ether; uint public exerciseFee = 20 ether; uint public settlementFee = 20 ether; uint public feesCollected = 0; string precisionError = "Precision";
uint public flatFee = 7 ether; uint public contractFee = 1 ether; uint public exerciseFee = 20 ether; uint public settlementFee = 20 ether; uint public feesCollected = 0; string precisionError = "Precision";
8,665
127
// The amount to be withdrawn must be the whole staked amount or must not exceed the diff between the entire amount and min allowed stake
uint256 minAllowedStake; if (_poolStakingAddress == _staker) { require(newStakeAmount >= _stakeInitial[_staker]); // initial validator cannot withdraw their initial stake minAllowedStake = candidateMinStake; } else {
uint256 minAllowedStake; if (_poolStakingAddress == _staker) { require(newStakeAmount >= _stakeInitial[_staker]); // initial validator cannot withdraw their initial stake minAllowedStake = candidateMinStake; } else {
49,040
76
// 授权转账
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; }
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; }
21,882
60
// This function iterates on calls and if needsTransferFromUser, transfers tokens from user
function transferTokensFromUserForCalls(Call[] calldata calls) private { uint callsLength = calls.length; Call calldata call; address token; for (uint256 i = 0; i < callsLength; i++) { call = calls[i]; token = call.swapFromToken; if (call.needsTransferFromUser && token != ETH) SafeERC20.safeTransferFrom(IERC20(call.swapFromToken), msg.sender, address(this), call.amount); } }
function transferTokensFromUserForCalls(Call[] calldata calls) private { uint callsLength = calls.length; Call calldata call; address token; for (uint256 i = 0; i < callsLength; i++) { call = calls[i]; token = call.swapFromToken; if (call.needsTransferFromUser && token != ETH) SafeERC20.safeTransferFrom(IERC20(call.swapFromToken), msg.sender, address(this), call.amount); } }
13,704
10
// check that this GTX ERC20 deployment is the Auction contract's attached ERC20 token
require(_gtxAuctionContract.ERC20() == address(this), "Auction contract does not have this token assigned"); gtxAuctionContract = _gtxAuctionContract; emit SetAuctionAddress(_gtxAuctionContract); return true;
require(_gtxAuctionContract.ERC20() == address(this), "Auction contract does not have this token assigned"); gtxAuctionContract = _gtxAuctionContract; emit SetAuctionAddress(_gtxAuctionContract); return true;
2,956
888
// Returns `sample`'s instant value for the logarithm of the invariant. /
function _instLogInvariant(bytes32 sample) private pure returns (int256) { return sample.decodeInt22(_INST_LOG_INVARIANT_OFFSET); }
function _instLogInvariant(bytes32 sample) private pure returns (int256) { return sample.decodeInt22(_INST_LOG_INVARIANT_OFFSET); }
52,307
120
// Used to unlock tokens, Only be called by the contract owner & also received by the owner as well./ It commulate the `releaseAmount` as per the time passed and release the/ commulated number of tokens./ e.g - Owner call this function at Monday, 08-Mar-21 10:00:00 UTC/ then commulated amount of tokens will beREWARDS_ALLOCATION + MARKETING_ALLOCATION
function unlockTokens() external onlyOwner { uint256 currentTime = now; uint256 releaseAmount = 0; if (!isRewardsTokensAllocated && currentTime >= REWARDS_ALLOCATION_RELEASE_AT) { releaseAmount = REWARDS_ALLOCATION; isRewardsTokensAllocated = true; } if (!isMarketingTokensAllocated && currentTime >= MARKETING_ALLOCATION_RELEASE_AT) { releaseAmount += MARKETING_ALLOCATION; isMarketingTokensAllocated = true; } if (!isTeamTokensAllocated && currentTime >= TEAM_ALLOCATION_RELEASE_AT) { releaseAmount += TEAM_ALLOCATION; isTeamTokensAllocated = true; } require(releaseAmount > 0, "Tokens are locked"); // Transfer funds to owner. _transfer(address(this), _msgSender(), releaseAmount); emit TokensUnlocked(_msgSender(), releaseAmount); }
function unlockTokens() external onlyOwner { uint256 currentTime = now; uint256 releaseAmount = 0; if (!isRewardsTokensAllocated && currentTime >= REWARDS_ALLOCATION_RELEASE_AT) { releaseAmount = REWARDS_ALLOCATION; isRewardsTokensAllocated = true; } if (!isMarketingTokensAllocated && currentTime >= MARKETING_ALLOCATION_RELEASE_AT) { releaseAmount += MARKETING_ALLOCATION; isMarketingTokensAllocated = true; } if (!isTeamTokensAllocated && currentTime >= TEAM_ALLOCATION_RELEASE_AT) { releaseAmount += TEAM_ALLOCATION; isTeamTokensAllocated = true; } require(releaseAmount > 0, "Tokens are locked"); // Transfer funds to owner. _transfer(address(this), _msgSender(), releaseAmount); emit TokensUnlocked(_msgSender(), releaseAmount); }
54,908
206
// todo : need to mint 40 tokens for the user at the beginning
// function founderMint(uint tokenQuantity) external onlyOwner { // require(totalSupply() + tokenQuantity <= DOGS_MAX_COUNT, "EXCEED_MAX"); // for(uint i = 0; i < tokenQuantity; i++) { // _safeMint(msg.sender, totalSupply() + 1); // } // }
// function founderMint(uint tokenQuantity) external onlyOwner { // require(totalSupply() + tokenQuantity <= DOGS_MAX_COUNT, "EXCEED_MAX"); // for(uint i = 0; i < tokenQuantity; i++) { // _safeMint(msg.sender, totalSupply() + 1); // } // }
8,196
1
// func to added buyer func prinim one argument - addr pokupatelya (buyer) tolko public not view tak kak func must been update|write
function addBuyer(address _addr) public { // address - type var, _addr - local var require(owner == msg.sender, "You are not an owner"); buyers[_addr] = true; }
function addBuyer(address _addr) public { // address - type var, _addr - local var require(owner == msg.sender, "You are not an owner"); buyers[_addr] = true; }
38,415
17
// The number of combinations in CoinFlip game
uint constant internal GAME_OPTIONS_COIN_FLIP_MODULO = 2;
uint constant internal GAME_OPTIONS_COIN_FLIP_MODULO = 2;
37,345
147
// initialize variables
minReportDelay = 0; maxReportDelay = 86400; profitFactor = 100; debtThreshold = 0;
minReportDelay = 0; maxReportDelay = 86400; profitFactor = 100; debtThreshold = 0;
47,388
6
// Get the address currently stored as fxRootSenderreturn fxRootSender contract originating a cross-chain tranasaction - likely the aave governance executor /
function getFxRootSender() external view returns (address) { return _fxRootSender; }
function getFxRootSender() external view returns (address) { return _fxRootSender; }
2,308
5
// Address of the admin
address public admin;
address public admin;
26,457
75
// Add liquidity of `bAmount` in base token New liquidity provider token will be issued to the provider /
function addLiquidity(uint256 bAmount) external;
function addLiquidity(uint256 bAmount) external;
59,711
6
// Checks recipient of a Grant is an address created by the OrgFactoryrecipient The address of the Grant recipient.orgFactoryContractAddress Address of the OrgFactory contract.return Boolean of status of given recipient status. /
function checkRecipient(address recipient, address orgFactoryContractAddress) public view returns (bool)
function checkRecipient(address recipient, address orgFactoryContractAddress) public view returns (bool)
14,370
37
// Require that there is enough Ether in the transaction
require(msg.value == _listPrices[tokenId], VALUE_MUST_EQUAL_PRICE); BaseERC721._buy(tokenId); safeTransferFrom(seller, msg.sender, tokenId);
require(msg.value == _listPrices[tokenId], VALUE_MUST_EQUAL_PRICE); BaseERC721._buy(tokenId); safeTransferFrom(seller, msg.sender, tokenId);
50,475
7
// this function is intended to be called by owner to create a light client and initialize light client data.chainNamethe counterparty chain nameclientAddresslight client contract addressclientStatelight client statusconsensusState light client consensus status /
function createClient( string calldata chainName, address clientAddress, bytes calldata clientState, bytes calldata consensusState
function createClient( string calldata chainName, address clientAddress, bytes calldata clientState, bytes calldata consensusState
46,333
39
// Private seed for the PRNG used for calculating damage amount.
uint _seed;
uint _seed;
26,455
2
// Concatenate undefinite number of bytes chunks./Faster than looping on `abi.encodePacked(output, _buffs[ix])`.
function concat(bytes[] memory _buffs) internal pure returns (bytes memory output)
function concat(bytes[] memory _buffs) internal pure returns (bytes memory output)
21,587
466
// more than lottery token holders. We got that covered.
require( finalScores.length > 0 ); uint K = cfg.winnerCount - 1; if( K > finalScores.length-1 )
require( finalScores.length > 0 ); uint K = cfg.winnerCount - 1; if( K > finalScores.length-1 )
4,691
12
// Check for owner or the athority itself
require(isOwner(msg.sender) || (_authority == msg.sender && isAuthority(msg.sender))); require(authoritiesSize > 0); for(uint i = 0; i < authoritiesSize; i++) { if(authorities[i] == _authority) authorities[i] = address(0x00); }
require(isOwner(msg.sender) || (_authority == msg.sender && isAuthority(msg.sender))); require(authoritiesSize > 0); for(uint i = 0; i < authoritiesSize; i++) { if(authorities[i] == _authority) authorities[i] = address(0x00); }
11,273
37
// address private crowdsale;
constructor(
constructor(
43,959
87
// Bounty Campaign: 5,000,000 UFT
uint256 bountyAmountUFT = token.supplySeed().mul(5).div(100); token.transferFromVault(token, fundWallet, bountyAmountUFT);
uint256 bountyAmountUFT = token.supplySeed().mul(5).div(100); token.transferFromVault(token, fundWallet, bountyAmountUFT);
33,346
18
// indicates weither any token exist with a given id, or not/
function exists(uint256 id) public view override returns (bool) { return planets[id].maxSupply > 0; }
function exists(uint256 id) public view override returns (bool) { return planets[id].maxSupply > 0; }
18,205
121
// token contract address => token balance of this contract
mapping (address => uint) public tokenBalances;
mapping (address => uint) public tokenBalances;
54,010
77
// - orderState: state of the order (refers to {LoanState} enum)- duration: duration in block for this loan order- price: amount of ERC720 tokens to pay for the loan- whitelisted: `true` if the whitelisted is enabled for this order (`false` otherwhise)- whitelistedTaker: address that is entitled to accept the loan (address(0) if no whitelist)orderId ID of the loan order to fetch the details of /
function getLoanOrderDetails(uint256 orderId) public view returns (LoanOrder memory) { return loanOrderDetails[orderId]; }
function getLoanOrderDetails(uint256 orderId) public view returns (LoanOrder memory) { return loanOrderDetails[orderId]; }
24,087
144
// Creates a new clone token with the initial distribution being this token at `_snapshotBlock` _cloneTokenName Name of the clone token _cloneDecimalUnits Number of decimals of the smallest unit _cloneTokenSymbol Symbol of the clone token _snapshotBlock Block when the distribution of the parent token is copied to set the initial distribution of the new clone token; if the block is zero than the actual block, the current block is used _transfersEnabled True if transfers are allowed in the clonereturn The address of the new MiniMeToken Contract /
function createCloneToken( string calldata _cloneTokenName,
function createCloneToken( string calldata _cloneTokenName,
36,121
1
// funcId => delegate contract
mapping(bytes4 => address) internal delegates;
mapping(bytes4 => address) internal delegates;
6,852
88
// maps address -> amount owed in wei
mapping(address => uint) amounts;
mapping(address => uint) amounts;
1,876
35
// Note: can only be invoked once the resolver has all the targets needed added
address destination = resolver.requireAndGetAddress( name, string(abi.encodePacked("Resolver missing target: ", name)) ); addressCache[name] = destination; emit CacheUpdated(name, destination);
address destination = resolver.requireAndGetAddress( name, string(abi.encodePacked("Resolver missing target: ", name)) ); addressCache[name] = destination; emit CacheUpdated(name, destination);
3,310
66
// low level token purchase DO NOT OVERRIDEThis function has a non-reentrancy guard, so it shouldn't be called byanother `nonReentrant` function. beneficiary Recipient of the token purchase /
function buyTokens(address beneficiary) public nonReentrant payable { uint256 weiAmount = msg.value; _preValidatePurchase(beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state _weiRaised = _weiRaised.add(weiAmount); _processPurchase(beneficiary, tokens); emit TokensPurchased(msg.sender, beneficiary, weiAmount, tokens); _updatePurchasingState(beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(beneficiary, weiAmount); }
function buyTokens(address beneficiary) public nonReentrant payable { uint256 weiAmount = msg.value; _preValidatePurchase(beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state _weiRaised = _weiRaised.add(weiAmount); _processPurchase(beneficiary, tokens); emit TokensPurchased(msg.sender, beneficiary, weiAmount, tokens); _updatePurchasingState(beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(beneficiary, weiAmount); }
44,807
6
// starting supply of Token
string public constant symbol = "GWC"; string public constant name = "Gold Way Coin"; uint8 public constant decimals = 18; mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) allowed;
string public constant symbol = "GWC"; string public constant name = "Gold Way Coin"; uint8 public constant decimals = 18; mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) allowed;
2,608
59
// Emitted by `_addPoolActive` internal function to signal that/ the specified staking address created a new pool./poolStakingAddress The staking address of newly added pool.
event AddedPool(address indexed poolStakingAddress);
event AddedPool(address indexed poolStakingAddress);
6,739
75
// ERC721 token with storage based token URI management. /
abstract contract ERC721URIStorage is ERC721 { using Strings for uint256; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = _baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } return super.tokenURI(tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual override { super._burn(tokenId); if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } }
abstract contract ERC721URIStorage is ERC721 { using Strings for uint256; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = _baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } return super.tokenURI(tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual override { super._burn(tokenId); if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } }
2,680
42
// Declare a variable to track errors encountered with amount.
let errorBuffer
let errorBuffer
16,582
158
// |/ Get the balance of an account's Tokens _ownerThe address of the token holder _id ID of the Tokenreturn The _owner's balance of the Token type requested /
function balanceOf(address _owner, uint256 _id) public view returns (uint256)
function balanceOf(address _owner, uint256 _id) public view returns (uint256)
7,795
24
// Transfer tokens from one address to another from address The address which you want to send tokens from to address The address which you want to transfer to value uint the amout of tokens to be transfered /
function transferFrom(address from, address to, uint value) public returns (bool success) { uint allowance = allowed[from][msg.sender]; // Check is not needed because sub(allowance, value) will already throw if this condition is not met // require(value <= allowance); // SafeMath uses assert instead of require though, beware when using an analysis tool balances[from] = balances[from].sub(value); balances[to] = balances[to].add(value); allowed[from][msg.sender] = allowance.sub(value); emit Transfer(from, to, value); return true; }
function transferFrom(address from, address to, uint value) public returns (bool success) { uint allowance = allowed[from][msg.sender]; // Check is not needed because sub(allowance, value) will already throw if this condition is not met // require(value <= allowance); // SafeMath uses assert instead of require though, beware when using an analysis tool balances[from] = balances[from].sub(value); balances[to] = balances[to].add(value); allowed[from][msg.sender] = allowance.sub(value); emit Transfer(from, to, value); return true; }
22,717
454
// Careful Math Compound Derived from OpenZeppelin's SafeMath library /
contract CarefulMath { /** * @dev Possible error codes that we can return */ enum MathError { NO_ERROR, DIVISION_BY_ZERO, INTEGER_OVERFLOW, INTEGER_UNDERFLOW } /** * @dev Multiplies two numbers, returns an error on overflow. */ function mulUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { if (a == 0) { return (MathError.NO_ERROR, 0); } uint256 c = a * b; if (c / a != b) { return (MathError.INTEGER_OVERFLOW, 0); } else { return (MathError.NO_ERROR, c); } } /** * @dev Integer division of two numbers, truncating the quotient. */ function divUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { if (b == 0) { return (MathError.DIVISION_BY_ZERO, 0); } return (MathError.NO_ERROR, a / b); } /** * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). */ function subUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { if (b <= a) { return (MathError.NO_ERROR, a - b); } else { return (MathError.INTEGER_UNDERFLOW, 0); } } /** * @dev Adds two numbers, returns an error on overflow. */ function addUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { uint256 c = a + b; if (c >= a) { return (MathError.NO_ERROR, c); } else { return (MathError.INTEGER_OVERFLOW, 0); } } /** * @dev add a and b and then subtract c */ function addThenSubUInt( uint256 a, uint256 b, uint256 c ) internal pure returns (MathError, uint256) { (MathError err0, uint256 sum) = addUInt(a, b); if (err0 != MathError.NO_ERROR) { return (err0, 0); } return subUInt(sum, c); } }
contract CarefulMath { /** * @dev Possible error codes that we can return */ enum MathError { NO_ERROR, DIVISION_BY_ZERO, INTEGER_OVERFLOW, INTEGER_UNDERFLOW } /** * @dev Multiplies two numbers, returns an error on overflow. */ function mulUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { if (a == 0) { return (MathError.NO_ERROR, 0); } uint256 c = a * b; if (c / a != b) { return (MathError.INTEGER_OVERFLOW, 0); } else { return (MathError.NO_ERROR, c); } } /** * @dev Integer division of two numbers, truncating the quotient. */ function divUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { if (b == 0) { return (MathError.DIVISION_BY_ZERO, 0); } return (MathError.NO_ERROR, a / b); } /** * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). */ function subUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { if (b <= a) { return (MathError.NO_ERROR, a - b); } else { return (MathError.INTEGER_UNDERFLOW, 0); } } /** * @dev Adds two numbers, returns an error on overflow. */ function addUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) { uint256 c = a + b; if (c >= a) { return (MathError.NO_ERROR, c); } else { return (MathError.INTEGER_OVERFLOW, 0); } } /** * @dev add a and b and then subtract c */ function addThenSubUInt( uint256 a, uint256 b, uint256 c ) internal pure returns (MathError, uint256) { (MathError err0, uint256 sum) = addUInt(a, b); if (err0 != MathError.NO_ERROR) { return (err0, 0); } return subUInt(sum, c); } }
31,970
606
// Decreases the allowance granted to the caller by `src`, unless src == msg.sender or _allowance[src][msg.sender] == MAX
* Emits an {Approval} event indicating the updated allowance, if the allowance is updated. * * Requirements: * * - `spender` must have allowance for the caller of at least * `wad`, unless src == msg.sender */ /// if_succeeds {:msg "Decrease allowance - underflow"} old(_allowance[src][msg.sender]) <= _allowance[src][msg.sender]; function _decreaseAllowance(address src, uint wad) internal virtual returns (bool) { if (src != msg.sender) { uint256 allowed = _allowance[src][msg.sender]; if (allowed != type(uint).max) { require(allowed >= wad, "ERC20: Insufficient approval"); unchecked { _setAllowance(src, msg.sender, allowed - wad); } } } return true; }
* Emits an {Approval} event indicating the updated allowance, if the allowance is updated. * * Requirements: * * - `spender` must have allowance for the caller of at least * `wad`, unless src == msg.sender */ /// if_succeeds {:msg "Decrease allowance - underflow"} old(_allowance[src][msg.sender]) <= _allowance[src][msg.sender]; function _decreaseAllowance(address src, uint wad) internal virtual returns (bool) { if (src != msg.sender) { uint256 allowed = _allowance[src][msg.sender]; if (allowed != type(uint).max) { require(allowed >= wad, "ERC20: Insufficient approval"); unchecked { _setAllowance(src, msg.sender, allowed - wad); } } } return true; }
20,146
109
// dai = pricecollateral
if (collateral == WETH){ (,, uint256 spot,,) = vat.ilks(WETH); // Stability fee and collateralization ratio for Weth return muld(posted[collateral][user], spot); } else if (collateral == CHAI) {
if (collateral == WETH){ (,, uint256 spot,,) = vat.ilks(WETH); // Stability fee and collateralization ratio for Weth return muld(posted[collateral][user], spot); } else if (collateral == CHAI) {
78,333
8
// Transaction info used by module transactions.
to, value, data, operation,
to, value, data, operation,
48,242
10
// take the user's amount
NFTX.transferFrom(msg.sender, address(this), _amount); UserStakeInfo storage userStakeInfo = _userStakes[msg.sender];
NFTX.transferFrom(msg.sender, address(this), _amount); UserStakeInfo storage userStakeInfo = _userStakes[msg.sender];
47,430
12
// @inheritdoc IERC20Wnft
address public override asset;
address public override asset;
39,478
150
// Called by {IRelayHub} on approved relay call requests, before the relayed call is executed. This allows to e.g.pre-charge the sender of the transaction. `context` is the second value returned in the tuple by {acceptRelayedCall}. Returns a value to be passed to {postRelayedCall}. {preRelayedCall} is called with 100k gas: if it runs out during exection or otherwise reverts, the relayed callwill not be executed, but the recipient will still be charged for the transaction's cost. /
function preRelayedCall(bytes calldata context) external returns (bytes32);
function preRelayedCall(bytes calldata context) external returns (bytes32);
18,566
17
// Owner functions
function withdraw() public onlyOwner { uint balance = address(this).balance; payable(msg.sender).transfer(balance); }
function withdraw() public onlyOwner { uint balance = address(this).balance; payable(msg.sender).transfer(balance); }
13,019
21
// Emitted when the pause is triggered by `account`. /
event Paused(address account);
event Paused(address account);
375
10
// Close an open edition for minting. /
function closeOpenEdition(uint256 tokenId) public whenNotPaused { require( hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "must have admin role" ); openEditions[tokenId].isOpen = false; }
function closeOpenEdition(uint256 tokenId) public whenNotPaused { require( hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "must have admin role" ); openEditions[tokenId].isOpen = false; }
36,488
105
// Initiates a new rebase operation, provided the minimum time period has elapsed.The supply adjustment equals (_totalSupplyDeviationFromTargetRate) / rebaseLag Where DeviationFromTargetRate is (MarketOracleRate - targetRate) / targetRate and targetRate is 1 /
function rebase() external onlyOrchestrator { require(inRebaseWindow()); // This comparison also ensures there is no reentrancy. require(lastRebaseTimestampSec.add(minRebaseTimeIntervalSec) < now); // Snap the rebase time to the start of this window. lastRebaseTimestampSec = now.sub( now.mod(minRebaseTimeIntervalSec)).add(rebaseWindowOffsetSec); epoch = epoch.add(1); uint256 targetRate = TARGET_RATE; uint256 exchangeRate; bool rateValid; (exchangeRate, rateValid) = marketOracle.getData(); require(rateValid); if (exchangeRate > MAX_RATE) { exchangeRate = MAX_RATE; } int256 supplyDelta = computeSupplyDelta(exchangeRate, targetRate); // Apply the Dampening factor. supplyDelta = supplyDelta.div(rebaseLag.toInt256Safe()); if (supplyDelta > 0 && uFrags.totalSupply().add(uint256(supplyDelta)) > MAX_SUPPLY) { supplyDelta = (MAX_SUPPLY.sub(uFrags.totalSupply())).toInt256Safe(); } uint256 supplyAfterRebase = uFrags.rebase(epoch, supplyDelta); assert(supplyAfterRebase <= MAX_SUPPLY); emit LogRebase(epoch, exchangeRate, supplyDelta, now); }
function rebase() external onlyOrchestrator { require(inRebaseWindow()); // This comparison also ensures there is no reentrancy. require(lastRebaseTimestampSec.add(minRebaseTimeIntervalSec) < now); // Snap the rebase time to the start of this window. lastRebaseTimestampSec = now.sub( now.mod(minRebaseTimeIntervalSec)).add(rebaseWindowOffsetSec); epoch = epoch.add(1); uint256 targetRate = TARGET_RATE; uint256 exchangeRate; bool rateValid; (exchangeRate, rateValid) = marketOracle.getData(); require(rateValid); if (exchangeRate > MAX_RATE) { exchangeRate = MAX_RATE; } int256 supplyDelta = computeSupplyDelta(exchangeRate, targetRate); // Apply the Dampening factor. supplyDelta = supplyDelta.div(rebaseLag.toInt256Safe()); if (supplyDelta > 0 && uFrags.totalSupply().add(uint256(supplyDelta)) > MAX_SUPPLY) { supplyDelta = (MAX_SUPPLY.sub(uFrags.totalSupply())).toInt256Safe(); } uint256 supplyAfterRebase = uFrags.rebase(epoch, supplyDelta); assert(supplyAfterRebase <= MAX_SUPPLY); emit LogRebase(epoch, exchangeRate, supplyDelta, now); }
24,758
183
// Skip writing to save gas if unchanged
_tOwned[address(this)] += tLiquidity;
_tOwned[address(this)] += tLiquidity;
44,523
125
// not set token wallet or reserve is the token wallet, no need to check allowance
return token.balanceOf(address(this));
return token.balanceOf(address(this));
24,274
13
// ========== INTERNAL FUNCTIONS ========== //Get the decimals of an asset.Assumes that the given asset follows ERC20 standard._asset Address of the asset. return number of decimals of the asset./
function _getDecimals(address _asset) internal view returns (uint) { return IERC20(_asset).decimals(); }
function _getDecimals(address _asset) internal view returns (uint) { return IERC20(_asset).decimals(); }
47,182
7
// Prices of mystery boxes
mapping(uint256=>uint256) private _mysteryBoxesPrices;
mapping(uint256=>uint256) private _mysteryBoxesPrices;
4,776
48
// Make sure enough funds were sent.
require(_value >= price); address seller = auction.seller; if (price > 0) { uint256 totalFee = _calculateFee(price); uint256 proceeds = price - totalFee;
require(_value >= price); address seller = auction.seller; if (price > 0) { uint256 totalFee = _calculateFee(price); uint256 proceeds = price - totalFee;
12,482
35
// Returns current game players./
function getPlayedGamePlayers() public view returns (uint)
function getPlayedGamePlayers() public view returns (uint)
11,493
256
// _staker address the staker who has deposited Uniswap Liquidity tokens _depositNumber uint256 the deposit number of which deposit A deposit needs to be locked for at least 30 days to be eligible for claiming yields.A deposit locked for less than 30 days has 0 rewards /
function isDepositEligibleForEarlyBonus(address _staker, uint256 _depositNumber) public view returns (bool)
function isDepositEligibleForEarlyBonus(address _staker, uint256 _depositNumber) public view returns (bool)
79,450
630
// res += val(coefficients[288] + coefficients[289]adjustments[16]).
res := addmod(res, mulmod(val, add(/*coefficients[288]*/ mload(0x2840), mulmod(/*coefficients[289]*/ mload(0x2860),
res := addmod(res, mulmod(val, add(/*coefficients[288]*/ mload(0x2840), mulmod(/*coefficients[289]*/ mload(0x2860),
24,888
183
// Indicator that this is a Controller contract (for inspection)
bool public constant isController = true;
bool public constant isController = true;
31,134
9
// Approves the transfer for the swap. Approves for 0 first to comply with tokens that implement the anti frontrunning approval fix.
IERC20(assetToSwapFrom).safeApprove(address(UNISWAP_ROUTER), 0); IERC20(assetToSwapFrom).safeApprove(address(UNISWAP_ROUTER), amountToSwap); address[] memory path; if (useEthPath) { path = new address[](3); path[0] = assetToSwapFrom; path[1] = WETH_ADDRESS; path[2] = assetToSwapTo; } else {
IERC20(assetToSwapFrom).safeApprove(address(UNISWAP_ROUTER), 0); IERC20(assetToSwapFrom).safeApprove(address(UNISWAP_ROUTER), amountToSwap); address[] memory path; if (useEthPath) { path = new address[](3); path[0] = assetToSwapFrom; path[1] = WETH_ADDRESS; path[2] = assetToSwapTo; } else {
60,588
676
// arise warrior
function finishRitual(address _owner) whenNotPaused external { // Check ritual time is over uint256 timeBlock = ritualTimeBlock[_owner]; require(timeBlock > 0 && timeBlock <= block.number); uint256 souls = soulCounter[_owner]; require(souls >= 10); uint256 identity = _generateIdentity(uint256(_owner), souls, timeBlock - 1, 0); uint256 warriorId = coreContract.ariseWarrior(identity, _owner, block.number + (SUMMONING_SICKENESS / coreContract.secondsPerBlock())); soulCounter[_owner] = 0; ritualTimeBlock[_owner] = 0; //send compensation msg.sender.transfer(RITUAL_COMPENSATION); RitualFinished(_owner, 10, warriorId); }
function finishRitual(address _owner) whenNotPaused external { // Check ritual time is over uint256 timeBlock = ritualTimeBlock[_owner]; require(timeBlock > 0 && timeBlock <= block.number); uint256 souls = soulCounter[_owner]; require(souls >= 10); uint256 identity = _generateIdentity(uint256(_owner), souls, timeBlock - 1, 0); uint256 warriorId = coreContract.ariseWarrior(identity, _owner, block.number + (SUMMONING_SICKENESS / coreContract.secondsPerBlock())); soulCounter[_owner] = 0; ritualTimeBlock[_owner] = 0; //send compensation msg.sender.transfer(RITUAL_COMPENSATION); RitualFinished(_owner, 10, warriorId); }
24,336
62
// Delete the address associated with the member id.
delete memberToAddress_[_memberId];
delete memberToAddress_[_memberId];
83,458
6
// addrs The address received funds will be split between.
function Splitter(address[] addrs) { count = addrs.length; for (uint i = 0; i < addrs.length; i++) { // loop over addrs and update set of included accounts address included = addrs[i]; between[included] = true; } }
function Splitter(address[] addrs) { count = addrs.length; for (uint i = 0; i < addrs.length; i++) { // loop over addrs and update set of included accounts address included = addrs[i]; between[included] = true; } }
25,297
25
// Payer pays in ETH, recipient receives Tokens
function ethToTokenPayment( uint256 _minTokens, uint256 _timeout, address _recipient ) external payable
function ethToTokenPayment( uint256 _minTokens, uint256 _timeout, address _recipient ) external payable
20,280
148
// Approve spender to transfer tokens and then execute a callback on recipient. spender The address allowed to transfer to. value The amount allowed to be transferred. data Additional data with no specified format.return A boolean that indicates if the operation was successful. /
function approveAndCall(address spender, uint256 value, bytes memory data) public override returns (bool) { approve(spender, value); require(_checkAndCallApprove(spender, value, data), "ERC1363: _checkAndCallApprove reverts"); return true; }
function approveAndCall(address spender, uint256 value, bytes memory data) public override returns (bool) { approve(spender, value); require(_checkAndCallApprove(spender, value, data), "ERC1363: _checkAndCallApprove reverts"); return true; }
6,442
43
// if(_currentCollection.maxSupply == 99) {
buffer.appendSafe(bytes(_traitData));
buffer.appendSafe(bytes(_traitData));
5,311
283
// Validates a deposit action reserve The reserve object on which the user is depositing amount The amount to be deposited /
function validateDeposit(DataTypes.ReserveData storage reserve, uint256 amount) external view { (bool isActive, bool isFrozen, , ) = reserve.configuration.getFlags(); require(amount != 0, Errors.VL_INVALID_AMOUNT); require(isActive, Errors.VL_NO_ACTIVE_RESERVE); require(!isFrozen, Errors.VL_RESERVE_FROZEN); }
function validateDeposit(DataTypes.ReserveData storage reserve, uint256 amount) external view { (bool isActive, bool isFrozen, , ) = reserve.configuration.getFlags(); require(amount != 0, Errors.VL_INVALID_AMOUNT); require(isActive, Errors.VL_NO_ACTIVE_RESERVE); require(!isFrozen, Errors.VL_RESERVE_FROZEN); }
39,874
51
// every reward era, the reward amount halves.
return (50 * 10**uint(decimals) ).div( 2**rewardEra ) ;
return (50 * 10**uint(decimals) ).div( 2**rewardEra ) ;
17,639
129
// Transfer to marketing address
transferToAddressETH(feecollector, sharedETH); emit SwapAndLiquify(threequarters, sharedETH, onequarter);
transferToAddressETH(feecollector, sharedETH); emit SwapAndLiquify(threequarters, sharedETH, onequarter);
20,514
124
// exclude from receiving dividends
dividendTracker.excludeFromDividends(address(dividendTracker)); dividendTracker.excludeFromDividends(address(this)); dividendTracker.excludeFromDividends(0x000000000000000000000000000000000000dEaD); dividendTracker.excludeFromDividends(address(_uniswapV2Router));
dividendTracker.excludeFromDividends(address(dividendTracker)); dividendTracker.excludeFromDividends(address(this)); dividendTracker.excludeFromDividends(0x000000000000000000000000000000000000dEaD); dividendTracker.excludeFromDividends(address(_uniswapV2Router));
4,452
33
// Checks how much is user able to commit and processes that commitment. Users must approve contract prior to committing tokens to auction. _from User ERC20 address. _amount Amount of approved ERC20 tokens. /
function commitTokensFrom( address _from, uint256 _amount, bool readAndAgreedToMarketParticipationAgreement ) public nonReentrant
function commitTokensFrom( address _from, uint256 _amount, bool readAndAgreedToMarketParticipationAgreement ) public nonReentrant
48,107
10
// 设置价格和是否可以交易
nftMapping[_nft_address].nft_price = _price; nftMapping[_nft_address].nft_sale = _sale;
nftMapping[_nft_address].nft_price = _price; nftMapping[_nft_address].nft_sale = _sale;
8,802
3
// Modifier for functions that require to be called only by the Cryptograph Factory
modifier restrictedToFactory(){ require((msg.sender == factory), "Only the Cryptograph Factory smart contract can call this function"); _; }
modifier restrictedToFactory(){ require((msg.sender == factory), "Only the Cryptograph Factory smart contract can call this function"); _; }
11,318
15
// uint public nulldayeth;
mapping(uint => mapping(uint => uint)) allprize;
mapping(uint => mapping(uint => uint)) allprize;
8,591
140
// if user does not want to stake
IERC20(ASG).transfer(_recipient, _amount); // send payout
IERC20(ASG).transfer(_recipient, _amount); // send payout
60,438
5
// MAINNET ADDRESSES The contracts in this list should correspond to MCD core contracts, verify against the current release list at: https:changelog.makerdao.com/releases/mainnet/1.0.9/contracts.json
address constant public MCD_VAT = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; uint256 constant public RAD = 10**45; uint256 constant public MILLION = 10**6;
address constant public MCD_VAT = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; uint256 constant public RAD = 10**45; uint256 constant public MILLION = 10**6;
11,524
20
// Emit an event indicating that the conduit has been deployed.
emit NewConduit(conduit, conduitKey);
emit NewConduit(conduit, conduitKey);
15,905
8
// restrict access
require(isStaker(msg.sender) || Operated.isActiveOperator(msg.sender), "only staker or active operator");
require(isStaker(msg.sender) || Operated.isActiveOperator(msg.sender), "only staker or active operator");
32,715
67
// Permission market contract to spent collateral token
collateralToken.approve(address(marketCollateralPool), collateralNeeded);
collateralToken.approve(address(marketCollateralPool), collateralNeeded);
10,934
18
// one can buy holds from anyone who set up an price,and u can buy @ price higher than he setup /
function buyFrom(address from) public payable whenNotPaused { require(sellPrice[from] > 0); uint256 amount = msg.value / sellPrice[from]; if (amount >= holds[from]) { amount = holds[from]; } if (amount >= toSell[from]) { amount = toSell[from]; } require(amount > 0); toSell[from] -= amount; transferHolds(from, msg.sender, amount); from.transfer(msg.value); emit SELL_HOLDS(from, msg.sender, amount, sellPrice[from]); }
function buyFrom(address from) public payable whenNotPaused { require(sellPrice[from] > 0); uint256 amount = msg.value / sellPrice[from]; if (amount >= holds[from]) { amount = holds[from]; } if (amount >= toSell[from]) { amount = toSell[from]; } require(amount > 0); toSell[from] -= amount; transferHolds(from, msg.sender, amount); from.transfer(msg.value); emit SELL_HOLDS(from, msg.sender, amount, sellPrice[from]); }
46,943
9
// Change the CardboardUnicorns token contract managed by this contract /
function changeCardboardUnicornTokenAddress(address _newTokenAddress) onlyOwner { CardboardUnicorns cu = CardboardUnicorns(_newTokenAddress); require(cu.owner() == address(this)); // We must be the owner of the token cardboardUnicornTokenAddress = _newTokenAddress; }
function changeCardboardUnicornTokenAddress(address _newTokenAddress) onlyOwner { CardboardUnicorns cu = CardboardUnicorns(_newTokenAddress); require(cu.owner() == address(this)); // We must be the owner of the token cardboardUnicornTokenAddress = _newTokenAddress; }
15,695
10
// We commit to a different final owner of the name.
bytes32 ownerDigest = keccak256(abi.encodePacked(owner, salt)); factory.commitToOrgName(registrar, commitment, ownerDigest); hevm.roll(block.number + registrar.minCommitmentAge() + 1); bytes32 node = keccak256(abi.encodePacked(registrar.radNode(), keccak256(bytes(name)))); factory.registerAndReclaim(registrar, registrar.radNode(), name, salt, owner); assertEq(ens.owner(node), owner);
bytes32 ownerDigest = keccak256(abi.encodePacked(owner, salt)); factory.commitToOrgName(registrar, commitment, ownerDigest); hevm.roll(block.number + registrar.minCommitmentAge() + 1); bytes32 node = keccak256(abi.encodePacked(registrar.radNode(), keccak256(bytes(name)))); factory.registerAndReclaim(registrar, registrar.radNode(), name, salt, owner); assertEq(ens.owner(node), owner);
12,144
82
// Sets `amount` as the allowance of `spender` over the caller's tokens. Returns a boolean value indicating whether the operation succeeded. IMPORTANT: Beware that changing an allowance with this method brings the riskthat someone may use both the old and the new allowance by unfortunatetransaction ordering. One possible solution to mitigate this racecondition is to first reduce the spender's allowance to 0 and set thedesired value afterwards: Emits an {Approval} event. /
function approve(address spender, uint256 amount) external returns (bool);
function approve(address spender, uint256 amount) external returns (bool);
11,289
81
// Update the total supply.
_totalSupply = startingSupply + recipients.length;
_totalSupply = startingSupply + recipients.length;
11,169
44
// sets the contract used to get NFT to ERC20 conversion rate values /
function setRateEngine(address rateEngine) external;
function setRateEngine(address rateEngine) external;
62,000
50
// MasterYak Controls rewards distribution for network /
contract MasterYak is ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; /// @notice Current owner of this contract address public owner; /// @notice Info of each user. struct UserInfo { uint256 amount; // How many tokens the user has provided. uint256 rewardTokenDebt; // Reward debt for reward token. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of reward tokens // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accRewardsPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws tokens to a pool. Here's what happens: // 1. The pool's `accRewardsPerShare` (and `lastRewardTimestamp`) 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. } /// @notice Info of each pool. struct PoolInfo { IERC20 token; // Address of token contract. uint256 allocPoint; // How many allocation points assigned to this pool. Reward tokens to distribute per second. uint256 lastRewardTimestamp; // Last timestamp where reward tokens were distributed. uint256 accRewardsPerShare; // Accumulated reward tokens per share, times 1e12. See below. uint256 totalStaked; // Total amount of token staked via Rewards Manager bool vpForDeposit; // Do users get voting power for deposits of this token? } /// @notice LockManager contract ILockManager public lockManager; /// @notice Rewards rewarded per second uint256 public rewardsPerSecond; /// @notice Info of each pool. PoolInfo[] public poolInfo; /// @notice Info of each user that stakes tokens mapping (uint256 => mapping (address => UserInfo)) public userInfo; /// @notice Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint; /// @notice The timestamp when rewards start. uint256 public startTimestamp; /// @notice The timestamp when rewards end. uint256 public endTimestamp; /// @notice only owner can call function modifier onlyOwner { require(msg.sender == owner, "not owner"); _; } /// @notice Event emitted when a user deposits funds in the rewards manager event Deposit(address indexed user, uint256 indexed pid, uint256 amount); /// @notice Event emitted when a user withdraws their original funds + rewards from the rewards manager event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); /// @notice Event emitted when a user withdraws their original funds from the rewards manager without claiming rewards event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); /// @notice Event emitted when new pool is added to the rewards manager event PoolAdded(uint256 indexed pid, address indexed token, uint256 allocPoints, uint256 totalAllocPoints, uint256 rewardStartTimestamp, bool vpForDeposit); /// @notice Event emitted when pool allocation points are updated event PoolUpdated(uint256 indexed pid, uint256 oldAllocPoints, uint256 newAllocPoints, uint256 newTotalAllocPoints); /// @notice Event emitted when the owner of the rewards manager contract is updated event ChangedOwner(address indexed oldOwner, address indexed newOwner); /// @notice Event emitted when the amount of reward tokens per seconds is updated event ChangedRewardsPerSecond(uint256 indexed oldRewardsPerSecond, uint256 indexed newRewardsPerSecond); /// @notice Event emitted when the rewards start timestamp is set event SetRewardsStartTimestamp(uint256 indexed startTimestamp); /// @notice Event emitted when the rewards end timestamp is updated event ChangedRewardsEndTimestamp(uint256 indexed oldEndTimestamp, uint256 indexed newEndTimestamp); /// @notice Event emitted when contract address is changed event ChangedAddress(string indexed addressType, address indexed oldAddress, address indexed newAddress); /** * @notice Create a new Rewards Manager contract * @param _owner owner of contract * @param _lockManager address of LockManager contract * @param _startTimestamp timestamp when rewards will start * @param _rewardsPerSecond initial amount of reward tokens to be distributed per second */ constructor( address _owner, address _lockManager, uint256 _startTimestamp, uint256 _rewardsPerSecond ) { owner = _owner; emit ChangedOwner(address(0), _owner); lockManager = ILockManager(_lockManager); emit ChangedAddress("LOCK_MANAGER", address(0), _lockManager); startTimestamp = _startTimestamp == 0 ? block.timestamp : _startTimestamp; emit SetRewardsStartTimestamp(startTimestamp); rewardsPerSecond = _rewardsPerSecond; emit ChangedRewardsPerSecond(0, _rewardsPerSecond); } receive() external payable {} /** * @notice View function to see current poolInfo array length * @return pool length */ function poolLength() external view returns (uint256) { return poolInfo.length; } /** * @notice Add a new reward token to the pool * @dev Can only be called by the owner. DO NOT add the same token more than once. Rewards will be messed up if you do. * @param allocPoint Number of allocation points to allot to this token/pool * @param token The token that will be staked for rewards * @param withUpdate if specified, update all pools before adding new pool * @param vpForDeposit If true, users get voting power for deposits */ function add( uint256 allocPoint, address token, bool withUpdate, bool vpForDeposit ) external onlyOwner { if (withUpdate) { massUpdatePools(); } uint256 rewardStartTimestamp = block.timestamp > startTimestamp ? block.timestamp : startTimestamp; if (totalAllocPoint == 0) { _setRewardsEndTimestamp(); } totalAllocPoint = totalAllocPoint.add(allocPoint); poolInfo.push(PoolInfo({ token: IERC20(token), allocPoint: allocPoint, lastRewardTimestamp: rewardStartTimestamp, accRewardsPerShare: 0, totalStaked: 0, vpForDeposit: vpForDeposit })); emit PoolAdded(poolInfo.length - 1, token, allocPoint, totalAllocPoint, rewardStartTimestamp, vpForDeposit); } /** * @notice Update the given pool's allocation points * @dev Can only be called by the owner * @param pid The RewardManager pool id * @param allocPoint New number of allocation points for pool * @param withUpdate if specified, update all pools before setting allocation points */ function set( uint256 pid, uint256 allocPoint, bool withUpdate ) external onlyOwner { if (withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[pid].allocPoint).add(allocPoint); emit PoolUpdated(pid, poolInfo[pid].allocPoint, allocPoint, totalAllocPoint); poolInfo[pid].allocPoint = allocPoint; } /** * @notice Returns true if rewards are actively being accumulated */ function rewardsActive() public view returns (bool) { return block.timestamp >= startTimestamp && block.timestamp <= endTimestamp && totalAllocPoint > 0 ? true : false; } /** * @notice Return reward multiplier over the given from to to timestamp. * @param from From timestamp * @param to To timestamp * @return multiplier */ function getMultiplier(uint256 from, uint256 to) public view returns (uint256) { uint256 toTimestamp = to > endTimestamp ? endTimestamp : to; return toTimestamp > from ? toTimestamp.sub(from) : 0; } /** * @notice View function to see pending rewards on frontend. * @param pid pool id * @param account user account to check * @return pending rewards */ function pendingRewards(uint256 pid, address account) external view returns (uint256) { PoolInfo storage pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][account]; uint256 accRewardsPerShare = pool.accRewardsPerShare; uint256 tokenSupply = pool.totalStaked; if (block.timestamp > pool.lastRewardTimestamp && tokenSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardTimestamp, block.timestamp); uint256 totalReward = multiplier.mul(rewardsPerSecond).mul(pool.allocPoint).div(totalAllocPoint); accRewardsPerShare = accRewardsPerShare.add(totalReward.mul(1e12).div(tokenSupply)); } uint256 accumulatedRewards = user.amount.mul(accRewardsPerShare).div(1e12); if (accumulatedRewards < user.rewardTokenDebt) { return 0; } return accumulatedRewards.sub(user.rewardTokenDebt); } /** * @notice Update reward variables for all pools * @dev Be careful of gas spending! */ function massUpdatePools() public { for (uint256 pid = 0; pid < poolInfo.length; ++pid) { updatePool(pid); } } /** * @notice Update reward variables of the given pool to be up-to-date * @param pid pool id */ function updatePool(uint256 pid) public { PoolInfo storage pool = poolInfo[pid]; if (block.timestamp <= pool.lastRewardTimestamp) { return; } uint256 tokenSupply = pool.totalStaked; if (tokenSupply == 0) { pool.lastRewardTimestamp = block.timestamp; return; } uint256 multiplier = getMultiplier(pool.lastRewardTimestamp, block.timestamp); uint256 totalReward = multiplier.mul(rewardsPerSecond).mul(pool.allocPoint).div(totalAllocPoint); pool.accRewardsPerShare = pool.accRewardsPerShare.add(totalReward.mul(1e12).div(tokenSupply)); pool.lastRewardTimestamp = block.timestamp; } /** * @notice Deposit tokens to MasterYak for rewards allocation. * @param pid pool id * @param amount number of tokens to deposit */ function deposit(uint256 pid, uint256 amount) external nonReentrant { PoolInfo storage pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][msg.sender]; _deposit(pid, amount, pool, user); } /** * @notice Deposit tokens to MasterYak for rewards allocation, using permit for approval * @dev It is up to the frontend developer to ensure the pool token implements permit - otherwise this will fail * @param pid pool id * @param amount number of tokens to deposit * @param deadline The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function depositWithPermit( uint256 pid, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external nonReentrant { PoolInfo storage pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][msg.sender]; pool.token.permit(msg.sender, address(this), amount, deadline, v, r, s); _deposit(pid, amount, pool, user); } /** * @notice Withdraw tokens from MasterYak, claiming rewards. * @param pid pool id * @param amount number of tokens to withdraw */ function withdraw(uint256 pid, uint256 amount) external nonReentrant { require(amount > 0, "MasterYak::withdraw: amount must be > 0"); PoolInfo storage pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][msg.sender]; _withdraw(pid, amount, pool, user); } /** * @notice Withdraw without caring about rewards. EMERGENCY ONLY. * @param pid pool id */ function emergencyWithdraw(uint256 pid) external nonReentrant { PoolInfo storage pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][msg.sender]; if (user.amount > 0) { if (pool.vpForDeposit) { lockManager.removeVotingPower(msg.sender, address(pool.token), user.amount); } pool.totalStaked = pool.totalStaked.sub(user.amount); pool.token.safeTransfer(msg.sender, user.amount); emit EmergencyWithdraw(msg.sender, pid, user.amount); user.amount = 0; user.rewardTokenDebt = 0; } } /** * @notice Set new rewards per second * @dev Can only be called by the owner * @param newRewardsPerSecond new amount of rewards to reward each second */ function setRewardsPerSecond(uint256 newRewardsPerSecond) external onlyOwner { emit ChangedRewardsPerSecond(rewardsPerSecond, newRewardsPerSecond); rewardsPerSecond = newRewardsPerSecond; _setRewardsEndTimestamp(); } /** * @notice Set new LockManager address * @param newAddress address of new LockManager */ function setLockManager(address newAddress) external onlyOwner { emit ChangedAddress("LOCK_MANAGER", address(lockManager), newAddress); lockManager = ILockManager(newAddress); } /** * @notice Add rewards to contract * @dev Can only be called by the owner */ function addRewardsBalance() external payable onlyOwner { _setRewardsEndTimestamp(); } /** * @notice Change owner of vesting contract * @dev Can only be called by the owner * @param newOwner New owner address */ function changeOwner(address newOwner) external onlyOwner { require(newOwner != address(0) && newOwner != address(this), "MasterYak::changeOwner: not valid address"); emit ChangedOwner(owner, newOwner); owner = newOwner; } /** * @notice Internal implementation of deposit * @param pid pool id * @param amount number of tokens to deposit * @param pool the pool info * @param user the user info */ function _deposit( uint256 pid, uint256 amount, PoolInfo storage pool, UserInfo storage user ) internal { updatePool(pid); if (user.amount > 0) { uint256 pendingRewardAmount = user.amount.mul(pool.accRewardsPerShare).div(1e12).sub(user.rewardTokenDebt); if (pendingRewardAmount > 0) { _safeRewardsTransfer(msg.sender, pendingRewardAmount); } } pool.token.safeTransferFrom(msg.sender, address(this), amount); pool.totalStaked = pool.totalStaked.add(amount); user.amount = user.amount.add(amount); user.rewardTokenDebt = user.amount.mul(pool.accRewardsPerShare).div(1e12); if (amount > 0 && pool.vpForDeposit) { lockManager.grantVotingPower(msg.sender, address(pool.token), amount); } emit Deposit(msg.sender, pid, amount); } /** * @notice Internal implementation of withdraw * @param pid pool id * @param amount number of tokens to withdraw * @param pool the pool info * @param user the user info */ function _withdraw( uint256 pid, uint256 amount, PoolInfo storage pool, UserInfo storage user ) internal { require(user.amount >= amount, "MasterYak::_withdraw: amount > user balance"); updatePool(pid); uint256 pendingRewardAmount = user.amount.mul(pool.accRewardsPerShare).div(1e12).sub(user.rewardTokenDebt); user.amount = user.amount.sub(amount); user.rewardTokenDebt = user.amount.mul(pool.accRewardsPerShare).div(1e12); if (pendingRewardAmount > 0) { _safeRewardsTransfer(msg.sender, pendingRewardAmount); } if (pool.vpForDeposit) { lockManager.removeVotingPower(msg.sender, address(pool.token), amount); } pool.totalStaked = pool.totalStaked.sub(amount); pool.token.safeTransfer(msg.sender, amount); emit Withdraw(msg.sender, pid, amount); } /** * @notice Safe reward transfer function, just in case if rounding error causes pool to not have enough reward token. * @param to account that is receiving rewards * @param amount amount of rewards to send */ function _safeRewardsTransfer(address payable to, uint256 amount) internal { uint256 rewardTokenBalance = address(this).balance; if (amount > rewardTokenBalance) { to.transfer(rewardTokenBalance); } else { to.transfer(amount); } } /** * @notice Internal function that updates rewards end timestamp based on rewards per second and the balance of the contract */ function _setRewardsEndTimestamp() internal { if(rewardsPerSecond > 0) { uint256 rewardFromTimestamp = block.timestamp >= startTimestamp ? block.timestamp : startTimestamp; uint256 newEndTimestamp = rewardFromTimestamp.add(address(this).balance.div(rewardsPerSecond)); if(newEndTimestamp > rewardFromTimestamp && newEndTimestamp != endTimestamp) { emit ChangedRewardsEndTimestamp(endTimestamp, newEndTimestamp); endTimestamp = newEndTimestamp; } } } }
contract MasterYak is ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; /// @notice Current owner of this contract address public owner; /// @notice Info of each user. struct UserInfo { uint256 amount; // How many tokens the user has provided. uint256 rewardTokenDebt; // Reward debt for reward token. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of reward tokens // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accRewardsPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws tokens to a pool. Here's what happens: // 1. The pool's `accRewardsPerShare` (and `lastRewardTimestamp`) 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. } /// @notice Info of each pool. struct PoolInfo { IERC20 token; // Address of token contract. uint256 allocPoint; // How many allocation points assigned to this pool. Reward tokens to distribute per second. uint256 lastRewardTimestamp; // Last timestamp where reward tokens were distributed. uint256 accRewardsPerShare; // Accumulated reward tokens per share, times 1e12. See below. uint256 totalStaked; // Total amount of token staked via Rewards Manager bool vpForDeposit; // Do users get voting power for deposits of this token? } /// @notice LockManager contract ILockManager public lockManager; /// @notice Rewards rewarded per second uint256 public rewardsPerSecond; /// @notice Info of each pool. PoolInfo[] public poolInfo; /// @notice Info of each user that stakes tokens mapping (uint256 => mapping (address => UserInfo)) public userInfo; /// @notice Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint; /// @notice The timestamp when rewards start. uint256 public startTimestamp; /// @notice The timestamp when rewards end. uint256 public endTimestamp; /// @notice only owner can call function modifier onlyOwner { require(msg.sender == owner, "not owner"); _; } /// @notice Event emitted when a user deposits funds in the rewards manager event Deposit(address indexed user, uint256 indexed pid, uint256 amount); /// @notice Event emitted when a user withdraws their original funds + rewards from the rewards manager event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); /// @notice Event emitted when a user withdraws their original funds from the rewards manager without claiming rewards event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); /// @notice Event emitted when new pool is added to the rewards manager event PoolAdded(uint256 indexed pid, address indexed token, uint256 allocPoints, uint256 totalAllocPoints, uint256 rewardStartTimestamp, bool vpForDeposit); /// @notice Event emitted when pool allocation points are updated event PoolUpdated(uint256 indexed pid, uint256 oldAllocPoints, uint256 newAllocPoints, uint256 newTotalAllocPoints); /// @notice Event emitted when the owner of the rewards manager contract is updated event ChangedOwner(address indexed oldOwner, address indexed newOwner); /// @notice Event emitted when the amount of reward tokens per seconds is updated event ChangedRewardsPerSecond(uint256 indexed oldRewardsPerSecond, uint256 indexed newRewardsPerSecond); /// @notice Event emitted when the rewards start timestamp is set event SetRewardsStartTimestamp(uint256 indexed startTimestamp); /// @notice Event emitted when the rewards end timestamp is updated event ChangedRewardsEndTimestamp(uint256 indexed oldEndTimestamp, uint256 indexed newEndTimestamp); /// @notice Event emitted when contract address is changed event ChangedAddress(string indexed addressType, address indexed oldAddress, address indexed newAddress); /** * @notice Create a new Rewards Manager contract * @param _owner owner of contract * @param _lockManager address of LockManager contract * @param _startTimestamp timestamp when rewards will start * @param _rewardsPerSecond initial amount of reward tokens to be distributed per second */ constructor( address _owner, address _lockManager, uint256 _startTimestamp, uint256 _rewardsPerSecond ) { owner = _owner; emit ChangedOwner(address(0), _owner); lockManager = ILockManager(_lockManager); emit ChangedAddress("LOCK_MANAGER", address(0), _lockManager); startTimestamp = _startTimestamp == 0 ? block.timestamp : _startTimestamp; emit SetRewardsStartTimestamp(startTimestamp); rewardsPerSecond = _rewardsPerSecond; emit ChangedRewardsPerSecond(0, _rewardsPerSecond); } receive() external payable {} /** * @notice View function to see current poolInfo array length * @return pool length */ function poolLength() external view returns (uint256) { return poolInfo.length; } /** * @notice Add a new reward token to the pool * @dev Can only be called by the owner. DO NOT add the same token more than once. Rewards will be messed up if you do. * @param allocPoint Number of allocation points to allot to this token/pool * @param token The token that will be staked for rewards * @param withUpdate if specified, update all pools before adding new pool * @param vpForDeposit If true, users get voting power for deposits */ function add( uint256 allocPoint, address token, bool withUpdate, bool vpForDeposit ) external onlyOwner { if (withUpdate) { massUpdatePools(); } uint256 rewardStartTimestamp = block.timestamp > startTimestamp ? block.timestamp : startTimestamp; if (totalAllocPoint == 0) { _setRewardsEndTimestamp(); } totalAllocPoint = totalAllocPoint.add(allocPoint); poolInfo.push(PoolInfo({ token: IERC20(token), allocPoint: allocPoint, lastRewardTimestamp: rewardStartTimestamp, accRewardsPerShare: 0, totalStaked: 0, vpForDeposit: vpForDeposit })); emit PoolAdded(poolInfo.length - 1, token, allocPoint, totalAllocPoint, rewardStartTimestamp, vpForDeposit); } /** * @notice Update the given pool's allocation points * @dev Can only be called by the owner * @param pid The RewardManager pool id * @param allocPoint New number of allocation points for pool * @param withUpdate if specified, update all pools before setting allocation points */ function set( uint256 pid, uint256 allocPoint, bool withUpdate ) external onlyOwner { if (withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[pid].allocPoint).add(allocPoint); emit PoolUpdated(pid, poolInfo[pid].allocPoint, allocPoint, totalAllocPoint); poolInfo[pid].allocPoint = allocPoint; } /** * @notice Returns true if rewards are actively being accumulated */ function rewardsActive() public view returns (bool) { return block.timestamp >= startTimestamp && block.timestamp <= endTimestamp && totalAllocPoint > 0 ? true : false; } /** * @notice Return reward multiplier over the given from to to timestamp. * @param from From timestamp * @param to To timestamp * @return multiplier */ function getMultiplier(uint256 from, uint256 to) public view returns (uint256) { uint256 toTimestamp = to > endTimestamp ? endTimestamp : to; return toTimestamp > from ? toTimestamp.sub(from) : 0; } /** * @notice View function to see pending rewards on frontend. * @param pid pool id * @param account user account to check * @return pending rewards */ function pendingRewards(uint256 pid, address account) external view returns (uint256) { PoolInfo storage pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][account]; uint256 accRewardsPerShare = pool.accRewardsPerShare; uint256 tokenSupply = pool.totalStaked; if (block.timestamp > pool.lastRewardTimestamp && tokenSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardTimestamp, block.timestamp); uint256 totalReward = multiplier.mul(rewardsPerSecond).mul(pool.allocPoint).div(totalAllocPoint); accRewardsPerShare = accRewardsPerShare.add(totalReward.mul(1e12).div(tokenSupply)); } uint256 accumulatedRewards = user.amount.mul(accRewardsPerShare).div(1e12); if (accumulatedRewards < user.rewardTokenDebt) { return 0; } return accumulatedRewards.sub(user.rewardTokenDebt); } /** * @notice Update reward variables for all pools * @dev Be careful of gas spending! */ function massUpdatePools() public { for (uint256 pid = 0; pid < poolInfo.length; ++pid) { updatePool(pid); } } /** * @notice Update reward variables of the given pool to be up-to-date * @param pid pool id */ function updatePool(uint256 pid) public { PoolInfo storage pool = poolInfo[pid]; if (block.timestamp <= pool.lastRewardTimestamp) { return; } uint256 tokenSupply = pool.totalStaked; if (tokenSupply == 0) { pool.lastRewardTimestamp = block.timestamp; return; } uint256 multiplier = getMultiplier(pool.lastRewardTimestamp, block.timestamp); uint256 totalReward = multiplier.mul(rewardsPerSecond).mul(pool.allocPoint).div(totalAllocPoint); pool.accRewardsPerShare = pool.accRewardsPerShare.add(totalReward.mul(1e12).div(tokenSupply)); pool.lastRewardTimestamp = block.timestamp; } /** * @notice Deposit tokens to MasterYak for rewards allocation. * @param pid pool id * @param amount number of tokens to deposit */ function deposit(uint256 pid, uint256 amount) external nonReentrant { PoolInfo storage pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][msg.sender]; _deposit(pid, amount, pool, user); } /** * @notice Deposit tokens to MasterYak for rewards allocation, using permit for approval * @dev It is up to the frontend developer to ensure the pool token implements permit - otherwise this will fail * @param pid pool id * @param amount number of tokens to deposit * @param deadline The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function depositWithPermit( uint256 pid, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external nonReentrant { PoolInfo storage pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][msg.sender]; pool.token.permit(msg.sender, address(this), amount, deadline, v, r, s); _deposit(pid, amount, pool, user); } /** * @notice Withdraw tokens from MasterYak, claiming rewards. * @param pid pool id * @param amount number of tokens to withdraw */ function withdraw(uint256 pid, uint256 amount) external nonReentrant { require(amount > 0, "MasterYak::withdraw: amount must be > 0"); PoolInfo storage pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][msg.sender]; _withdraw(pid, amount, pool, user); } /** * @notice Withdraw without caring about rewards. EMERGENCY ONLY. * @param pid pool id */ function emergencyWithdraw(uint256 pid) external nonReentrant { PoolInfo storage pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][msg.sender]; if (user.amount > 0) { if (pool.vpForDeposit) { lockManager.removeVotingPower(msg.sender, address(pool.token), user.amount); } pool.totalStaked = pool.totalStaked.sub(user.amount); pool.token.safeTransfer(msg.sender, user.amount); emit EmergencyWithdraw(msg.sender, pid, user.amount); user.amount = 0; user.rewardTokenDebt = 0; } } /** * @notice Set new rewards per second * @dev Can only be called by the owner * @param newRewardsPerSecond new amount of rewards to reward each second */ function setRewardsPerSecond(uint256 newRewardsPerSecond) external onlyOwner { emit ChangedRewardsPerSecond(rewardsPerSecond, newRewardsPerSecond); rewardsPerSecond = newRewardsPerSecond; _setRewardsEndTimestamp(); } /** * @notice Set new LockManager address * @param newAddress address of new LockManager */ function setLockManager(address newAddress) external onlyOwner { emit ChangedAddress("LOCK_MANAGER", address(lockManager), newAddress); lockManager = ILockManager(newAddress); } /** * @notice Add rewards to contract * @dev Can only be called by the owner */ function addRewardsBalance() external payable onlyOwner { _setRewardsEndTimestamp(); } /** * @notice Change owner of vesting contract * @dev Can only be called by the owner * @param newOwner New owner address */ function changeOwner(address newOwner) external onlyOwner { require(newOwner != address(0) && newOwner != address(this), "MasterYak::changeOwner: not valid address"); emit ChangedOwner(owner, newOwner); owner = newOwner; } /** * @notice Internal implementation of deposit * @param pid pool id * @param amount number of tokens to deposit * @param pool the pool info * @param user the user info */ function _deposit( uint256 pid, uint256 amount, PoolInfo storage pool, UserInfo storage user ) internal { updatePool(pid); if (user.amount > 0) { uint256 pendingRewardAmount = user.amount.mul(pool.accRewardsPerShare).div(1e12).sub(user.rewardTokenDebt); if (pendingRewardAmount > 0) { _safeRewardsTransfer(msg.sender, pendingRewardAmount); } } pool.token.safeTransferFrom(msg.sender, address(this), amount); pool.totalStaked = pool.totalStaked.add(amount); user.amount = user.amount.add(amount); user.rewardTokenDebt = user.amount.mul(pool.accRewardsPerShare).div(1e12); if (amount > 0 && pool.vpForDeposit) { lockManager.grantVotingPower(msg.sender, address(pool.token), amount); } emit Deposit(msg.sender, pid, amount); } /** * @notice Internal implementation of withdraw * @param pid pool id * @param amount number of tokens to withdraw * @param pool the pool info * @param user the user info */ function _withdraw( uint256 pid, uint256 amount, PoolInfo storage pool, UserInfo storage user ) internal { require(user.amount >= amount, "MasterYak::_withdraw: amount > user balance"); updatePool(pid); uint256 pendingRewardAmount = user.amount.mul(pool.accRewardsPerShare).div(1e12).sub(user.rewardTokenDebt); user.amount = user.amount.sub(amount); user.rewardTokenDebt = user.amount.mul(pool.accRewardsPerShare).div(1e12); if (pendingRewardAmount > 0) { _safeRewardsTransfer(msg.sender, pendingRewardAmount); } if (pool.vpForDeposit) { lockManager.removeVotingPower(msg.sender, address(pool.token), amount); } pool.totalStaked = pool.totalStaked.sub(amount); pool.token.safeTransfer(msg.sender, amount); emit Withdraw(msg.sender, pid, amount); } /** * @notice Safe reward transfer function, just in case if rounding error causes pool to not have enough reward token. * @param to account that is receiving rewards * @param amount amount of rewards to send */ function _safeRewardsTransfer(address payable to, uint256 amount) internal { uint256 rewardTokenBalance = address(this).balance; if (amount > rewardTokenBalance) { to.transfer(rewardTokenBalance); } else { to.transfer(amount); } } /** * @notice Internal function that updates rewards end timestamp based on rewards per second and the balance of the contract */ function _setRewardsEndTimestamp() internal { if(rewardsPerSecond > 0) { uint256 rewardFromTimestamp = block.timestamp >= startTimestamp ? block.timestamp : startTimestamp; uint256 newEndTimestamp = rewardFromTimestamp.add(address(this).balance.div(rewardsPerSecond)); if(newEndTimestamp > rewardFromTimestamp && newEndTimestamp != endTimestamp) { emit ChangedRewardsEndTimestamp(endTimestamp, newEndTimestamp); endTimestamp = newEndTimestamp; } } } }
37,144
34
// create a modifier that checks if challenge state is valid for joining the challenge
modifier challengeStateIsValidForJoin { ChallengeState _challengeState = forecastChallengeState(); require(_challengeState == ChallengeState.DRAFT || _challengeState == ChallengeState.RUNNING, 'Invalid challenge state for joining'); _; }
modifier challengeStateIsValidForJoin { ChallengeState _challengeState = forecastChallengeState(); require(_challengeState == ChallengeState.DRAFT || _challengeState == ChallengeState.RUNNING, 'Invalid challenge state for joining'); _; }
24,404
183
// /
function __mint(address to, uint256 tokenId) external override onlyInternal
function __mint(address to, uint256 tokenId) external override onlyInternal
909
93
// Emitted after the mint actionfrom The address performing the mintvalue The amount beingindex The new liquidity index of the reserve//Mints `amount` kTokens to `user`user The address receiving the minted tokensamount The amount of tokens getting mintedindex The new liquidity index of the reserve return `true` if the the previous balance of the user was 0/
function mint( address user, uint256 amount, uint256 index ) external returns (bool);
function mint( address user, uint256 amount, uint256 index ) external returns (bool);
30,335
32
// Transfer ETH to Exchange
TransferHelper.safeTransferETH(exchange, ethBal);
TransferHelper.safeTransferETH(exchange, ethBal);
16,465