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
815
// Reads the uint8 at `mPtr` in memory.
function readUint8(MemoryPointer mPtr) internal pure returns (uint8 value) { assembly { value := mload(mPtr) } }
function readUint8(MemoryPointer mPtr) internal pure returns (uint8 value) { assembly { value := mload(mPtr) } }
23,748
7
// remove an address from the whitelist _operator address /
function removeAddressFromWhitelist(address _operator) public onlyOwner
function removeAddressFromWhitelist(address _operator) public onlyOwner
20,309
40
// add caregory in `_packId`, can only be called when market is open _packId pack adding category _category category to list /
function addPackCategory(uint256 _packId, bytes4 _category)
function addPackCategory(uint256 _packId, bytes4 _category)
43,176
260
// Require msg.sender to be the creator of the token id /
modifier creatorOnly(uint256 _id) { require( _isCreatorOrProxy(_id, _msgSender()), "AssetContractShared#creatorOnly: ONLY_CREATOR_ALLOWED" ); _; }
modifier creatorOnly(uint256 _id) { require( _isCreatorOrProxy(_id, _msgSender()), "AssetContractShared#creatorOnly: ONLY_CREATOR_ALLOWED" ); _; }
12,179
759
// Returns factors for calculating exchange rates/ return/rateScalar: a scalar value in rate precision that defines the slope of the line/totalCashUnderlying: the converted asset cash to underlying cash for calculating/the exchange rates for the trade/rateAnchor: an offset from the x axis to maintain interest rate continuity over time
function getExchangeRateFactors( MarketParameters memory market, CashGroupParameters memory cashGroup, uint256 timeToMaturity, uint256 marketIndex ) internal pure returns ( int256,
function getExchangeRateFactors( MarketParameters memory market, CashGroupParameters memory cashGroup, uint256 timeToMaturity, uint256 marketIndex ) internal pure returns ( int256,
16,187
337
// Returns contract address.Requirements:- Contract must exist. /
function getDelegationPeriodManager() external view returns (address) { return getContract(DELEGATION_PERIOD_MANAGER); }
function getDelegationPeriodManager() external view returns (address) { return getContract(DELEGATION_PERIOD_MANAGER); }
81,664
148
// Internal function to add deposit of a channel _self storage data of CelerLedger contract _channelId ID of the channel _receiver address of the receiver _amount the amount to be deposited /
function _addDeposit(
function _addDeposit(
43,417
53
// Function to get application details by job ID and applicant address
function getApplicationDetails(uint jobId, address applicantAddress) public view returns (bool accepted, bool rejected) { // Ensure the application exists require(applications[jobId][applicantAddress].applicantAddress == applicantAddress, "Application does not exist."); // Return the application details return (applications[jobId][applicantAddress].accepted, applications[jobId][applicantAddress].rejected); }
function getApplicationDetails(uint jobId, address applicantAddress) public view returns (bool accepted, bool rejected) { // Ensure the application exists require(applications[jobId][applicantAddress].applicantAddress == applicantAddress, "Application does not exist."); // Return the application details return (applications[jobId][applicantAddress].accepted, applications[jobId][applicantAddress].rejected); }
20,452
176
// solhint-disable-next-line reentrancy
bentoBox.transfer(asset, address(this), masterContract.feeTo(), feeShare); totalAsset.elastic = totalAsset.elastic.add(returnedShare.sub(feeShare).to128()); emit LogAddAsset(address(swapper), address(this), extraShare.sub(feeShare), 0);
bentoBox.transfer(asset, address(this), masterContract.feeTo(), feeShare); totalAsset.elastic = totalAsset.elastic.add(returnedShare.sub(feeShare).to128()); emit LogAddAsset(address(swapper), address(this), extraShare.sub(feeShare), 0);
9,218
648
// Event to be broadcasted to public when content creator/host/The AO earning is released from escrow recipientType: 0 => Content Creator (Stake Owner) 1 => Node Host 2 => The AO
event EarningUnescrowed(address indexed recipient, bytes32 indexed purchaseId, uint256 paymentEarning, uint256 inflationBonus, uint8 recipientType);
event EarningUnescrowed(address indexed recipient, bytes32 indexed purchaseId, uint256 paymentEarning, uint256 inflationBonus, uint8 recipientType);
32,744
8
// Public functions /
function setBaseURI(string memory baseURI) public onlyAuthorized { _baseTokenURI = baseURI; }
function setBaseURI(string memory baseURI) public onlyAuthorized { _baseTokenURI = baseURI; }
50,452
48
// custom number configurations
if (_max > 1) { randomNumbers[_requestor].max = _max; }
if (_max > 1) { randomNumbers[_requestor].max = _max; }
35,673
0
// Constructor sets the default valuex The initial value/
constructor(string memory x) public { _x = x; }
constructor(string memory x) public { _x = x; }
44,421
130
// On July 04, 2022@ UTC 23:59 = FTST2625/100000 (2.625% of final total supply of tokens) to the wallet [E].
if (order == 8) {
if (order == 8) {
46,256
349
// Oraclize call for next MCR calculation
_callOracliseForMCR();
_callOracliseForMCR();
6,071
12
// previous limit is _maxLimit, and previous block number is current block number
_prevLockLimit = initialMaxLockLimit; _prevReleaseLimit = initialMaxReleaseLimit; _prevLockBlockNumber = block.number; _prevReleaseBlockNumber = block.number; _token = initialToken;
_prevLockLimit = initialMaxLockLimit; _prevReleaseLimit = initialMaxReleaseLimit; _prevLockBlockNumber = block.number; _prevReleaseBlockNumber = block.number; _token = initialToken;
46,183
8
// Get the original Element Merkle Root, given a Size Proof
function get_root_from_size_proof(uint256 element_count, bytes32[] memory proof) internal pure returns (bytes32 hash)
function get_root_from_size_proof(uint256 element_count, bytes32[] memory proof) internal pure returns (bytes32 hash)
19,642
1
// Inverse finance governance timelock
address public timelock;
address public timelock;
71,963
5
// slots for each participant unchanged
require( allocationA[0].destination == allocationB[0].destination && allocationA[1].destination == allocationB[1].destination, 'destinations may not change' );
require( allocationA[0].destination == allocationB[0].destination && allocationA[1].destination == allocationB[1].destination, 'destinations may not change' );
29,582
112
// Split LP per Credit
uint256 totalRLP = rebasingLP.balanceOf(address(this)); require(totalRLP > 0, "Sanity check failure 1");
uint256 totalRLP = rebasingLP.balanceOf(address(this)); require(totalRLP > 0, "Sanity check failure 1");
17,603
148
// We might need to return want to the vault
if (_debtOutstanding > 0) { uint256 _amountFreed = 0; (_amountFreed, _loss) = liquidatePosition(_debtOutstanding); _debtPayment = Math.min(_amountFreed, _debtOutstanding); if (_loss > 0) { _profit = 0; }
if (_debtOutstanding > 0) { uint256 _amountFreed = 0; (_amountFreed, _loss) = liquidatePosition(_debtOutstanding); _debtPayment = Math.min(_amountFreed, _debtOutstanding); if (_loss > 0) { _profit = 0; }
33,259
626
// for each action that corresponds to the auth
for (uint256 i = 0; i < auth.numActions; i++) { Actions.ActionArgs memory action = actions[startIdx + i];
for (uint256 i = 0; i < auth.numActions; i++) { Actions.ActionArgs memory action = actions[startIdx + i];
23,973
16
// ============ External Functions ============ //ONLY METHODOLOGIST : Called by the methodologist to enable contract. All `interactManager`calls revert until this is invoked. Lets methodologist review and authorize initial protectedmodule settings. /
function authorizeInitialization() external onlyMethodologist { require(!initialized, "Initialization authorized"); initialized = true; }
function authorizeInitialization() external onlyMethodologist { require(!initialized, "Initialization authorized"); initialized = true; }
21,923
102
// Read the rdata
uint rdataLength = iter.data.readUint16(off); off += 2; iter.rdataOffset = off; iter.nextOffset = off + rdataLength;
uint rdataLength = iter.data.readUint16(off); off += 2; iter.rdataOffset = off; iter.nextOffset = off + rdataLength;
13,240
4
// Returns the node hash for a given account's reverse records. addr The address to hashreturn The ENS node hash. /
function node(address addr) constant returns (bytes32 ret) { return sha3(rootNode, sha3HexAddress(addr)); }
function node(address addr) constant returns (bytes32 ret) { return sha3(rootNode, sha3HexAddress(addr)); }
19,594
41
// The ordered list of calldata to be passed to each call
bytes[] calldatas;
bytes[] calldatas;
48,915
53
// Only owner function to deliver tokens for pre-ICO investors_to account address who will receive the tokens_value quantity of tokens to deliver/
function preICOTokenDelivery(address _to, uint _value) onlyOwner public { _tokenDelivery(msg.sender, _to, _value, frozenDaysForPreICO); }
function preICOTokenDelivery(address _to, uint _value) onlyOwner public { _tokenDelivery(msg.sender, _to, _value, frozenDaysForPreICO); }
73,523
2
// initialMint_
10**6 * 10**9, // 1,000,000 * decimals
10**6 * 10**9, // 1,000,000 * decimals
6,857
1
// this operation is safe, as the difference cannot be greater than 1/deposit.liquidity
uint256 secondsInsideX128 = secondsPerLiquidityInsideX128 * liquidity; if (activeTime == 0) { reward = FullMath.mulDiv(totalReward, liquidity, totalLiquidity); // liquidity <= totalLiquidity } else {
uint256 secondsInsideX128 = secondsPerLiquidityInsideX128 * liquidity; if (activeTime == 0) { reward = FullMath.mulDiv(totalReward, liquidity, totalLiquidity); // liquidity <= totalLiquidity } else {
15,415
193
// avoid SSTORE in loop
rewardTokenAmounts = _rewardTokenAmounts; adminFeeAmount = _adminFeeAmount; emit AdminFee(_adminFeeAmount);
rewardTokenAmounts = _rewardTokenAmounts; adminFeeAmount = _adminFeeAmount; emit AdminFee(_adminFeeAmount);
17,969
54
// Returns the parameters of a debt issuance in the registry. TODO(kayvon): protect this function with our `onlyExtantEntry` modifier once the restrictionon the size of the call stack has been addressed. /
function get(bytes32 agreementId) public view returns(address, address, address, uint, address, bytes32, uint)
function get(bytes32 agreementId) public view returns(address, address, address, uint, address, bytes32, uint)
53,212
75
// Mint `MINTING_REWARD` to msg.sender.
_mint(msg.sender, MINTING_REWARD);
_mint(msg.sender, MINTING_REWARD);
20,093
22
// USDC interest rate
uint256 usdcRate;
uint256 usdcRate;
14,475
189
// Allow havven to burn a certain number ofnomins from an account. /
{ tokenState.setBalanceOf(account, safeSub(tokenState.balanceOf(account), amount)); totalSupply = safeSub(totalSupply, amount); emitTransfer(account, address(0), amount); emitBurned(account, amount); }
{ tokenState.setBalanceOf(account, safeSub(tokenState.balanceOf(account), amount)); totalSupply = safeSub(totalSupply, amount); emitTransfer(account, address(0), amount); emitBurned(account, amount); }
49,920
55
// Loop and push the outbound components
for (uint256 i = 0; i < _outboundAddresses.length; i++) { proposalDetails[_fund].outboundTradeComponents.push( TradeComponent({ componentAddress: _outboundAddresses[i], tradeRealUnits: _outboundRealUnitsArray[i] })
for (uint256 i = 0; i < _outboundAddresses.length; i++) { proposalDetails[_fund].outboundTradeComponents.push( TradeComponent({ componentAddress: _outboundAddresses[i], tradeRealUnits: _outboundRealUnitsArray[i] })
10,260
407
// This function allows any participant to retrievethe receipt for a given proposal and voter. _proposalId Proposal id. _voter Voter address.return Voter receipt. /
function getReceipt(uint128 _proposalId, address _voter) external view returns (Receipt memory) { return proposals[_proposalId].receipts[_voter]; }
function getReceipt(uint128 _proposalId, address _voter) external view returns (Receipt memory) { return proposals[_proposalId].receipts[_voter]; }
36,420
174
// The denominator applied to all earnings to determine what portion goes to maintenance budget/For example, if this is 10, then at most 1/10th of all revenue will be added to the maintenance budget.
function MAINTENANCE_FEE() external view returns (uint8);
function MAINTENANCE_FEE() external view returns (uint8);
57,827
46
// Note: in some cases this will fail due to changes in the OO and the method will refund the relayer.
bool success = _requestProposeDispute( relayData.slowRelayer, msg.sender, relayData.proposerBond, relayData.finalFee, _getRelayAncillaryData(relayHash) );
bool success = _requestProposeDispute( relayData.slowRelayer, msg.sender, relayData.proposerBond, relayData.finalFee, _getRelayAncillaryData(relayHash) );
7,989
81
// Generate new randomness.
random = keccak256(abi.encodePacked(random));
random = keccak256(abi.encodePacked(random));
38,148
10
// Challenge a registration request._value The value of the item subject to the registering request. /
function challengeRegistration(bytes32 _value) public payable { Item storage item = items[_value]; uint arbitratorCost = arbitrator.arbitrationCost(arbitratorExtraData); require(msg.value >= stake + arbitratorCost, "Not enough ETH."); require(item.status == ItemStatus.Resubmitted || item.status == ItemStatus.Submitted, "Item in wrong status for challenging."); require(!item.disputed, "Item cannot be already challenged."); if (item.balance >= arbitratorCost) { // In the general case, create a dispute. item.challenger = msg.sender; item.balance += msg.value-arbitratorCost; item.disputed = true; item.disputeID = arbitrator.createDispute.value(arbitratorCost)(2,arbitratorExtraData); disputeIDToItem[item.disputeID] = _value; emit Dispute(arbitrator, item.disputeID, 0, 0); } else { // In the case the arbitration fees increased so much that the deposit of the requester is not high enough. Cancel the request. if (item.status == ItemStatus.Resubmitted) item.status = ItemStatus.Cleared; else item.status = ItemStatus.Absent; item.submitter.send(item.balance); // Deliberate use of send in order to not block the contract in case of reverting fallback. item.balance = 0; msg.sender.transfer(msg.value); } item.lastAction = now; emit ItemStatusChange(item.submitter, item.challenger, _value, item.status, item.disputed); }
function challengeRegistration(bytes32 _value) public payable { Item storage item = items[_value]; uint arbitratorCost = arbitrator.arbitrationCost(arbitratorExtraData); require(msg.value >= stake + arbitratorCost, "Not enough ETH."); require(item.status == ItemStatus.Resubmitted || item.status == ItemStatus.Submitted, "Item in wrong status for challenging."); require(!item.disputed, "Item cannot be already challenged."); if (item.balance >= arbitratorCost) { // In the general case, create a dispute. item.challenger = msg.sender; item.balance += msg.value-arbitratorCost; item.disputed = true; item.disputeID = arbitrator.createDispute.value(arbitratorCost)(2,arbitratorExtraData); disputeIDToItem[item.disputeID] = _value; emit Dispute(arbitrator, item.disputeID, 0, 0); } else { // In the case the arbitration fees increased so much that the deposit of the requester is not high enough. Cancel the request. if (item.status == ItemStatus.Resubmitted) item.status = ItemStatus.Cleared; else item.status = ItemStatus.Absent; item.submitter.send(item.balance); // Deliberate use of send in order to not block the contract in case of reverting fallback. item.balance = 0; msg.sender.transfer(msg.value); } item.lastAction = now; emit ItemStatusChange(item.submitter, item.challenger, _value, item.status, item.disputed); }
46,834
0
// Internal Functions//RLP encodes a byte string. _in The byte string to encode.return _out The RLP encoded string in bytes. /
function writeBytes( bytes memory _in ) internal pure returns ( bytes memory _out ) { bytes memory encoded;
function writeBytes( bytes memory _in ) internal pure returns ( bytes memory _out ) { bytes memory encoded;
23,181
87
// they just bought so add 1 block cooldown - fuck you frontrunners
if (!_isExcluded[recipient]) { timestamp[recipient] = block.timestamp.add(_CoolDown); }
if (!_isExcluded[recipient]) { timestamp[recipient] = block.timestamp.add(_CoolDown); }
36,580
9
// ========== Modifiers =============== /
modifier directorExists { require( balanceOf(msg.sender) > 0, 'Boardroom: The director does not exist' ); _; }
modifier directorExists { require( balanceOf(msg.sender) > 0, 'Boardroom: The director does not exist' ); _; }
49,730
2
// -- owner2
currUserID++; userStruct2 = UserStruct({ isExist: true, id: currUserID, referrerID: 1, referral: new address[](0) });
currUserID++; userStruct2 = UserStruct({ isExist: true, id: currUserID, referrerID: 1, referral: new address[](0) });
41,968
25
// 1 = 1%
function setDailySaleLimitPercent(uint _dailySaleLimitPercent) public onlyOwner returns(bool)
function setDailySaleLimitPercent(uint _dailySaleLimitPercent) public onlyOwner returns(bool)
4,414
21
// Set controller. Only callable by current controller _controller Controller contract address /
function setController(address _controller) external onlyController { controller = IController(_controller); emit SetController(_controller); }
function setController(address _controller) external onlyController { controller = IController(_controller); emit SetController(_controller); }
7,132
80
// If zx overflowed:
if iszero(eq(div(zx, x), z)) {
if iszero(eq(div(zx, x), z)) {
19,037
1
// The address of the Doobem contract to be tested
Doobem doobem = Doobem(DeployedAddresses.Doobem());
Doobem doobem = Doobem(DeployedAddresses.Doobem());
44,937
1
// users mapping
mapping(uint=> User) public users;
mapping(uint=> User) public users;
16,417
255
// If user hasn't claimed their free mint and is minting more than 1 NFT, deduct price of 1 NFT from totalCost
else if (!hasClaimedFreeMint[msg.sender] && qty > 1) { totalCost -= pricePublic; qty += 1; // They get one additional free NFT hasClaimedFreeMint[msg.sender] = true; }
else if (!hasClaimedFreeMint[msg.sender] && qty > 1) { totalCost -= pricePublic; qty += 1; // They get one additional free NFT hasClaimedFreeMint[msg.sender] = true; }
45,027
241
// mint farmingToken equals to stake liquidity
address farmingToken = farms[fId].farmingToken; if (farmingToken != address(0)) _mintFarmingToken(farmingToken, receiver, totalLiquidity); emit Deposit(fId, rangeId, nftIds, msg.sender, receiver);
address farmingToken = farms[fId].farmingToken; if (farmingToken != address(0)) _mintFarmingToken(farmingToken, receiver, totalLiquidity); emit Deposit(fId, rangeId, nftIds, msg.sender, receiver);
4,204
49
// set the ICO end date and time/
function setICOEndDate(uint timestamp) public onlyOwner { token.addICOEndDate(timestamp); }
function setICOEndDate(uint timestamp) public onlyOwner { token.addICOEndDate(timestamp); }
52,352
52
// ONLY OWNER: Updates supply cap /
function updateSupplyCap(uint256 _newCap) external onlyOwner { supplyCap = _newCap;
function updateSupplyCap(uint256 _newCap) external onlyOwner { supplyCap = _newCap;
17,387
150
// Because it is possible that a quotient gets truncated, we can't just call "Signed(a.rawValue.div(b))" similarly to mulCeil with an int256 as the second parameter. Therefore we need to convert b into an Signed. This creates the possibility of overflow if b is very large.
return divAwayFromZero(a, fromUnscaledInt(b));
return divAwayFromZero(a, fromUnscaledInt(b));
17,461
117
// Gets total number of tokens staked during voting by Claim Assessors. _claimId Claim Id. _verdict 1 to get total number of accept tokens, -1 to get total number of deny tokens.return token token Number of tokens(either accept or deny on the basis of verdict given as parameter). /
function getClaimVote(uint _claimId, int8 _verdict) external view returns(uint claimId, uint token) { claimId = _claimId; token = 0; for (uint i = 0; i < claimVoteCA[_claimId].length; i++) { if (allvotes[claimVoteCA[_claimId][i]].verdict == _verdict) token = token.add(allvotes[claimVoteCA[_claimId][i]].tokens); } }
function getClaimVote(uint _claimId, int8 _verdict) external view returns(uint claimId, uint token) { claimId = _claimId; token = 0; for (uint i = 0; i < claimVoteCA[_claimId].length; i++) { if (allvotes[claimVoteCA[_claimId][i]].verdict == _verdict) token = token.add(allvotes[claimVoteCA[_claimId][i]].tokens); } }
22,169
35
// tokenShare[contracts[i]] = div(tokenBalances[contracts[i]], div(add(totalSupply, circulatingSupply), 1 ether));
tokenShare[contracts[i]] = div(tokenBalances[contracts[i]], circulatingSupply);
tokenShare[contracts[i]] = div(tokenBalances[contracts[i]], circulatingSupply);
13,185
38
// DATA TYPES //The main struct representation of a robot part. Each robot in Etherbots is represented by four copies/of this structure, one for each of the four parts comprising it:/ 1. Right Arm (Melee),/ 2. Left Arm (Defence),/ 3. Head (Turret),/ 4. Body. store token id on this?
struct Part { uint32 tokenId; uint8 partType; uint8 partSubType; uint8 rarity; uint8 element; uint32 battlesLastDay; uint32 experience; uint32 forgeTime; uint32 battlesLastReset; }
struct Part { uint32 tokenId; uint8 partType; uint8 partSubType; uint8 rarity; uint8 element; uint32 battlesLastDay; uint32 experience; uint32 forgeTime; uint32 battlesLastReset; }
38,133
292
// Burns the provided token id if you own it.Reduces the supply by 1.tokenId - the ID of the token to be burned. /
function burn(uint256 tokenId) public { require(ownerOf(tokenId) == msg.sender, "You do not own this token"); _burn(tokenId); }
function burn(uint256 tokenId) public { require(ownerOf(tokenId) == msg.sender, "You do not own this token"); _burn(tokenId); }
26,708
3
// Hash construction
function getLiquidityAdditionHash(LiquidityAddition memory addition) internal pure returns (bytes32)
function getLiquidityAdditionHash(LiquidityAddition memory addition) internal pure returns (bytes32)
19,857
71
// currentIssueRemaining=SafeMath.sub(currentIssueRemaining,1);if this is the last remaining token for sale, issue moreif(currentIssueRemaining == 0){_createOpinionSet();}
4,347
33
// Requirements: check that underlying asset is a registered ERC20.
_checkUnderlyingAsset(assets_[i], assets_);
_checkUnderlyingAsset(assets_[i], assets_);
11,351
313
// _isVotable check if the proposal is votable_proposalId the ID of the proposal return bool true or false/
function _isVotable(bytes32 _proposalId) internal view returns(bool) { ProposalState pState = proposals[_proposalId].state; return ((pState == ProposalState.PreBoosted)|| (pState == ProposalState.Boosted)|| (pState == ProposalState.QuietEndingPeriod)|| (pState == ProposalState.Queued) ); }
function _isVotable(bytes32 _proposalId) internal view returns(bool) { ProposalState pState = proposals[_proposalId].state; return ((pState == ProposalState.PreBoosted)|| (pState == ProposalState.Boosted)|| (pState == ProposalState.QuietEndingPeriod)|| (pState == ProposalState.Queued) ); }
56,913
23
// AdminableHelper contract to support initializer functions. To use it, replacethe constructor with a function that has the `initializer` modifier.WARNING: Unlike constructors, initializer functions must be manuallyinvoked. This applies both to deploying an Initializable contract, as wellas extending an Initializable contract via inheritance.WARNING: When used with inheritance, manual care must be taken to not invokea parent initializer twice, or ensure that all initializers are idempotent,because this is not dealt with automatically as with constructors. /
contract Adminable is Initializable { /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "org.zeppelinos.proxy.admin", and is * validated in the constructor. */ bytes32 private constant ADMIN_SLOT = 0x10d6a54a4754c8869d6886b5f5d7fbfa5b4522237ea5c60d11bc4e7a1ff9390b; /** * @dev Modifier to check whether the `msg.sender` is the admin. * If it is, it will run the function. Otherwise, fails. */ modifier ifAdmin() { require(msg.sender == _admin()); _; } function admin() external view returns (address) { return _admin(); } function implementation() external view returns (address impl) { bytes32 slot = 0x7050c9e0f4ca769c69bd3a8ef740bc37934f8e2c036e5a723fd8ee048ed3f8c3; assembly { impl := sload(slot) } } /** * @return The admin slot. */ function _admin() internal view returns (address adm) { bytes32 slot = ADMIN_SLOT; assembly { adm := sload(slot) } } }
contract Adminable is Initializable { /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "org.zeppelinos.proxy.admin", and is * validated in the constructor. */ bytes32 private constant ADMIN_SLOT = 0x10d6a54a4754c8869d6886b5f5d7fbfa5b4522237ea5c60d11bc4e7a1ff9390b; /** * @dev Modifier to check whether the `msg.sender` is the admin. * If it is, it will run the function. Otherwise, fails. */ modifier ifAdmin() { require(msg.sender == _admin()); _; } function admin() external view returns (address) { return _admin(); } function implementation() external view returns (address impl) { bytes32 slot = 0x7050c9e0f4ca769c69bd3a8ef740bc37934f8e2c036e5a723fd8ee048ed3f8c3; assembly { impl := sload(slot) } } /** * @return The admin slot. */ function _admin() internal view returns (address adm) { bytes32 slot = ADMIN_SLOT; assembly { adm := sload(slot) } } }
10,045
880
// Copied from CTokenInterface
function balanceOfUnderlying(address owner) external returns (uint256); function exchangeRateCurrent() external view returns (uint256); function exchangeRateStored() external view returns (uint256);
function balanceOfUnderlying(address owner) external returns (uint256); function exchangeRateCurrent() external view returns (uint256); function exchangeRateStored() external view returns (uint256);
33,131
453
// Calculate number of tokens of collateral asset to seize given an underlying amount Used in liquidation (called in gToken.liquidateBorrowFresh) gTokenBorrowed The address of the borrowed gToken gTokenCollateral The address of the collateral gToken actualRepayAmount The amount of gTokenBorrowed underlying to convert into gTokenCollateral tokensreturn (errorCode, number of gTokenCollateral tokens to be seized in a liquidation) /
function liquidateCalculateSeizeTokens(address gTokenBorrowed, address gTokenCollateral, uint actualRepayAmount) external view returns (uint, uint) { /* Read oracle prices for borrowed and collateral markets */ uint priceBorrowedMantissa = oracle.getUnderlyingPrice(GToken(gTokenBorrowed)); uint priceCollateralMantissa = oracle.getUnderlyingPrice(GToken(gTokenCollateral)); if (priceBorrowedMantissa == 0 || priceCollateralMantissa == 0) { return (uint(Error.PRICE_ERROR), 0); } /* * Get the exchange rate and calculate the number of collateral tokens to seize: * seizeAmount = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral * seizeTokens = seizeAmount / exchangeRate * = actualRepayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate) */ uint exchangeRateMantissa = GToken(gTokenCollateral).exchangeRateStored(); // Note: reverts on error uint seizeTokens; Exp memory numerator; Exp memory denominator; Exp memory ratio; MathError mathErr; (mathErr, numerator) = mulExp(liquidationIncentiveMantissa, priceBorrowedMantissa); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } (mathErr, denominator) = mulExp(priceCollateralMantissa, exchangeRateMantissa); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } (mathErr, ratio) = divExp(numerator, denominator); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } (mathErr, seizeTokens) = mulScalarTruncate(ratio, actualRepayAmount); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } return (uint(Error.NO_ERROR), seizeTokens); }
function liquidateCalculateSeizeTokens(address gTokenBorrowed, address gTokenCollateral, uint actualRepayAmount) external view returns (uint, uint) { /* Read oracle prices for borrowed and collateral markets */ uint priceBorrowedMantissa = oracle.getUnderlyingPrice(GToken(gTokenBorrowed)); uint priceCollateralMantissa = oracle.getUnderlyingPrice(GToken(gTokenCollateral)); if (priceBorrowedMantissa == 0 || priceCollateralMantissa == 0) { return (uint(Error.PRICE_ERROR), 0); } /* * Get the exchange rate and calculate the number of collateral tokens to seize: * seizeAmount = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral * seizeTokens = seizeAmount / exchangeRate * = actualRepayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate) */ uint exchangeRateMantissa = GToken(gTokenCollateral).exchangeRateStored(); // Note: reverts on error uint seizeTokens; Exp memory numerator; Exp memory denominator; Exp memory ratio; MathError mathErr; (mathErr, numerator) = mulExp(liquidationIncentiveMantissa, priceBorrowedMantissa); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } (mathErr, denominator) = mulExp(priceCollateralMantissa, exchangeRateMantissa); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } (mathErr, ratio) = divExp(numerator, denominator); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } (mathErr, seizeTokens) = mulScalarTruncate(ratio, actualRepayAmount); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } return (uint(Error.NO_ERROR), seizeTokens); }
77,576
49
// Upgrade the implementation of the proxy, and then call a function from the new implementation as specifiedby `data`, which should be an encoded function call. This is useful to initialize new storage variables in theproxied contract.
* NOTE: Only the admin can call this function. See {ProxyAdmin-upgradeAndCall}. */ function upgradeToAndCall(address newImplementation, bytes calldata data) external override payable ifAdmin { _upgradeTo(newImplementation); // solhint-disable-next-line avoid-low-level-calls (bool success,) = newImplementation.delegatecall(data); require(success); }
* NOTE: Only the admin can call this function. See {ProxyAdmin-upgradeAndCall}. */ function upgradeToAndCall(address newImplementation, bytes calldata data) external override payable ifAdmin { _upgradeTo(newImplementation); // solhint-disable-next-line avoid-low-level-calls (bool success,) = newImplementation.delegatecall(data); require(success); }
72,003
2
// withdrawETH transfers all the accumlated ether the collector address /
function withdrawETH() external payable { collector.transfer(address(this).balance); }
function withdrawETH() external payable { collector.transfer(address(this).balance); }
617
3
// Function to withdraw all Ether from this contract.
function withdraw() public {
function withdraw() public {
29,459
78
// internal method to save new improvement score
function saveNewImprovement(uint impScoreRatio, uint impScoreReserve) internal { bestRatioImprovement = impScoreRatio; bestReserveImprovement = impScoreReserve; }
function saveNewImprovement(uint impScoreRatio, uint impScoreReserve) internal { bestRatioImprovement = impScoreRatio; bestReserveImprovement = impScoreReserve; }
48,721
9
// Throws if called by any sender that doesn't match one of the supplied contract or is the latest version of that contract /
modifier onlyLatestContract( string memory _contractName, address _contractAddress
modifier onlyLatestContract( string memory _contractName, address _contractAddress
28,767
6
// Revert if shipment state is not correct_shipmentUuid bytes16 representation of the shipment's UUID._state Shipment.State required state._message string Revert message./
modifier shipmentHasState(bytes16 _shipmentUuid, Shipment.State _state, string memory _message) { require(allShipmentData[_shipmentUuid].state == _state, _message); _; }
modifier shipmentHasState(bytes16 _shipmentUuid, Shipment.State _state, string memory _message) { require(allShipmentData[_shipmentUuid].state == _state, _message); _; }
50,944
141
// require(timeinterval > 180, "timelimit-6hours is not finished yet");
uint256 totaltokenamount = crops.totalSupply(); totaltokenamount = totaltokenamount.sub(totaltokenamount.mod(1000)); uint256 decaytokenvalue = totaltokenamount.div(1000);//1% of 10%decayvalue uint256 originaldeservedtoken = crops.balanceOf(address(this)); crops.globalDecay(); uint256 afterdeservedtoken = crops.balanceOf(address(this)); uint256 differtoken = originaldeservedtoken.sub(afterdeservedtoken);
uint256 totaltokenamount = crops.totalSupply(); totaltokenamount = totaltokenamount.sub(totaltokenamount.mod(1000)); uint256 decaytokenvalue = totaltokenamount.div(1000);//1% of 10%decayvalue uint256 originaldeservedtoken = crops.balanceOf(address(this)); crops.globalDecay(); uint256 afterdeservedtoken = crops.balanceOf(address(this)); uint256 differtoken = originaldeservedtoken.sub(afterdeservedtoken);
11,909
151
// Unlock tokens held by contract to beneficiary. /
function unlock() public onlyOperator nonReentrant { require(_released == true, "Crowdfunding: not already released"); uint256 amount = _token.balanceOf(address(this)); require(amount > 0, "Crowdfunding: no tokens to unlock"); _token.safeTransfer(_beneficiary, amount); }
function unlock() public onlyOperator nonReentrant { require(_released == true, "Crowdfunding: not already released"); uint256 amount = _token.balanceOf(address(this)); require(amount > 0, "Crowdfunding: no tokens to unlock"); _token.safeTransfer(_beneficiary, amount); }
24,818
24
// Investors (36 months)
registerRecipient(0x08AAE6A5979625F2173f1C31A3417251B2386777, 317097919800000, true); registerRecipient(0x6b339824883E59676EA605260E4DdA71DcCA29Ae, 158548959900000, true); registerRecipient(0xC71F1e087AadfBaE3e8578b5eFAFDeC8aFA95a16, 1268391679000000, true); registerRecipient(0x54a55291aF851f5d439536889eeF191B81D3c091, 4756468798000000, true); registerRecipient(0x51787a2C56d710c68140bdAdeFD3A98BfF96FeB4, 317097919800000, true);
registerRecipient(0x08AAE6A5979625F2173f1C31A3417251B2386777, 317097919800000, true); registerRecipient(0x6b339824883E59676EA605260E4DdA71DcCA29Ae, 158548959900000, true); registerRecipient(0xC71F1e087AadfBaE3e8578b5eFAFDeC8aFA95a16, 1268391679000000, true); registerRecipient(0x54a55291aF851f5d439536889eeF191B81D3c091, 4756468798000000, true); registerRecipient(0x51787a2C56d710c68140bdAdeFD3A98BfF96FeB4, 317097919800000, true);
36,106
225
// create temporary sub-stake for current or previous committed periods to leave locked amount in this period unchanged
if (_info.currentCommittedPeriod != 0 && _info.currentCommittedPeriod <= _currentPeriod || _info.nextCommittedPeriod != 0 && _info.nextCommittedPeriod <= _currentPeriod) { saveSubStake(_info, subStake.firstPeriod, _currentPeriod, 0, subStake.lockedValue); }
if (_info.currentCommittedPeriod != 0 && _info.currentCommittedPeriod <= _currentPeriod || _info.nextCommittedPeriod != 0 && _info.nextCommittedPeriod <= _currentPeriod) { saveSubStake(_info, subStake.firstPeriod, _currentPeriod, 0, subStake.lockedValue); }
50,065
16
// prepare the call data, 4 for signature + 32 for the address
bytes memory msgdata = new bytes(36); bytes4 sig = bytes4(keccak256("__constructor(address)")); assembly { mstore(add(msgdata,32),sig) mstore(add(msgdata,36), _owner) }
bytes memory msgdata = new bytes(36); bytes4 sig = bytes4(keccak256("__constructor(address)")); assembly { mstore(add(msgdata,32),sig) mstore(add(msgdata,36), _owner) }
50,187
74
// Pre-sale
if (now >= startPreSale && now < endPreSale && totalPreSale < maxPreSale){ tokens = weiAmount.mul(ratePreSale); if (maxPreSale.sub(totalPreSale) <= tokens){ endPreSale = now; startIco = now; endIco = startIco + 40 * 1 days; }
if (now >= startPreSale && now < endPreSale && totalPreSale < maxPreSale){ tokens = weiAmount.mul(ratePreSale); if (maxPreSale.sub(totalPreSale) <= tokens){ endPreSale = now; startIco = now; endIco = startIco + 40 * 1 days; }
70,063
10
// Inheritable function which authorizes someone/who the address to authorize
function _authorize(address who) internal { authorized[who] = true; }
function _authorize(address who) internal { authorized[who] = true; }
21,167
134
// Atomic Token Swap order Types.Order /
function swap(Types.Order calldata order) external;
function swap(Types.Order calldata order) external;
18,756
59
// Allows owner to update owner of contract
function updateOwner(address newOwner) external { // Revert if caller is not owner if (msg.sender != owner) revert NotOwner(); // Update new owner owner = newOwner; }
function updateOwner(address newOwner) external { // Revert if caller is not owner if (msg.sender != owner) revert NotOwner(); // Update new owner owner = newOwner; }
15,416
1
// Public variables
mapping(address => bool) public emissionTargets; mapping(address => uint256) public emissionInitialAllotments; // ex: 1337 * (10 ** 18) mapping(address => uint256) public emissionPreRevealMultipliers; // ex: 3 mapping(address => uint256) public emissionStarts; // ex: 1626307200 mapping(address => uint256) public emissionEnds; // ex: 1626307200 + (86400 * 365 * 5); // 5 Years mapping(address => uint256) public emissionPerDays; // ex: 7.37 * (10 ** 18) mapping(address => mapping(uint256 => uint256)) private _lastClaims;
mapping(address => bool) public emissionTargets; mapping(address => uint256) public emissionInitialAllotments; // ex: 1337 * (10 ** 18) mapping(address => uint256) public emissionPreRevealMultipliers; // ex: 3 mapping(address => uint256) public emissionStarts; // ex: 1626307200 mapping(address => uint256) public emissionEnds; // ex: 1626307200 + (86400 * 365 * 5); // 5 Years mapping(address => uint256) public emissionPerDays; // ex: 7.37 * (10 ** 18) mapping(address => mapping(uint256 => uint256)) private _lastClaims;
17,543
72
// Calculate and mint the amount of Bamboo the Panda is worth. The ratio will change overtime, as Bamboo is burned/minted and Panda deposited + gained from fees / withdrawn.
else { uint256 what = _amount.mul(totalShares).div(totalSushi); _mint(msg.sender, what); }
else { uint256 what = _amount.mul(totalShares).div(totalSushi); _mint(msg.sender, what); }
20,732
108
// /SushiSwap `msg.value` ETH to stake SUSHI into xSUSHI and BENTO for benefit of `to`.
function ethToStakeSushiToBento(address to) external payable { // INARIZUSHI (uint256 reserve0, uint256 reserve1, ) = sushiSwapSushiETHPair.getReserves(); uint256 amountInWithFee = msg.value.mul(997); uint256 amountOut = amountInWithFee.mul(reserve0) / reserve1.mul(1000).add(amountInWithFee); IWETH(wETH).deposit{value: msg.value}(); IERC20(wETH).safeTransfer(address(sushiSwapSushiETHPair), msg.value); sushiSwapSushiETHPair.swap(amountOut, 0, address(this), ""); ISushiBarBridge(sushiBar).enter(sushiToken.balanceOf(address(this))); // stake resulting SUSHI into `sushiBar` xSUSHI bento.deposit(IERC20(sushiBar), address(this), to, IERC20(sushiBar).balanceOf(address(this)), 0); // stake resulting xSUSHI into BENTO for `msg.sender` }
function ethToStakeSushiToBento(address to) external payable { // INARIZUSHI (uint256 reserve0, uint256 reserve1, ) = sushiSwapSushiETHPair.getReserves(); uint256 amountInWithFee = msg.value.mul(997); uint256 amountOut = amountInWithFee.mul(reserve0) / reserve1.mul(1000).add(amountInWithFee); IWETH(wETH).deposit{value: msg.value}(); IERC20(wETH).safeTransfer(address(sushiSwapSushiETHPair), msg.value); sushiSwapSushiETHPair.swap(amountOut, 0, address(this), ""); ISushiBarBridge(sushiBar).enter(sushiToken.balanceOf(address(this))); // stake resulting SUSHI into `sushiBar` xSUSHI bento.deposit(IERC20(sushiBar), address(this), to, IERC20(sushiBar).balanceOf(address(this)), 0); // stake resulting xSUSHI into BENTO for `msg.sender` }
3,838
0
// withdraw addresses
address t1 = 0xfc86A64a8DE22CF25410F7601AcBd8d6630Da93D; address t2 = 0x4265de963cdd60629d03FEE2cd3285e6d5ff6015; address t3 = 0x1b33EBa79c4DD7243E5a3456fc497b930Db054b2; address t4 = 0x92d79ccaCE3FC606845f3A66c9AeD75d8e5487A9;
address t1 = 0xfc86A64a8DE22CF25410F7601AcBd8d6630Da93D; address t2 = 0x4265de963cdd60629d03FEE2cd3285e6d5ff6015; address t3 = 0x1b33EBa79c4DD7243E5a3456fc497b930Db054b2; address t4 = 0x92d79ccaCE3FC606845f3A66c9AeD75d8e5487A9;
13,738
1
// ERC721 interfaceID
bytes4 public constant INTERFACE_ID_ERC721 = 0x80ac58cd;
bytes4 public constant INTERFACE_ID_ERC721 = 0x80ac58cd;
5,096
71
// Create a uniswap pair for this new token
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; balancer = address(new Balancer()); isExcludedFromFee[_msgSender()] = true; isExcludedFromFee[address(this)] = true;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; balancer = address(new Balancer()); isExcludedFromFee[_msgSender()] = true; isExcludedFromFee[address(this)] = true;
4,602
41
// Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations. _beneficiary Address performing the token purchase _weiAmount Value in wei involved in the purchase /
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal whenNotPaused { require(_beneficiary != address(0)); require(_weiAmount >= minInvest); require(now >= openingTime && now <= closingTime); }
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal whenNotPaused { require(_beneficiary != address(0)); require(_weiAmount >= minInvest); require(now >= openingTime && now <= closingTime); }
4,880
105
// 18 decimals nominator with decimals converter:Foreign = NativeRate(18) / nominatorNativeToForeign
uint256 nominatorForeignToNative; // 10**(18 + foreign decimals - native decimals) uint256 nominatorNativeToForeign; // 10**(18 + native decimals - foreign decimals) uint256 localNative; // already swapped Native tokens = _balanceOf[hashNative] uint256 localForeign; // already swapped Foreign tokens = decoded _balanceOf[hashForeign] uint256 localForeignRate; // Foreign token price / Native token price = decoded _balanceOf[hashForeign] address hashNative; // _getHashAddress(tokenA, tokenB, address(0), address(0)); address hashForeign; // _getHashAddress(tokenB, tokenA, address(0), address(0));
uint256 nominatorForeignToNative; // 10**(18 + foreign decimals - native decimals) uint256 nominatorNativeToForeign; // 10**(18 + native decimals - foreign decimals) uint256 localNative; // already swapped Native tokens = _balanceOf[hashNative] uint256 localForeign; // already swapped Foreign tokens = decoded _balanceOf[hashForeign] uint256 localForeignRate; // Foreign token price / Native token price = decoded _balanceOf[hashForeign] address hashNative; // _getHashAddress(tokenA, tokenB, address(0), address(0)); address hashForeign; // _getHashAddress(tokenB, tokenA, address(0), address(0));
15,334
21
// Make sure the contract has enough tokens.
require(contractBalance >= _amount, "Not enough tokens in contract");
require(contractBalance >= _amount, "Not enough tokens in contract");
10,614
15
// Request verification of claim from government.
function _requestVerification(uint _claimNum) private { Claim memory thisClaim = claims[_claimNum - 1]; address govContractAddress = factoryContract.getContractAddress(1, address(0)); GovInterface govContract = GovInterface(govContractAddress); govContract.addVerificationRequest( owner, _claimNum, thisClaim.expiryDate, thisClaim.dataIdentifier, thisClaim.description, thisClaim.verifierName, thisClaim.verifier, thisClaim.verified); }
function _requestVerification(uint _claimNum) private { Claim memory thisClaim = claims[_claimNum - 1]; address govContractAddress = factoryContract.getContractAddress(1, address(0)); GovInterface govContract = GovInterface(govContractAddress); govContract.addVerificationRequest( owner, _claimNum, thisClaim.expiryDate, thisClaim.dataIdentifier, thisClaim.description, thisClaim.verifierName, thisClaim.verifier, thisClaim.verified); }
8,698
6
// 1e18∫(rate(t) / totalSupply(t) dt) from 0 till checkpoint
uint256[100000000000000000000000000000] override public integrate_inv_supply; // bump epoch when rate() changes
uint256[100000000000000000000000000000] override public integrate_inv_supply; // bump epoch when rate() changes
28,536
100
// This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: ```solidity bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( keccak256("Mail(address to,string contents)"), mailTo, keccak256(bytes(mailContents)) ))); address signer = ECDSA.recover(digest, signature); ```/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash); }
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash); }
27,472
32
// `intensity >= 252` implies `intenseBg = true`
bgBitmap <<= 1; bgBitmap |= bgBitmapBits[i]; unchecked { ++i; }
bgBitmap <<= 1; bgBitmap |= bgBitmapBits[i]; unchecked { ++i; }
11,960
39
// Cyan Ape Coin Vault - Cyan's ApeCoin staking solution/Bulgantamir Gankhuyag - <bulgaa@usecyan.com>/Naranbayar Uuganbayar - <naba@usecyan.com>
contract CyanApeCoinVault is AccessControlUpgradeable, ReentrancyGuardUpgradeable, PausableUpgradeable { using SafeERC20Upgradeable for IERC20Upgradeable; bytes32 public constant CYAN_APE_PLAN_ROLE = keccak256("CYAN_APE_PLAN_ROLE"); event Deposit(address indexed recipient, uint256 amount, uint256 tokenAmount); event DepositBatch(uint256 totalAmount, uint256 totalCurrency, uint256 totalToken); event Lend(address indexed to, uint256 amount, uint256 poolId); event PayLoan(uint256 paymentAmount, uint256 profitAmount, uint256 poolId); event EarnInterest(uint256 profitAmount); event AutoCompounded(); event Withdraw(address indexed from, uint256 amount, uint256 tokenAmount); event UpdatedServiceFeePercent(uint256 from, uint256 to); event UpdatedSafetyFundPercent(uint256 from, uint256 to); event InitializedServiceFeePercent(uint256 to); event InitializedSafetyFundPercent(uint256 to); event CollectedServiceFee(); event InterestRateUpdated(uint256 poolId, uint256 interestRate); struct Amounts { uint256[4] loanedAmount; uint256 estimatedCollectedRewardAmount; uint256 collectedServiceFeeAmount; } struct DepositInfo { address recipient; uint256 amount; } CyanVaultTokenV1 public cyanVaultTokenContract; // Safety fund percent. (x100) uint256 public safetyFundPercent; // Cyan service fee percent. (x100) uint256 public serviceFeePercent; Amounts public amounts; IERC20Upgradeable public constant apeCoin = IERC20Upgradeable(0x4d224452801ACEd8B2F0aebE155379bb5D594381); IApeCoinStaking public constant apeStaking = IApeCoinStaking(0x5954aB967Bc958940b7EB73ee84797Dc8a2AFbb9); uint256 public constant APE_COIN_PRECISION = 1e18; // Loan interest rates for each pool. (x100) uint256[4] public interestRates; /** * @notice Initializes the CyanApeCoinVault contract * @param _cyanVaultTokenAddress Address of the CyanVaultToken contract * @param _cyanSuperAdmin Address of the Cyan Super Admin * @param _safetyFundPercent Percentage of the safety fund * @param _serviceFeePercent Percentage of the service fee * @param _baycPoolInterestRate Interest rate for the BAYC pool * @param _maycPoolInterestRate Interest rate for the MAYC pool * @param _bakcPoolInterestRate Interest rate for the BAKC pool */ function initialize( address _cyanVaultTokenAddress, address _cyanSuperAdmin, uint256 _safetyFundPercent, uint256 _serviceFeePercent, uint256 _baycPoolInterestRate, uint256 _maycPoolInterestRate, uint256 _bakcPoolInterestRate ) external initializer { require(_cyanVaultTokenAddress != address(0), "Cyan Vault Token address cannot be zero"); require(_cyanSuperAdmin != address(0), "Cyan Super Admin address cannot be zero"); require(_safetyFundPercent <= 10000, "Safety fund percent must be equal or less than 100 percent"); require(_serviceFeePercent <= 200, "Service fee percent must not be greater than 2 percent"); require(_baycPoolInterestRate <= 10000, "BAYC Pool interest rate must be equal or less than 100 percent"); require(_maycPoolInterestRate <= 10000, "MAYC Pool interest rate must be equal or less than 100 percent"); require(_bakcPoolInterestRate <= 10000, "BAKC Pool interest rate must be equal or less than 100 percent"); __AccessControl_init(); __ReentrancyGuard_init(); __Pausable_init(); cyanVaultTokenContract = CyanVaultTokenV1(_cyanVaultTokenAddress); safetyFundPercent = _safetyFundPercent; serviceFeePercent = _serviceFeePercent; apeCoin.approve(address(apeStaking), type(uint256).max); interestRates[1] = _baycPoolInterestRate; interestRates[2] = _maycPoolInterestRate; interestRates[3] = _bakcPoolInterestRate; _setupRole(DEFAULT_ADMIN_ROLE, _cyanSuperAdmin); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); emit InitializedServiceFeePercent(_serviceFeePercent); emit InitializedSafetyFundPercent(_safetyFundPercent); } /** * @notice Allows a user to deposit ApeCoin into the vault * @param depositInfo Information about the deposit including recipient and amount */ function deposit(DepositInfo calldata depositInfo) external nonReentrant whenNotPaused { require(depositInfo.amount > 0, "Must deposit more than zero"); // Cyan collecting service fee from deposits uint256 cyanServiceFee = (depositInfo.amount * serviceFeePercent) / 10000; uint256 userDepositedAmount = depositInfo.amount - cyanServiceFee; uint256 mintAmount = calculateTokenByCurrency(userDepositedAmount); apeCoin.safeTransferFrom(msg.sender, address(this), depositInfo.amount); amounts.collectedServiceFeeAmount += cyanServiceFee; claimRewardsAndStake(userDepositedAmount); cyanVaultTokenContract.mint(depositInfo.recipient, mintAmount); emit Deposit(depositInfo.recipient, userDepositedAmount, mintAmount); } /** * @notice Allows multiple deposits in a single batch from CyanApeCoinPlan contract * @param deposits An array of DepositInfo struct containing recipient and amount for each deposit */ function depositBatch(DepositInfo[] calldata deposits) external nonReentrant whenNotPaused onlyRole(CYAN_APE_PLAN_ROLE) { uint256 totalAmount; uint256 totalUserDeposits; (uint256 totalCurrency, uint256 totalToken) = getTotalCurrencyAndToken(); if (totalCurrency == 0 || totalToken == 0) { // Setting those to 1 for calculating token price rate totalCurrency = 1; totalToken = 1; } for (uint256 ind; ind < deposits.length; ) { uint256 amount = deposits[ind].amount; if (amount > 0) { address recipient = deposits[ind].recipient; uint256 cyanServiceFee = (amount * serviceFeePercent) / 10000; uint256 userDepositedAmount = amount - cyanServiceFee; uint256 mintAmount = (userDepositedAmount * totalToken) / totalCurrency; totalAmount += amount; totalUserDeposits += userDepositedAmount; cyanVaultTokenContract.mint(recipient, mintAmount); } unchecked { ++ind; } } apeCoin.safeTransferFrom(msg.sender, address(this), totalAmount); amounts.collectedServiceFeeAmount += (totalAmount - totalUserDeposits); claimRewardsAndStake(totalUserDeposits); emit DepositBatch(totalAmount, totalCurrency, totalToken); } /** * @notice Lends a specified amount from the vault * @param to Address to lend to * @param amount Amount to lend * @param poolId Id of the pool */ function lend( address to, uint256 amount, uint256 poolId ) external nonReentrant whenNotPaused onlyRole(CYAN_APE_PLAN_ROLE) { require(to != address(0), "to address cannot be zero"); uint256 maxWithdrawableAmount = getMaxWithdrawableAmount(); require(amount <= maxWithdrawableAmount, "Not enough balance in the Vault"); prepareApeCoinForRetrieval(amount); amounts.loanedAmount[poolId] += amount; apeCoin.safeTransfer(to, amount); emit Lend(to, amount, poolId); } /** * @notice Pays back a loan with profit to the vault * @param amount The loan amount to be paid back * @param profit The profit amount * @param poolId Id of the pool */ function pay( uint256 amount, uint256 profit, uint256 poolId ) external nonReentrant onlyRole(CYAN_APE_PLAN_ROLE) { uint256 totalAmount = amount + profit; apeCoin.safeTransferFrom(msg.sender, address(this), totalAmount); claimRewardsAndStake(totalAmount); if (amount > 0) { amounts.loanedAmount[poolId] -= amount; } if (profit > 0) { if (amounts.estimatedCollectedRewardAmount >= profit) { amounts.estimatedCollectedRewardAmount -= profit; } else { amounts.estimatedCollectedRewardAmount = 0; } } emit PayLoan(amount, profit, poolId); } /** * @notice Allows the Vault to earn interest * @param profit The profit amount */ function earn(uint256 profit) external nonReentrant onlyRole(CYAN_APE_PLAN_ROLE) { apeCoin.safeTransferFrom(msg.sender, address(this), profit); claimRewardsAndStake(profit); if (amounts.estimatedCollectedRewardAmount >= profit) { amounts.estimatedCollectedRewardAmount -= profit; } else { amounts.estimatedCollectedRewardAmount = 0; } emit EarnInterest(profit); } /** * @notice Compounds the rewards in the vault by claiming the collected rewards and staking them */ function autoCompound() external nonReentrant { claimRewardsAndStake(0); emit AutoCompounded(); } /** * @notice Allows a user to withdraw ApeCoin from the vault * @param tokenAmount The amount of tokens to withdraw */ function withdraw(uint256 tokenAmount) external nonReentrant whenNotPaused { require(tokenAmount > 0, "Non-positive token amount"); uint256 withdrawableTokenBalance = getWithdrawableBalance(msg.sender); require(tokenAmount <= withdrawableTokenBalance, "Not enough active balance in Cyan Vault"); uint256 withdrawAmount = calculateCurrencyByToken(tokenAmount); prepareApeCoinForRetrieval(withdrawAmount); cyanVaultTokenContract.burn(msg.sender, tokenAmount); apeCoin.safeTransfer(msg.sender, withdrawAmount); emit Withdraw(msg.sender, withdrawAmount, tokenAmount); } /** * @notice Get the withdrawable balance for a given user * @param user Address of the user * @return uint256 Amount of withdrawable balance for the user */ function getWithdrawableBalance(address user) public view returns (uint256) { uint256 tokenBalance = cyanVaultTokenContract.balanceOf(user); uint256 currencyAmountForToken = calculateCurrencyByToken(tokenBalance); uint256 maxWithdrawableAmount = getMaxWithdrawableAmount(); if (currencyAmountForToken <= maxWithdrawableAmount) { return tokenBalance; } return calculateTokenByCurrency(maxWithdrawableAmount); } /** * @notice Calculate the maximum amount that can be withdrawn considering safety fund percent * @return uint256 Maximum withdrawable amount */ function getMaxWithdrawableAmount() public view returns (uint256) { uint256 util = ((amounts.loanedAmount[1] + amounts.loanedAmount[2] + amounts.loanedAmount[3]) * safetyFundPercent) / 10000; IApeCoinStaking.DashboardStake memory dashboard = apeStaking.getApeCoinStake(address(this)); if (dashboard.deposited + dashboard.unclaimed > util) { return dashboard.deposited + dashboard.unclaimed - util; } return 0; } /** * @notice Gets the current asset amounts * @return Returns the amounts struct, deposited and unclaimed amounts */ function getCurrentAssetAmounts() external view returns ( Amounts memory, uint256, uint256 ) { IApeCoinStaking.DashboardStake memory dashboard = apeStaking.getApeCoinStake(address(this)); return (amounts, dashboard.deposited, dashboard.unclaimed); } /** * @notice Convert a given currency amount to its corresponding token amount * @param amount Amount of currency * @return uint256 Equivalent amount in tokens */ function calculateTokenByCurrency(uint256 amount) public view returns (uint256) { (uint256 totalCurrency, uint256 totalToken) = getTotalCurrencyAndToken(); if (totalCurrency == 0 || totalToken == 0) return amount; return (amount * totalToken) / totalCurrency; } /** * @notice Convert a given token amount to its corresponding currency amount * @param amount Amount of token * @return uint256 Equivalent amount in currency */ function calculateCurrencyByToken(uint256 amount) public view returns (uint256) { (uint256 totalCurrency, uint256 totalToken) = getTotalCurrencyAndToken(); if (totalCurrency == 0 || totalToken == 0) return amount; return (amount * totalCurrency) / totalToken; } /** * @notice Fetches the total currency and token amounts for the vault * @dev This considers the staked, unclaimed, loaned, estimated collected rewards, and interest amounts for the total currency value * @return uint256 Total currency amount * @return uint256 Total token supply of the vault */ function getTotalCurrencyAndToken() private view returns (uint256, uint256) { IApeCoinStaking.DashboardStake memory dashboard = apeStaking.getApeCoinStake(address(this)); uint256 totalCurrency = dashboard.deposited + dashboard.unclaimed + amounts.loanedAmount[1] + amounts.loanedAmount[2] + amounts.loanedAmount[3] + amounts.estimatedCollectedRewardAmount + calculateEstimatedCollectedInterests(dashboard); uint256 totalToken = cyanVaultTokenContract.totalSupply(); return (totalCurrency, totalToken); } /** * @notice Calculate the estimated collected interests based on the current stake status and loaned amounts * @param dashboard The current stake status of the contract * @return uint256 Estimated collected interest */ function calculateEstimatedCollectedInterests(IApeCoinStaking.DashboardStake memory dashboard) private view returns (uint256) { return dashboard.deposited == 0 ? 0 : ((amounts.loanedAmount[1] * interestRates[1] + amounts.loanedAmount[2] * interestRates[2] + amounts.loanedAmount[3] * interestRates[3]) * dashboard.unclaimed) / dashboard.deposited / 10000; } function getPoolInterestRates() external view returns (uint256[4] memory) { return interestRates; } /** * @notice Update the safety fund percentage * @param _safetyFundPercent New percentage value for the safety fund */ function updateSafetyFundPercent(uint256 _safetyFundPercent) external nonReentrant onlyRole(DEFAULT_ADMIN_ROLE) { require(_safetyFundPercent <= 10000, "Safety fund percent must be equal or less than 100 percent"); emit UpdatedSafetyFundPercent(safetyFundPercent, _safetyFundPercent); safetyFundPercent = _safetyFundPercent; } /** * @notice Update the service fee percentage. * This is the fee taken by Cyan for its services. * @param _serviceFeePercent The new fee percentage to be set. */ function updateServiceFeePercent(uint256 _serviceFeePercent) external nonReentrant onlyRole(DEFAULT_ADMIN_ROLE) { require(_serviceFeePercent <= 200, "Service fee percent must not be greater than 2 percent"); emit UpdatedServiceFeePercent(serviceFeePercent, _serviceFeePercent); serviceFeePercent = _serviceFeePercent; } /** * @notice Updates the interest rate for a particular staking pool. * @param poolId The ID of the pool to be updated. * @param interestRate The new interest rate to be set. */ function updatePoolInterestRate(uint256 poolId, uint256 interestRate) external onlyRole(DEFAULT_ADMIN_ROLE) { require(interestRate <= 10000, "Interest rate percent must not be greater than 100 percent"); interestRates[poolId] = interestRate; emit InterestRateUpdated(poolId, interestRate); } /** * @notice Allows the admin to collect the accumulated service fee. */ function collectServiceFee() external nonReentrant onlyRole(DEFAULT_ADMIN_ROLE) { require(amounts.collectedServiceFeeAmount > 0, "Not enough collected service fee"); apeCoin.safeTransfer(msg.sender, amounts.collectedServiceFeeAmount); amounts.collectedServiceFeeAmount = 0; emit CollectedServiceFee(); } /** * @notice Claims rewards and then stakes them back into the ApeCoin staking contract. * @param amount The amount of ApeCoin to be staked. */ function claimRewardsAndStake(uint256 amount) private { IApeCoinStaking.DashboardStake memory dashboard = apeStaking.getApeCoinStake(address(this)); if (dashboard.unclaimed > 0) { if (dashboard.unclaimed + amount < APE_COIN_PRECISION) { apeStaking.withdrawApeCoin(dashboard.deposited, address(this)); depositToApeStaking(dashboard.unclaimed + dashboard.deposited + amount); } else { apeStaking.claimApeCoin(address(this)); depositToApeStaking(dashboard.unclaimed + amount); } } else { depositToApeStaking(amount); } amounts.estimatedCollectedRewardAmount += calculateEstimatedCollectedInterests(dashboard); } /** * @notice Prepares a specific amount of ApeCoin for retrieval from the staking contract. * @param amount The amount of ApeCoin to be prepared for retrieval. */ function prepareApeCoinForRetrieval(uint256 amount) private { IApeCoinStaking.DashboardStake memory dashboard = apeStaking.getApeCoinStake(address(this)); if (dashboard.unclaimed > 0) { apeStaking.withdrawApeCoin(dashboard.deposited, address(this)); depositToApeStaking(dashboard.unclaimed + dashboard.deposited - amount); } else { apeStaking.withdrawApeCoin(amount, address(this)); } amounts.estimatedCollectedRewardAmount += calculateEstimatedCollectedInterests(dashboard); } /** * @notice Deposits ApeCoin into the ApeCoin staking contract. * @param amount The amount of ApeCoin to be deposited. */ function depositToApeStaking(uint256 amount) private { if (amount > 0) { apeStaking.depositApeCoin(amount, address(this)); } } /** * @notice Approve the max amount of ApeCoin for the ApeCoin staking contract */ function apeCoinApproval() external nonReentrant onlyRole(DEFAULT_ADMIN_ROLE) { apeCoin.approve(address(apeStaking), type(uint256).max); } function pause() external nonReentrant onlyRole(DEFAULT_ADMIN_ROLE) { _pause(); } function unpause() external nonReentrant onlyRole(DEFAULT_ADMIN_ROLE) { _unpause(); } }
contract CyanApeCoinVault is AccessControlUpgradeable, ReentrancyGuardUpgradeable, PausableUpgradeable { using SafeERC20Upgradeable for IERC20Upgradeable; bytes32 public constant CYAN_APE_PLAN_ROLE = keccak256("CYAN_APE_PLAN_ROLE"); event Deposit(address indexed recipient, uint256 amount, uint256 tokenAmount); event DepositBatch(uint256 totalAmount, uint256 totalCurrency, uint256 totalToken); event Lend(address indexed to, uint256 amount, uint256 poolId); event PayLoan(uint256 paymentAmount, uint256 profitAmount, uint256 poolId); event EarnInterest(uint256 profitAmount); event AutoCompounded(); event Withdraw(address indexed from, uint256 amount, uint256 tokenAmount); event UpdatedServiceFeePercent(uint256 from, uint256 to); event UpdatedSafetyFundPercent(uint256 from, uint256 to); event InitializedServiceFeePercent(uint256 to); event InitializedSafetyFundPercent(uint256 to); event CollectedServiceFee(); event InterestRateUpdated(uint256 poolId, uint256 interestRate); struct Amounts { uint256[4] loanedAmount; uint256 estimatedCollectedRewardAmount; uint256 collectedServiceFeeAmount; } struct DepositInfo { address recipient; uint256 amount; } CyanVaultTokenV1 public cyanVaultTokenContract; // Safety fund percent. (x100) uint256 public safetyFundPercent; // Cyan service fee percent. (x100) uint256 public serviceFeePercent; Amounts public amounts; IERC20Upgradeable public constant apeCoin = IERC20Upgradeable(0x4d224452801ACEd8B2F0aebE155379bb5D594381); IApeCoinStaking public constant apeStaking = IApeCoinStaking(0x5954aB967Bc958940b7EB73ee84797Dc8a2AFbb9); uint256 public constant APE_COIN_PRECISION = 1e18; // Loan interest rates for each pool. (x100) uint256[4] public interestRates; /** * @notice Initializes the CyanApeCoinVault contract * @param _cyanVaultTokenAddress Address of the CyanVaultToken contract * @param _cyanSuperAdmin Address of the Cyan Super Admin * @param _safetyFundPercent Percentage of the safety fund * @param _serviceFeePercent Percentage of the service fee * @param _baycPoolInterestRate Interest rate for the BAYC pool * @param _maycPoolInterestRate Interest rate for the MAYC pool * @param _bakcPoolInterestRate Interest rate for the BAKC pool */ function initialize( address _cyanVaultTokenAddress, address _cyanSuperAdmin, uint256 _safetyFundPercent, uint256 _serviceFeePercent, uint256 _baycPoolInterestRate, uint256 _maycPoolInterestRate, uint256 _bakcPoolInterestRate ) external initializer { require(_cyanVaultTokenAddress != address(0), "Cyan Vault Token address cannot be zero"); require(_cyanSuperAdmin != address(0), "Cyan Super Admin address cannot be zero"); require(_safetyFundPercent <= 10000, "Safety fund percent must be equal or less than 100 percent"); require(_serviceFeePercent <= 200, "Service fee percent must not be greater than 2 percent"); require(_baycPoolInterestRate <= 10000, "BAYC Pool interest rate must be equal or less than 100 percent"); require(_maycPoolInterestRate <= 10000, "MAYC Pool interest rate must be equal or less than 100 percent"); require(_bakcPoolInterestRate <= 10000, "BAKC Pool interest rate must be equal or less than 100 percent"); __AccessControl_init(); __ReentrancyGuard_init(); __Pausable_init(); cyanVaultTokenContract = CyanVaultTokenV1(_cyanVaultTokenAddress); safetyFundPercent = _safetyFundPercent; serviceFeePercent = _serviceFeePercent; apeCoin.approve(address(apeStaking), type(uint256).max); interestRates[1] = _baycPoolInterestRate; interestRates[2] = _maycPoolInterestRate; interestRates[3] = _bakcPoolInterestRate; _setupRole(DEFAULT_ADMIN_ROLE, _cyanSuperAdmin); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); emit InitializedServiceFeePercent(_serviceFeePercent); emit InitializedSafetyFundPercent(_safetyFundPercent); } /** * @notice Allows a user to deposit ApeCoin into the vault * @param depositInfo Information about the deposit including recipient and amount */ function deposit(DepositInfo calldata depositInfo) external nonReentrant whenNotPaused { require(depositInfo.amount > 0, "Must deposit more than zero"); // Cyan collecting service fee from deposits uint256 cyanServiceFee = (depositInfo.amount * serviceFeePercent) / 10000; uint256 userDepositedAmount = depositInfo.amount - cyanServiceFee; uint256 mintAmount = calculateTokenByCurrency(userDepositedAmount); apeCoin.safeTransferFrom(msg.sender, address(this), depositInfo.amount); amounts.collectedServiceFeeAmount += cyanServiceFee; claimRewardsAndStake(userDepositedAmount); cyanVaultTokenContract.mint(depositInfo.recipient, mintAmount); emit Deposit(depositInfo.recipient, userDepositedAmount, mintAmount); } /** * @notice Allows multiple deposits in a single batch from CyanApeCoinPlan contract * @param deposits An array of DepositInfo struct containing recipient and amount for each deposit */ function depositBatch(DepositInfo[] calldata deposits) external nonReentrant whenNotPaused onlyRole(CYAN_APE_PLAN_ROLE) { uint256 totalAmount; uint256 totalUserDeposits; (uint256 totalCurrency, uint256 totalToken) = getTotalCurrencyAndToken(); if (totalCurrency == 0 || totalToken == 0) { // Setting those to 1 for calculating token price rate totalCurrency = 1; totalToken = 1; } for (uint256 ind; ind < deposits.length; ) { uint256 amount = deposits[ind].amount; if (amount > 0) { address recipient = deposits[ind].recipient; uint256 cyanServiceFee = (amount * serviceFeePercent) / 10000; uint256 userDepositedAmount = amount - cyanServiceFee; uint256 mintAmount = (userDepositedAmount * totalToken) / totalCurrency; totalAmount += amount; totalUserDeposits += userDepositedAmount; cyanVaultTokenContract.mint(recipient, mintAmount); } unchecked { ++ind; } } apeCoin.safeTransferFrom(msg.sender, address(this), totalAmount); amounts.collectedServiceFeeAmount += (totalAmount - totalUserDeposits); claimRewardsAndStake(totalUserDeposits); emit DepositBatch(totalAmount, totalCurrency, totalToken); } /** * @notice Lends a specified amount from the vault * @param to Address to lend to * @param amount Amount to lend * @param poolId Id of the pool */ function lend( address to, uint256 amount, uint256 poolId ) external nonReentrant whenNotPaused onlyRole(CYAN_APE_PLAN_ROLE) { require(to != address(0), "to address cannot be zero"); uint256 maxWithdrawableAmount = getMaxWithdrawableAmount(); require(amount <= maxWithdrawableAmount, "Not enough balance in the Vault"); prepareApeCoinForRetrieval(amount); amounts.loanedAmount[poolId] += amount; apeCoin.safeTransfer(to, amount); emit Lend(to, amount, poolId); } /** * @notice Pays back a loan with profit to the vault * @param amount The loan amount to be paid back * @param profit The profit amount * @param poolId Id of the pool */ function pay( uint256 amount, uint256 profit, uint256 poolId ) external nonReentrant onlyRole(CYAN_APE_PLAN_ROLE) { uint256 totalAmount = amount + profit; apeCoin.safeTransferFrom(msg.sender, address(this), totalAmount); claimRewardsAndStake(totalAmount); if (amount > 0) { amounts.loanedAmount[poolId] -= amount; } if (profit > 0) { if (amounts.estimatedCollectedRewardAmount >= profit) { amounts.estimatedCollectedRewardAmount -= profit; } else { amounts.estimatedCollectedRewardAmount = 0; } } emit PayLoan(amount, profit, poolId); } /** * @notice Allows the Vault to earn interest * @param profit The profit amount */ function earn(uint256 profit) external nonReentrant onlyRole(CYAN_APE_PLAN_ROLE) { apeCoin.safeTransferFrom(msg.sender, address(this), profit); claimRewardsAndStake(profit); if (amounts.estimatedCollectedRewardAmount >= profit) { amounts.estimatedCollectedRewardAmount -= profit; } else { amounts.estimatedCollectedRewardAmount = 0; } emit EarnInterest(profit); } /** * @notice Compounds the rewards in the vault by claiming the collected rewards and staking them */ function autoCompound() external nonReentrant { claimRewardsAndStake(0); emit AutoCompounded(); } /** * @notice Allows a user to withdraw ApeCoin from the vault * @param tokenAmount The amount of tokens to withdraw */ function withdraw(uint256 tokenAmount) external nonReentrant whenNotPaused { require(tokenAmount > 0, "Non-positive token amount"); uint256 withdrawableTokenBalance = getWithdrawableBalance(msg.sender); require(tokenAmount <= withdrawableTokenBalance, "Not enough active balance in Cyan Vault"); uint256 withdrawAmount = calculateCurrencyByToken(tokenAmount); prepareApeCoinForRetrieval(withdrawAmount); cyanVaultTokenContract.burn(msg.sender, tokenAmount); apeCoin.safeTransfer(msg.sender, withdrawAmount); emit Withdraw(msg.sender, withdrawAmount, tokenAmount); } /** * @notice Get the withdrawable balance for a given user * @param user Address of the user * @return uint256 Amount of withdrawable balance for the user */ function getWithdrawableBalance(address user) public view returns (uint256) { uint256 tokenBalance = cyanVaultTokenContract.balanceOf(user); uint256 currencyAmountForToken = calculateCurrencyByToken(tokenBalance); uint256 maxWithdrawableAmount = getMaxWithdrawableAmount(); if (currencyAmountForToken <= maxWithdrawableAmount) { return tokenBalance; } return calculateTokenByCurrency(maxWithdrawableAmount); } /** * @notice Calculate the maximum amount that can be withdrawn considering safety fund percent * @return uint256 Maximum withdrawable amount */ function getMaxWithdrawableAmount() public view returns (uint256) { uint256 util = ((amounts.loanedAmount[1] + amounts.loanedAmount[2] + amounts.loanedAmount[3]) * safetyFundPercent) / 10000; IApeCoinStaking.DashboardStake memory dashboard = apeStaking.getApeCoinStake(address(this)); if (dashboard.deposited + dashboard.unclaimed > util) { return dashboard.deposited + dashboard.unclaimed - util; } return 0; } /** * @notice Gets the current asset amounts * @return Returns the amounts struct, deposited and unclaimed amounts */ function getCurrentAssetAmounts() external view returns ( Amounts memory, uint256, uint256 ) { IApeCoinStaking.DashboardStake memory dashboard = apeStaking.getApeCoinStake(address(this)); return (amounts, dashboard.deposited, dashboard.unclaimed); } /** * @notice Convert a given currency amount to its corresponding token amount * @param amount Amount of currency * @return uint256 Equivalent amount in tokens */ function calculateTokenByCurrency(uint256 amount) public view returns (uint256) { (uint256 totalCurrency, uint256 totalToken) = getTotalCurrencyAndToken(); if (totalCurrency == 0 || totalToken == 0) return amount; return (amount * totalToken) / totalCurrency; } /** * @notice Convert a given token amount to its corresponding currency amount * @param amount Amount of token * @return uint256 Equivalent amount in currency */ function calculateCurrencyByToken(uint256 amount) public view returns (uint256) { (uint256 totalCurrency, uint256 totalToken) = getTotalCurrencyAndToken(); if (totalCurrency == 0 || totalToken == 0) return amount; return (amount * totalCurrency) / totalToken; } /** * @notice Fetches the total currency and token amounts for the vault * @dev This considers the staked, unclaimed, loaned, estimated collected rewards, and interest amounts for the total currency value * @return uint256 Total currency amount * @return uint256 Total token supply of the vault */ function getTotalCurrencyAndToken() private view returns (uint256, uint256) { IApeCoinStaking.DashboardStake memory dashboard = apeStaking.getApeCoinStake(address(this)); uint256 totalCurrency = dashboard.deposited + dashboard.unclaimed + amounts.loanedAmount[1] + amounts.loanedAmount[2] + amounts.loanedAmount[3] + amounts.estimatedCollectedRewardAmount + calculateEstimatedCollectedInterests(dashboard); uint256 totalToken = cyanVaultTokenContract.totalSupply(); return (totalCurrency, totalToken); } /** * @notice Calculate the estimated collected interests based on the current stake status and loaned amounts * @param dashboard The current stake status of the contract * @return uint256 Estimated collected interest */ function calculateEstimatedCollectedInterests(IApeCoinStaking.DashboardStake memory dashboard) private view returns (uint256) { return dashboard.deposited == 0 ? 0 : ((amounts.loanedAmount[1] * interestRates[1] + amounts.loanedAmount[2] * interestRates[2] + amounts.loanedAmount[3] * interestRates[3]) * dashboard.unclaimed) / dashboard.deposited / 10000; } function getPoolInterestRates() external view returns (uint256[4] memory) { return interestRates; } /** * @notice Update the safety fund percentage * @param _safetyFundPercent New percentage value for the safety fund */ function updateSafetyFundPercent(uint256 _safetyFundPercent) external nonReentrant onlyRole(DEFAULT_ADMIN_ROLE) { require(_safetyFundPercent <= 10000, "Safety fund percent must be equal or less than 100 percent"); emit UpdatedSafetyFundPercent(safetyFundPercent, _safetyFundPercent); safetyFundPercent = _safetyFundPercent; } /** * @notice Update the service fee percentage. * This is the fee taken by Cyan for its services. * @param _serviceFeePercent The new fee percentage to be set. */ function updateServiceFeePercent(uint256 _serviceFeePercent) external nonReentrant onlyRole(DEFAULT_ADMIN_ROLE) { require(_serviceFeePercent <= 200, "Service fee percent must not be greater than 2 percent"); emit UpdatedServiceFeePercent(serviceFeePercent, _serviceFeePercent); serviceFeePercent = _serviceFeePercent; } /** * @notice Updates the interest rate for a particular staking pool. * @param poolId The ID of the pool to be updated. * @param interestRate The new interest rate to be set. */ function updatePoolInterestRate(uint256 poolId, uint256 interestRate) external onlyRole(DEFAULT_ADMIN_ROLE) { require(interestRate <= 10000, "Interest rate percent must not be greater than 100 percent"); interestRates[poolId] = interestRate; emit InterestRateUpdated(poolId, interestRate); } /** * @notice Allows the admin to collect the accumulated service fee. */ function collectServiceFee() external nonReentrant onlyRole(DEFAULT_ADMIN_ROLE) { require(amounts.collectedServiceFeeAmount > 0, "Not enough collected service fee"); apeCoin.safeTransfer(msg.sender, amounts.collectedServiceFeeAmount); amounts.collectedServiceFeeAmount = 0; emit CollectedServiceFee(); } /** * @notice Claims rewards and then stakes them back into the ApeCoin staking contract. * @param amount The amount of ApeCoin to be staked. */ function claimRewardsAndStake(uint256 amount) private { IApeCoinStaking.DashboardStake memory dashboard = apeStaking.getApeCoinStake(address(this)); if (dashboard.unclaimed > 0) { if (dashboard.unclaimed + amount < APE_COIN_PRECISION) { apeStaking.withdrawApeCoin(dashboard.deposited, address(this)); depositToApeStaking(dashboard.unclaimed + dashboard.deposited + amount); } else { apeStaking.claimApeCoin(address(this)); depositToApeStaking(dashboard.unclaimed + amount); } } else { depositToApeStaking(amount); } amounts.estimatedCollectedRewardAmount += calculateEstimatedCollectedInterests(dashboard); } /** * @notice Prepares a specific amount of ApeCoin for retrieval from the staking contract. * @param amount The amount of ApeCoin to be prepared for retrieval. */ function prepareApeCoinForRetrieval(uint256 amount) private { IApeCoinStaking.DashboardStake memory dashboard = apeStaking.getApeCoinStake(address(this)); if (dashboard.unclaimed > 0) { apeStaking.withdrawApeCoin(dashboard.deposited, address(this)); depositToApeStaking(dashboard.unclaimed + dashboard.deposited - amount); } else { apeStaking.withdrawApeCoin(amount, address(this)); } amounts.estimatedCollectedRewardAmount += calculateEstimatedCollectedInterests(dashboard); } /** * @notice Deposits ApeCoin into the ApeCoin staking contract. * @param amount The amount of ApeCoin to be deposited. */ function depositToApeStaking(uint256 amount) private { if (amount > 0) { apeStaking.depositApeCoin(amount, address(this)); } } /** * @notice Approve the max amount of ApeCoin for the ApeCoin staking contract */ function apeCoinApproval() external nonReentrant onlyRole(DEFAULT_ADMIN_ROLE) { apeCoin.approve(address(apeStaking), type(uint256).max); } function pause() external nonReentrant onlyRole(DEFAULT_ADMIN_ROLE) { _pause(); } function unpause() external nonReentrant onlyRole(DEFAULT_ADMIN_ROLE) { _unpause(); } }
11,206
717
// Used for selling the options contractswith the parameters chosen by the option buyersuch as the period of holding, option size (amount),strike price and the premium to be paid for the option. holder The option buyer address period The option period amount The option size strike The option strikereturn id ID of ERC721 token linked to the option /
) external override returns (uint256 id) { if (strike == 0) strike = _currentPrice(); uint256 balance = totalBalance(); uint256 amountToBeLocked = _calculateLockedAmount(amount); require(period >= 1 days, "Pool Error: The period is too short"); require(period <= 90 days, "Pool Error: The period is too long"); require( (lockedAmount + amountToBeLocked) * 100 <= balance * maxUtilizationRate, "Pool Error: The amount is too large" ); (uint256 settlementFee, uint256 premium) = _calculateTotalPremium(period, amount, strike); uint256 hedgedPremiumTotal = (premium * hedgedBalance) / balance; uint256 hedgeFee = (hedgedPremiumTotal * hedgeFeeRate) / 100; uint256 hedgePremium = hedgedPremiumTotal - hedgeFee; uint256 unhedgePremium = premium - hedgedPremiumTotal; lockedAmount += amountToBeLocked; id = optionsManager.createOptionFor(holder); options[id] = Option( OptionState.Active, strike, amount, amountToBeLocked, block.timestamp + period, hedgePremium, unhedgePremium ); token.safeTransferFrom( _msgSender(), address(this), premium + settlementFee ); token.safeTransfer(address(settlementFeeRecipient), settlementFee); settlementFeeRecipient.distributeUnrealizedRewards(); if (hedgeFee > 0) token.safeTransfer(hedgePool, hedgeFee); emit Acquired(id, settlementFee, premium); }
) external override returns (uint256 id) { if (strike == 0) strike = _currentPrice(); uint256 balance = totalBalance(); uint256 amountToBeLocked = _calculateLockedAmount(amount); require(period >= 1 days, "Pool Error: The period is too short"); require(period <= 90 days, "Pool Error: The period is too long"); require( (lockedAmount + amountToBeLocked) * 100 <= balance * maxUtilizationRate, "Pool Error: The amount is too large" ); (uint256 settlementFee, uint256 premium) = _calculateTotalPremium(period, amount, strike); uint256 hedgedPremiumTotal = (premium * hedgedBalance) / balance; uint256 hedgeFee = (hedgedPremiumTotal * hedgeFeeRate) / 100; uint256 hedgePremium = hedgedPremiumTotal - hedgeFee; uint256 unhedgePremium = premium - hedgedPremiumTotal; lockedAmount += amountToBeLocked; id = optionsManager.createOptionFor(holder); options[id] = Option( OptionState.Active, strike, amount, amountToBeLocked, block.timestamp + period, hedgePremium, unhedgePremium ); token.safeTransferFrom( _msgSender(), address(this), premium + settlementFee ); token.safeTransfer(address(settlementFeeRecipient), settlementFee); settlementFeeRecipient.distributeUnrealizedRewards(); if (hedgeFee > 0) token.safeTransfer(hedgePool, hedgeFee); emit Acquired(id, settlementFee, premium); }
8,565
145
// Call the specified target and supply the specified data.
(ok, returnData) = target.call.value(amount)(data);
(ok, returnData) = target.call.value(amount)(data);
10,406
30
// return rbool true if proof is valid
function verifyProof( uint[2] memory a, uint[2][2] memory b, uint[2] memory c, uint[1] memory input
function verifyProof( uint[2] memory a, uint[2][2] memory b, uint[2] memory c, uint[1] memory input
38,462
6
// parts[3] e parts[4]
if (greatness > 960) {
if (greatness > 960) {
4,843
60
// It's a punk Compute the punk ID
uint punkId = _createVia.sub(1);
uint punkId = _createVia.sub(1);
34,071
1,258
// Enqueue a request with the DVM.
_requestOraclePrice(disputedLiquidation.liquidationTime); emit LiquidationDisputed( sponsor, disputedLiquidation.liquidator, msg.sender, liquidationId, disputeBondAmount.rawValue ); totalPaid = disputeBondAmount.add(disputedLiquidation.finalFee);
_requestOraclePrice(disputedLiquidation.liquidationTime); emit LiquidationDisputed( sponsor, disputedLiquidation.liquidator, msg.sender, liquidationId, disputeBondAmount.rawValue ); totalPaid = disputeBondAmount.add(disputedLiquidation.finalFee);
10,417