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
24
// enable wallet to receive ETH
receive() external payable { if(msg.value > 0) { emit Deposited(msg.sender, msg.value); } }
receive() external payable { if(msg.value > 0) { emit Deposited(msg.sender, msg.value); } }
16,547
9
// Token URIs
mapping(uint256 => string) _tokenURIs;
mapping(uint256 => string) _tokenURIs;
39,065
36
// returns the last time a user interacted with the contract by deposit or withdraw
function userLastAction(address user) public view returns (uint256) { LibReignStorage.Stake memory stake = stakeAtTs(user, block.timestamp); return stake.timestamp; }
function userLastAction(address user) public view returns (uint256) { LibReignStorage.Stake memory stake = stakeAtTs(user, block.timestamp); return stake.timestamp; }
4,542
135
// Now use Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works in modular arithmetic, doubling the correct bits in each step.
inv *= 2 - denominator * inv; // inverse mod 2**8 inv *= 2 - denominator * inv; // inverse mod 2**16 inv *= 2 - denominator * inv; // inverse mod 2**32 inv *= 2 - denominator * inv; // inverse mod 2**64 inv *= 2 - denominator * inv; // inverse mod 2**128 inv *= 2 - denominator * inv; // inverse mod 2**256
inv *= 2 - denominator * inv; // inverse mod 2**8 inv *= 2 - denominator * inv; // inverse mod 2**16 inv *= 2 - denominator * inv; // inverse mod 2**32 inv *= 2 - denominator * inv; // inverse mod 2**64 inv *= 2 - denominator * inv; // inverse mod 2**128 inv *= 2 - denominator * inv; // inverse mod 2**256
30,810
26
// 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 _amount uint256 the amount of tokens to be transferred /
function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success) { require(_to != address(0)); require(balances[_from] >= _amount); require(allowed[_from][msg.sender] >= _amount); require(_amount > 0 && balances[_to].add(_amount) > balances[_to]); balances[_from] = balances[_from].sub(_amount); balances[_to] = balances[_to].add(_amount); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount); emit Transfer(_from, _to, _amount); return true; }
function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success) { require(_to != address(0)); require(balances[_from] >= _amount); require(allowed[_from][msg.sender] >= _amount); require(_amount > 0 && balances[_to].add(_amount) > balances[_to]); balances[_from] = balances[_from].sub(_amount); balances[_to] = balances[_to].add(_amount); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount); emit Transfer(_from, _to, _amount); return true; }
1,269
13
// Retrieves total entries of players address
function playerEntries(address _player) public view returns (uint256) { address addressOfPlayer = _player; uint arrayLength = players.length; uint totalEntries = 0; for (uint256 i; i < arrayLength; i++) { if(players[i] == addressOfPlayer) { totalEntries++; } } return totalEntries; }
function playerEntries(address _player) public view returns (uint256) { address addressOfPlayer = _player; uint arrayLength = players.length; uint totalEntries = 0; for (uint256 i; i < arrayLength; i++) { if(players[i] == addressOfPlayer) { totalEntries++; } } return totalEntries; }
59,362
49
// Stack to deep workaround: 0: rollupId 1: rollupSize 2: dataStartIndex 3: numTxs
uint256[4] memory nums, bytes32 oldDataRoot, bytes32 newDataRoot, bytes32 oldNullRoot, bytes32 newNullRoot, bytes32 oldRootRoot, bytes32 newRootRoot ) = decodeProof(proofData, numberOfAssets);
uint256[4] memory nums, bytes32 oldDataRoot, bytes32 newDataRoot, bytes32 oldNullRoot, bytes32 newNullRoot, bytes32 oldRootRoot, bytes32 newRootRoot ) = decodeProof(proofData, numberOfAssets);
36,629
329
// Update endpoint mapping
serviceProviderEndpointToId[keccak256(bytes(_endpoint))] = newServiceProviderID;
serviceProviderEndpointToId[keccak256(bytes(_endpoint))] = newServiceProviderID;
45,288
48
// Mint RAcoin locked-up tokens Using different types of minting functions has no effect on total limit of 20,000,000,000 RAC that can be created
function mintLockupTokens(address _target, uint _mintedAmount, uint _unlockTime) public onlyOwner returns (bool success) { require(_mintedAmount <= unmintedTokens); balancesLockup[_target].amount += _mintedAmount; balancesLockup[_target].unlockTime = _unlockTime; unmintedTokens -= _mintedAmount; _totalSupply += _mintedAmount; emit Transfer(1, _target, _mintedAmount); //TODO return true; }
function mintLockupTokens(address _target, uint _mintedAmount, uint _unlockTime) public onlyOwner returns (bool success) { require(_mintedAmount <= unmintedTokens); balancesLockup[_target].amount += _mintedAmount; balancesLockup[_target].unlockTime = _unlockTime; unmintedTokens -= _mintedAmount; _totalSupply += _mintedAmount; emit Transfer(1, _target, _mintedAmount); //TODO return true; }
49,893
117
// convert some LP tokens to USDC
function convertToUSDC(opVars memory vars) private { // get LP amount vars.pair = IUniswapV2Pair( vars.factory.getPair(vars.token0, vars.token1) ); vars.amount = vars.pair.balanceOf(address(this)); if (vars.amount == 0) return; // remove liquidity => get ETH + DAI vars.pair.approve(address(vars.router), vars.amount); (uint256 amountToken, uint256 amountETH) = vars.router.removeLiquidityETH( vars.token1, vars.amount, 0, 0, address(this), 1e18 ); // convert eth to USDC vars.router.swapExactETHForTokens.value(amountETH)( 0, getPath(vars.router.WETH(), usdcAddress), address(this), 1e18 ); // convert DAI to USDC (no need for usdc=>usdc swap) if (vars.token1 != usdcAddress) { IERC20 daiToken = IERC20(vars.token1); daiToken.approve(address(vars.router), amountToken); vars.router.swapExactTokensForTokens( amountToken, 0, getPath(vars.token1, usdcAddress), address(this), 1e18 ); } }
function convertToUSDC(opVars memory vars) private { // get LP amount vars.pair = IUniswapV2Pair( vars.factory.getPair(vars.token0, vars.token1) ); vars.amount = vars.pair.balanceOf(address(this)); if (vars.amount == 0) return; // remove liquidity => get ETH + DAI vars.pair.approve(address(vars.router), vars.amount); (uint256 amountToken, uint256 amountETH) = vars.router.removeLiquidityETH( vars.token1, vars.amount, 0, 0, address(this), 1e18 ); // convert eth to USDC vars.router.swapExactETHForTokens.value(amountETH)( 0, getPath(vars.router.WETH(), usdcAddress), address(this), 1e18 ); // convert DAI to USDC (no need for usdc=>usdc swap) if (vars.token1 != usdcAddress) { IERC20 daiToken = IERC20(vars.token1); daiToken.approve(address(vars.router), amountToken); vars.router.swapExactTokensForTokens( amountToken, 0, getPath(vars.token1, usdcAddress), address(this), 1e18 ); } }
53,696
14
// returns the id (index in the powerUps[] array) of the PowerUp refered to by the `index`th element of a given `keyword` array. ie: getPowerUpIdAtIndex("shoes",23) will return the id of the 23rd PowerUp that burned tokens in association with the keyword "shoes".keyword Keyword string for which the PowerUp ids will be fetchedindex Index at which id of the PowerUp needs to be fetched/
function getPowerUpIdAtIndex( bytes32 keyword, uint256 index ) external view returns (uint256 id)
function getPowerUpIdAtIndex( bytes32 keyword, uint256 index ) external view returns (uint256 id)
19,957
21
// used by the owner account to be able to drain ERC721 tokens received as airdropsfor the lockedcollateral NFT-s _tokenAddress - address of the token contract for the token to be sent out _tokenId - id token to be sent out _receiver - receiver of the token /
function drainERC721Airdrop( address _tokenAddress, uint256 _tokenId, address _receiver
function drainERC721Airdrop( address _tokenAddress, uint256 _tokenId, address _receiver
40,273
197
// compute unstake amount in shares
uint256 shares = totalStakingShares.mul(amount).div(totalStaked()); require(shares > 0, "Geyser: preview amount too small"); uint256 rawShareSeconds = 0; uint256 timeBonusShareSeconds = 0;
uint256 shares = totalStakingShares.mul(amount).div(totalStaked()); require(shares > 0, "Geyser: preview amount too small"); uint256 rawShareSeconds = 0; uint256 timeBonusShareSeconds = 0;
1,618
128
// Forward to Price smart contract.
function getPrice(address tokenAddress, uint srcQty) public view returns (uint price){ require(tokenAddress != address(0)); (, price) = priceProvider.getRates(tokenAddress, srcQty); return price; }
function getPrice(address tokenAddress, uint srcQty) public view returns (uint price){ require(tokenAddress != address(0)); (, price) = priceProvider.getRates(tokenAddress, srcQty); return price; }
50,413
106
// Extension of ERC721 with the ERC2981 NFT Royalty Standard, a standardized way to retrieve royalty paymentinformation.
* Royalty information can be specified globally for all token ids via {_setDefaultRoyalty}, and/or individually for * specific token ids via {_setTokenRoyalty}. The latter takes precedence over the first. * * IMPORTANT: ERC-2981 only specifies a way to signal royalty information and does not enforce its payment. See * https://eips.ethereum.org/EIPS/eip-2981#optional-royalty-payments[Rationale] in the EIP. Marketplaces are expected to * voluntarily pay royalties together with sales, but note that this standard is not yet widely supported. * * _Available since v4.5._ */ abstract contract ERC721Royalty is ERC2981, ERC721 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC2981) returns (bool) { return super.supportsInterface(interfaceId); } /** * @dev See {ERC721-_burn}. This override additionally clears the royalty information for the token. */ function _burn(uint256 tokenId) internal virtual override { super._burn(tokenId); _resetTokenRoyalty(tokenId); } }
* Royalty information can be specified globally for all token ids via {_setDefaultRoyalty}, and/or individually for * specific token ids via {_setTokenRoyalty}. The latter takes precedence over the first. * * IMPORTANT: ERC-2981 only specifies a way to signal royalty information and does not enforce its payment. See * https://eips.ethereum.org/EIPS/eip-2981#optional-royalty-payments[Rationale] in the EIP. Marketplaces are expected to * voluntarily pay royalties together with sales, but note that this standard is not yet widely supported. * * _Available since v4.5._ */ abstract contract ERC721Royalty is ERC2981, ERC721 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC2981) returns (bool) { return super.supportsInterface(interfaceId); } /** * @dev See {ERC721-_burn}. This override additionally clears the royalty information for the token. */ function _burn(uint256 tokenId) internal virtual override { super._burn(tokenId); _resetTokenRoyalty(tokenId); } }
20,662
292
// Store the `subscriptionOrRegistrantToCopy`.
mstore(0x24, subscriptionOrRegistrantToCopy)
mstore(0x24, subscriptionOrRegistrantToCopy)
7,523
7
// calculate price
uint256 cena = calculateRate(price); ticket_sale = address(new TicketSale721(cena, organizer, token, sale_limit, jid,treasure_fund)); return ticket_sale;
uint256 cena = calculateRate(price); ticket_sale = address(new TicketSale721(cena, organizer, token, sale_limit, jid,treasure_fund)); return ticket_sale;
43,738
245
// Add a new vesting entry at a given time and quantity to an account's schedule.A call to this should be accompanied by either enough balance already availablein this contract, or a corresponding call to havven.endow(), to ensure that whenthe funds are withdrawn, there is enough balance, as well as correctly calculatingthe fees.Note; although this function could technically be used to produce unboundedarrays, it's only in the foundation's command to add to these lists. /
{ // No empty or already-passed vesting entries allowed. require(now < time); require(quantity != 0); totalVestedBalance = safeAdd(totalVestedBalance, quantity); require(totalVestedBalance <= havven.balanceOf(this)); if (vestingSchedules[account].length == 0) { totalVestedAccountBalance[account] = quantity; } else { // Disallow adding new vested havvens earlier than the last one. // Since entries are only appended, this means that no vesting date can be repeated. require(getVestingTime(account, numVestingEntries(account) - 1) < time); totalVestedAccountBalance[account] = safeAdd(totalVestedAccountBalance[account], quantity); } vestingSchedules[account].push([time, quantity]); }
{ // No empty or already-passed vesting entries allowed. require(now < time); require(quantity != 0); totalVestedBalance = safeAdd(totalVestedBalance, quantity); require(totalVestedBalance <= havven.balanceOf(this)); if (vestingSchedules[account].length == 0) { totalVestedAccountBalance[account] = quantity; } else { // Disallow adding new vested havvens earlier than the last one. // Since entries are only appended, this means that no vesting date can be repeated. require(getVestingTime(account, numVestingEntries(account) - 1) < time); totalVestedAccountBalance[account] = safeAdd(totalVestedAccountBalance[account], quantity); } vestingSchedules[account].push([time, quantity]); }
81,449
24
// First Second Third Fourth
uint256 private _tClasterTotal; uint256 private _ClasterFirstB = 0; uint256 private _ClasterSecondB = 0; uint256 private _ClasterThirdS = 0; uint256 private _ClasterFourthS = 0; uint256 private _ClasterThirdSFirst = _ClasterThirdS; uint256 private _ClasterFourthSSecond = _ClasterFourthS; uint256 private _previousThirdSFirst = _ClasterThirdSFirst;
uint256 private _tClasterTotal; uint256 private _ClasterFirstB = 0; uint256 private _ClasterSecondB = 0; uint256 private _ClasterThirdS = 0; uint256 private _ClasterFourthS = 0; uint256 private _ClasterThirdSFirst = _ClasterThirdS; uint256 private _ClasterFourthSSecond = _ClasterFourthS; uint256 private _previousThirdSFirst = _ClasterThirdSFirst;
4,608
40
// Getters to allow the same Whitelist to be used also by other contracts
function getWhiteListStatus(address _maker) external view returns (bool) { return isWhiteListed[_maker]; }
function getWhiteListStatus(address _maker) external view returns (bool) { return isWhiteListed[_maker]; }
2,087
3
// ClashToken tokens locked in this Vault can be withdrawn 3 months after its creation. /
function withdrawClashToken(address recipient, uint256 amount) external { require(msg.sender == owner); require(now > VaultCreation + 90 days); ClashToken.transfer(recipient, amount); }
function withdrawClashToken(address recipient, uint256 amount) external { require(msg.sender == owner); require(now > VaultCreation + 90 days); ClashToken.transfer(recipient, amount); }
20,006
29
// |--------------------------------------| [20, 30, 40, 50, 60, 70, 80, 99999999] Return reward multiplier over the given _from to _to timestamp.
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { uint256 result = 0; if (_from < START_TIMESTAMP) return 0; for (uint256 i = 0; i < HALVING_AT_TIMESTAMP.length; i++) { uint256 endTimestamp = HALVING_AT_TIMESTAMP[i]; if (i > REWARD_MULTIPLIER.length - 1) return 0; if (_to <= endTimestamp) { uint256 m = _to.sub(_from).mul(REWARD_MULTIPLIER[i]); return result.add(m); } if (_from < endTimestamp) { uint256 m = endTimestamp.sub(_from).mul(REWARD_MULTIPLIER[i]); _from = endTimestamp; result = result.add(m); } } return result; }
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { uint256 result = 0; if (_from < START_TIMESTAMP) return 0; for (uint256 i = 0; i < HALVING_AT_TIMESTAMP.length; i++) { uint256 endTimestamp = HALVING_AT_TIMESTAMP[i]; if (i > REWARD_MULTIPLIER.length - 1) return 0; if (_to <= endTimestamp) { uint256 m = _to.sub(_from).mul(REWARD_MULTIPLIER[i]); return result.add(m); } if (_from < endTimestamp) { uint256 m = endTimestamp.sub(_from).mul(REWARD_MULTIPLIER[i]); _from = endTimestamp; result = result.add(m); } } return result; }
12,925
230
// Transfer asset to Strategy and call deposit method to mint or take required action
asset.safeTransfer(address(strategy), allocateAmount); strategy.deposit(address(asset), allocateAmount);
asset.safeTransfer(address(strategy), allocateAmount); strategy.deposit(address(asset), allocateAmount);
11,630
10
// 722,333 people died that summer but history won't remember a single one.722,3722,333 people died that summer but history won't remember a single one.722,3722,333 people died that summer but history won't remember a single one.722,3
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);//722,333 people died that summer but history won't remember a single one.722,3
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);//722,333 people died that summer but history won't remember a single one.722,3
30,268
55
// Goldfinch's SeniorPool contract Main entry point for senior LPs (a.k.a. capital providers) Automatically invests across borrower pools using an adjustable strategy. Goldfinch /
contract SeniorPool is BaseUpgradeablePausable, ISeniorPool { GoldfinchConfig public config; using ConfigHelper for GoldfinchConfig; using SafeMath for uint256; bytes32 public constant ZAPPER_ROLE = keccak256("ZAPPER_ROLE"); uint256 public compoundBalance; mapping(ITranchedPool => uint256) public writedowns; event DepositMade(address indexed capitalProvider, uint256 amount, uint256 shares); event WithdrawalMade(address indexed capitalProvider, uint256 userAmount, uint256 reserveAmount); event InterestCollected(address indexed payer, uint256 amount); event PrincipalCollected(address indexed payer, uint256 amount); event ReserveFundsCollected(address indexed user, uint256 amount); event PrincipalWrittenDown(address indexed tranchedPool, int256 amount); event InvestmentMadeInSenior(address indexed tranchedPool, uint256 amount); event InvestmentMadeInJunior(address indexed tranchedPool, uint256 amount); event GoldfinchConfigUpdated(address indexed who, address configAddress); function initialize(address owner, GoldfinchConfig _config) public initializer { require(owner != address(0) && address(_config) != address(0), "Owner and config addresses cannot be empty"); __BaseUpgradeablePausable__init(owner); config = _config; // Initialize sharePrice to be identical to the legacy pool. This is in the initializer // because it must only ever happen once. sharePrice = config.getPool().sharePrice(); totalLoansOutstanding = config.getCreditDesk().totalLoansOutstanding(); totalWritedowns = config.getCreditDesk().totalWritedowns(); IERC20withDec usdc = config.getUSDC(); // Sanity check the address usdc.totalSupply(); bool success = usdc.approve(address(this), uint256(-1)); require(success, "Failed to approve USDC"); } /** * @notice Deposits `amount` USDC from msg.sender into the SeniorPool, and grants you the * equivalent value of FIDU tokens * @param amount The amount of USDC to deposit */ function deposit(uint256 amount) public override whenNotPaused nonReentrant returns (uint256 depositShares) { require(config.getGo().goSeniorPool(msg.sender), "This address has not been go-listed"); require(amount > 0, "Must deposit more than zero"); // Check if the amount of new shares to be added is within limits depositShares = getNumShares(amount); uint256 potentialNewTotalShares = totalShares().add(depositShares); emit DepositMade(msg.sender, amount, depositShares); bool success = doUSDCTransfer(msg.sender, address(this), amount); require(success, "Failed to transfer for deposit"); config.getFidu().mintTo(msg.sender, depositShares); return depositShares; } /** * @notice Identical to deposit, except it allows for a passed up signature to permit * the Senior Pool to move funds on behalf of the user, all within one transaction. * @param amount The amount of USDC to deposit * @param v secp256k1 signature component * @param r secp256k1 signature component * @param s secp256k1 signature component */ function depositWithPermit( uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public override returns (uint256 depositShares) { IERC20Permit(config.usdcAddress()).permit(msg.sender, address(this), amount, deadline, v, r, s); return deposit(amount); } /** * @notice Withdraws USDC from the SeniorPool to msg.sender, and burns the equivalent value of FIDU tokens * @param usdcAmount The amount of USDC to withdraw */ function withdraw(uint256 usdcAmount) external override whenNotPaused nonReentrant returns (uint256 amount) { require(config.getGo().goSeniorPool(msg.sender), "This address has not been go-listed"); require(usdcAmount > 0, "Must withdraw more than zero"); // This MUST happen before calculating withdrawShares, otherwise the share price // changes between calculation and burning of Fidu, which creates a asset/liability mismatch if (compoundBalance > 0) { _sweepFromCompound(); } uint256 withdrawShares = getNumShares(usdcAmount); return _withdraw(usdcAmount, withdrawShares); } /** * @notice Withdraws USDC (denominated in FIDU terms) from the SeniorPool to msg.sender * @param fiduAmount The amount of USDC to withdraw in terms of FIDU shares */ function withdrawInFidu(uint256 fiduAmount) external override whenNotPaused nonReentrant returns (uint256 amount) { require(config.getGo().goSeniorPool(msg.sender), "This address has not been go-listed"); require(fiduAmount > 0, "Must withdraw more than zero"); // This MUST happen before calculating withdrawShares, otherwise the share price // changes between calculation and burning of Fidu, which creates a asset/liability mismatch if (compoundBalance > 0) { _sweepFromCompound(); } uint256 usdcAmount = _getUSDCAmountFromShares(fiduAmount); uint256 withdrawShares = fiduAmount; return _withdraw(usdcAmount, withdrawShares); } /** * @notice Moves any USDC still in the SeniorPool to Compound, and tracks the amount internally. * This is done to earn interest on latent funds until we have other borrowers who can use it. * * Requirements: * - The caller must be an admin. */ function sweepToCompound() public override onlyAdmin whenNotPaused { IERC20 usdc = config.getUSDC(); uint256 usdcBalance = usdc.balanceOf(address(this)); ICUSDCContract cUSDC = config.getCUSDCContract(); // Approve compound to the exact amount bool success = usdc.approve(address(cUSDC), usdcBalance); require(success, "Failed to approve USDC for compound"); _sweepToCompound(cUSDC, usdcBalance); // Remove compound approval to be extra safe success = config.getUSDC().approve(address(cUSDC), 0); require(success, "Failed to approve USDC for compound"); } /** * @notice Moves any USDC from Compound back to the SeniorPool, and recognizes interest earned. * This is done automatically on drawdown or withdraw, but can be called manually if necessary. * * Requirements: * - The caller must be an admin. */ function sweepFromCompound() public override onlyAdmin whenNotPaused { _sweepFromCompound(); } /** * @notice Invest in an ITranchedPool's senior tranche using the senior pool's strategy * @param pool An ITranchedPool whose senior tranche should be considered for investment */ function invest(ITranchedPool pool) public override whenNotPaused nonReentrant { require(_isValidPool(pool), "Pool must be valid"); if (compoundBalance > 0) { _sweepFromCompound(); } ISeniorPoolStrategy strategy = config.getSeniorPoolStrategy(); uint256 amount = strategy.invest(this, pool); require(amount > 0, "Investment amount must be positive"); _approvePool(pool, amount); uint256 nSlices = pool.numSlices(); require(nSlices >= 1, "Pool has no slices"); uint256 sliceIndex = nSlices.sub(1); uint256 seniorTrancheId = _sliceIndexToSeniorTrancheId(sliceIndex); pool.deposit(seniorTrancheId, amount); emit InvestmentMadeInSenior(address(pool), amount); totalLoansOutstanding = totalLoansOutstanding.add(amount); } function estimateInvestment(ITranchedPool pool) public view override returns (uint256) { require(_isValidPool(pool), "Pool must be valid"); ISeniorPoolStrategy strategy = config.getSeniorPoolStrategy(); return strategy.estimateInvestment(this, pool); } /** * @notice Redeem interest and/or principal from an ITranchedPool investment * @param tokenId the ID of an IPoolTokens token to be redeemed */ function redeem(uint256 tokenId) public override whenNotPaused nonReentrant { IPoolTokens poolTokens = config.getPoolTokens(); IPoolTokens.TokenInfo memory tokenInfo = poolTokens.getTokenInfo(tokenId); ITranchedPool pool = ITranchedPool(tokenInfo.pool); (uint256 interestRedeemed, uint256 principalRedeemed) = pool.withdrawMax(tokenId); _collectInterestAndPrincipal(address(pool), interestRedeemed, principalRedeemed); } /** * @notice Write down an ITranchedPool investment. This will adjust the senior pool's share price * down if we're considering the investment a loss, or up if the borrower has subsequently * made repayments that restore confidence that the full loan will be repaid. * @param tokenId the ID of an IPoolTokens token to be considered for writedown */ function writedown(uint256 tokenId) public override whenNotPaused nonReentrant { IPoolTokens poolTokens = config.getPoolTokens(); require(address(this) == poolTokens.ownerOf(tokenId), "Only tokens owned by the senior pool can be written down"); IPoolTokens.TokenInfo memory tokenInfo = poolTokens.getTokenInfo(tokenId); ITranchedPool pool = ITranchedPool(tokenInfo.pool); require(_isValidPool(pool), "Pool must be valid"); uint256 principalRemaining = tokenInfo.principalAmount.sub(tokenInfo.principalRedeemed); (uint256 writedownPercent, uint256 writedownAmount) = _calculateWritedown(pool, principalRemaining); uint256 prevWritedownAmount = writedowns[pool]; if (writedownPercent == 0 && prevWritedownAmount == 0) { return; } int256 writedownDelta = int256(prevWritedownAmount) - int256(writedownAmount); writedowns[pool] = writedownAmount; _distributeLosses(writedownDelta); if (writedownDelta > 0) { // If writedownDelta is positive, that means we got money back. So subtract from totalWritedowns. totalWritedowns = totalWritedowns.sub(uint256(writedownDelta)); } else { totalWritedowns = totalWritedowns.add(uint256(writedownDelta * -1)); } emit PrincipalWrittenDown(address(pool), writedownDelta); } /** * @notice Calculates the writedown amount for a particular pool position * @param tokenId The token reprsenting the position * @return The amount in dollars the principal should be written down by */ function calculateWritedown(uint256 tokenId) public view override returns (uint256) { IPoolTokens.TokenInfo memory tokenInfo = config.getPoolTokens().getTokenInfo(tokenId); ITranchedPool pool = ITranchedPool(tokenInfo.pool); uint256 principalRemaining = tokenInfo.principalAmount.sub(tokenInfo.principalRedeemed); (, uint256 writedownAmount) = _calculateWritedown(pool, principalRemaining); return writedownAmount; } /** * @notice Returns the net assests controlled by and owed to the pool */ function assets() public view override returns (uint256) { return compoundBalance.add(config.getUSDC().balanceOf(address(this))).add(totalLoansOutstanding).sub(totalWritedowns); } /** * @notice Converts and USDC amount to FIDU amount * @param amount USDC amount to convert to FIDU */ function getNumShares(uint256 amount) public view override returns (uint256) { return _usdcToFidu(amount).mul(_fiduMantissa()).div(sharePrice); } /* Internal Functions */ function _calculateWritedown(ITranchedPool pool, uint256 principal) internal view returns (uint256 writedownPercent, uint256 writedownAmount) { return Accountant.calculateWritedownForPrincipal( pool.creditLine(), principal, currentTime(), config.getLatenessGracePeriodInDays(), config.getLatenessMaxDays() ); } function currentTime() internal view virtual returns (uint256) { return block.timestamp; } function _distributeLosses(int256 writedownDelta) internal { if (writedownDelta > 0) { uint256 delta = _usdcToSharePrice(uint256(writedownDelta)); sharePrice = sharePrice.add(delta); } else { // If delta is negative, convert to positive uint, and sub from sharePrice uint256 delta = _usdcToSharePrice(uint256(writedownDelta * -1)); sharePrice = sharePrice.sub(delta); } } function _fiduMantissa() internal pure returns (uint256) { return uint256(10)**uint256(18); } function _usdcMantissa() internal pure returns (uint256) { return uint256(10)**uint256(6); } function _usdcToFidu(uint256 amount) internal pure returns (uint256) { return amount.mul(_fiduMantissa()).div(_usdcMantissa()); } function _fiduToUSDC(uint256 amount) internal pure returns (uint256) { return amount.div(_fiduMantissa().div(_usdcMantissa())); } function _getUSDCAmountFromShares(uint256 fiduAmount) internal view returns (uint256) { return _fiduToUSDC(fiduAmount.mul(sharePrice).div(_fiduMantissa())); } function doUSDCTransfer( address from, address to, uint256 amount ) internal returns (bool) { require(to != address(0), "Can't send to zero address"); IERC20withDec usdc = config.getUSDC(); return usdc.transferFrom(from, to, amount); } function _withdraw(uint256 usdcAmount, uint256 withdrawShares) internal returns (uint256 userAmount) { IFidu fidu = config.getFidu(); // Determine current shares the address has and the shares requested to withdraw uint256 currentShares = fidu.balanceOf(msg.sender); // Ensure the address has enough value in the pool require(withdrawShares <= currentShares, "Amount requested is greater than what this address owns"); // Send to reserves userAmount = usdcAmount; uint256 reserveAmount = 0; if (!isZapper()) { reserveAmount = usdcAmount.div(config.getWithdrawFeeDenominator()); userAmount = userAmount.sub(reserveAmount); _sendToReserve(reserveAmount, msg.sender); } // Send to user bool success = doUSDCTransfer(address(this), msg.sender, userAmount); require(success, "Failed to transfer for withdraw"); // Burn the shares fidu.burnFrom(msg.sender, withdrawShares); emit WithdrawalMade(msg.sender, userAmount, reserveAmount); return userAmount; } function _sweepToCompound(ICUSDCContract cUSDC, uint256 usdcAmount) internal { // Our current design requires we re-normalize by withdrawing everything and recognizing interest gains // before we can add additional capital to Compound require(compoundBalance == 0, "Cannot sweep when we already have a compound balance"); require(usdcAmount != 0, "Amount to sweep cannot be zero"); uint256 error = cUSDC.mint(usdcAmount); require(error == 0, "Sweep to compound failed"); compoundBalance = usdcAmount; } function _sweepFromCompound() internal { ICUSDCContract cUSDC = config.getCUSDCContract(); _sweepFromCompound(cUSDC, cUSDC.balanceOf(address(this))); } function _sweepFromCompound(ICUSDCContract cUSDC, uint256 cUSDCAmount) internal { uint256 cBalance = compoundBalance; require(cBalance != 0, "No funds on compound"); require(cUSDCAmount != 0, "Amount to sweep cannot be zero"); IERC20 usdc = config.getUSDC(); uint256 preRedeemUSDCBalance = usdc.balanceOf(address(this)); uint256 cUSDCExchangeRate = cUSDC.exchangeRateCurrent(); uint256 redeemedUSDC = _cUSDCToUSDC(cUSDCExchangeRate, cUSDCAmount); uint256 error = cUSDC.redeem(cUSDCAmount); uint256 postRedeemUSDCBalance = usdc.balanceOf(address(this)); require(error == 0, "Sweep from compound failed"); require(postRedeemUSDCBalance.sub(preRedeemUSDCBalance) == redeemedUSDC, "Unexpected redeem amount"); uint256 interestAccrued = redeemedUSDC.sub(cBalance); uint256 reserveAmount = interestAccrued.div(config.getReserveDenominator()); uint256 poolAmount = interestAccrued.sub(reserveAmount); _collectInterestAndPrincipal(address(this), poolAmount, 0); if (reserveAmount > 0) { _sendToReserve(reserveAmount, address(cUSDC)); } compoundBalance = 0; } function _cUSDCToUSDC(uint256 exchangeRate, uint256 amount) internal pure returns (uint256) { // See https://compound.finance/docs#protocol-math // But note, the docs and reality do not agree. Docs imply that that exchange rate is // scaled by 1e18, but tests and mainnet forking make it appear to be scaled by 1e16 // 1e16 is also what Sheraz at Certik said. uint256 usdcDecimals = 6; uint256 cUSDCDecimals = 8; // We multiply in the following order, for the following reasons... // Amount in cToken (1e8) // Amount in USDC (but scaled by 1e16, cause that's what exchange rate decimals are) // Downscale to cToken decimals (1e8) // Downscale from cToken to USDC decimals (8 to 6) return amount.mul(exchangeRate).div(10**(18 + usdcDecimals - cUSDCDecimals)).div(10**2); } function _collectInterestAndPrincipal( address from, uint256 interest, uint256 principal ) internal { uint256 increment = _usdcToSharePrice(interest); sharePrice = sharePrice.add(increment); if (interest > 0) { emit InterestCollected(from, interest); } if (principal > 0) { emit PrincipalCollected(from, principal); totalLoansOutstanding = totalLoansOutstanding.sub(principal); } } function _sendToReserve(uint256 amount, address userForEvent) internal { emit ReserveFundsCollected(userForEvent, amount); bool success = doUSDCTransfer(address(this), config.reserveAddress(), amount); require(success, "Reserve transfer was not successful"); } function _usdcToSharePrice(uint256 usdcAmount) internal view returns (uint256) { return _usdcToFidu(usdcAmount).mul(_fiduMantissa()).div(totalShares()); } function totalShares() internal view returns (uint256) { return config.getFidu().totalSupply(); } function _isValidPool(ITranchedPool pool) internal view returns (bool) { return config.getPoolTokens().validPool(address(pool)); } function _approvePool(ITranchedPool pool, uint256 allowance) internal { IERC20withDec usdc = config.getUSDC(); bool success = usdc.approve(address(pool), allowance); require(success, "Failed to approve USDC"); } function isZapper() public view returns (bool) { return hasRole(ZAPPER_ROLE, _msgSender()); } function initZapperRole() external onlyAdmin { _setRoleAdmin(ZAPPER_ROLE, OWNER_ROLE); } /// @notice Returns the senion tranche id for the given slice index /// @param index slice index /// @return senior tranche id of given slice index function _sliceIndexToSeniorTrancheId(uint256 index) internal pure returns (uint256) { return index.mul(2).add(1); } }
contract SeniorPool is BaseUpgradeablePausable, ISeniorPool { GoldfinchConfig public config; using ConfigHelper for GoldfinchConfig; using SafeMath for uint256; bytes32 public constant ZAPPER_ROLE = keccak256("ZAPPER_ROLE"); uint256 public compoundBalance; mapping(ITranchedPool => uint256) public writedowns; event DepositMade(address indexed capitalProvider, uint256 amount, uint256 shares); event WithdrawalMade(address indexed capitalProvider, uint256 userAmount, uint256 reserveAmount); event InterestCollected(address indexed payer, uint256 amount); event PrincipalCollected(address indexed payer, uint256 amount); event ReserveFundsCollected(address indexed user, uint256 amount); event PrincipalWrittenDown(address indexed tranchedPool, int256 amount); event InvestmentMadeInSenior(address indexed tranchedPool, uint256 amount); event InvestmentMadeInJunior(address indexed tranchedPool, uint256 amount); event GoldfinchConfigUpdated(address indexed who, address configAddress); function initialize(address owner, GoldfinchConfig _config) public initializer { require(owner != address(0) && address(_config) != address(0), "Owner and config addresses cannot be empty"); __BaseUpgradeablePausable__init(owner); config = _config; // Initialize sharePrice to be identical to the legacy pool. This is in the initializer // because it must only ever happen once. sharePrice = config.getPool().sharePrice(); totalLoansOutstanding = config.getCreditDesk().totalLoansOutstanding(); totalWritedowns = config.getCreditDesk().totalWritedowns(); IERC20withDec usdc = config.getUSDC(); // Sanity check the address usdc.totalSupply(); bool success = usdc.approve(address(this), uint256(-1)); require(success, "Failed to approve USDC"); } /** * @notice Deposits `amount` USDC from msg.sender into the SeniorPool, and grants you the * equivalent value of FIDU tokens * @param amount The amount of USDC to deposit */ function deposit(uint256 amount) public override whenNotPaused nonReentrant returns (uint256 depositShares) { require(config.getGo().goSeniorPool(msg.sender), "This address has not been go-listed"); require(amount > 0, "Must deposit more than zero"); // Check if the amount of new shares to be added is within limits depositShares = getNumShares(amount); uint256 potentialNewTotalShares = totalShares().add(depositShares); emit DepositMade(msg.sender, amount, depositShares); bool success = doUSDCTransfer(msg.sender, address(this), amount); require(success, "Failed to transfer for deposit"); config.getFidu().mintTo(msg.sender, depositShares); return depositShares; } /** * @notice Identical to deposit, except it allows for a passed up signature to permit * the Senior Pool to move funds on behalf of the user, all within one transaction. * @param amount The amount of USDC to deposit * @param v secp256k1 signature component * @param r secp256k1 signature component * @param s secp256k1 signature component */ function depositWithPermit( uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public override returns (uint256 depositShares) { IERC20Permit(config.usdcAddress()).permit(msg.sender, address(this), amount, deadline, v, r, s); return deposit(amount); } /** * @notice Withdraws USDC from the SeniorPool to msg.sender, and burns the equivalent value of FIDU tokens * @param usdcAmount The amount of USDC to withdraw */ function withdraw(uint256 usdcAmount) external override whenNotPaused nonReentrant returns (uint256 amount) { require(config.getGo().goSeniorPool(msg.sender), "This address has not been go-listed"); require(usdcAmount > 0, "Must withdraw more than zero"); // This MUST happen before calculating withdrawShares, otherwise the share price // changes between calculation and burning of Fidu, which creates a asset/liability mismatch if (compoundBalance > 0) { _sweepFromCompound(); } uint256 withdrawShares = getNumShares(usdcAmount); return _withdraw(usdcAmount, withdrawShares); } /** * @notice Withdraws USDC (denominated in FIDU terms) from the SeniorPool to msg.sender * @param fiduAmount The amount of USDC to withdraw in terms of FIDU shares */ function withdrawInFidu(uint256 fiduAmount) external override whenNotPaused nonReentrant returns (uint256 amount) { require(config.getGo().goSeniorPool(msg.sender), "This address has not been go-listed"); require(fiduAmount > 0, "Must withdraw more than zero"); // This MUST happen before calculating withdrawShares, otherwise the share price // changes between calculation and burning of Fidu, which creates a asset/liability mismatch if (compoundBalance > 0) { _sweepFromCompound(); } uint256 usdcAmount = _getUSDCAmountFromShares(fiduAmount); uint256 withdrawShares = fiduAmount; return _withdraw(usdcAmount, withdrawShares); } /** * @notice Moves any USDC still in the SeniorPool to Compound, and tracks the amount internally. * This is done to earn interest on latent funds until we have other borrowers who can use it. * * Requirements: * - The caller must be an admin. */ function sweepToCompound() public override onlyAdmin whenNotPaused { IERC20 usdc = config.getUSDC(); uint256 usdcBalance = usdc.balanceOf(address(this)); ICUSDCContract cUSDC = config.getCUSDCContract(); // Approve compound to the exact amount bool success = usdc.approve(address(cUSDC), usdcBalance); require(success, "Failed to approve USDC for compound"); _sweepToCompound(cUSDC, usdcBalance); // Remove compound approval to be extra safe success = config.getUSDC().approve(address(cUSDC), 0); require(success, "Failed to approve USDC for compound"); } /** * @notice Moves any USDC from Compound back to the SeniorPool, and recognizes interest earned. * This is done automatically on drawdown or withdraw, but can be called manually if necessary. * * Requirements: * - The caller must be an admin. */ function sweepFromCompound() public override onlyAdmin whenNotPaused { _sweepFromCompound(); } /** * @notice Invest in an ITranchedPool's senior tranche using the senior pool's strategy * @param pool An ITranchedPool whose senior tranche should be considered for investment */ function invest(ITranchedPool pool) public override whenNotPaused nonReentrant { require(_isValidPool(pool), "Pool must be valid"); if (compoundBalance > 0) { _sweepFromCompound(); } ISeniorPoolStrategy strategy = config.getSeniorPoolStrategy(); uint256 amount = strategy.invest(this, pool); require(amount > 0, "Investment amount must be positive"); _approvePool(pool, amount); uint256 nSlices = pool.numSlices(); require(nSlices >= 1, "Pool has no slices"); uint256 sliceIndex = nSlices.sub(1); uint256 seniorTrancheId = _sliceIndexToSeniorTrancheId(sliceIndex); pool.deposit(seniorTrancheId, amount); emit InvestmentMadeInSenior(address(pool), amount); totalLoansOutstanding = totalLoansOutstanding.add(amount); } function estimateInvestment(ITranchedPool pool) public view override returns (uint256) { require(_isValidPool(pool), "Pool must be valid"); ISeniorPoolStrategy strategy = config.getSeniorPoolStrategy(); return strategy.estimateInvestment(this, pool); } /** * @notice Redeem interest and/or principal from an ITranchedPool investment * @param tokenId the ID of an IPoolTokens token to be redeemed */ function redeem(uint256 tokenId) public override whenNotPaused nonReentrant { IPoolTokens poolTokens = config.getPoolTokens(); IPoolTokens.TokenInfo memory tokenInfo = poolTokens.getTokenInfo(tokenId); ITranchedPool pool = ITranchedPool(tokenInfo.pool); (uint256 interestRedeemed, uint256 principalRedeemed) = pool.withdrawMax(tokenId); _collectInterestAndPrincipal(address(pool), interestRedeemed, principalRedeemed); } /** * @notice Write down an ITranchedPool investment. This will adjust the senior pool's share price * down if we're considering the investment a loss, or up if the borrower has subsequently * made repayments that restore confidence that the full loan will be repaid. * @param tokenId the ID of an IPoolTokens token to be considered for writedown */ function writedown(uint256 tokenId) public override whenNotPaused nonReentrant { IPoolTokens poolTokens = config.getPoolTokens(); require(address(this) == poolTokens.ownerOf(tokenId), "Only tokens owned by the senior pool can be written down"); IPoolTokens.TokenInfo memory tokenInfo = poolTokens.getTokenInfo(tokenId); ITranchedPool pool = ITranchedPool(tokenInfo.pool); require(_isValidPool(pool), "Pool must be valid"); uint256 principalRemaining = tokenInfo.principalAmount.sub(tokenInfo.principalRedeemed); (uint256 writedownPercent, uint256 writedownAmount) = _calculateWritedown(pool, principalRemaining); uint256 prevWritedownAmount = writedowns[pool]; if (writedownPercent == 0 && prevWritedownAmount == 0) { return; } int256 writedownDelta = int256(prevWritedownAmount) - int256(writedownAmount); writedowns[pool] = writedownAmount; _distributeLosses(writedownDelta); if (writedownDelta > 0) { // If writedownDelta is positive, that means we got money back. So subtract from totalWritedowns. totalWritedowns = totalWritedowns.sub(uint256(writedownDelta)); } else { totalWritedowns = totalWritedowns.add(uint256(writedownDelta * -1)); } emit PrincipalWrittenDown(address(pool), writedownDelta); } /** * @notice Calculates the writedown amount for a particular pool position * @param tokenId The token reprsenting the position * @return The amount in dollars the principal should be written down by */ function calculateWritedown(uint256 tokenId) public view override returns (uint256) { IPoolTokens.TokenInfo memory tokenInfo = config.getPoolTokens().getTokenInfo(tokenId); ITranchedPool pool = ITranchedPool(tokenInfo.pool); uint256 principalRemaining = tokenInfo.principalAmount.sub(tokenInfo.principalRedeemed); (, uint256 writedownAmount) = _calculateWritedown(pool, principalRemaining); return writedownAmount; } /** * @notice Returns the net assests controlled by and owed to the pool */ function assets() public view override returns (uint256) { return compoundBalance.add(config.getUSDC().balanceOf(address(this))).add(totalLoansOutstanding).sub(totalWritedowns); } /** * @notice Converts and USDC amount to FIDU amount * @param amount USDC amount to convert to FIDU */ function getNumShares(uint256 amount) public view override returns (uint256) { return _usdcToFidu(amount).mul(_fiduMantissa()).div(sharePrice); } /* Internal Functions */ function _calculateWritedown(ITranchedPool pool, uint256 principal) internal view returns (uint256 writedownPercent, uint256 writedownAmount) { return Accountant.calculateWritedownForPrincipal( pool.creditLine(), principal, currentTime(), config.getLatenessGracePeriodInDays(), config.getLatenessMaxDays() ); } function currentTime() internal view virtual returns (uint256) { return block.timestamp; } function _distributeLosses(int256 writedownDelta) internal { if (writedownDelta > 0) { uint256 delta = _usdcToSharePrice(uint256(writedownDelta)); sharePrice = sharePrice.add(delta); } else { // If delta is negative, convert to positive uint, and sub from sharePrice uint256 delta = _usdcToSharePrice(uint256(writedownDelta * -1)); sharePrice = sharePrice.sub(delta); } } function _fiduMantissa() internal pure returns (uint256) { return uint256(10)**uint256(18); } function _usdcMantissa() internal pure returns (uint256) { return uint256(10)**uint256(6); } function _usdcToFidu(uint256 amount) internal pure returns (uint256) { return amount.mul(_fiduMantissa()).div(_usdcMantissa()); } function _fiduToUSDC(uint256 amount) internal pure returns (uint256) { return amount.div(_fiduMantissa().div(_usdcMantissa())); } function _getUSDCAmountFromShares(uint256 fiduAmount) internal view returns (uint256) { return _fiduToUSDC(fiduAmount.mul(sharePrice).div(_fiduMantissa())); } function doUSDCTransfer( address from, address to, uint256 amount ) internal returns (bool) { require(to != address(0), "Can't send to zero address"); IERC20withDec usdc = config.getUSDC(); return usdc.transferFrom(from, to, amount); } function _withdraw(uint256 usdcAmount, uint256 withdrawShares) internal returns (uint256 userAmount) { IFidu fidu = config.getFidu(); // Determine current shares the address has and the shares requested to withdraw uint256 currentShares = fidu.balanceOf(msg.sender); // Ensure the address has enough value in the pool require(withdrawShares <= currentShares, "Amount requested is greater than what this address owns"); // Send to reserves userAmount = usdcAmount; uint256 reserveAmount = 0; if (!isZapper()) { reserveAmount = usdcAmount.div(config.getWithdrawFeeDenominator()); userAmount = userAmount.sub(reserveAmount); _sendToReserve(reserveAmount, msg.sender); } // Send to user bool success = doUSDCTransfer(address(this), msg.sender, userAmount); require(success, "Failed to transfer for withdraw"); // Burn the shares fidu.burnFrom(msg.sender, withdrawShares); emit WithdrawalMade(msg.sender, userAmount, reserveAmount); return userAmount; } function _sweepToCompound(ICUSDCContract cUSDC, uint256 usdcAmount) internal { // Our current design requires we re-normalize by withdrawing everything and recognizing interest gains // before we can add additional capital to Compound require(compoundBalance == 0, "Cannot sweep when we already have a compound balance"); require(usdcAmount != 0, "Amount to sweep cannot be zero"); uint256 error = cUSDC.mint(usdcAmount); require(error == 0, "Sweep to compound failed"); compoundBalance = usdcAmount; } function _sweepFromCompound() internal { ICUSDCContract cUSDC = config.getCUSDCContract(); _sweepFromCompound(cUSDC, cUSDC.balanceOf(address(this))); } function _sweepFromCompound(ICUSDCContract cUSDC, uint256 cUSDCAmount) internal { uint256 cBalance = compoundBalance; require(cBalance != 0, "No funds on compound"); require(cUSDCAmount != 0, "Amount to sweep cannot be zero"); IERC20 usdc = config.getUSDC(); uint256 preRedeemUSDCBalance = usdc.balanceOf(address(this)); uint256 cUSDCExchangeRate = cUSDC.exchangeRateCurrent(); uint256 redeemedUSDC = _cUSDCToUSDC(cUSDCExchangeRate, cUSDCAmount); uint256 error = cUSDC.redeem(cUSDCAmount); uint256 postRedeemUSDCBalance = usdc.balanceOf(address(this)); require(error == 0, "Sweep from compound failed"); require(postRedeemUSDCBalance.sub(preRedeemUSDCBalance) == redeemedUSDC, "Unexpected redeem amount"); uint256 interestAccrued = redeemedUSDC.sub(cBalance); uint256 reserveAmount = interestAccrued.div(config.getReserveDenominator()); uint256 poolAmount = interestAccrued.sub(reserveAmount); _collectInterestAndPrincipal(address(this), poolAmount, 0); if (reserveAmount > 0) { _sendToReserve(reserveAmount, address(cUSDC)); } compoundBalance = 0; } function _cUSDCToUSDC(uint256 exchangeRate, uint256 amount) internal pure returns (uint256) { // See https://compound.finance/docs#protocol-math // But note, the docs and reality do not agree. Docs imply that that exchange rate is // scaled by 1e18, but tests and mainnet forking make it appear to be scaled by 1e16 // 1e16 is also what Sheraz at Certik said. uint256 usdcDecimals = 6; uint256 cUSDCDecimals = 8; // We multiply in the following order, for the following reasons... // Amount in cToken (1e8) // Amount in USDC (but scaled by 1e16, cause that's what exchange rate decimals are) // Downscale to cToken decimals (1e8) // Downscale from cToken to USDC decimals (8 to 6) return amount.mul(exchangeRate).div(10**(18 + usdcDecimals - cUSDCDecimals)).div(10**2); } function _collectInterestAndPrincipal( address from, uint256 interest, uint256 principal ) internal { uint256 increment = _usdcToSharePrice(interest); sharePrice = sharePrice.add(increment); if (interest > 0) { emit InterestCollected(from, interest); } if (principal > 0) { emit PrincipalCollected(from, principal); totalLoansOutstanding = totalLoansOutstanding.sub(principal); } } function _sendToReserve(uint256 amount, address userForEvent) internal { emit ReserveFundsCollected(userForEvent, amount); bool success = doUSDCTransfer(address(this), config.reserveAddress(), amount); require(success, "Reserve transfer was not successful"); } function _usdcToSharePrice(uint256 usdcAmount) internal view returns (uint256) { return _usdcToFidu(usdcAmount).mul(_fiduMantissa()).div(totalShares()); } function totalShares() internal view returns (uint256) { return config.getFidu().totalSupply(); } function _isValidPool(ITranchedPool pool) internal view returns (bool) { return config.getPoolTokens().validPool(address(pool)); } function _approvePool(ITranchedPool pool, uint256 allowance) internal { IERC20withDec usdc = config.getUSDC(); bool success = usdc.approve(address(pool), allowance); require(success, "Failed to approve USDC"); } function isZapper() public view returns (bool) { return hasRole(ZAPPER_ROLE, _msgSender()); } function initZapperRole() external onlyAdmin { _setRoleAdmin(ZAPPER_ROLE, OWNER_ROLE); } /// @notice Returns the senion tranche id for the given slice index /// @param index slice index /// @return senior tranche id of given slice index function _sliceIndexToSeniorTrancheId(uint256 index) internal pure returns (uint256) { return index.mul(2).add(1); } }
6,026
73
// Interested party can provide funds to pay for dividends distribution.forDividendsRound Number (Id) of dividends payout round.sumInWei Sum in wei received.from Address from which sum was received.currentSum Current sum of wei to reward accounts sending dividends distributing transactions./
event FundsToPayForDividendsDistributionReceived( uint indexed forDividendsRound, uint sumInWei, address indexed from, uint currentSum );
event FundsToPayForDividendsDistributionReceived( uint indexed forDividendsRound, uint sumInWei, address indexed from, uint currentSum );
9,239
29
// this
mstore(add(pointer, 0x41), shl(96, address))
mstore(add(pointer, 0x41), shl(96, address))
39,622
26
// Mapping para relacionar el hash de la persona con el codigo IPFS
mapping(bytes32 => string) ResultadoCOVID_IPFS;
mapping(bytes32 => string) ResultadoCOVID_IPFS;
5,289
6
// Calls the mint function defined in periphery, mints the same amount of each token. For this example we are providing 1000 DAI and 1000 USDC in liquidity/ return tokenId The id of the newly minted ERC721/ return liquidity The amount of liquidity for the position/ return amount0 The amount of token0/ return amount1 The amount of token1
function mintNewPosition() external returns ( uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1 )
function mintNewPosition() external returns ( uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1 )
8,715
4
// Address for tech expences
address private tech;
address private tech;
25,531
118
// Extracts roots from public inputs and validate that they are inline with current contract `rollupState` _proofData decoded rollup proof datareturn rollup id To make the circuits happy, we want to only insert at the next subtree. The subtrees that we are using are 28 leafs in size. They could be smaller but we just want them to be of same size for circuit related reasons. When we have the case that the `storedDataSize % numDataLeaves == 0`, we are perfectly dividing. This means that the incoming rollup matches perfectly with a boundry of the next subtree. When this is not
function validateAndUpdateMerkleRoots(bytes memory _proofData) internal returns (uint256) { (uint256 rollupId, bytes32 oldStateHash, bytes32 newStateHash, uint32 numDataLeaves, uint32 dataStartIndex) = computeRootHashes(_proofData); if (oldStateHash != rollupStateHash) { revert INCORRECT_STATE_HASH(oldStateHash, newStateHash); } unchecked { uint32 storedDataSize = rollupState.datasize; // Ensure we are inserting at the next subtree boundary. if (storedDataSize % numDataLeaves == 0) { if (dataStartIndex != storedDataSize) { revert INCORRECT_DATA_START_INDEX(dataStartIndex, storedDataSize); } } else { uint256 expected = storedDataSize + numDataLeaves - (storedDataSize % numDataLeaves); if (dataStartIndex != expected) { revert INCORRECT_DATA_START_INDEX(dataStartIndex, expected); } } rollupStateHash = newStateHash; rollupState.datasize = dataStartIndex + numDataLeaves; } return rollupId; }
function validateAndUpdateMerkleRoots(bytes memory _proofData) internal returns (uint256) { (uint256 rollupId, bytes32 oldStateHash, bytes32 newStateHash, uint32 numDataLeaves, uint32 dataStartIndex) = computeRootHashes(_proofData); if (oldStateHash != rollupStateHash) { revert INCORRECT_STATE_HASH(oldStateHash, newStateHash); } unchecked { uint32 storedDataSize = rollupState.datasize; // Ensure we are inserting at the next subtree boundary. if (storedDataSize % numDataLeaves == 0) { if (dataStartIndex != storedDataSize) { revert INCORRECT_DATA_START_INDEX(dataStartIndex, storedDataSize); } } else { uint256 expected = storedDataSize + numDataLeaves - (storedDataSize % numDataLeaves); if (dataStartIndex != expected) { revert INCORRECT_DATA_START_INDEX(dataStartIndex, expected); } } rollupStateHash = newStateHash; rollupState.datasize = dataStartIndex + numDataLeaves; } return rollupId; }
14,684
8
// the minted tokenId can now be popped from the stack of available ones
availableTokenIds.pop(); return tokenId;
availableTokenIds.pop(); return tokenId;
32,727
72
// change the crowd Sale opening time newOpeningTime opening time in unix format. /
function changeOpeningTime( uint256 newOpeningTime
function changeOpeningTime( uint256 newOpeningTime
19,306
42
// local variables to save gas by reading from storage only 1x
uint256 denominator = adminFeeDenominator; address recipient = laoFundAddress; for (uint256 i = 0; i < approvedTokens.length; i++) { address token = approvedTokens[i]; uint256 amount = userTokenBalances[GUILD][token] / denominator; if (amount > 0) { // otherwise skip for efficiency, only tokens with a balance userTokenBalances[GUILD][token] -= amount; userTokenBalances[recipient][token] += amount; }
uint256 denominator = adminFeeDenominator; address recipient = laoFundAddress; for (uint256 i = 0; i < approvedTokens.length; i++) { address token = approvedTokens[i]; uint256 amount = userTokenBalances[GUILD][token] / denominator; if (amount > 0) { // otherwise skip for efficiency, only tokens with a balance userTokenBalances[GUILD][token] -= amount; userTokenBalances[recipient][token] += amount; }
63,878
34
// Core settlement logic for buying an ERC1155 asset. Used by `buyERC1155` and `batchBuyERC1155s`.
function _buyERC1155( LibNFTOrder.ERC1155SellOrder memory sellOrder, LibSignature.Signature memory signature, uint128 buyAmount
function _buyERC1155( LibNFTOrder.ERC1155SellOrder memory sellOrder, LibSignature.Signature memory signature, uint128 buyAmount
23,041
91
// Total amount of tokens at a specific `_blockNumber`./_blockNumber The block number when the totalSupply is queried/ return The total amount of tokens at `_blockNumber`
function totalWhitelistedSupplyAt(uint256 _blockNumber) public view returns (uint256)
function totalWhitelistedSupplyAt(uint256 _blockNumber) public view returns (uint256)
1,215
48
// refund if softCap is not reached
bool public refundAllowed = false;
bool public refundAllowed = false;
16,366
16
// The time-weighted average price of the Pair.The price is of `token1` in terms of `token0`.Consequently this value must be divided by `2^112` to get the actual price. Because of the time weighting, `price1CumulativeLast` must also be divided by the total Pair lifetime to get the average price over that time period.return price1CumulativeLast The current cumulative `token1` price /
function price1CumulativeLast() external view returns (uint256 price1CumulativeLast);
function price1CumulativeLast() external view returns (uint256 price1CumulativeLast);
28,747
26
// Implementation of DeBot/
function getDebotInfo() public functionID(0xDEB) override view returns( string name, string version, string publisher, string caption, string author, address support, string hello, string language, string dabi, bytes icon
function getDebotInfo() public functionID(0xDEB) override view returns( string name, string version, string publisher, string caption, string author, address support, string hello, string language, string dabi, bytes icon
31,117
43
// Raise event
return true;
return true;
28,142
40
// Deprecated. This function has issues similar to the ones found in
// * {IERC20-approve}, and its usage is discouraged. // * // * Whenever possible, use {safeIncreaseAllowance} and // * {safeDecreaseAllowance} instead. // */ // function safeApprove(IERC20 token, address spender, uint256 value) internal { // // safeApprove should only be called when setting an initial allowance, // // or when resetting it to zero. To increase and decrease it, use // // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // // solhint-disable-next-line max-line-length // require((value == 0) || (token.allowance(address(this), spender) == 0), // "SafeERC20: approve from non-zero to non-zero allowance" // ); // _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); // }
// * {IERC20-approve}, and its usage is discouraged. // * // * Whenever possible, use {safeIncreaseAllowance} and // * {safeDecreaseAllowance} instead. // */ // function safeApprove(IERC20 token, address spender, uint256 value) internal { // // safeApprove should only be called when setting an initial allowance, // // or when resetting it to zero. To increase and decrease it, use // // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // // solhint-disable-next-line max-line-length // require((value == 0) || (token.allowance(address(this), spender) == 0), // "SafeERC20: approve from non-zero to non-zero allowance" // ); // _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); // }
3,292
16
// [ERC20]Transfers _value amount of tokens to address _to, and MUST fire the Transfer event.The function SHOULD throw if the _from account balance does not have enough tokens to spend. Note Transfers of 0 values MUST be treated as normal transfers and fire the Transfer event. /
function transfer(address _to, uint256 _value) public returns (bool success) { _transfer(msg.sender, _to, _value); return true; }
function transfer(address _to, uint256 _value) public returns (bool success) { _transfer(msg.sender, _to, _value); return true; }
5,252
12
// uint256 count = woolf.balanceOf(owner);
WolfGameInstance[] memory list = new WolfGameInstance[](endIndex - startIndex); uint16 index = 0; for (uint256 i = startIndex; i < endIndex; i++) { uint256 tokenId = woolf.tokenOfOwnerByIndex(owner, i); if (tokenId != 0) { list[index].apeWolf = woolf.getTokenTraits(tokenId); list[index].tokenURI = woolf.tokenURI(tokenId); index++; }
WolfGameInstance[] memory list = new WolfGameInstance[](endIndex - startIndex); uint16 index = 0; for (uint256 i = startIndex; i < endIndex; i++) { uint256 tokenId = woolf.tokenOfOwnerByIndex(owner, i); if (tokenId != 0) { list[index].apeWolf = woolf.getTokenTraits(tokenId); list[index].tokenURI = woolf.tokenURI(tokenId); index++; }
22,906
19
// Total supply of outstanding tokens in the contract
uint total_supply;
uint total_supply;
17,985
20
// no empty slot for add master, return false
return false;
return false;
29,133
149
// Creates a new Vault that accepts a specific underlying token./_UNDERLYING The ERC20 compliant token the Vault should accept.
constructor(ERC20 _UNDERLYING) ERC20(
constructor(ERC20 _UNDERLYING) ERC20(
55,393
193
// in case we need to migrate to new MM owner
function transferMMOwnership() public onlyOwner { require(mm.owner() == address(this), "!notMMOwner"); mm.transferOwnership(owner()); }
function transferMMOwnership() public onlyOwner { require(mm.owner() == address(this), "!notMMOwner"); mm.transferOwnership(owner()); }
16,249
2
// Historical location of all users
mapping (address => LocationStamp[]) public userLocations;
mapping (address => LocationStamp[]) public userLocations;
28,575
19
// transfer Plutus token to owner
require( _safeTransferETH(item.owner, plutusAmount.mul(ownerPercent).div(PERCENTS_DIVIDER)), "failed to transfer to owner" );
require( _safeTransferETH(item.owner, plutusAmount.mul(ownerPercent).div(PERCENTS_DIVIDER)), "failed to transfer to owner" );
3,403
122
// Checks if requested set of features is enabled globally on the contractrequired set of features to check againstreturn true if all the features requested are enabled, false otherwise /
function isFeatureEnabled(uint256 required) public view returns(bool) { // delegate call to `__hasRole`, passing `features` property return __hasRole(features(), required); }
function isFeatureEnabled(uint256 required) public view returns(bool) { // delegate call to `__hasRole`, passing `features` property return __hasRole(features(), required); }
24,224
6
// element hash => index
mapping(bytes32 => uint256) map;
mapping(bytes32 => uint256) map;
7,291
6
// has the participant yet reported its energy for the current period
bool reported;
bool reported;
35,588
15
// Nominate a candidate to become the new owner of the contract/The nominated candidate need to call claimOwnership function
function transferOwnership(address newOwner) public virtual override onlyOwner
function transferOwnership(address newOwner) public virtual override onlyOwner
17,131
0
// Merkle root of the line, will get assigned on constructor
bytes32 public lineMerkleRoot; address public owner; mapping(address => bool) public authUsers;
bytes32 public lineMerkleRoot; address public owner; mapping(address => bool) public authUsers;
34,329
8
// Sets the address of the current implementation newImplementation address representing the new implementation to be set /
function setImplementation(address newImplementation) internal { bytes32 position = implementationPosition; assembly { sstore(position, newImplementation) } }
function setImplementation(address newImplementation) internal { bytes32 position = implementationPosition; assembly { sstore(position, newImplementation) } }
6,645
14
// Receive hook to fractionalize Batch-NFTs into ERC20's/Function is called with `operator` as `_msgSender()` in a reference implementation by OZ/ `from` is the previous owner, not necessarily the same as operator./ The hook checks if NFT collection is whitelisted and next if attributes are matching this ERC20 contract
function onERC721Received( address, /* operator */ address from, uint256 tokenId, bytes calldata /* data */
function onERC721Received( address, /* operator */ address from, uint256 tokenId, bytes calldata /* data */
7,027
419
// no space, cannot join
if (accountAssets[borrower].length >= maxAssets) { return Error.TOO_MANY_ASSETS; }
if (accountAssets[borrower].length >= maxAssets) { return Error.TOO_MANY_ASSETS; }
979
3,672
// 1837
entry "white-haired" : ENG_ADJECTIVE
entry "white-haired" : ENG_ADJECTIVE
18,449
74
// Redeem shares in the vault for the respective amount of underlying assets and claim the HAT reward that the user has earned. Can only be performed if a withdraw request has been previously submitted, and the pending period had passed, and while the withdraw enabled timeout had not passed. Withdrawals are not permitted during safety periods or while there is an active claim for a bounty payout.shares Amount of shares to redeemreceiver Address of receiver of the funds owner Address of owner of the funds See {IERC4626-redeem}./
function redeemAndClaim(uint256 shares, address receiver, address owner)
function redeemAndClaim(uint256 shares, address receiver, address owner)
14,640
52
// Cap parameters
uint256 public baseTargetInWei; // Target for bonus rate of tokens uint256 public icoCapInWei; // Max cap of the ICO in Wei event logPurchase (address indexed purchaser, uint value, uint256 tokens);
uint256 public baseTargetInWei; // Target for bonus rate of tokens uint256 public icoCapInWei; // Max cap of the ICO in Wei event logPurchase (address indexed purchaser, uint value, uint256 tokens);
50,833
13
// Sale represents a gated sale, with mapping links to different sale phases
struct Sale { uint256 id; // The ID of the sale uint256 editionId; // The ID of the edition the sale will mint address creator; // Set on creation to save gas - the original edition creator address fundsReceiver; // Where are the funds set uint256 maxEditionId; // Stores the max edition ID for the edition - used when assigning tokens uint16 mintCounter; // Keeps a pointer to the overall mint count for the full sale uint8 paused; // Whether the sale is currently paused > 0 is paused }
struct Sale { uint256 id; // The ID of the sale uint256 editionId; // The ID of the edition the sale will mint address creator; // Set on creation to save gas - the original edition creator address fundsReceiver; // Where are the funds set uint256 maxEditionId; // Stores the max edition ID for the edition - used when assigning tokens uint16 mintCounter; // Keeps a pointer to the overall mint count for the full sale uint8 paused; // Whether the sale is currently paused > 0 is paused }
54,397
18
// NOTE: Check that the orders were completely filled and update their filled amounts to avoid replaying them. The limit price and order validity have already been verified when executing the swap through the `limit` and `deadline` parameters.
require(filledAmount[orderUid] == 0, "GPv2: order filled"); if (order.kind == GPv2Order.KIND_SELL) { require( executedSellAmount == order.sellAmount, "GPv2: sell amount not respected" ); filledAmount[orderUid] = order.sellAmount; } else {
require(filledAmount[orderUid] == 0, "GPv2: order filled"); if (order.kind == GPv2Order.KIND_SELL) { require( executedSellAmount == order.sellAmount, "GPv2: sell amount not respected" ); filledAmount[orderUid] = order.sellAmount; } else {
54,660
23
// Setting the candidate to zero prevents calling this repeatedly and generating multiple redundant events, and also allows checking (perhaps by a UI) whether there is a pending transfer.
_managerCandidate = address(0);
_managerCandidate = address(0);
15,784
328
// Harvest profits from the vault's strategy. Harvesting adds profits to the vault's balance and deducts fees. No performance fees are charged on profit used to repay debt.return `true` if successful. /
function harvest() public onlyPoolOrMaintenance returns (bool) { return _harvest(); }
function harvest() public onlyPoolOrMaintenance returns (bool) { return _harvest(); }
9,705
455
// round 46
ark(i, q, 6266270088302506215402996795500854910256503071464802875821837403486057988208); sbox_partial(i, q); mix(i, q);
ark(i, q, 6266270088302506215402996795500854910256503071464802875821837403486057988208); sbox_partial(i, q); mix(i, q);
44,118
38
// ------------------------------------------------------------------------ Token holders can stake their tokens using this functiontokens number of tokens to stake ------------------------------------------------------------------------
function STAKE(uint256 tokens) external { require(REWARDTOKEN(rewtkn).transferFrom(msg.sender, address(this), tokens), "Tokens cannot be transferred from user account"); uint256 _stakingFee = 0; _stakingFee= (onePercent(tokens).mul(stakingFee)).div(10); reward.totalreward = (reward.totalreward).add(stakingFee); stakers[msg.sender].stakedTokens = (tokens.sub(_stakingFee)).add(stakers[msg.sender].stakedTokens); stakers[msg.sender].creationTime = now; totalStakes = totalStakes.add(tokens.sub(_stakingFee)); emit STAKED(msg.sender, tokens.sub(_stakingFee), _stakingFee); }
function STAKE(uint256 tokens) external { require(REWARDTOKEN(rewtkn).transferFrom(msg.sender, address(this), tokens), "Tokens cannot be transferred from user account"); uint256 _stakingFee = 0; _stakingFee= (onePercent(tokens).mul(stakingFee)).div(10); reward.totalreward = (reward.totalreward).add(stakingFee); stakers[msg.sender].stakedTokens = (tokens.sub(_stakingFee)).add(stakers[msg.sender].stakedTokens); stakers[msg.sender].creationTime = now; totalStakes = totalStakes.add(tokens.sub(_stakingFee)); emit STAKED(msg.sender, tokens.sub(_stakingFee), _stakingFee); }
10,407
189
// Return the level and the mint timestamp of tokenIdtokenId The tokenId to query return mintTimestamp The timestamp token was mintedreturn level The level token belongs to /
function getTokenData(uint256 tokenId)
function getTokenData(uint256 tokenId)
66,430
15
// only the seller can call this function
require(msg.sender == deal.seller, 'OTC04');
require(msg.sender == deal.seller, 'OTC04');
30,694
5
// Forwards funds to the tokensale wallet/
function forwardFunds() internal { novaMultiSig.transfer(msg.value); }
function forwardFunds() internal { novaMultiSig.transfer(msg.value); }
49,538
8
// 6. forward the rewards to the attacker
IERC20 rewardToken = rewarderPool.rewardToken(); rewardToken.transfer(attacker, rewardToken.balanceOf(address(this)));
IERC20 rewardToken = rewarderPool.rewardToken(); rewardToken.transfer(attacker, rewardToken.balanceOf(address(this)));
15,305
62
// Default Partition Management
function getDefaultPartitions(address tokenHolder) external view returns (bytes32[] memory); // 5/10 function setDefaultPartitions(bytes32[] calldata partitions) external; // 6/10
function getDefaultPartitions(address tokenHolder) external view returns (bytes32[] memory); // 5/10 function setDefaultPartitions(bytes32[] calldata partitions) external; // 6/10
48,118
32
// Making sure sent amount is greater than or equal to the sellingPrice
require(msg.value >= sellingPrice); uint256 payment = uint256(SafeMath.div(SafeMath.mul(sellingPrice, 92), 100)); uint256 purchaseExcess = SafeMath.sub(msg.value, sellingPrice);
require(msg.value >= sellingPrice); uint256 payment = uint256(SafeMath.div(SafeMath.mul(sellingPrice, 92), 100)); uint256 purchaseExcess = SafeMath.sub(msg.value, sellingPrice);
903
35
// Hashed Timelock Contracts (HTLCs) on Ethereum ETH. This contract provides a way to create and keep HTLCs for ETH.Protocol:1) newContract(receiver, hashlock, timelock) - a sender calls this to create a new HTLC and gets back a 32 byte contract id 2) withdraw(contractId, preimage) - once the receiver knows the preimage of the hashlock hash they can claim the ETH with this function 3) refund() - after timelock has expired and if the receiver did notwithdraw funds the sender / creater of the HTLC can get their ETHback with this function. /
contract HashedTimelock { using SafeMath for uint256; event LogHTLCNew( bytes32 indexed contractId, address indexed sender, address indexed receiver, uint amount, uint timelock ); event LogHTLCWithdraw(bytes32 indexed contractId, bytes32 preimage); event LogHTLCRefund(bytes32 indexed contractId); struct LockContract { address payable sender; address payable receiver; uint amount; uint timelock; // UNIX timestamp seconds - locked UNTIL this time bool withdrawn; bool refunded; bytes32 preimage; } modifier fundsSent() { require(msg.value > 0, "msg.value must be > 0"); _; } modifier futureTimelock(uint _time) { // only requirement is the timelock time is after the last blocktime (now). // probably want something a bit further in the future then this. // but this is still a useful sanity check: require(_time > now + 1 hours, "timelock time must be in the future"); _; } modifier contractExists(bytes32 _contractId) { require(haveContract(_contractId), "contractId does not exist"); _; } modifier hashlockMatches(bytes32 _contractId, bytes32 _x) { require( _contractId == keccak256(abi.encodePacked(_x)), "hashlock hash does not match" ); _; } modifier withdrawable(bytes32 _contractId) { require(contracts[_contractId].receiver == msg.sender, "withdrawable: not receiver"); require(contracts[_contractId].withdrawn == false, "withdrawable: already withdrawn"); _; } modifier refundable(bytes32 _contractId) { require(contracts[_contractId].sender == msg.sender, "refundable: not sender"); require(contracts[_contractId].refunded == false, "refundable: already refunded"); require(contracts[_contractId].withdrawn == false, "refundable: already withdrawn"); require(contracts[_contractId].timelock <= now, "refundable: timelock not yet passed"); _; } modifier onlyOwner() { require(msg.sender == owner, "you are not an owner"); _; } mapping (bytes32 => LockContract) contracts; uint256 public feePercent; // 5 == 0.05 % uint oneHundredPercent = 10000; // 100 % address payable public owner; uint feeToWithdraw; constructor(address payable _owner, uint256 _feePercent) public { feePercent = _feePercent; owner = _owner; } function setFeePercent(uint256 _feePercent) external onlyOwner { require(_feePercent < oneHundredPercent.div(2), "should be less than 50%"); feePercent = _feePercent; } /** * @dev Sender sets up a new hash time lock contract depositing the ETH and * providing the reciever lock terms. * * @param _receiver Receiver of the ETH. * @param _hashlock A keccak256 hash hashlock. * @param _timelock UNIX epoch seconds time that the lock expires at. * Refunds can be made after this time. */ function newContract(address payable _receiver, bytes32 _hashlock, uint _timelock) external payable fundsSent futureTimelock(_timelock) { uint256 swapValue = msg.value.mul(oneHundredPercent).div(oneHundredPercent.add(feePercent)); uint feeValue = msg.value.sub(swapValue); feeToWithdraw = feeValue.add(feeToWithdraw); // Reject if a contract already exists with the same parameters. The // sender must change one of these parameters to create a new distinct // contract. if (haveContract(_hashlock)) { revert("contract exist"); } contracts[_hashlock] = LockContract( msg.sender, _receiver, swapValue, _timelock, false, false, 0x0 ); emit LogHTLCNew( _hashlock, msg.sender, _receiver, swapValue, _timelock ); } /** * @dev Called by the receiver once they know the preimage of the hashlock. * This will transfer the locked funds to their address. * * @param _contractId Id of the HTLC. * @param _preimage keccak256(_preimage) should equal the contract hashlock. * @return bool true on success */ function withdraw(bytes32 _contractId, bytes32 _preimage) external contractExists(_contractId) hashlockMatches(_contractId, _preimage) withdrawable(_contractId) returns (bool) { LockContract storage c = contracts[_contractId]; c.preimage = _preimage; c.withdrawn = true; c.receiver.transfer(c.amount); emit LogHTLCWithdraw(_contractId, _preimage); return true; } /** * @dev Called by the sender if there was no withdraw AND the time lock has * expired. This will refund the contract amount. * * @param _contractId Id of HTLC to refund from. * @return bool true on success */ function refund(bytes32 _contractId) external contractExists(_contractId) refundable(_contractId) returns (bool) { LockContract storage c = contracts[_contractId]; c.refunded = true; c.sender.transfer(c.amount); emit LogHTLCRefund(_contractId); return true; } function claimTokens(address _token) external onlyOwner { if (_token == address(0)) { owner.transfer(feeToWithdraw); return; } IERC20 erc20token = IERC20(_token); uint256 balance = erc20token.balanceOf(address(this)); erc20token.transfer(owner, balance); } /** * @dev Get contract details. * @param _contractId HTLC contract id * @return All parameters in struct LockContract for _contractId HTLC */ function getContract(bytes32 _contractId) public view returns ( address sender, address receiver, uint amount, uint timelock, bool withdrawn, bool refunded, bytes32 preimage ) { if (haveContract(_contractId) == false) return (address(0), address(0), 0, 0, false, false, 0); LockContract storage c = contracts[_contractId]; return (c.sender, c.receiver, c.amount, c.timelock, c.withdrawn, c.refunded, c.preimage); } /** * @dev Is there a contract with id _contractId. * @param _contractId Id into contracts mapping. */ function haveContract(bytes32 _contractId) public view returns (bool exists) { exists = (contracts[_contractId].sender != address(0)); } }
contract HashedTimelock { using SafeMath for uint256; event LogHTLCNew( bytes32 indexed contractId, address indexed sender, address indexed receiver, uint amount, uint timelock ); event LogHTLCWithdraw(bytes32 indexed contractId, bytes32 preimage); event LogHTLCRefund(bytes32 indexed contractId); struct LockContract { address payable sender; address payable receiver; uint amount; uint timelock; // UNIX timestamp seconds - locked UNTIL this time bool withdrawn; bool refunded; bytes32 preimage; } modifier fundsSent() { require(msg.value > 0, "msg.value must be > 0"); _; } modifier futureTimelock(uint _time) { // only requirement is the timelock time is after the last blocktime (now). // probably want something a bit further in the future then this. // but this is still a useful sanity check: require(_time > now + 1 hours, "timelock time must be in the future"); _; } modifier contractExists(bytes32 _contractId) { require(haveContract(_contractId), "contractId does not exist"); _; } modifier hashlockMatches(bytes32 _contractId, bytes32 _x) { require( _contractId == keccak256(abi.encodePacked(_x)), "hashlock hash does not match" ); _; } modifier withdrawable(bytes32 _contractId) { require(contracts[_contractId].receiver == msg.sender, "withdrawable: not receiver"); require(contracts[_contractId].withdrawn == false, "withdrawable: already withdrawn"); _; } modifier refundable(bytes32 _contractId) { require(contracts[_contractId].sender == msg.sender, "refundable: not sender"); require(contracts[_contractId].refunded == false, "refundable: already refunded"); require(contracts[_contractId].withdrawn == false, "refundable: already withdrawn"); require(contracts[_contractId].timelock <= now, "refundable: timelock not yet passed"); _; } modifier onlyOwner() { require(msg.sender == owner, "you are not an owner"); _; } mapping (bytes32 => LockContract) contracts; uint256 public feePercent; // 5 == 0.05 % uint oneHundredPercent = 10000; // 100 % address payable public owner; uint feeToWithdraw; constructor(address payable _owner, uint256 _feePercent) public { feePercent = _feePercent; owner = _owner; } function setFeePercent(uint256 _feePercent) external onlyOwner { require(_feePercent < oneHundredPercent.div(2), "should be less than 50%"); feePercent = _feePercent; } /** * @dev Sender sets up a new hash time lock contract depositing the ETH and * providing the reciever lock terms. * * @param _receiver Receiver of the ETH. * @param _hashlock A keccak256 hash hashlock. * @param _timelock UNIX epoch seconds time that the lock expires at. * Refunds can be made after this time. */ function newContract(address payable _receiver, bytes32 _hashlock, uint _timelock) external payable fundsSent futureTimelock(_timelock) { uint256 swapValue = msg.value.mul(oneHundredPercent).div(oneHundredPercent.add(feePercent)); uint feeValue = msg.value.sub(swapValue); feeToWithdraw = feeValue.add(feeToWithdraw); // Reject if a contract already exists with the same parameters. The // sender must change one of these parameters to create a new distinct // contract. if (haveContract(_hashlock)) { revert("contract exist"); } contracts[_hashlock] = LockContract( msg.sender, _receiver, swapValue, _timelock, false, false, 0x0 ); emit LogHTLCNew( _hashlock, msg.sender, _receiver, swapValue, _timelock ); } /** * @dev Called by the receiver once they know the preimage of the hashlock. * This will transfer the locked funds to their address. * * @param _contractId Id of the HTLC. * @param _preimage keccak256(_preimage) should equal the contract hashlock. * @return bool true on success */ function withdraw(bytes32 _contractId, bytes32 _preimage) external contractExists(_contractId) hashlockMatches(_contractId, _preimage) withdrawable(_contractId) returns (bool) { LockContract storage c = contracts[_contractId]; c.preimage = _preimage; c.withdrawn = true; c.receiver.transfer(c.amount); emit LogHTLCWithdraw(_contractId, _preimage); return true; } /** * @dev Called by the sender if there was no withdraw AND the time lock has * expired. This will refund the contract amount. * * @param _contractId Id of HTLC to refund from. * @return bool true on success */ function refund(bytes32 _contractId) external contractExists(_contractId) refundable(_contractId) returns (bool) { LockContract storage c = contracts[_contractId]; c.refunded = true; c.sender.transfer(c.amount); emit LogHTLCRefund(_contractId); return true; } function claimTokens(address _token) external onlyOwner { if (_token == address(0)) { owner.transfer(feeToWithdraw); return; } IERC20 erc20token = IERC20(_token); uint256 balance = erc20token.balanceOf(address(this)); erc20token.transfer(owner, balance); } /** * @dev Get contract details. * @param _contractId HTLC contract id * @return All parameters in struct LockContract for _contractId HTLC */ function getContract(bytes32 _contractId) public view returns ( address sender, address receiver, uint amount, uint timelock, bool withdrawn, bool refunded, bytes32 preimage ) { if (haveContract(_contractId) == false) return (address(0), address(0), 0, 0, false, false, 0); LockContract storage c = contracts[_contractId]; return (c.sender, c.receiver, c.amount, c.timelock, c.withdrawn, c.refunded, c.preimage); } /** * @dev Is there a contract with id _contractId. * @param _contractId Id into contracts mapping. */ function haveContract(bytes32 _contractId) public view returns (bool exists) { exists = (contracts[_contractId].sender != address(0)); } }
46,542
66
// Emitted after a successful harvest. user The authorized user who triggered the harvest. strategies The trusted strategies that were harvested. /
event Harvest(address indexed user, Strategy[] strategies);
event Harvest(address indexed user, Strategy[] strategies);
18,308
22
// Total number of committed requests./Used in checks: if the request matches the operation on Rollup contract and if provided number of requests is not too big
uint64 public totalCommittedPriorityRequests;
uint64 public totalCommittedPriorityRequests;
29,896
14
// emit UniswapDebug(LoanContract, ReserveIn, ReserveOut, initialAmountIn, amountToRepay);TEMP
Sequence(initialAmountIn, amountToRepay, swapRequests); ERC20Token(RepayToken).transfer(msg.sender, amountToRepay);
Sequence(initialAmountIn, amountToRepay, swapRequests); ERC20Token(RepayToken).transfer(msg.sender, amountToRepay);
37,065
99
// swap weth to Universe tokens
function _swapWethToUniverseByEthIn(uint256[] memory _ethInUniswap) internal returns (uint256 poolAmountOut) { uint256[] memory tokensInUniverse; (tokensInUniverse, poolAmountOut) = _swapAndApproveTokensForJoin(_ethInUniswap); if (isSmartPool) { BPoolInterface controller = BPoolInterface(universeBP.getController()); controller.joinPool(poolAmountOut, tokensInUniverse); controller.safeTransfer(msg.sender, poolAmountOut); } else { universeBP.joinPool(poolAmountOut, tokensInUniverse); universeBP.safeTransfer(msg.sender, poolAmountOut); } }
function _swapWethToUniverseByEthIn(uint256[] memory _ethInUniswap) internal returns (uint256 poolAmountOut) { uint256[] memory tokensInUniverse; (tokensInUniverse, poolAmountOut) = _swapAndApproveTokensForJoin(_ethInUniswap); if (isSmartPool) { BPoolInterface controller = BPoolInterface(universeBP.getController()); controller.joinPool(poolAmountOut, tokensInUniverse); controller.safeTransfer(msg.sender, poolAmountOut); } else { universeBP.joinPool(poolAmountOut, tokensInUniverse); universeBP.safeTransfer(msg.sender, poolAmountOut); } }
23,605
55
// Only trucks can call this function
require (keccak256(abi.encodePacked(roles[msg.sender])) == keccak256(abi.encodePacked("truck")));
require (keccak256(abi.encodePacked(roles[msg.sender])) == keccak256(abi.encodePacked("truck")));
23,368
601
// swap to wantToken and send to user
ISwapToken(dex).swapExactTokensForTokens(_amount, 0, path, swapInfo.user, type(uint256).max);
ISwapToken(dex).swapExactTokensForTokens(_amount, 0, path, swapInfo.user, type(uint256).max);
5,375
75
// Hard goal in Wei
uint public hardFundingGoal;
uint public hardFundingGoal;
18,902
39
// ensure the order has not been partially filled when not allowed.
if (onlyAllowUnused) {
if (onlyAllowUnused) {
20,456
28
// pay everyone!
function payAll() public { uint totalToPay ; //inject UNINIT LOCAL/STATE VAR uint[] memory payments = new uint[](payrollLength); uint amount; for (uint i ; i<payrollLength; i++){ //inject UNINIT LOCAL/STATE VAR amount = (now - payroll[i].lastPaid) * payroll[i].payRate; totalToPay += amount; payments[i] = amount; } compound.withdraw(daiAddress, totalToPay); for (uint i ; i<payrollLength; i++){ //inject UNINIT LOCAL/STATE VAR payroll[i].lastPaid = now; dai.transfer(payroll[i].recipient, payments[i]); emit MemberPaid(payroll[i].recipient, payments[i], 'payAll'); } }
function payAll() public { uint totalToPay ; //inject UNINIT LOCAL/STATE VAR uint[] memory payments = new uint[](payrollLength); uint amount; for (uint i ; i<payrollLength; i++){ //inject UNINIT LOCAL/STATE VAR amount = (now - payroll[i].lastPaid) * payroll[i].payRate; totalToPay += amount; payments[i] = amount; } compound.withdraw(daiAddress, totalToPay); for (uint i ; i<payrollLength; i++){ //inject UNINIT LOCAL/STATE VAR payroll[i].lastPaid = now; dai.transfer(payroll[i].recipient, payments[i]); emit MemberPaid(payroll[i].recipient, payments[i], 'payAll'); } }
24,529
0
// 0xfa80e7480e9c42a9241e16d6c1e7518c1b1757e4
constructor (address parentAddress, address signerAddress, uint256 _chainId) public { signer = signerAddress; chainId = _chainId; parent = WebaverseERC20(parentAddress); }
constructor (address parentAddress, address signerAddress, uint256 _chainId) public { signer = signerAddress; chainId = _chainId; parent = WebaverseERC20(parentAddress); }
15,773
26
// 0 is an invalid address
require(newOwner != address(0)); owners[newOwner] = true;
require(newOwner != address(0)); owners[newOwner] = true;
11,327
123
// maxDayForMonthField returns the maximum valid day given the month field month the month fieldreturn the max day /
function maxDayForMonthField(Field memory month) private pure returns (uint8) { // DEV: ranges are always safe because any two consecutive months will always // contain a month with 31 days if (month.fieldType == FieldType.WILD || month.fieldType == FieldType.RANGE) { return 31; } else if (month.fieldType == FieldType.EXACT) { // DEV: assume leap year in order to get max value return DateTime.getDaysInMonth(month.singleValue, 4); } else if (month.fieldType == FieldType.INTERVAL) { if (month.interval == 9 || month.interval == 11) { return 30; } else { return 31; } } else if (month.fieldType == FieldType.LIST) { uint8 result; for (uint256 idx = 0; idx < month.listLength; idx++) { // DEV: assume leap year in order to get max value uint8 daysInMonth = DateTime.getDaysInMonth(month.list[idx], 4); if (daysInMonth == 31) { return daysInMonth; } if (daysInMonth > result) { result = daysInMonth; } } return result; } else { revert UnknownFieldType(); } }
function maxDayForMonthField(Field memory month) private pure returns (uint8) { // DEV: ranges are always safe because any two consecutive months will always // contain a month with 31 days if (month.fieldType == FieldType.WILD || month.fieldType == FieldType.RANGE) { return 31; } else if (month.fieldType == FieldType.EXACT) { // DEV: assume leap year in order to get max value return DateTime.getDaysInMonth(month.singleValue, 4); } else if (month.fieldType == FieldType.INTERVAL) { if (month.interval == 9 || month.interval == 11) { return 30; } else { return 31; } } else if (month.fieldType == FieldType.LIST) { uint8 result; for (uint256 idx = 0; idx < month.listLength; idx++) { // DEV: assume leap year in order to get max value uint8 daysInMonth = DateTime.getDaysInMonth(month.list[idx], 4); if (daysInMonth == 31) { return daysInMonth; } if (daysInMonth > result) { result = daysInMonth; } } return result; } else { revert UnknownFieldType(); } }
33,138
18
// Return reward multiplier over the given _from to _to block/_from From block/_to To block/ return Multiplier value
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { return _to.sub(_from).mul(BONUS_MULTIPLIER); }
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { return _to.sub(_from).mul(BONUS_MULTIPLIER); }
22,425
67
// This function allows users to retireve all information about a staker _staker address of staker inquiring aboutreturn uint current state of stakerreturn uint startDate of staking /
// function getStakerInfo(TellorStorage.TellorStorageStruct storage self,address _staker) internal view returns(uint,uint){ // return (self.stakerDetails[_staker].currentStatus,self.stakerDetails[_staker].startDate); // }
// function getStakerInfo(TellorStorage.TellorStorageStruct storage self,address _staker) internal view returns(uint,uint){ // return (self.stakerDetails[_staker].currentStatus,self.stakerDetails[_staker].startDate); // }
34,755
16
//
contract VRF02 is VRFConsumerBaseV2 { // 宣告物件,建構子內會建立物件 VRFCoordinatorV2Interface COORDINATOR; // 訂閱 ID,部署的時候會傳入,我目前使用「7667」 uint64 s_subscriptionId = 7667; // 訂閱調度子 address vrfCoordinator = 0x2Ca8E0C643bDe4C2E08ab1fA0da3401AdAD7734D; // 訂閱哈希值(雜湊) bytes32 keyHash = 0x79d3d8832d904592c0bf9818b621522c988bb8b0c05cdc3b15aea1b6e8db0c15; // 回呼函數的 gas 上限 // 當 Chainlink VRF 產生完隨機數後會呼叫 fulfillRandomWords 這個 callback // 每產生一組隨機數通常只需要 20000 gas,因為但這邊也要包含到你的其它邏輯 // 所以當 callback 邏輯較複雜的話,需設定一個上限避免太過耗 gas // 暫定 100000 為預設值 uint32 callbackGasLimit = 100000; // 規定要幾個節點驗證過後才進行 callback,越高越安全 uint16 requestConfirmations = 3; // 請求隨機數組數,設定為 2 組 uint32 numWords = 2; // uint256[] public s_randomWords; uint256 public s_requestId; address s_owner; // 建構子 // constructor(uint64 subscriptionId) VRFConsumerBaseV2(vrfCoordinator) { // COORDINATOR = VRFCoordinatorV2Interface(vrfCoordinator); // s_owner = msg.sender; // s_subscriptionId = subscriptionId; // } /* 改寫建構子:不用傳入 subscriptionId */ // 建構子 constructor() VRFConsumerBaseV2(vrfCoordinator) { COORDINATOR = VRFCoordinatorV2Interface(vrfCoordinator); s_owner = msg.sender; // 已經定義了 // s_subscriptionId = subscriptionId; } // 外部函數:請求(產生)隨機數字 // 完成時 s_requestId 及 s_randomWords 會更新 function requestRandomWords() external onlyOwner { // Will revert if subscription is not set and funded. s_requestId = COORDINATOR.requestRandomWords( keyHash, s_subscriptionId, requestConfirmations, callbackGasLimit, numWords ); } // 內部函數:會將隨機數字存入 s_randomWords 陣列 function fulfillRandomWords( uint256, /* requestId */ uint256[] memory randomWords ) internal override { s_randomWords = randomWords; } // 修飾字:只有合約擁有者才能呼叫 modifier onlyOwner() { require(msg.sender == s_owner); _; } }
contract VRF02 is VRFConsumerBaseV2 { // 宣告物件,建構子內會建立物件 VRFCoordinatorV2Interface COORDINATOR; // 訂閱 ID,部署的時候會傳入,我目前使用「7667」 uint64 s_subscriptionId = 7667; // 訂閱調度子 address vrfCoordinator = 0x2Ca8E0C643bDe4C2E08ab1fA0da3401AdAD7734D; // 訂閱哈希值(雜湊) bytes32 keyHash = 0x79d3d8832d904592c0bf9818b621522c988bb8b0c05cdc3b15aea1b6e8db0c15; // 回呼函數的 gas 上限 // 當 Chainlink VRF 產生完隨機數後會呼叫 fulfillRandomWords 這個 callback // 每產生一組隨機數通常只需要 20000 gas,因為但這邊也要包含到你的其它邏輯 // 所以當 callback 邏輯較複雜的話,需設定一個上限避免太過耗 gas // 暫定 100000 為預設值 uint32 callbackGasLimit = 100000; // 規定要幾個節點驗證過後才進行 callback,越高越安全 uint16 requestConfirmations = 3; // 請求隨機數組數,設定為 2 組 uint32 numWords = 2; // uint256[] public s_randomWords; uint256 public s_requestId; address s_owner; // 建構子 // constructor(uint64 subscriptionId) VRFConsumerBaseV2(vrfCoordinator) { // COORDINATOR = VRFCoordinatorV2Interface(vrfCoordinator); // s_owner = msg.sender; // s_subscriptionId = subscriptionId; // } /* 改寫建構子:不用傳入 subscriptionId */ // 建構子 constructor() VRFConsumerBaseV2(vrfCoordinator) { COORDINATOR = VRFCoordinatorV2Interface(vrfCoordinator); s_owner = msg.sender; // 已經定義了 // s_subscriptionId = subscriptionId; } // 外部函數:請求(產生)隨機數字 // 完成時 s_requestId 及 s_randomWords 會更新 function requestRandomWords() external onlyOwner { // Will revert if subscription is not set and funded. s_requestId = COORDINATOR.requestRandomWords( keyHash, s_subscriptionId, requestConfirmations, callbackGasLimit, numWords ); } // 內部函數:會將隨機數字存入 s_randomWords 陣列 function fulfillRandomWords( uint256, /* requestId */ uint256[] memory randomWords ) internal override { s_randomWords = randomWords; } // 修飾字:只有合約擁有者才能呼叫 modifier onlyOwner() { require(msg.sender == s_owner); _; } }
23,712
50
// Start at .000000000051 cents
targetRate = (5508 * 10 ** (DECIMALS-14)); negDamp = 2; posDamp = 20; rebaseCooldown = 8 hours; lastRebaseTimestampSec = block.timestamp + rebaseCooldown; epoch = 1; rebaseLocked = true; posRebaseEnabled = true;
targetRate = (5508 * 10 ** (DECIMALS-14)); negDamp = 2; posDamp = 20; rebaseCooldown = 8 hours; lastRebaseTimestampSec = block.timestamp + rebaseCooldown; epoch = 1; rebaseLocked = true; posRebaseEnabled = true;
2,625
43
// Check that there's no bad debt left
require(safeEngine.debtBalance(address(this)) == 0, "StabilityFeeTreasury/outstanding-bad-debt");
require(safeEngine.debtBalance(address(this)) == 0, "StabilityFeeTreasury/outstanding-bad-debt");
20,029
4
// Emitted when a new rewards distributor is registered. poolId The id of the pool whose reward distributor was registered. collateralType The address of the collateral used in the pool's rewards. distributor The address of the newly registered reward distributor. /
event RewardsDistributorRegistered(
event RewardsDistributorRegistered(
26,004
42
// Rarely used! Only happen when extreme circumstances
function changeBankAccount(address newBank) external callByBank{ require(newBank!=address(0)); BANKACCOUNT = newBank; }
function changeBankAccount(address newBank) external callByBank{ require(newBank!=address(0)); BANKACCOUNT = newBank; }
29,092
40
// Makes a simple ERC20 -> ERC20 token trade_srcToken - IERC20 token_destToken - IERC20 token _srcAmount - uint256 amount to be converted_destAmount - uint256 amount to get after conversion return uint256 for the change. 0 if there is no change/
function convert( IERC20 _srcToken, IERC20 _destToken, uint256 _srcAmount, uint256 _destAmount ) external returns (uint256);
function convert( IERC20 _srcToken, IERC20 _destToken, uint256 _srcAmount, uint256 _destAmount ) external returns (uint256);
48,164
48
// These are the tokens that cannot be moved except by the vault
function getProtectedTokens() public view override returns (address[] memory)
function getProtectedTokens() public view override returns (address[] memory)
67,096
74
//
if ( _ranges.length > 0 && rangeToCollection[tokenToRange[_tokenId]] == tokenToCollection(_tokenId) ) { require( _ranges[tokenToRange[_tokenId]].lockedTokens == 0, "RAIR ERC721: Transfers for this range are currently locked" ); }
if ( _ranges.length > 0 && rangeToCollection[tokenToRange[_tokenId]] == tokenToCollection(_tokenId) ) { require( _ranges[tokenToRange[_tokenId]].lockedTokens == 0, "RAIR ERC721: Transfers for this range are currently locked" ); }
12,740
108
// Updates start block if the new start block is bigger than actual block numberand dividend pool has not started /
function updateStartBlock(uint256 _startBlock) external onlyOwner { require( block.number < startBlock, "cannot change start block if dividend pool has already started" ); require( block.number < _startBlock, "New startBlock must be bigger than actual block" ); poolInfo.lastRewardBlock = _startBlock; startBlock = _startBlock; updateRewardPerBlock(UpdateRewardType.UpdateStartOp); emit UpdateStartBlock(startBlock); }
function updateStartBlock(uint256 _startBlock) external onlyOwner { require( block.number < startBlock, "cannot change start block if dividend pool has already started" ); require( block.number < _startBlock, "New startBlock must be bigger than actual block" ); poolInfo.lastRewardBlock = _startBlock; startBlock = _startBlock; updateRewardPerBlock(UpdateRewardType.UpdateStartOp); emit UpdateStartBlock(startBlock); }
2,333
131
// Hook that is called before any token transfer. This includes mintingand burning. Calling conditions: - When `from` and `to` are both non-zero, ``from``'s `tokenId` will betransferred to `to`.- When `from` is zero, `tokenId` will be minted for `to`.- When `to` is zero, ``from``'s `tokenId` will be burned.- `from` cannot be the zero address.- `to` cannot be the zero address. To learn more about hooks, head to xref:ROOT:extending-contracts.adocusing-hooks[Using Hooks]. /
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } }
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } }
591
76
// Add lockup period stage /
function _addLockupStage(LockupStage _stage) internal { emit AddLockupStage(_stage.secondsSinceLockupStart, _stage.unlockedTokensPercentage); lockupStages.push(_stage); }
function _addLockupStage(LockupStage _stage) internal { emit AddLockupStage(_stage.secondsSinceLockupStart, _stage.unlockedTokensPercentage); lockupStages.push(_stage); }
28,805
119
// withdraw spaceport tokens percentile withdrawls allows fee on transfer or rebasing tokens to still work
function userWithdrawTokens () external nonReentrant { require(STATUS.LP_GENERATION_COMPLETE, 'AWAITING LP GENERATION'); BuyerInfo storage buyer = BUYERS[msg.sender]; require(STATUS.LP_GENERATION_COMPLETE_TIME + SPACEPORT_VESTING.vestingCliff < block.timestamp, "vesting cliff : not time yet"); if (buyer.lastUpdate < STATUS.LP_GENERATION_COMPLETE_TIME ) { buyer.lastUpdate = STATUS.LP_GENERATION_COMPLETE_TIME; } uint256 tokensOwed = 0; if(STATUS.LP_GENERATION_COMPLETE_TIME + SPACEPORT_VESTING.vestingEnd < block.timestamp) { tokensOwed = buyer.tokensOwed.sub(buyer.tokensClaimed); } else { tokensOwed = buyer.tokensOwed.mul(block.timestamp - buyer.lastUpdate).div(SPACEPORT_VESTING.vestingEnd); } buyer.lastUpdate = block.timestamp; buyer.tokensClaimed = buyer.tokensClaimed.add(tokensOwed); require(tokensOwed > 0, 'NOTHING TO CLAIM'); require(buyer.tokensClaimed <= buyer.tokensOwed, 'CLAIM TOKENS ERROR'); STATUS.TOTAL_TOKENS_WITHDRAWN = STATUS.TOTAL_TOKENS_WITHDRAWN.add(tokensOwed); TransferHelper.safeTransfer(address(SPACEPORT_INFO.S_TOKEN), msg.sender, tokensOwed); emit spaceportUserWithdrawTokens(tokensOwed); }
function userWithdrawTokens () external nonReentrant { require(STATUS.LP_GENERATION_COMPLETE, 'AWAITING LP GENERATION'); BuyerInfo storage buyer = BUYERS[msg.sender]; require(STATUS.LP_GENERATION_COMPLETE_TIME + SPACEPORT_VESTING.vestingCliff < block.timestamp, "vesting cliff : not time yet"); if (buyer.lastUpdate < STATUS.LP_GENERATION_COMPLETE_TIME ) { buyer.lastUpdate = STATUS.LP_GENERATION_COMPLETE_TIME; } uint256 tokensOwed = 0; if(STATUS.LP_GENERATION_COMPLETE_TIME + SPACEPORT_VESTING.vestingEnd < block.timestamp) { tokensOwed = buyer.tokensOwed.sub(buyer.tokensClaimed); } else { tokensOwed = buyer.tokensOwed.mul(block.timestamp - buyer.lastUpdate).div(SPACEPORT_VESTING.vestingEnd); } buyer.lastUpdate = block.timestamp; buyer.tokensClaimed = buyer.tokensClaimed.add(tokensOwed); require(tokensOwed > 0, 'NOTHING TO CLAIM'); require(buyer.tokensClaimed <= buyer.tokensOwed, 'CLAIM TOKENS ERROR'); STATUS.TOTAL_TOKENS_WITHDRAWN = STATUS.TOTAL_TOKENS_WITHDRAWN.add(tokensOwed); TransferHelper.safeTransfer(address(SPACEPORT_INFO.S_TOKEN), msg.sender, tokensOwed); emit spaceportUserWithdrawTokens(tokensOwed); }
38,276
13
// Public Functions//transfer ownership _newOwner new owner address /
function transferOwnership(address _newOwner) public onlyOwner { require(_newOwner != address(0), "Ownable: new owner is the zero address"); address oldOwner = _owner; _owner = _newOwner; emit TransferOwnership(oldOwner, _newOwner); }
function transferOwnership(address _newOwner) public onlyOwner { require(_newOwner != address(0), "Ownable: new owner is the zero address"); address oldOwner = _owner; _owner = _newOwner; emit TransferOwnership(oldOwner, _newOwner); }
20,391