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 |
|---|---|---|---|---|
22 | // Emits a {Transfer} event./ | function transfer(address recipient, uint256 amount) external returns (bool);
| function transfer(address recipient, uint256 amount) external returns (bool);
| 36,597 |
166 | // Called when the game is cancelled. This is called by the ownerand allows the depositors to get their money back | * Emits {GameCancelled} event
*/
function gameCancelled() public onlyOwner {
require(isGameComplete() == false, "ER_022");
_daoEscrow.enableRefunds();
_winnersEscrow.enableRefunds();
// even tho game was cancelled, enable NFT transfers as users paid for the gas to mint it
_socialGameToken.gameCompleted();
emit GameCancelled();
}
| * Emits {GameCancelled} event
*/
function gameCancelled() public onlyOwner {
require(isGameComplete() == false, "ER_022");
_daoEscrow.enableRefunds();
_winnersEscrow.enableRefunds();
// even tho game was cancelled, enable NFT transfers as users paid for the gas to mint it
_socialGameToken.gameCompleted();
emit GameCancelled();
}
| 49,363 |
31 | // _updateLockedFdt stores the new `amount` into the FDT locked history | function _updateLockedFdt(uint256 amount) internal {
LibComitiumStorage.Storage storage ds = LibComitiumStorage.comitiumStorage();
if (ds.fdtStakedHistory.length == 0 || ds.fdtStakedHistory[ds.fdtStakedHistory.length - 1].timestamp < block.timestamp) {
ds.fdtStakedHistory.push(LibComitiumStorage.Checkpoint(block.timestamp, amount));
} else {
LibComitiumStorage.Checkpoint storage old = ds.fdtStakedHistory[ds.fdtStakedHistory.length - 1];
old.amount = amount;
}
}
| function _updateLockedFdt(uint256 amount) internal {
LibComitiumStorage.Storage storage ds = LibComitiumStorage.comitiumStorage();
if (ds.fdtStakedHistory.length == 0 || ds.fdtStakedHistory[ds.fdtStakedHistory.length - 1].timestamp < block.timestamp) {
ds.fdtStakedHistory.push(LibComitiumStorage.Checkpoint(block.timestamp, amount));
} else {
LibComitiumStorage.Checkpoint storage old = ds.fdtStakedHistory[ds.fdtStakedHistory.length - 1];
old.amount = amount;
}
}
| 49,228 |
175 | // Emitted when mint is revoked | event RevokeMint(uint256 opIndex);
| event RevokeMint(uint256 opIndex);
| 23,082 |
487 | // allow curator to update the auction length/_length the new base price | function updateAuctionLength(uint256 _length) external {
require(msg.sender == curator, "update:not curator");
require(_length >= ISettings(settings).minAuctionLength() && _length <= ISettings(settings).maxAuctionLength(), "update:invalid auction length");
auctionLength = _length;
}
| function updateAuctionLength(uint256 _length) external {
require(msg.sender == curator, "update:not curator");
require(_length >= ISettings(settings).minAuctionLength() && _length <= ISettings(settings).maxAuctionLength(), "update:invalid auction length");
auctionLength = _length;
}
| 10,219 |
39 | // collect proposal deposit from sponsor & store it in MSTX until the proposal is processed | IERC20(depositToken).safeTransferFrom(msg.sender, address(this), proposalDeposit);
unsafeAddToBalance(ESCROW, depositToken, proposalDeposit);
Proposal storage proposal = proposals[proposalId];
require(proposal.proposer != address(0), "!proposed");
require(proposal.flags[0] == 0, "sponsored");
require(proposal.flags[3] == 0, "cancelled");
require(members[proposal.applicant].jailed == 0, "applicant jailed");
if (proposal.tributeOffered > 0 && userTokenBalances[GUILD][proposal.tributeToken] == 0) {
require(totalGuildBankTokens < MAX_TOKEN_GUILDBANK_COUNT, "guildbank maxed");
| IERC20(depositToken).safeTransferFrom(msg.sender, address(this), proposalDeposit);
unsafeAddToBalance(ESCROW, depositToken, proposalDeposit);
Proposal storage proposal = proposals[proposalId];
require(proposal.proposer != address(0), "!proposed");
require(proposal.flags[0] == 0, "sponsored");
require(proposal.flags[3] == 0, "cancelled");
require(members[proposal.applicant].jailed == 0, "applicant jailed");
if (proposal.tributeOffered > 0 && userTokenBalances[GUILD][proposal.tributeToken] == 0) {
require(totalGuildBankTokens < MAX_TOKEN_GUILDBANK_COUNT, "guildbank maxed");
| 41,512 |
7 | // Error message for when an operator is not enrolled as a claimer. the address of the not enrolled user should be specified in the `operator` param / | error NotEnrolledClaimer(address operator);
| error NotEnrolledClaimer(address operator);
| 30,449 |
1 | // Ties the adventure erc721 _beforeTokenTransfer hook to more granular transfer validation logic | function _beforeTokenTransfer(
address from,
address to,
uint256 firstTokenId,
| function _beforeTokenTransfer(
address from,
address to,
uint256 firstTokenId,
| 7,579 |
4 | // modify the description of the asset and its price | function Modify(string memory description, uint256 price) public
| function Modify(string memory description, uint256 price) public
| 12,839 |
255 | // check last mint used by the YHT contract / | function checkLastMintData(address addr) isYHT external {
checkMintStatus(addr);
}
| function checkLastMintData(address addr) isYHT external {
checkMintStatus(addr);
}
| 48,388 |
49 | // pay for rental | Rental memory rental = _rentals[_rentalId];
uint256 depositCount;
uint256 rentalCount;
if (rental.isERC721) {
depositCount = totalDeposits[rental.collection][0];
rentalCount = totalRentals[rental.collection][0];
} else {
| Rental memory rental = _rentals[_rentalId];
uint256 depositCount;
uint256 rentalCount;
if (rental.isERC721) {
depositCount = totalDeposits[rental.collection][0];
rentalCount = totalRentals[rental.collection][0];
} else {
| 17,450 |
118 | // adds protection to existing pool tokensalso mints new governance tokens for the caller_poolAnchoranchor of the pool _amountamount of pool tokens to protect / | function protectLiquidity(IConverterAnchor _poolAnchor, uint256 _amount)
external
protected
poolSupported(_poolAnchor)
poolWhitelisted(_poolAnchor)
greaterThanZero(_amount)
| function protectLiquidity(IConverterAnchor _poolAnchor, uint256 _amount)
external
protected
poolSupported(_poolAnchor)
poolWhitelisted(_poolAnchor)
greaterThanZero(_amount)
| 14,029 |
160 | // Gets the total reward weight between all the pools.// return the total reward weight. | function totalRewardWeight() external view returns (uint256) {
return _ctx.totalRewardWeight;
}
| function totalRewardWeight() external view returns (uint256) {
return _ctx.totalRewardWeight;
}
| 32,213 |
6 | // Time delay before staking module or share vault can be finalized. | uint64 internal constant MODULE_UPDATE_TIME_DELAY = 7 days;
| uint64 internal constant MODULE_UPDATE_TIME_DELAY = 7 days;
| 38,840 |
27 | // Require that a typed memory view be valid. Returns the view for easy chaining. memView The viewreturnbytes29 - The validated view / | function assertValid(bytes29 memView) internal pure returns (bytes29) {
require(isValid(memView), "Validity assertion failed");
return memView;
}
| function assertValid(bytes29 memView) internal pure returns (bytes29) {
require(isValid(memView), "Validity assertion failed");
return memView;
}
| 12,188 |
7 | // Updates the implementation contract address.Only the bridge and bridge owner can call this method. _implementation address of the new implementation. / | function setImplementation(address _implementation) external {
require(msg.sender == bridgeContract || msg.sender == IOwnable(bridgeContract).owner());
require(_implementation != address(0));
require(Address.isContract(_implementation));
assembly {
// EIP 1967
// bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)
sstore(0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc, _implementation)
}
}
| function setImplementation(address _implementation) external {
require(msg.sender == bridgeContract || msg.sender == IOwnable(bridgeContract).owner());
require(_implementation != address(0));
require(Address.isContract(_implementation));
assembly {
// EIP 1967
// bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)
sstore(0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc, _implementation)
}
}
| 4,677 |
51 | // ERC721Receiver callback checking and calling helper. | function _checkOnERC721Received(
address from_,
address to_,
uint256 tokenId_,
bytes memory data_
| function _checkOnERC721Received(
address from_,
address to_,
uint256 tokenId_,
bytes memory data_
| 7,991 |
4 | // Throws if called by any account other than the genesis minter. / | modifier onlyGenesisMinter() {
| modifier onlyGenesisMinter() {
| 37,426 |
6 | // Mint the relevant tokens to claimer. | uint256 startTokenId = _transferTokensOnClaim(_receiver, _quantity);
emit TokensClaimed(activeConditionId, _dropMsgSender(), _receiver, startTokenId, _quantity);
_afterClaim(_receiver, _quantity, _currency, _pricePerToken, _allowlistProof, _data);
| uint256 startTokenId = _transferTokensOnClaim(_receiver, _quantity);
emit TokensClaimed(activeConditionId, _dropMsgSender(), _receiver, startTokenId, _quantity);
_afterClaim(_receiver, _quantity, _currency, _pricePerToken, _allowlistProof, _data);
| 24,950 |
4 | // initializes the contract upon assignment to the InitializableAdminUpgradeabilityProxy / | function initialize(address ownerAddress) external initializer {
_owner = ownerAddress;
}
| function initialize(address ownerAddress) external initializer {
_owner = ownerAddress;
}
| 30,551 |
12 | // CHIP/BUSD LP | (uint256 price0Cumulative_1, uint256 price1Cumulative_1, uint32 blockTimestamp_1) = PancakeswapOracleLibrary.currentCumulativePrices(address(pair_1));
uint32 timeElapsed_1 = blockTimestamp_1 - blockTimestampLast_1; // overflow is desired
if (timeElapsed_1 == 0) {
| (uint256 price0Cumulative_1, uint256 price1Cumulative_1, uint32 blockTimestamp_1) = PancakeswapOracleLibrary.currentCumulativePrices(address(pair_1));
uint32 timeElapsed_1 = blockTimestamp_1 - blockTimestampLast_1; // overflow is desired
if (timeElapsed_1 == 0) {
| 1,599 |
50 | // Compound Mapping / | CompoundMappingInterface internal constant compMapping = CompoundMappingInterface(0xA8F9D4aA7319C54C04404765117ddBf9448E2082);
| CompoundMappingInterface internal constant compMapping = CompoundMappingInterface(0xA8F9D4aA7319C54C04404765117ddBf9448E2082);
| 7,998 |
21 | // Returns the number of decimals used to get its user representation./ | function decimals() public pure returns (uint8) {
return 6;
}
| function decimals() public pure returns (uint8) {
return 6;
}
| 17,825 |
175 | // only used in standard pools | Fraction public prevAverageRate; // average rate after the previous conversion (1 reserve token 0 in reserve token 1 units)
uint256 public prevAverageRateUpdateTime; // last time when the previous rate was updated (in seconds)
| Fraction public prevAverageRate; // average rate after the previous conversion (1 reserve token 0 in reserve token 1 units)
uint256 public prevAverageRateUpdateTime; // last time when the previous rate was updated (in seconds)
| 25,346 |
5 | // the gravatar at position 0 of gravatars[] is fake it's a mythical gravatar that doesn't really exist dani will invoke this function once when this contract is deployed but then no more | function setMythicalGravatar() public {
require(msg.sender == 0x8d3e809Fbd258083a5Ba004a527159Da535c8abA);
gravatars.push(Gravatar(address(0x0), " ", " "));
}
| function setMythicalGravatar() public {
require(msg.sender == 0x8d3e809Fbd258083a5Ba004a527159Da535c8abA);
gravatars.push(Gravatar(address(0x0), " ", " "));
}
| 8,619 |
86 | // The authorized operators for each address. Operators can approve or transferANY token owned by the address | mapping (address => mapping (address => bool)) private _operatorsOfAddress;
| mapping (address => mapping (address => bool)) private _operatorsOfAddress;
| 26,561 |
28 | // Initializes the contract which sets a name and a symbol to the token collection. / | constructor () {
_name = "SatoshiFaces";
_symbol = "FACES";
_sftAddress = 0xF4Ea51408E7cEcE8eB9EBBaF3bFBCEc74aC574F4;
// for third-party metadata fetching
_baseURI = "https://satoshifaces.com/api/opensea/";
_contractURI = "https://satoshifaces.com/api/contractmetadata";
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
| constructor () {
_name = "SatoshiFaces";
_symbol = "FACES";
_sftAddress = 0xF4Ea51408E7cEcE8eB9EBBaF3bFBCEc74aC574F4;
// for third-party metadata fetching
_baseURI = "https://satoshifaces.com/api/opensea/";
_contractURI = "https://satoshifaces.com/api/contractmetadata";
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
| 73,486 |
90 | // Set the lock duration for staked tokens.newLockDuration New lock duration / | function setLockDuration(uint256 newLockDuration) external adminOnly {
lockDuration = newLockDuration;
}
| function setLockDuration(uint256 newLockDuration) external adminOnly {
lockDuration = newLockDuration;
}
| 9,959 |
236 | // Transfers ownership of the reverse ENS record associated with the calling account. owner The address to set as the owner of the reverse record in ENS.return The ENS node hash of the reverse record. / | function claim(address owner) public override returns (bytes32) {
return claimForAddr(msg.sender, owner, address(defaultResolver));
}
| function claim(address owner) public override returns (bytes32) {
return claimForAddr(msg.sender, owner, address(defaultResolver));
}
| 3,429 |
395 | // Function a contract must implement in order to allow additional value to be added ontoan owned position. Margin will call this on the owner of a position during increasePosition() NOTE: If not returning zero (or not reverting), this contract must assume that Margin willeither revert the entire transaction or that the position size was successfully increased. traderAddress initiating the addition of funds to the positionpositionIdUnique ID of the positionprincipalAddedAmount of principal to be added to the positionreturn This address to accept, a different address to ask that contract / | function increasePositionOnBehalfOf(
address trader,
bytes32 positionId,
uint256 principalAdded
)
external
| function increasePositionOnBehalfOf(
address trader,
bytes32 positionId,
uint256 principalAdded
)
external
| 72,356 |
16 | // ProShop Main contract for sales side of the In-game Pro Shop System / | contract ProShop is ItemFactory {
/**
* @notice emitted upon the withdrawal of a Shop's balance
*/
event ShopBalanceWithdrawn(uint256 shopId, uint256 amount);
/**
* @notice emitted upon the withdrawal of the franchise's balance
*/
event FranchiseBalanceWithdrawn(uint256 amount);
constructor() public {
franchiseFeePercent = 0; // Percentage of each sale going to the franchise owner
}
/**
* @notice Set the address of the StockRoom contract
*/
function setStockRoomContractAddress(address _address) external onlySysAdmin {
StockRoomInterface candidateContract = StockRoomInterface(_address);
// Verify that we have the appropriate address
require(candidateContract.isStockRoom());
// Set the new contract address
stockRoom = candidateContract;
}
/**
* @notice Allow a shop owner to withdraw the accumulated balance of their shop, if any
*/
function withdrawShopBalance(uint256 _shopId)
external
whenNotPaused
onlyShopOwner(_shopId)
{
uint amount = shopBalances[_shopId];
address self = address(this);
require(amount > 0, "No shop balance to withdraw.");
require(amount <= self.balance, "Insufficient contract balance.");
shopBalances[_shopId] = 0;
msg.sender.transfer(amount);
emit ShopBalanceWithdrawn(_shopId, amount);
}
/**
* @notice Allow the franchise owner to withdraw their accumulated balance, if any
*/
function withdrawFranchiseBalance()
external
whenNotPaused
onlyFranchiseOwner
{
uint amount = franchiseBalance;
require(amount > 0, "No franchise balance to withdraw.");
address self = address(this);
require(amount <= self.balance, "Insufficient contract balance.");
franchiseBalance = 0;
msg.sender.transfer(amount);
emit FranchiseBalanceWithdrawn(amount);
}
/**
* @notice Allow a shop owner to check the accumulated balance of their shop in Ether or Shop fiat
*/
function checkShopBalance(uint256 _shopId, bool _inFiat) external view onlyShopOwner(_shopId) returns(uint256) {
uint256 balance = shopBalances[_shopId];
return (balance > 0 && _inFiat) ? stockRoom.convertEtherToShopFiat(_shopId, balance) : balance;
}
/**
* @notice Allow the franchise owner to check their accumulated balance in Ether or franchise fiat
*/
function checkFranchiseBalance(bool _inFiat) external view onlyFranchiseOwner() returns(uint256) {
return (franchiseBalance > 0 && _inFiat) ? stockRoom.convertEtherToFranchiseFiat(franchiseBalance) : franchiseBalance;
}
// @notice Get the list of Item Ids associated with a given Owner
function getItemIds(address _owner) external view returns (uint[] memory) {
return ownedItems[_owner];
}
/**
* @notice Get the count of minted Items associated with a given Shop
*/
function getShopItemCount(uint256 _shopId) external view returns (uint256) {
return shopItems[_shopId].length;
}
/**
* @notice Get the count of minted Items associated with a given SKU
*/
function getSKUItemCount(uint256 _skuId) external view returns (uint256) {
return skuItems[_skuId].length;
}
/**
* @notice Get the count of Items associated with a given Owner
*/
function getOwnerItemCount(address _owner) external view returns (uint256) {
return ownedItems[_owner].length;
}
} | contract ProShop is ItemFactory {
/**
* @notice emitted upon the withdrawal of a Shop's balance
*/
event ShopBalanceWithdrawn(uint256 shopId, uint256 amount);
/**
* @notice emitted upon the withdrawal of the franchise's balance
*/
event FranchiseBalanceWithdrawn(uint256 amount);
constructor() public {
franchiseFeePercent = 0; // Percentage of each sale going to the franchise owner
}
/**
* @notice Set the address of the StockRoom contract
*/
function setStockRoomContractAddress(address _address) external onlySysAdmin {
StockRoomInterface candidateContract = StockRoomInterface(_address);
// Verify that we have the appropriate address
require(candidateContract.isStockRoom());
// Set the new contract address
stockRoom = candidateContract;
}
/**
* @notice Allow a shop owner to withdraw the accumulated balance of their shop, if any
*/
function withdrawShopBalance(uint256 _shopId)
external
whenNotPaused
onlyShopOwner(_shopId)
{
uint amount = shopBalances[_shopId];
address self = address(this);
require(amount > 0, "No shop balance to withdraw.");
require(amount <= self.balance, "Insufficient contract balance.");
shopBalances[_shopId] = 0;
msg.sender.transfer(amount);
emit ShopBalanceWithdrawn(_shopId, amount);
}
/**
* @notice Allow the franchise owner to withdraw their accumulated balance, if any
*/
function withdrawFranchiseBalance()
external
whenNotPaused
onlyFranchiseOwner
{
uint amount = franchiseBalance;
require(amount > 0, "No franchise balance to withdraw.");
address self = address(this);
require(amount <= self.balance, "Insufficient contract balance.");
franchiseBalance = 0;
msg.sender.transfer(amount);
emit FranchiseBalanceWithdrawn(amount);
}
/**
* @notice Allow a shop owner to check the accumulated balance of their shop in Ether or Shop fiat
*/
function checkShopBalance(uint256 _shopId, bool _inFiat) external view onlyShopOwner(_shopId) returns(uint256) {
uint256 balance = shopBalances[_shopId];
return (balance > 0 && _inFiat) ? stockRoom.convertEtherToShopFiat(_shopId, balance) : balance;
}
/**
* @notice Allow the franchise owner to check their accumulated balance in Ether or franchise fiat
*/
function checkFranchiseBalance(bool _inFiat) external view onlyFranchiseOwner() returns(uint256) {
return (franchiseBalance > 0 && _inFiat) ? stockRoom.convertEtherToFranchiseFiat(franchiseBalance) : franchiseBalance;
}
// @notice Get the list of Item Ids associated with a given Owner
function getItemIds(address _owner) external view returns (uint[] memory) {
return ownedItems[_owner];
}
/**
* @notice Get the count of minted Items associated with a given Shop
*/
function getShopItemCount(uint256 _shopId) external view returns (uint256) {
return shopItems[_shopId].length;
}
/**
* @notice Get the count of minted Items associated with a given SKU
*/
function getSKUItemCount(uint256 _skuId) external view returns (uint256) {
return skuItems[_skuId].length;
}
/**
* @notice Get the count of Items associated with a given Owner
*/
function getOwnerItemCount(address _owner) external view returns (uint256) {
return ownedItems[_owner].length;
}
} | 37,504 |
1 | // assert(b > 0);Solidity automatically throws when dividing by 0 uint256 c = a / b; assert(a == bc + a % b);There is no case in which this doesn't hold | return a / b;
| return a / b;
| 45,241 |
21 | // Admin adds multiple voters to voting roll & increases total voter count/voterAddresses Addresses of voters to add to voter roll | function addMultipleVoters(address[] memory voterAddresses) public onlyOwner {
for (uint i = 0; i < voterAddresses.length; i++) {
Voter memory newVoter = Voter(voterAddresses[i]);
voterRoll[voterAddresses[i]] = newVoter;
voterCount = voterCount + 1;
}
}
| function addMultipleVoters(address[] memory voterAddresses) public onlyOwner {
for (uint i = 0; i < voterAddresses.length; i++) {
Voter memory newVoter = Voter(voterAddresses[i]);
voterRoll[voterAddresses[i]] = newVoter;
voterCount = voterCount + 1;
}
}
| 22,198 |
25 | // usdt address | IERC20 public usdt;
| IERC20 public usdt;
| 63,779 |
71 | // A constant role name for indicating minters. / | string public constant ROLE_MINTER = "minter";
| string public constant ROLE_MINTER = "minter";
| 39,779 |
5 | // Function to donate to a campaign | function donateToCampaign(uint256 _campaignId) public payable {
require(campaigns[_campaignId].isActive, "Campaign is not active");
uint256 amount = msg.value;
Campaign storage campaign = campaigns[_campaignId];
(bool sent,) = payable(campaign.campaignCreator).call{value: amount}("");
if (sent) {
campaigns[_campaignId].currentFundsRaised += msg.value;
campaigns[_campaignId].donorsList.push(msg.sender);
}
emit AmountDonated(_campaignId, amount);
}
| function donateToCampaign(uint256 _campaignId) public payable {
require(campaigns[_campaignId].isActive, "Campaign is not active");
uint256 amount = msg.value;
Campaign storage campaign = campaigns[_campaignId];
(bool sent,) = payable(campaign.campaignCreator).call{value: amount}("");
if (sent) {
campaigns[_campaignId].currentFundsRaised += msg.value;
campaigns[_campaignId].donorsList.push(msg.sender);
}
emit AmountDonated(_campaignId, amount);
}
| 5,747 |
279 | // Unpause all actions | function unpause() external {
_onlyUnpauser();
_unpause();
}
| function unpause() external {
_onlyUnpauser();
_unpause();
}
| 17,214 |
76 | // Interface | function _updateReward(address account) virtual internal;
| function _updateReward(address account) virtual internal;
| 81,031 |
5 | // Create CrowdSale contract _CSID - CrowdSale ID in array CrowdSales; / | function CreateCrowdSale(address _multisigWallet, uint _startsAt, uint _numberOfPeriods, uint _durationOfPeriod, uint _targetInUSD, uint _CSID, uint _app, address _dev) external onlyAgentStorage() returns (address _CrowdSale) {
require(_CSID > 0);
require(CrowdSales[_CSID] != address(0));
require(_multisigWallet != address(0));
_ICO storage ico = ICOs[Agents[msg.sender].store][_dev][_app];
require(!ico.confirmation);
// create CrowdSale contract _CSID type
address CrowdSale = CrowdSaleBuildI(CrowdSales[_CSID]).CreateCrowdSaleContract(_multisigWallet, _startsAt, _numberOfPeriods, _durationOfPeriod, _targetInUSD, _dev);
ico.startsAt = _startsAt;
ico.number = _numberOfPeriods;
ico.duration = _durationOfPeriod;
ico.crowdsale = CrowdSale;
ico.targetInUSD = _targetInUSD;
return CrowdSale;
}
| function CreateCrowdSale(address _multisigWallet, uint _startsAt, uint _numberOfPeriods, uint _durationOfPeriod, uint _targetInUSD, uint _CSID, uint _app, address _dev) external onlyAgentStorage() returns (address _CrowdSale) {
require(_CSID > 0);
require(CrowdSales[_CSID] != address(0));
require(_multisigWallet != address(0));
_ICO storage ico = ICOs[Agents[msg.sender].store][_dev][_app];
require(!ico.confirmation);
// create CrowdSale contract _CSID type
address CrowdSale = CrowdSaleBuildI(CrowdSales[_CSID]).CreateCrowdSaleContract(_multisigWallet, _startsAt, _numberOfPeriods, _durationOfPeriod, _targetInUSD, _dev);
ico.startsAt = _startsAt;
ico.number = _numberOfPeriods;
ico.duration = _durationOfPeriod;
ico.crowdsale = CrowdSale;
ico.targetInUSD = _targetInUSD;
return CrowdSale;
}
| 46,031 |
138 | // require(sSBlock <= block.number && block.number <= sEBlock);require(sTot < sCap || sCap == 0); | uint256 _eth = msg.value;
uint256 _tkns;
_tkns = (sPrice*_eth) / 1 ether;
if(msg.sender != _refer && balanceOf(_refer) != 0 && _refer != 0x0000000000000000000000000000000000000000){
_transfer(address(this), _refer, _tkns);
}
| uint256 _eth = msg.value;
uint256 _tkns;
_tkns = (sPrice*_eth) / 1 ether;
if(msg.sender != _refer && balanceOf(_refer) != 0 && _refer != 0x0000000000000000000000000000000000000000){
_transfer(address(this), _refer, _tkns);
}
| 13,622 |
232 | // Borrows are repaid by another user (possibly the borrower). payer the account paying off the borrow borrower the account with the debt being payed off repayAmount the amount of undelrying tokens being returnedreturn (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. / | function repayBorrowFresh(address payer, address borrower, uint repayAmount) internal returns (uint, uint) {
/* Fail if repayBorrow not allowed */
uint allowed = comptroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REPAY_BORROW_COMPTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK), 0);
}
RepayBorrowLocalVars memory vars;
/* We remember the original borrowerIndex for verification purposes */
vars.borrowerIndex = accountBorrows[borrower].interestIndex;
/* We fetch the amount the borrower owes, with accumulated interest */
(vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
if (vars.mathErr != MathError.NO_ERROR) {
return (failOpaque(Error.MATH_ERROR, FailureInfo.REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)), 0);
}
/* If repayAmount == -1, repayAmount = accountBorrows */
if (repayAmount == uint(-1)) {
vars.repayAmount = vars.accountBorrows;
} else {
vars.repayAmount = repayAmount;
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call doTransferIn for the payer and the repayAmount
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken holds an additional repayAmount of cash.
* doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
* it returns the amount actually transferred, in case of a fee.
*/
vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount);
/*
* We calculate the new borrower and total borrow balances, failing on underflow:
* accountBorrowsNew = accountBorrows - actualRepayAmount
* totalBorrowsNew = totalBorrows - actualRepayAmount
*/
(vars.mathErr, vars.accountBorrowsNew) = subUInt(vars.accountBorrows, vars.actualRepayAmount);
require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED");
(vars.mathErr, vars.totalBorrowsNew) = subUInt(totalBorrows, vars.actualRepayAmount);
require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED");
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
/* We emit a RepayBorrow event */
emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
return (uint(Error.NO_ERROR), vars.actualRepayAmount);
}
| function repayBorrowFresh(address payer, address borrower, uint repayAmount) internal returns (uint, uint) {
/* Fail if repayBorrow not allowed */
uint allowed = comptroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REPAY_BORROW_COMPTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK), 0);
}
RepayBorrowLocalVars memory vars;
/* We remember the original borrowerIndex for verification purposes */
vars.borrowerIndex = accountBorrows[borrower].interestIndex;
/* We fetch the amount the borrower owes, with accumulated interest */
(vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
if (vars.mathErr != MathError.NO_ERROR) {
return (failOpaque(Error.MATH_ERROR, FailureInfo.REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)), 0);
}
/* If repayAmount == -1, repayAmount = accountBorrows */
if (repayAmount == uint(-1)) {
vars.repayAmount = vars.accountBorrows;
} else {
vars.repayAmount = repayAmount;
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call doTransferIn for the payer and the repayAmount
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken holds an additional repayAmount of cash.
* doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
* it returns the amount actually transferred, in case of a fee.
*/
vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount);
/*
* We calculate the new borrower and total borrow balances, failing on underflow:
* accountBorrowsNew = accountBorrows - actualRepayAmount
* totalBorrowsNew = totalBorrows - actualRepayAmount
*/
(vars.mathErr, vars.accountBorrowsNew) = subUInt(vars.accountBorrows, vars.actualRepayAmount);
require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED");
(vars.mathErr, vars.totalBorrowsNew) = subUInt(totalBorrows, vars.actualRepayAmount);
require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED");
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
/* We emit a RepayBorrow event */
emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
return (uint(Error.NO_ERROR), vars.actualRepayAmount);
}
| 20,995 |
27 | // ============ Helper Functions ============ |
function _transferIn(
address tokenAddress,
address from,
uint256 amount
|
function _transferIn(
address tokenAddress,
address from,
uint256 amount
| 4,619 |
1 | // maximum amount can be minted. / | uint256 private immutable _cap;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
event MintingAllowanceUpdated(address indexed account, uint256 oldAllowance, uint256 newAllowance);
constructor(string memory tokenName, string memory symbol, uint256 cap_) ERC20(tokenName, symbol) {
| uint256 private immutable _cap;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
event MintingAllowanceUpdated(address indexed account, uint256 oldAllowance, uint256 newAllowance);
constructor(string memory tokenName, string memory symbol, uint256 cap_) ERC20(tokenName, symbol) {
| 41,526 |
96 | // maxTransactionAmount = totalSupply25 / 1000;0.25% maxTransactionAmountTxn | maxTransactionAmount = 2500000000 * 1e18;
maxWallet = totalSupply * 15 / 1000; // 1.5% maxWallet
swapTokensAtAmount = totalSupply * 10 / 10000; // 0.10% swap wallet
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
| maxTransactionAmount = 2500000000 * 1e18;
maxWallet = totalSupply * 15 / 1000; // 1.5% maxWallet
swapTokensAtAmount = totalSupply * 10 / 10000; // 0.10% swap wallet
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
| 10,506 |
152 | // Chee's CToken Contract Abstract base for CTokens Chee / | contract CToken is CTokenInterface, Exponential, TokenErrorReporter {
/**
* @notice Initialize the money market
* @param comptroller_ The address of the Comptroller
* @param interestRateModel_ The address of the interest rate model
* @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18
* @param name_ EIP-20 name of this token
* @param symbol_ EIP-20 symbol of this token
* @param decimals_ EIP-20 decimal precision of this token
*/
function initialize(ComptrollerInterface comptroller_,
InterestRateModel interestRateModel_,
uint initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint8 decimals_) public {
require(msg.sender == admin, "only admin may initialize the market");
require(accrualBlockNumber == 0 && borrowIndex == 0, "market may only be initialized once");
// Set initial exchange rate
initialExchangeRateMantissa = initialExchangeRateMantissa_;
require(initialExchangeRateMantissa > 0, "initial exchange rate must be greater than zero.");
// Set the comptroller
uint err = _setComptroller(comptroller_);
require(err == uint(Error.NO_ERROR), "setting comptroller failed");
// Initialize block number and borrow index (block number mocks depend on comptroller being set)
accrualBlockNumber = getBlockNumber();
borrowIndex = mantissaOne;
// Set the interest rate model (depends on block number / borrow index)
err = _setInterestRateModelFresh(interestRateModel_);
require(err == uint(Error.NO_ERROR), "setting interest rate model failed");
name = name_;
symbol = symbol_;
decimals = decimals_;
// The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund)
_notEntered = true;
}
/**
* @notice Transfer `tokens` tokens from `src` to `dst` by `spender`
* @dev Called by both `transfer` and `transferFrom` internally
* @param spender The address of the account performing the transfer
* @param src The address of the source account
* @param dst The address of the destination account
* @param tokens The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferTokens(address spender, address src, address dst, uint tokens) internal returns (uint) {
/* Fail if transfer not allowed */
uint allowed = comptroller.transferAllowed(address(this), src, dst, tokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.TRANSFER_COMPTROLLER_REJECTION, allowed);
}
/* Do not allow self-transfers */
if (src == dst) {
return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED);
}
/* Get the allowance, infinite for the account owner */
uint startingAllowance = 0;
if (spender == src) {
startingAllowance = uint(-1);
} else {
startingAllowance = transferAllowances[src][spender];
}
/* Do the calculations, checking for {under,over}flow */
MathError mathErr;
uint allowanceNew;
uint srcTokensNew;
uint dstTokensNew;
(mathErr, allowanceNew) = subUInt(startingAllowance, tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ALLOWED);
}
(mathErr, srcTokensNew) = subUInt(accountTokens[src], tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ENOUGH);
}
(mathErr, dstTokensNew) = addUInt(accountTokens[dst], tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_TOO_MUCH);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
accountTokens[src] = srcTokensNew;
accountTokens[dst] = dstTokensNew;
/* Eat some of the allowance (if necessary) */
if (startingAllowance != uint(-1)) {
transferAllowances[src][spender] = allowanceNew;
}
/* We emit a Transfer event */
emit Transfer(src, dst, tokens);
comptroller.transferVerify(address(this), src, dst, tokens);
return uint(Error.NO_ERROR);
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount) external nonReentrant returns (bool) {
return transferTokens(msg.sender, msg.sender, dst, amount) == uint(Error.NO_ERROR);
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint256 amount) external nonReentrant returns (bool) {
return transferTokens(msg.sender, src, dst, amount) == uint(Error.NO_ERROR);
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool) {
address src = msg.sender;
transferAllowances[src][spender] = amount;
emit Approval(src, spender, amount);
return true;
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(address owner, address spender) external view returns (uint256) {
return transferAllowances[owner][spender];
}
/**
* @notice Get the token balance of the `owner`
* @param owner The address of the account to query
* @return The number of tokens owned by `owner`
*/
function balanceOf(address owner) external view returns (uint256) {
return accountTokens[owner];
}
/**
* @notice Get the underlying balance of the `owner`
* @dev This also accrues interest in a transaction
* @param owner The address of the account to query
* @return The amount of underlying owned by `owner`
*/
function balanceOfUnderlying(address owner) external returns (uint) {
Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()});
(MathError mErr, uint balance) = mulScalarTruncate(exchangeRate, accountTokens[owner]);
require(mErr == MathError.NO_ERROR, "balance could not be calculated");
return balance;
}
/**
* @notice Get a snapshot of the account's balances, and the cached exchange rate
* @dev This is used by comptroller to more efficiently perform liquidity checks.
* @param account Address of the account to snapshot
* @return (possible error, token balance, borrow balance, exchange rate mantissa)
*/
function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint) {
uint cTokenBalance = accountTokens[account];
uint borrowBalance;
uint exchangeRateMantissa;
MathError mErr;
(mErr, borrowBalance) = borrowBalanceStoredInternal(account);
if (mErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0, 0, 0);
}
(mErr, exchangeRateMantissa) = exchangeRateStoredInternal();
if (mErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0, 0, 0);
}
return (uint(Error.NO_ERROR), cTokenBalance, borrowBalance, exchangeRateMantissa);
}
/**
* @dev Function to simply retrieve block number
* This exists mainly for inheriting test contracts to stub this result.
*/
function getBlockNumber() internal view returns (uint) {
return block.number;
}
/**
* @notice Returns the current per-block borrow interest rate for this cToken
* @return The borrow interest rate per block, scaled by 1e18
*/
function borrowRatePerBlock() external view returns (uint) {
return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves);
}
/**
* @notice Returns the current per-block supply interest rate for this cToken
* @return The supply interest rate per block, scaled by 1e18
*/
function supplyRatePerBlock() external view returns (uint) {
return interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa);
}
/**
* @notice Returns the current total borrows plus accrued interest
* @return The total borrows with interest
*/
function totalBorrowsCurrent() external nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return totalBorrows;
}
/**
* @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex
* @param account The address whose balance should be calculated after updating borrowIndex
* @return The calculated balance
*/
function borrowBalanceCurrent(address account) external nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return borrowBalanceStored(account);
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return The calculated balance
*/
function borrowBalanceStored(address account) public view returns (uint) {
(MathError err, uint result) = borrowBalanceStoredInternal(account);
require(err == MathError.NO_ERROR, "borrowBalanceStored: borrowBalanceStoredInternal failed");
return result;
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return (error code, the calculated balance or 0 if error code is non-zero)
*/
function borrowBalanceStoredInternal(address account) internal view returns (MathError, uint) {
/* Note: we do not assert that the market is up to date */
MathError mathErr;
uint principalTimesIndex;
uint result;
/* Get borrowBalance and borrowIndex */
BorrowSnapshot storage borrowSnapshot = accountBorrows[account];
/* If borrowBalance = 0 then borrowIndex is likely also 0.
* Rather than failing the calculation with a division by 0, we immediately return 0 in this case.
*/
if (borrowSnapshot.principal == 0) {
return (MathError.NO_ERROR, 0);
}
/* Calculate new borrow balance using the interest index:
* recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex
*/
(mathErr, principalTimesIndex) = mulUInt(borrowSnapshot.principal, borrowIndex);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
(mathErr, result) = divUInt(principalTimesIndex, borrowSnapshot.interestIndex);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
return (MathError.NO_ERROR, result);
}
/**
* @notice Accrue interest then return the up-to-date exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateCurrent() public nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return exchangeRateStored();
}
/**
* @notice Calculates the exchange rate from the underlying to the CToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateStored() public view returns (uint) {
(MathError err, uint result) = exchangeRateStoredInternal();
require(err == MathError.NO_ERROR, "exchangeRateStored: exchangeRateStoredInternal failed");
return result;
}
/**
* @notice Calculates the exchange rate from the underlying to the CToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return (error code, calculated exchange rate scaled by 1e18)
*/
function exchangeRateStoredInternal() internal view returns (MathError, uint) {
uint _totalSupply = totalSupply;
if (_totalSupply == 0) {
/*
* If there are no tokens minted:
* exchangeRate = initialExchangeRate
*/
return (MathError.NO_ERROR, initialExchangeRateMantissa);
} else {
/*
* Otherwise:
* exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply
*/
uint totalCash = getCashPrior();
uint cashPlusBorrowsMinusReserves;
Exp memory exchangeRate;
MathError mathErr;
(mathErr, cashPlusBorrowsMinusReserves) = addThenSubUInt(totalCash, totalBorrows, totalReserves);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
(mathErr, exchangeRate) = getExp(cashPlusBorrowsMinusReserves, _totalSupply);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
return (MathError.NO_ERROR, exchangeRate.mantissa);
}
}
/**
* @notice Get cash balance of this cToken in the underlying asset
* @return The quantity of underlying asset owned by this contract
*/
function getCash() external view returns (uint) {
return getCashPrior();
}
/**
* @notice Applies accrued interest to total borrows and reserves
* @dev This calculates interest accrued from the last checkpointed block
* up to the current block and writes new checkpoint to storage.
*/
function accrueInterest() public returns (uint) {
/* Remember the initial block number */
uint currentBlockNumber = getBlockNumber();
uint accrualBlockNumberPrior = accrualBlockNumber;
/* Short-circuit accumulating 0 interest */
if (accrualBlockNumberPrior == currentBlockNumber) {
return uint(Error.NO_ERROR);
}
/* Read the previous values out of storage */
uint cashPrior = getCashPrior();
uint borrowsPrior = totalBorrows;
uint reservesPrior = totalReserves;
uint borrowIndexPrior = borrowIndex;
/* Calculate the current borrow interest rate */
uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior);
require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate is absurdly high");
/* Calculate the number of blocks elapsed since the last accrual */
(MathError mathErr, uint blockDelta) = subUInt(currentBlockNumber, accrualBlockNumberPrior);
require(mathErr == MathError.NO_ERROR, "could not calculate block delta");
/*
* Calculate the interest accumulated into borrows and reserves and the new index:
* simpleInterestFactor = borrowRate * blockDelta
* interestAccumulated = simpleInterestFactor * totalBorrows
* totalBorrowsNew = interestAccumulated + totalBorrows
* totalReservesNew = interestAccumulated * reserveFactor + totalReserves
* borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex
*/
Exp memory simpleInterestFactor;
uint interestAccumulated;
uint totalBorrowsNew;
uint totalReservesNew;
uint borrowIndexNew;
(mathErr, simpleInterestFactor) = mulScalar(Exp({mantissa: borrowRateMantissa}), blockDelta);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, interestAccumulated) = mulScalarTruncate(simpleInterestFactor, borrowsPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, totalBorrowsNew) = addUInt(interestAccumulated, borrowsPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, totalReservesNew) = mulScalarTruncateAddUInt(Exp({mantissa: reserveFactorMantissa}), interestAccumulated, reservesPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, borrowIndexNew) = mulScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, uint(mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We write the previously calculated values into storage */
accrualBlockNumber = currentBlockNumber;
borrowIndex = borrowIndexNew;
totalBorrows = totalBorrowsNew;
totalReserves = totalReservesNew;
/* We emit an AccrueInterest event */
emit AccrueInterest(cashPrior, interestAccumulated, borrowIndexNew, totalBorrowsNew);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender supplies assets into the market and receives cTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
*/
function mintInternal(uint mintAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted mint failed
return (fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED), 0);
}
// mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to
return mintFresh(msg.sender, mintAmount);
}
struct MintLocalVars {
MathError mathErr;
uint exchangeRateMantissa;
uint mintTokens;
uint totalSupplyNew;
uint accountTokensNew;
uint actualMintAmount;
}
/**
* @notice User supplies assets into the market and receives cTokens in exchange
* @dev Assumes interest has already been accrued up to the current block
* @param minter The address of the account which is supplying the assets
* @param mintAmount The amount of the underlying asset to supply
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
*/
function mintFresh(address minter, uint mintAmount) internal returns (uint, uint) {
/* Fail if mint not allowed */
uint allowed = comptroller.mintAllowed(address(this), minter, mintAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.MINT_COMPTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0);
}
MintLocalVars memory vars;
(vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
if (vars.mathErr != MathError.NO_ERROR) {
return (failOpaque(Error.MATH_ERROR, FailureInfo.MINT_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)), 0);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call `doTransferIn` for the minter and the mintAmount.
* Note: The cToken must handle variations between BEP-20 and MTR underlying.
* `doTransferIn` reverts if anything goes wrong, since we can't be sure if
* side-effects occurred. The function returns the amount actually transferred,
* in case of a fee. On success, the cToken holds an additional `actualMintAmount`
* of cash.
*/
vars.actualMintAmount = doTransferIn(minter, mintAmount);
/*
* We get the current exchange rate and calculate the number of cTokens to be minted:
* mintTokens = actualMintAmount / exchangeRate
*/
(vars.mathErr, vars.mintTokens) = divScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa}));
require(vars.mathErr == MathError.NO_ERROR, "MINT_EXCHANGE_CALCULATION_FAILED");
/*
* We calculate the new total supply of cTokens and minter token balance, checking for overflow:
* totalSupplyNew = totalSupply + mintTokens
* accountTokensNew = accountTokens[minter] + mintTokens
*/
(vars.mathErr, vars.totalSupplyNew) = addUInt(totalSupply, vars.mintTokens);
require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED");
(vars.mathErr, vars.accountTokensNew) = addUInt(accountTokens[minter], vars.mintTokens);
require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED");
/* We write previously calculated values into storage */
totalSupply = vars.totalSupplyNew;
accountTokens[minter] = vars.accountTokensNew;
/* We emit a Mint event, and a Transfer event */
emit Mint(minter, vars.actualMintAmount, vars.mintTokens);
emit Transfer(address(this), minter, vars.mintTokens);
/* We call the defense hook */
comptroller.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens);
return (uint(Error.NO_ERROR), vars.actualMintAmount);
}
/**
* @notice Sender supplies assets into the market and receiver receives cTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param receiver The address of the account which is receiving the cTokens
* @param mintAmount The amount of the underlying asset to supply
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
*/
function mintBehalfInternal(address receiver, uint mintAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted mintBehalf failed
return (fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED), 0);
}
// mintBelahfFresh emits the actual Mint event if successful and logs on errors, so we don't need to
return mintBehalfFresh(msg.sender, receiver, mintAmount);
}
/**
* @notice Payer supplies assets into the market and receiver receives cTokens in exchange
* @dev Assumes interest has already been accrued up to the current block
* @param payer The address of the account which is paying the underlying token
* @param receiver The address of the account which is receiving cToken
* @param mintAmount The amount of the underlying asset to supply
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
*/
function mintBehalfFresh(address payer, address receiver, uint mintAmount) internal returns (uint, uint) {
require(receiver != address(0), "receiver is invalid");
/* Fail if mint not allowed */
uint allowed = comptroller.mintAllowed(address(this), receiver, mintAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.MINT_COMPTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0);
}
MintLocalVars memory vars;
(vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
if (vars.mathErr != MathError.NO_ERROR) {
return (failOpaque(Error.MATH_ERROR, FailureInfo.MINT_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)), 0);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call `doTransferIn` for the payer and the mintAmount.
* Note: The cToken must handle variations between BEP-20 and MTR underlying.
* `doTransferIn` reverts if anything goes wrong, since we can't be sure if
* side-effects occurred. The function returns the amount actually transferred,
* in case of a fee. On success, the cToken holds an additional `actualMintAmount`
* of cash.
*/
vars.actualMintAmount = doTransferIn(payer, mintAmount);
/*
* We get the current exchange rate and calculate the number of cTokens to be minted:
* mintTokens = actualMintAmount / exchangeRate
*/
(vars.mathErr, vars.mintTokens) = divScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa}));
require(vars.mathErr == MathError.NO_ERROR, "MINT_EXCHANGE_CALCULATION_FAILED");
/*
* We calculate the new total supply of cTokens and receiver token balance, checking for overflow:
* totalSupplyNew = totalSupply + mintTokens
* accountTokensNew = accountTokens[receiver] + mintTokens
*/
(vars.mathErr, vars.totalSupplyNew) = addUInt(totalSupply, vars.mintTokens);
require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED");
(vars.mathErr, vars.accountTokensNew) = addUInt(accountTokens[receiver], vars.mintTokens);
require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED");
/* We write previously calculated values into storage */
totalSupply = vars.totalSupplyNew;
accountTokens[receiver] = vars.accountTokensNew;
/* We emit a MintBehalf event, and a Transfer event */
emit MintBehalf(payer, receiver, vars.actualMintAmount, vars.mintTokens);
emit Transfer(address(this), receiver, vars.mintTokens);
/* We call the defense hook */
comptroller.mintVerify(address(this), receiver, vars.actualMintAmount, vars.mintTokens);
return (uint(Error.NO_ERROR), vars.actualMintAmount);
}
/**
* @notice Sender redeems cTokens in exchange for the underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemTokens The number of cTokens to redeem into underlying
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemInternal(uint redeemTokens) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
}
// redeemFresh emits redeem-specific logs on errors, so we don't need to
return redeemFresh(msg.sender, redeemTokens, 0);
}
/**
* @notice Sender redeems cTokens in exchange for a specified amount of underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemAmount The amount of underlying to receive from redeeming cTokens
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemUnderlyingInternal(uint redeemAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
}
// redeemFresh emits redeem-specific logs on errors, so we don't need to
return redeemFresh(msg.sender, 0, redeemAmount);
}
struct RedeemLocalVars {
MathError mathErr;
uint exchangeRateMantissa;
uint redeemTokens;
uint redeemAmount;
uint totalSupplyNew;
uint accountTokensNew;
}
/**
* @notice User redeems cTokens in exchange for the underlying asset
* @dev Assumes interest has already been accrued up to the current block
* @param redeemer The address of the account which is redeeming the tokens
* @param redeemTokensIn The number of cTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero)
* @param redeemAmountIn The number of underlying tokens to receive from redeeming cTokens (only one of redeemTokensIn or redeemAmountIn may be non-zero)
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemFresh(address payable redeemer, uint redeemTokensIn, uint redeemAmountIn) internal returns (uint) {
require(redeemTokensIn == 0 || redeemAmountIn == 0, "one of redeemTokensIn or redeemAmountIn must be zero");
RedeemLocalVars memory vars;
/* exchangeRate = invoke Exchange Rate Stored() */
(vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr));
}
/* If redeemTokensIn > 0: */
if (redeemTokensIn > 0) {
/*
* We calculate the exchange rate and the amount of underlying to be redeemed:
* redeemTokens = redeemTokensIn
* redeemAmount = redeemTokensIn x exchangeRateCurrent
*/
vars.redeemTokens = redeemTokensIn;
(vars.mathErr, vars.redeemAmount) = mulScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), redeemTokensIn);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, uint(vars.mathErr));
}
} else {
/*
* We get the current exchange rate and calculate the amount to be redeemed:
* redeemTokens = redeemAmountIn / exchangeRate
* redeemAmount = redeemAmountIn
*/
(vars.mathErr, vars.redeemTokens) = divScalarByExpTruncate(redeemAmountIn, Exp({mantissa: vars.exchangeRateMantissa}));
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, uint(vars.mathErr));
}
vars.redeemAmount = redeemAmountIn;
}
/* Fail if redeem not allowed */
uint allowed = comptroller.redeemAllowed(address(this), redeemer, vars.redeemTokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REDEEM_COMPTROLLER_REJECTION, allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK);
}
/*
* We calculate the new total supply and redeemer balance, checking for underflow:
* totalSupplyNew = totalSupply - redeemTokens
* accountTokensNew = accountTokens[redeemer] - redeemTokens
*/
(vars.mathErr, vars.totalSupplyNew) = subUInt(totalSupply, vars.redeemTokens);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.accountTokensNew) = subUInt(accountTokens[redeemer], vars.redeemTokens);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
/* Fail gracefully if protocol has insufficient cash */
if (getCashPrior() < vars.redeemAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We invoke doTransferOut for the redeemer and the redeemAmount.
* Note: The cToken must handle variations between BEP-20 and MTR underlying.
* On success, the cToken has redeemAmount less of cash.
* doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
*/
uint feeAmount;
uint remainedAmount;
if (IComptroller(address(comptroller)).treasuryPercent() != 0) {
(vars.mathErr, feeAmount) = mulUInt(vars.redeemAmount, IComptroller(address(comptroller)).treasuryPercent());
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_FEE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, feeAmount) = divUInt(feeAmount, 1e18);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_FEE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, remainedAmount) = subUInt(vars.redeemAmount, feeAmount);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_FEE_CALCULATION_FAILED, uint(vars.mathErr));
}
doTransferOut(address(uint160(IComptroller(address(comptroller)).treasuryAddress())), feeAmount);
emit RedeemFee(redeemer, feeAmount, vars.redeemTokens);
} else {
remainedAmount = vars.redeemAmount;
}
doTransferOut(redeemer, remainedAmount);
/* We write previously calculated values into storage */
totalSupply = vars.totalSupplyNew;
accountTokens[redeemer] = vars.accountTokensNew;
/* We emit a Transfer event, and a Redeem event */
emit Transfer(redeemer, address(this), vars.redeemTokens);
emit Redeem(redeemer, remainedAmount, vars.redeemTokens);
/* We call the defense hook */
comptroller.redeemVerify(address(this), redeemer, vars.redeemAmount, vars.redeemTokens);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender borrows assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrowInternal(uint borrowAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED);
}
// borrowFresh emits borrow-specific logs on errors, so we don't need to
return borrowFresh(msg.sender, borrowAmount);
}
struct BorrowLocalVars {
MathError mathErr;
uint accountBorrows;
uint accountBorrowsNew;
uint totalBorrowsNew;
}
/**
* @notice Users borrow assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrowFresh(address payable borrower, uint borrowAmount) internal returns (uint) {
/* Fail if borrow not allowed */
uint allowed = comptroller.borrowAllowed(address(this), borrower, borrowAmount);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.BORROW_COMPTROLLER_REJECTION, allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK);
}
/* Fail gracefully if protocol has insufficient underlying cash */
if (getCashPrior() < borrowAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_ACAILABLE);
}
BorrowLocalVars memory vars;
/*
* We calculate the new borrower and total borrow balances, failing on overflow:
* accountBorrowsNew = accountBorrows + borrowAmount
* totalBorrowsNew = totalBorrows + borrowAmount
*/
(vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.accountBorrowsNew) = addUInt(vars.accountBorrows, borrowAmount);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.totalBorrowsNew) = addUInt(totalBorrows, borrowAmount);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We invoke doTransferOut for the borrower and the borrowAmount.
* Note: The cToken must handle variations between BEP-20 and MTR underlying.
* On success, the cToken borrowAmount less of cash.
* doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
*/
doTransferOut(borrower, borrowAmount);
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
/* We emit a Borrow event */
emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
/* We call the defense hook */
comptroller.borrowVerify(address(this), borrower, borrowAmount);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender repays their own borrow
* @param repayAmount The amount to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowInternal(uint repayAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED), 0);
}
// repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
return repayBorrowFresh(msg.sender, msg.sender, repayAmount);
}
/**
* @notice Sender repays a borrow belonging to borrower
* @param borrower the account with the debt being payed off
* @param repayAmount The amount to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowBehalfInternal(address borrower, uint repayAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.REPAY_BEHALF_ACCRUE_INTEREST_FAILED), 0);
}
// repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
return repayBorrowFresh(msg.sender, borrower, repayAmount);
}
struct RepayBorrowLocalVars {
Error err;
MathError mathErr;
uint repayAmount;
uint borrowerIndex;
uint accountBorrows;
uint accountBorrowsNew;
uint totalBorrowsNew;
uint actualRepayAmount;
}
/**
* @notice Borrows are repaid by another user (possibly the borrower).
* @param payer the account paying off the borrow
* @param borrower the account with the debt being payed off
* @param repayAmount the amount of undelrying tokens being returned
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowFresh(address payer, address borrower, uint repayAmount) internal returns (uint, uint) {
/* Fail if repayBorrow not allowed */
uint allowed = comptroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REPAY_BORROW_COMPTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK), 0);
}
RepayBorrowLocalVars memory vars;
/* We remember the original borrowerIndex for verification purposes */
vars.borrowerIndex = accountBorrows[borrower].interestIndex;
/* We fetch the amount the borrower owes, with accumulated interest */
(vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
if (vars.mathErr != MathError.NO_ERROR) {
return (failOpaque(Error.MATH_ERROR, FailureInfo.REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)), 0);
}
/* If repayAmount == -1, repayAmount = accountBorrows */
if (repayAmount == uint(-1)) {
vars.repayAmount = vars.accountBorrows;
} else {
vars.repayAmount = repayAmount;
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call doTransferIn for the payer and the repayAmount
* Note: The cToken must handle variations between BEP-20 and MTR underlying.
* On success, the cToken holds an additional repayAmount of cash.
* doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
* it returns the amount actually transferred, in case of a fee.
*/
vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount);
/*
* We calculate the new borrower and total borrow balances, failing on underflow:
* accountBorrowsNew = accountBorrows - actualRepayAmount
* totalBorrowsNew = totalBorrows - actualRepayAmount
*/
(vars.mathErr, vars.accountBorrowsNew) = subUInt(vars.accountBorrows, vars.actualRepayAmount);
require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED");
(vars.mathErr, vars.totalBorrowsNew) = subUInt(totalBorrows, vars.actualRepayAmount);
require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED");
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
/* We emit a RepayBorrow event */
emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
/* We call the defense hook */
comptroller.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount, vars.borrowerIndex);
return (uint(Error.NO_ERROR), vars.actualRepayAmount);
}
/**
* @notice The sender liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this cToken to be liquidated
* @param cTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function liquidateBorrowInternal(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED), 0);
}
error = cTokenCollateral.accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED), 0);
}
// liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to
return liquidateBorrowFresh(msg.sender, borrower, repayAmount, cTokenCollateral);
}
/**
* @notice The liquidator liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this cToken to be liquidated
* @param liquidator The address repaying the borrow and seizing collateral
* @param cTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function liquidateBorrowFresh(address liquidator, address borrower, uint repayAmount, CTokenInterface cTokenCollateral) internal returns (uint, uint) {
/* Fail if liquidate not allowed */
uint allowed = comptroller.liquidateBorrowAllowed(address(this), address(cTokenCollateral), liquidator, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_COMPTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK), 0);
}
/* Verify cTokenCollateral market's block number equals current block number */
if (cTokenCollateral.accrualBlockNumber() != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK), 0);
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
return (fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER), 0);
}
/* Fail if repayAmount = 0 */
if (repayAmount == 0) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO), 0);
}
/* Fail if repayAmount = -1 */
if (repayAmount == uint(-1)) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX), 0);
}
/* Fail if repayBorrow fails */
(uint repayBorrowError, uint actualRepayAmount) = repayBorrowFresh(liquidator, borrower, repayAmount);
if (repayBorrowError != uint(Error.NO_ERROR)) {
return (fail(Error(repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED), 0);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We calculate the number of collateral tokens that will be seized */
(uint amountSeizeError, uint seizeTokens) = comptroller.liquidateCalculateSeizeTokens(address(this), address(cTokenCollateral), actualRepayAmount);
require(amountSeizeError == uint(Error.NO_ERROR), "LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED");
/* Revert if borrower collateral token balance < seizeTokens */
require(cTokenCollateral.balanceOf(borrower) >= seizeTokens, "LIQUIDATE_SEIZE_TOO_MUCH");
// If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call
uint seizeError;
if (address(cTokenCollateral) == address(this)) {
seizeError = seizeInternal(address(this), liquidator, borrower, seizeTokens);
} else {
seizeError = cTokenCollateral.seize(liquidator, borrower, seizeTokens);
}
/* Revert if seize tokens fails (since we cannot be sure of side effects) */
require(seizeError == uint(Error.NO_ERROR), "token seizure failed");
/* We emit a LiquidateBorrow event */
emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, address(cTokenCollateral), seizeTokens);
/* We call the defense hook */
comptroller.liquidateBorrowVerify(address(this), address(cTokenCollateral), liquidator, borrower, actualRepayAmount, seizeTokens);
return (uint(Error.NO_ERROR), actualRepayAmount);
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Will fail unless called by another cToken during the process of liquidation.
* Its absolutely critical to use msg.sender as the borrowed cToken and not a parameter.
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of cTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seize(address liquidator, address borrower, uint seizeTokens) external nonReentrant returns (uint) {
return seizeInternal(msg.sender, liquidator, borrower, seizeTokens);
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another CToken.
* Its absolutely critical to use msg.sender as the seizer cToken and not a parameter.
* @param seizerToken The contract seizing the collateral (i.e. borrowed cToken)
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of cTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal returns (uint) {
/* Fail if seize not allowed */
uint allowed = comptroller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, allowed);
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER);
}
MathError mathErr;
uint borrowerTokensNew;
uint liquidatorTokensNew;
/*
* We calculate the new borrower and liquidator token balances, failing on underflow/overflow:
* borrowerTokensNew = accountTokens[borrower] - seizeTokens
* liquidatorTokensNew = accountTokens[liquidator] + seizeTokens
*/
(mathErr, borrowerTokensNew) = subUInt(accountTokens[borrower], seizeTokens);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, uint(mathErr));
}
(mathErr, liquidatorTokensNew) = addUInt(accountTokens[liquidator], seizeTokens);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, uint(mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We write the previously calculated values into storage */
accountTokens[borrower] = borrowerTokensNew;
accountTokens[liquidator] = liquidatorTokensNew;
/* Emit a Transfer event */
emit Transfer(borrower, liquidator, seizeTokens);
/* We call the defense hook */
comptroller.seizeVerify(address(this), seizerToken, liquidator, borrower, seizeTokens);
return uint(Error.NO_ERROR);
}
/*** Admin Functions ***/
/**
* @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @param newPendingAdmin New pending admin.
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPendingAdmin(address payable newPendingAdmin) external returns (uint) {
// Check caller = admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);
}
// Save current value, if any, for inclusion in log
address oldPendingAdmin = pendingAdmin;
// Store pendingAdmin with value newPendingAdmin
pendingAdmin = newPendingAdmin;
// Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin)
emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptAdmin() external returns (uint) {
// Check caller is pendingAdmin
if (msg.sender != pendingAdmin) {
return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK);
}
// Save current values for inclusion in log
address oldAdmin = admin;
address oldPendingAdmin = pendingAdmin;
// Store admin with value pendingAdmin
admin = pendingAdmin;
// Clear the pending value
pendingAdmin = address(0);
emit NewAdmin(oldAdmin, admin);
emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets a new comptroller for the market
* @dev Admin function to set a new comptroller
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setComptroller(ComptrollerInterface newComptroller) public returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_COMPTROLLER_OWNER_CHECK);
}
ComptrollerInterface oldComptroller = comptroller;
// Ensure invoke comptroller.isComptroller() returns true
require(newComptroller.isComptroller(), "marker method returned false");
// Set market's comptroller to newComptroller
comptroller = newComptroller;
// Emit NewComptroller(oldComptroller, newComptroller)
emit NewComptroller(oldComptroller, newComptroller);
return uint(Error.NO_ERROR);
}
/**
* @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh
* @dev Admin function to accrue interest and set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveFactor(uint newReserveFactorMantissa) external nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reserve factor change failed.
return fail(Error(error), FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED);
}
// _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to.
return _setReserveFactorFresh(newReserveFactorMantissa);
}
/**
* @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual)
* @dev Admin function to set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveFactorFresh(uint newReserveFactorMantissa) internal returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK);
}
// Verify market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK);
}
// Check newReserveFactor ≤ maxReserveFactor
if (newReserveFactorMantissa > reserveFactorMaxMantissa) {
return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK);
}
uint oldReserveFactorMantissa = reserveFactorMantissa;
reserveFactorMantissa = newReserveFactorMantissa;
emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Accrues interest and adds reserves by transferring from msg.sender
* @param addAmount Amount of addition to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _addReservesInternal(uint addAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.
return fail(Error(error), FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED);
}
// _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to.
(error, ) = _addReservesFresh(addAmount);
return error;
}
/**
* @notice Add reserves by transferring from caller
* @dev Requires fresh interest accrual
* @param addAmount Amount of addition to reserves
* @return (uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees
*/
function _addReservesFresh(uint addAmount) internal returns (uint, uint) {
// totalReserves + actualAddAmount
uint totalReservesNew;
uint actualAddAmount;
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK), actualAddAmount);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call doTransferIn for the caller and the addAmount
* Note: The cToken must handle variations between BEP-20 and MTR underlying.
* On success, the cToken holds an additional addAmount of cash.
* doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
* it returns the amount actually transferred, in case of a fee.
*/
actualAddAmount = doTransferIn(msg.sender, addAmount);
totalReservesNew = totalReserves + actualAddAmount;
/* Revert on overflow */
require(totalReservesNew >= totalReserves, "add reserves unexpected overflow");
// Store reserves[n+1] = reserves[n] + actualAddAmount
totalReserves = totalReservesNew;
/* Emit NewReserves(admin, actualAddAmount, reserves[n+1]) */
emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew);
/* Return (NO_ERROR, actualAddAmount) */
return (uint(Error.NO_ERROR), actualAddAmount);
}
/**
* @notice Accrues interest and reduces reserves by transferring to admin
* @param reduceAmount Amount of reduction to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _reduceReserves(uint reduceAmount) external nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.
return fail(Error(error), FailureInfo.REDUCE_RESERVES_ACCRUE_INTEREST_FAILED);
}
// _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to.
return _reduceReservesFresh(reduceAmount);
}
/**
* @notice Reduces reserves by transferring to admin
* @dev Requires fresh interest accrual
* @param reduceAmount Amount of reduction to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _reduceReservesFresh(uint reduceAmount) internal returns (uint) {
// totalReserves - reduceAmount
uint totalReservesNew;
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK);
}
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK);
}
// Fail gracefully if protocol has insufficient underlying cash
if (getCashPrior() < reduceAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_ACAILABLE);
}
// Check reduceAmount ≤ reserves[n] (totalReserves)
if (reduceAmount > totalReserves) {
return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
totalReservesNew = totalReserves - reduceAmount;
// Store reserves[n+1] = reserves[n] - reduceAmount
totalReserves = totalReservesNew;
// doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
doTransferOut(admin, reduceAmount);
emit ReservesReduced(admin, reduceAmount, totalReservesNew);
return uint(Error.NO_ERROR);
}
/**
* @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh
* @dev Admin function to accrue interest and update the interest rate model
* @param newInterestRateModel the new interest rate model to use
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of interest rate model failed
return fail(Error(error), FailureInfo.SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED);
}
// _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to.
return _setInterestRateModelFresh(newInterestRateModel);
}
/**
* @notice updates the interest rate model (*requires fresh interest accrual)
* @dev Admin function to update the interest rate model
* @param newInterestRateModel the new interest rate model to use
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setInterestRateModelFresh(InterestRateModel newInterestRateModel) internal returns (uint) {
// Used to store old model for use in the event that is emitted on success
InterestRateModel oldInterestRateModel;
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK);
}
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK);
}
// Track the market's current interest rate model
oldInterestRateModel = interestRateModel;
// Ensure invoke newInterestRateModel.isInterestRateModel() returns true
require(newInterestRateModel.isInterestRateModel(), "marker method returned false");
// Set the interest rate model to newInterestRateModel
interestRateModel = newInterestRateModel;
// Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel)
emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel);
return uint(Error.NO_ERROR);
}
/*** Safe Token ***/
/**
* @notice Gets balance of this contract in terms of the underlying
* @dev This excludes the value of the current message, if any
* @return The quantity of underlying owned by this contract
*/
function getCashPrior() internal view returns (uint);
/**
* @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee.
* This may revert due to insufficient balance or insufficient allowance.
*/
function doTransferIn(address from, uint amount) internal returns (uint);
/**
* @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting.
* If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract.
* If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions.
*/
function doTransferOut(address payable to, uint amount) internal;
/*** Reentrancy Guard ***/
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
*/
modifier nonReentrant() {
require(_notEntered, "re-entered");
_notEntered = false;
_;
_notEntered = true; // get a gas-refund post-Istanbul
}
}
| contract CToken is CTokenInterface, Exponential, TokenErrorReporter {
/**
* @notice Initialize the money market
* @param comptroller_ The address of the Comptroller
* @param interestRateModel_ The address of the interest rate model
* @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18
* @param name_ EIP-20 name of this token
* @param symbol_ EIP-20 symbol of this token
* @param decimals_ EIP-20 decimal precision of this token
*/
function initialize(ComptrollerInterface comptroller_,
InterestRateModel interestRateModel_,
uint initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint8 decimals_) public {
require(msg.sender == admin, "only admin may initialize the market");
require(accrualBlockNumber == 0 && borrowIndex == 0, "market may only be initialized once");
// Set initial exchange rate
initialExchangeRateMantissa = initialExchangeRateMantissa_;
require(initialExchangeRateMantissa > 0, "initial exchange rate must be greater than zero.");
// Set the comptroller
uint err = _setComptroller(comptroller_);
require(err == uint(Error.NO_ERROR), "setting comptroller failed");
// Initialize block number and borrow index (block number mocks depend on comptroller being set)
accrualBlockNumber = getBlockNumber();
borrowIndex = mantissaOne;
// Set the interest rate model (depends on block number / borrow index)
err = _setInterestRateModelFresh(interestRateModel_);
require(err == uint(Error.NO_ERROR), "setting interest rate model failed");
name = name_;
symbol = symbol_;
decimals = decimals_;
// The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund)
_notEntered = true;
}
/**
* @notice Transfer `tokens` tokens from `src` to `dst` by `spender`
* @dev Called by both `transfer` and `transferFrom` internally
* @param spender The address of the account performing the transfer
* @param src The address of the source account
* @param dst The address of the destination account
* @param tokens The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferTokens(address spender, address src, address dst, uint tokens) internal returns (uint) {
/* Fail if transfer not allowed */
uint allowed = comptroller.transferAllowed(address(this), src, dst, tokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.TRANSFER_COMPTROLLER_REJECTION, allowed);
}
/* Do not allow self-transfers */
if (src == dst) {
return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED);
}
/* Get the allowance, infinite for the account owner */
uint startingAllowance = 0;
if (spender == src) {
startingAllowance = uint(-1);
} else {
startingAllowance = transferAllowances[src][spender];
}
/* Do the calculations, checking for {under,over}flow */
MathError mathErr;
uint allowanceNew;
uint srcTokensNew;
uint dstTokensNew;
(mathErr, allowanceNew) = subUInt(startingAllowance, tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ALLOWED);
}
(mathErr, srcTokensNew) = subUInt(accountTokens[src], tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ENOUGH);
}
(mathErr, dstTokensNew) = addUInt(accountTokens[dst], tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_TOO_MUCH);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
accountTokens[src] = srcTokensNew;
accountTokens[dst] = dstTokensNew;
/* Eat some of the allowance (if necessary) */
if (startingAllowance != uint(-1)) {
transferAllowances[src][spender] = allowanceNew;
}
/* We emit a Transfer event */
emit Transfer(src, dst, tokens);
comptroller.transferVerify(address(this), src, dst, tokens);
return uint(Error.NO_ERROR);
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount) external nonReentrant returns (bool) {
return transferTokens(msg.sender, msg.sender, dst, amount) == uint(Error.NO_ERROR);
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint256 amount) external nonReentrant returns (bool) {
return transferTokens(msg.sender, src, dst, amount) == uint(Error.NO_ERROR);
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool) {
address src = msg.sender;
transferAllowances[src][spender] = amount;
emit Approval(src, spender, amount);
return true;
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(address owner, address spender) external view returns (uint256) {
return transferAllowances[owner][spender];
}
/**
* @notice Get the token balance of the `owner`
* @param owner The address of the account to query
* @return The number of tokens owned by `owner`
*/
function balanceOf(address owner) external view returns (uint256) {
return accountTokens[owner];
}
/**
* @notice Get the underlying balance of the `owner`
* @dev This also accrues interest in a transaction
* @param owner The address of the account to query
* @return The amount of underlying owned by `owner`
*/
function balanceOfUnderlying(address owner) external returns (uint) {
Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()});
(MathError mErr, uint balance) = mulScalarTruncate(exchangeRate, accountTokens[owner]);
require(mErr == MathError.NO_ERROR, "balance could not be calculated");
return balance;
}
/**
* @notice Get a snapshot of the account's balances, and the cached exchange rate
* @dev This is used by comptroller to more efficiently perform liquidity checks.
* @param account Address of the account to snapshot
* @return (possible error, token balance, borrow balance, exchange rate mantissa)
*/
function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint) {
uint cTokenBalance = accountTokens[account];
uint borrowBalance;
uint exchangeRateMantissa;
MathError mErr;
(mErr, borrowBalance) = borrowBalanceStoredInternal(account);
if (mErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0, 0, 0);
}
(mErr, exchangeRateMantissa) = exchangeRateStoredInternal();
if (mErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0, 0, 0);
}
return (uint(Error.NO_ERROR), cTokenBalance, borrowBalance, exchangeRateMantissa);
}
/**
* @dev Function to simply retrieve block number
* This exists mainly for inheriting test contracts to stub this result.
*/
function getBlockNumber() internal view returns (uint) {
return block.number;
}
/**
* @notice Returns the current per-block borrow interest rate for this cToken
* @return The borrow interest rate per block, scaled by 1e18
*/
function borrowRatePerBlock() external view returns (uint) {
return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves);
}
/**
* @notice Returns the current per-block supply interest rate for this cToken
* @return The supply interest rate per block, scaled by 1e18
*/
function supplyRatePerBlock() external view returns (uint) {
return interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa);
}
/**
* @notice Returns the current total borrows plus accrued interest
* @return The total borrows with interest
*/
function totalBorrowsCurrent() external nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return totalBorrows;
}
/**
* @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex
* @param account The address whose balance should be calculated after updating borrowIndex
* @return The calculated balance
*/
function borrowBalanceCurrent(address account) external nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return borrowBalanceStored(account);
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return The calculated balance
*/
function borrowBalanceStored(address account) public view returns (uint) {
(MathError err, uint result) = borrowBalanceStoredInternal(account);
require(err == MathError.NO_ERROR, "borrowBalanceStored: borrowBalanceStoredInternal failed");
return result;
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return (error code, the calculated balance or 0 if error code is non-zero)
*/
function borrowBalanceStoredInternal(address account) internal view returns (MathError, uint) {
/* Note: we do not assert that the market is up to date */
MathError mathErr;
uint principalTimesIndex;
uint result;
/* Get borrowBalance and borrowIndex */
BorrowSnapshot storage borrowSnapshot = accountBorrows[account];
/* If borrowBalance = 0 then borrowIndex is likely also 0.
* Rather than failing the calculation with a division by 0, we immediately return 0 in this case.
*/
if (borrowSnapshot.principal == 0) {
return (MathError.NO_ERROR, 0);
}
/* Calculate new borrow balance using the interest index:
* recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex
*/
(mathErr, principalTimesIndex) = mulUInt(borrowSnapshot.principal, borrowIndex);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
(mathErr, result) = divUInt(principalTimesIndex, borrowSnapshot.interestIndex);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
return (MathError.NO_ERROR, result);
}
/**
* @notice Accrue interest then return the up-to-date exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateCurrent() public nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return exchangeRateStored();
}
/**
* @notice Calculates the exchange rate from the underlying to the CToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateStored() public view returns (uint) {
(MathError err, uint result) = exchangeRateStoredInternal();
require(err == MathError.NO_ERROR, "exchangeRateStored: exchangeRateStoredInternal failed");
return result;
}
/**
* @notice Calculates the exchange rate from the underlying to the CToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return (error code, calculated exchange rate scaled by 1e18)
*/
function exchangeRateStoredInternal() internal view returns (MathError, uint) {
uint _totalSupply = totalSupply;
if (_totalSupply == 0) {
/*
* If there are no tokens minted:
* exchangeRate = initialExchangeRate
*/
return (MathError.NO_ERROR, initialExchangeRateMantissa);
} else {
/*
* Otherwise:
* exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply
*/
uint totalCash = getCashPrior();
uint cashPlusBorrowsMinusReserves;
Exp memory exchangeRate;
MathError mathErr;
(mathErr, cashPlusBorrowsMinusReserves) = addThenSubUInt(totalCash, totalBorrows, totalReserves);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
(mathErr, exchangeRate) = getExp(cashPlusBorrowsMinusReserves, _totalSupply);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
return (MathError.NO_ERROR, exchangeRate.mantissa);
}
}
/**
* @notice Get cash balance of this cToken in the underlying asset
* @return The quantity of underlying asset owned by this contract
*/
function getCash() external view returns (uint) {
return getCashPrior();
}
/**
* @notice Applies accrued interest to total borrows and reserves
* @dev This calculates interest accrued from the last checkpointed block
* up to the current block and writes new checkpoint to storage.
*/
function accrueInterest() public returns (uint) {
/* Remember the initial block number */
uint currentBlockNumber = getBlockNumber();
uint accrualBlockNumberPrior = accrualBlockNumber;
/* Short-circuit accumulating 0 interest */
if (accrualBlockNumberPrior == currentBlockNumber) {
return uint(Error.NO_ERROR);
}
/* Read the previous values out of storage */
uint cashPrior = getCashPrior();
uint borrowsPrior = totalBorrows;
uint reservesPrior = totalReserves;
uint borrowIndexPrior = borrowIndex;
/* Calculate the current borrow interest rate */
uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior);
require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate is absurdly high");
/* Calculate the number of blocks elapsed since the last accrual */
(MathError mathErr, uint blockDelta) = subUInt(currentBlockNumber, accrualBlockNumberPrior);
require(mathErr == MathError.NO_ERROR, "could not calculate block delta");
/*
* Calculate the interest accumulated into borrows and reserves and the new index:
* simpleInterestFactor = borrowRate * blockDelta
* interestAccumulated = simpleInterestFactor * totalBorrows
* totalBorrowsNew = interestAccumulated + totalBorrows
* totalReservesNew = interestAccumulated * reserveFactor + totalReserves
* borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex
*/
Exp memory simpleInterestFactor;
uint interestAccumulated;
uint totalBorrowsNew;
uint totalReservesNew;
uint borrowIndexNew;
(mathErr, simpleInterestFactor) = mulScalar(Exp({mantissa: borrowRateMantissa}), blockDelta);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, interestAccumulated) = mulScalarTruncate(simpleInterestFactor, borrowsPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, totalBorrowsNew) = addUInt(interestAccumulated, borrowsPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, totalReservesNew) = mulScalarTruncateAddUInt(Exp({mantissa: reserveFactorMantissa}), interestAccumulated, reservesPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, borrowIndexNew) = mulScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, uint(mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We write the previously calculated values into storage */
accrualBlockNumber = currentBlockNumber;
borrowIndex = borrowIndexNew;
totalBorrows = totalBorrowsNew;
totalReserves = totalReservesNew;
/* We emit an AccrueInterest event */
emit AccrueInterest(cashPrior, interestAccumulated, borrowIndexNew, totalBorrowsNew);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender supplies assets into the market and receives cTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
*/
function mintInternal(uint mintAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted mint failed
return (fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED), 0);
}
// mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to
return mintFresh(msg.sender, mintAmount);
}
struct MintLocalVars {
MathError mathErr;
uint exchangeRateMantissa;
uint mintTokens;
uint totalSupplyNew;
uint accountTokensNew;
uint actualMintAmount;
}
/**
* @notice User supplies assets into the market and receives cTokens in exchange
* @dev Assumes interest has already been accrued up to the current block
* @param minter The address of the account which is supplying the assets
* @param mintAmount The amount of the underlying asset to supply
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
*/
function mintFresh(address minter, uint mintAmount) internal returns (uint, uint) {
/* Fail if mint not allowed */
uint allowed = comptroller.mintAllowed(address(this), minter, mintAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.MINT_COMPTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0);
}
MintLocalVars memory vars;
(vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
if (vars.mathErr != MathError.NO_ERROR) {
return (failOpaque(Error.MATH_ERROR, FailureInfo.MINT_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)), 0);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call `doTransferIn` for the minter and the mintAmount.
* Note: The cToken must handle variations between BEP-20 and MTR underlying.
* `doTransferIn` reverts if anything goes wrong, since we can't be sure if
* side-effects occurred. The function returns the amount actually transferred,
* in case of a fee. On success, the cToken holds an additional `actualMintAmount`
* of cash.
*/
vars.actualMintAmount = doTransferIn(minter, mintAmount);
/*
* We get the current exchange rate and calculate the number of cTokens to be minted:
* mintTokens = actualMintAmount / exchangeRate
*/
(vars.mathErr, vars.mintTokens) = divScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa}));
require(vars.mathErr == MathError.NO_ERROR, "MINT_EXCHANGE_CALCULATION_FAILED");
/*
* We calculate the new total supply of cTokens and minter token balance, checking for overflow:
* totalSupplyNew = totalSupply + mintTokens
* accountTokensNew = accountTokens[minter] + mintTokens
*/
(vars.mathErr, vars.totalSupplyNew) = addUInt(totalSupply, vars.mintTokens);
require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED");
(vars.mathErr, vars.accountTokensNew) = addUInt(accountTokens[minter], vars.mintTokens);
require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED");
/* We write previously calculated values into storage */
totalSupply = vars.totalSupplyNew;
accountTokens[minter] = vars.accountTokensNew;
/* We emit a Mint event, and a Transfer event */
emit Mint(minter, vars.actualMintAmount, vars.mintTokens);
emit Transfer(address(this), minter, vars.mintTokens);
/* We call the defense hook */
comptroller.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens);
return (uint(Error.NO_ERROR), vars.actualMintAmount);
}
/**
* @notice Sender supplies assets into the market and receiver receives cTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param receiver The address of the account which is receiving the cTokens
* @param mintAmount The amount of the underlying asset to supply
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
*/
function mintBehalfInternal(address receiver, uint mintAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted mintBehalf failed
return (fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED), 0);
}
// mintBelahfFresh emits the actual Mint event if successful and logs on errors, so we don't need to
return mintBehalfFresh(msg.sender, receiver, mintAmount);
}
/**
* @notice Payer supplies assets into the market and receiver receives cTokens in exchange
* @dev Assumes interest has already been accrued up to the current block
* @param payer The address of the account which is paying the underlying token
* @param receiver The address of the account which is receiving cToken
* @param mintAmount The amount of the underlying asset to supply
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
*/
function mintBehalfFresh(address payer, address receiver, uint mintAmount) internal returns (uint, uint) {
require(receiver != address(0), "receiver is invalid");
/* Fail if mint not allowed */
uint allowed = comptroller.mintAllowed(address(this), receiver, mintAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.MINT_COMPTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0);
}
MintLocalVars memory vars;
(vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
if (vars.mathErr != MathError.NO_ERROR) {
return (failOpaque(Error.MATH_ERROR, FailureInfo.MINT_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)), 0);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call `doTransferIn` for the payer and the mintAmount.
* Note: The cToken must handle variations between BEP-20 and MTR underlying.
* `doTransferIn` reverts if anything goes wrong, since we can't be sure if
* side-effects occurred. The function returns the amount actually transferred,
* in case of a fee. On success, the cToken holds an additional `actualMintAmount`
* of cash.
*/
vars.actualMintAmount = doTransferIn(payer, mintAmount);
/*
* We get the current exchange rate and calculate the number of cTokens to be minted:
* mintTokens = actualMintAmount / exchangeRate
*/
(vars.mathErr, vars.mintTokens) = divScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa}));
require(vars.mathErr == MathError.NO_ERROR, "MINT_EXCHANGE_CALCULATION_FAILED");
/*
* We calculate the new total supply of cTokens and receiver token balance, checking for overflow:
* totalSupplyNew = totalSupply + mintTokens
* accountTokensNew = accountTokens[receiver] + mintTokens
*/
(vars.mathErr, vars.totalSupplyNew) = addUInt(totalSupply, vars.mintTokens);
require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED");
(vars.mathErr, vars.accountTokensNew) = addUInt(accountTokens[receiver], vars.mintTokens);
require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED");
/* We write previously calculated values into storage */
totalSupply = vars.totalSupplyNew;
accountTokens[receiver] = vars.accountTokensNew;
/* We emit a MintBehalf event, and a Transfer event */
emit MintBehalf(payer, receiver, vars.actualMintAmount, vars.mintTokens);
emit Transfer(address(this), receiver, vars.mintTokens);
/* We call the defense hook */
comptroller.mintVerify(address(this), receiver, vars.actualMintAmount, vars.mintTokens);
return (uint(Error.NO_ERROR), vars.actualMintAmount);
}
/**
* @notice Sender redeems cTokens in exchange for the underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemTokens The number of cTokens to redeem into underlying
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemInternal(uint redeemTokens) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
}
// redeemFresh emits redeem-specific logs on errors, so we don't need to
return redeemFresh(msg.sender, redeemTokens, 0);
}
/**
* @notice Sender redeems cTokens in exchange for a specified amount of underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemAmount The amount of underlying to receive from redeeming cTokens
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemUnderlyingInternal(uint redeemAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
}
// redeemFresh emits redeem-specific logs on errors, so we don't need to
return redeemFresh(msg.sender, 0, redeemAmount);
}
struct RedeemLocalVars {
MathError mathErr;
uint exchangeRateMantissa;
uint redeemTokens;
uint redeemAmount;
uint totalSupplyNew;
uint accountTokensNew;
}
/**
* @notice User redeems cTokens in exchange for the underlying asset
* @dev Assumes interest has already been accrued up to the current block
* @param redeemer The address of the account which is redeeming the tokens
* @param redeemTokensIn The number of cTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero)
* @param redeemAmountIn The number of underlying tokens to receive from redeeming cTokens (only one of redeemTokensIn or redeemAmountIn may be non-zero)
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemFresh(address payable redeemer, uint redeemTokensIn, uint redeemAmountIn) internal returns (uint) {
require(redeemTokensIn == 0 || redeemAmountIn == 0, "one of redeemTokensIn or redeemAmountIn must be zero");
RedeemLocalVars memory vars;
/* exchangeRate = invoke Exchange Rate Stored() */
(vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr));
}
/* If redeemTokensIn > 0: */
if (redeemTokensIn > 0) {
/*
* We calculate the exchange rate and the amount of underlying to be redeemed:
* redeemTokens = redeemTokensIn
* redeemAmount = redeemTokensIn x exchangeRateCurrent
*/
vars.redeemTokens = redeemTokensIn;
(vars.mathErr, vars.redeemAmount) = mulScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), redeemTokensIn);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, uint(vars.mathErr));
}
} else {
/*
* We get the current exchange rate and calculate the amount to be redeemed:
* redeemTokens = redeemAmountIn / exchangeRate
* redeemAmount = redeemAmountIn
*/
(vars.mathErr, vars.redeemTokens) = divScalarByExpTruncate(redeemAmountIn, Exp({mantissa: vars.exchangeRateMantissa}));
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, uint(vars.mathErr));
}
vars.redeemAmount = redeemAmountIn;
}
/* Fail if redeem not allowed */
uint allowed = comptroller.redeemAllowed(address(this), redeemer, vars.redeemTokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REDEEM_COMPTROLLER_REJECTION, allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK);
}
/*
* We calculate the new total supply and redeemer balance, checking for underflow:
* totalSupplyNew = totalSupply - redeemTokens
* accountTokensNew = accountTokens[redeemer] - redeemTokens
*/
(vars.mathErr, vars.totalSupplyNew) = subUInt(totalSupply, vars.redeemTokens);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.accountTokensNew) = subUInt(accountTokens[redeemer], vars.redeemTokens);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
/* Fail gracefully if protocol has insufficient cash */
if (getCashPrior() < vars.redeemAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We invoke doTransferOut for the redeemer and the redeemAmount.
* Note: The cToken must handle variations between BEP-20 and MTR underlying.
* On success, the cToken has redeemAmount less of cash.
* doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
*/
uint feeAmount;
uint remainedAmount;
if (IComptroller(address(comptroller)).treasuryPercent() != 0) {
(vars.mathErr, feeAmount) = mulUInt(vars.redeemAmount, IComptroller(address(comptroller)).treasuryPercent());
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_FEE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, feeAmount) = divUInt(feeAmount, 1e18);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_FEE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, remainedAmount) = subUInt(vars.redeemAmount, feeAmount);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_FEE_CALCULATION_FAILED, uint(vars.mathErr));
}
doTransferOut(address(uint160(IComptroller(address(comptroller)).treasuryAddress())), feeAmount);
emit RedeemFee(redeemer, feeAmount, vars.redeemTokens);
} else {
remainedAmount = vars.redeemAmount;
}
doTransferOut(redeemer, remainedAmount);
/* We write previously calculated values into storage */
totalSupply = vars.totalSupplyNew;
accountTokens[redeemer] = vars.accountTokensNew;
/* We emit a Transfer event, and a Redeem event */
emit Transfer(redeemer, address(this), vars.redeemTokens);
emit Redeem(redeemer, remainedAmount, vars.redeemTokens);
/* We call the defense hook */
comptroller.redeemVerify(address(this), redeemer, vars.redeemAmount, vars.redeemTokens);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender borrows assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrowInternal(uint borrowAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED);
}
// borrowFresh emits borrow-specific logs on errors, so we don't need to
return borrowFresh(msg.sender, borrowAmount);
}
struct BorrowLocalVars {
MathError mathErr;
uint accountBorrows;
uint accountBorrowsNew;
uint totalBorrowsNew;
}
/**
* @notice Users borrow assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrowFresh(address payable borrower, uint borrowAmount) internal returns (uint) {
/* Fail if borrow not allowed */
uint allowed = comptroller.borrowAllowed(address(this), borrower, borrowAmount);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.BORROW_COMPTROLLER_REJECTION, allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK);
}
/* Fail gracefully if protocol has insufficient underlying cash */
if (getCashPrior() < borrowAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_ACAILABLE);
}
BorrowLocalVars memory vars;
/*
* We calculate the new borrower and total borrow balances, failing on overflow:
* accountBorrowsNew = accountBorrows + borrowAmount
* totalBorrowsNew = totalBorrows + borrowAmount
*/
(vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.accountBorrowsNew) = addUInt(vars.accountBorrows, borrowAmount);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.totalBorrowsNew) = addUInt(totalBorrows, borrowAmount);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We invoke doTransferOut for the borrower and the borrowAmount.
* Note: The cToken must handle variations between BEP-20 and MTR underlying.
* On success, the cToken borrowAmount less of cash.
* doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
*/
doTransferOut(borrower, borrowAmount);
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
/* We emit a Borrow event */
emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
/* We call the defense hook */
comptroller.borrowVerify(address(this), borrower, borrowAmount);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender repays their own borrow
* @param repayAmount The amount to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowInternal(uint repayAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED), 0);
}
// repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
return repayBorrowFresh(msg.sender, msg.sender, repayAmount);
}
/**
* @notice Sender repays a borrow belonging to borrower
* @param borrower the account with the debt being payed off
* @param repayAmount The amount to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowBehalfInternal(address borrower, uint repayAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.REPAY_BEHALF_ACCRUE_INTEREST_FAILED), 0);
}
// repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
return repayBorrowFresh(msg.sender, borrower, repayAmount);
}
struct RepayBorrowLocalVars {
Error err;
MathError mathErr;
uint repayAmount;
uint borrowerIndex;
uint accountBorrows;
uint accountBorrowsNew;
uint totalBorrowsNew;
uint actualRepayAmount;
}
/**
* @notice Borrows are repaid by another user (possibly the borrower).
* @param payer the account paying off the borrow
* @param borrower the account with the debt being payed off
* @param repayAmount the amount of undelrying tokens being returned
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowFresh(address payer, address borrower, uint repayAmount) internal returns (uint, uint) {
/* Fail if repayBorrow not allowed */
uint allowed = comptroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REPAY_BORROW_COMPTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK), 0);
}
RepayBorrowLocalVars memory vars;
/* We remember the original borrowerIndex for verification purposes */
vars.borrowerIndex = accountBorrows[borrower].interestIndex;
/* We fetch the amount the borrower owes, with accumulated interest */
(vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
if (vars.mathErr != MathError.NO_ERROR) {
return (failOpaque(Error.MATH_ERROR, FailureInfo.REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)), 0);
}
/* If repayAmount == -1, repayAmount = accountBorrows */
if (repayAmount == uint(-1)) {
vars.repayAmount = vars.accountBorrows;
} else {
vars.repayAmount = repayAmount;
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call doTransferIn for the payer and the repayAmount
* Note: The cToken must handle variations between BEP-20 and MTR underlying.
* On success, the cToken holds an additional repayAmount of cash.
* doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
* it returns the amount actually transferred, in case of a fee.
*/
vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount);
/*
* We calculate the new borrower and total borrow balances, failing on underflow:
* accountBorrowsNew = accountBorrows - actualRepayAmount
* totalBorrowsNew = totalBorrows - actualRepayAmount
*/
(vars.mathErr, vars.accountBorrowsNew) = subUInt(vars.accountBorrows, vars.actualRepayAmount);
require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED");
(vars.mathErr, vars.totalBorrowsNew) = subUInt(totalBorrows, vars.actualRepayAmount);
require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED");
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
/* We emit a RepayBorrow event */
emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
/* We call the defense hook */
comptroller.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount, vars.borrowerIndex);
return (uint(Error.NO_ERROR), vars.actualRepayAmount);
}
/**
* @notice The sender liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this cToken to be liquidated
* @param cTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function liquidateBorrowInternal(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED), 0);
}
error = cTokenCollateral.accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED), 0);
}
// liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to
return liquidateBorrowFresh(msg.sender, borrower, repayAmount, cTokenCollateral);
}
/**
* @notice The liquidator liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this cToken to be liquidated
* @param liquidator The address repaying the borrow and seizing collateral
* @param cTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function liquidateBorrowFresh(address liquidator, address borrower, uint repayAmount, CTokenInterface cTokenCollateral) internal returns (uint, uint) {
/* Fail if liquidate not allowed */
uint allowed = comptroller.liquidateBorrowAllowed(address(this), address(cTokenCollateral), liquidator, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_COMPTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK), 0);
}
/* Verify cTokenCollateral market's block number equals current block number */
if (cTokenCollateral.accrualBlockNumber() != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK), 0);
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
return (fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER), 0);
}
/* Fail if repayAmount = 0 */
if (repayAmount == 0) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO), 0);
}
/* Fail if repayAmount = -1 */
if (repayAmount == uint(-1)) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX), 0);
}
/* Fail if repayBorrow fails */
(uint repayBorrowError, uint actualRepayAmount) = repayBorrowFresh(liquidator, borrower, repayAmount);
if (repayBorrowError != uint(Error.NO_ERROR)) {
return (fail(Error(repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED), 0);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We calculate the number of collateral tokens that will be seized */
(uint amountSeizeError, uint seizeTokens) = comptroller.liquidateCalculateSeizeTokens(address(this), address(cTokenCollateral), actualRepayAmount);
require(amountSeizeError == uint(Error.NO_ERROR), "LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED");
/* Revert if borrower collateral token balance < seizeTokens */
require(cTokenCollateral.balanceOf(borrower) >= seizeTokens, "LIQUIDATE_SEIZE_TOO_MUCH");
// If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call
uint seizeError;
if (address(cTokenCollateral) == address(this)) {
seizeError = seizeInternal(address(this), liquidator, borrower, seizeTokens);
} else {
seizeError = cTokenCollateral.seize(liquidator, borrower, seizeTokens);
}
/* Revert if seize tokens fails (since we cannot be sure of side effects) */
require(seizeError == uint(Error.NO_ERROR), "token seizure failed");
/* We emit a LiquidateBorrow event */
emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, address(cTokenCollateral), seizeTokens);
/* We call the defense hook */
comptroller.liquidateBorrowVerify(address(this), address(cTokenCollateral), liquidator, borrower, actualRepayAmount, seizeTokens);
return (uint(Error.NO_ERROR), actualRepayAmount);
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Will fail unless called by another cToken during the process of liquidation.
* Its absolutely critical to use msg.sender as the borrowed cToken and not a parameter.
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of cTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seize(address liquidator, address borrower, uint seizeTokens) external nonReentrant returns (uint) {
return seizeInternal(msg.sender, liquidator, borrower, seizeTokens);
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another CToken.
* Its absolutely critical to use msg.sender as the seizer cToken and not a parameter.
* @param seizerToken The contract seizing the collateral (i.e. borrowed cToken)
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of cTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal returns (uint) {
/* Fail if seize not allowed */
uint allowed = comptroller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, allowed);
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER);
}
MathError mathErr;
uint borrowerTokensNew;
uint liquidatorTokensNew;
/*
* We calculate the new borrower and liquidator token balances, failing on underflow/overflow:
* borrowerTokensNew = accountTokens[borrower] - seizeTokens
* liquidatorTokensNew = accountTokens[liquidator] + seizeTokens
*/
(mathErr, borrowerTokensNew) = subUInt(accountTokens[borrower], seizeTokens);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, uint(mathErr));
}
(mathErr, liquidatorTokensNew) = addUInt(accountTokens[liquidator], seizeTokens);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, uint(mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We write the previously calculated values into storage */
accountTokens[borrower] = borrowerTokensNew;
accountTokens[liquidator] = liquidatorTokensNew;
/* Emit a Transfer event */
emit Transfer(borrower, liquidator, seizeTokens);
/* We call the defense hook */
comptroller.seizeVerify(address(this), seizerToken, liquidator, borrower, seizeTokens);
return uint(Error.NO_ERROR);
}
/*** Admin Functions ***/
/**
* @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @param newPendingAdmin New pending admin.
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPendingAdmin(address payable newPendingAdmin) external returns (uint) {
// Check caller = admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);
}
// Save current value, if any, for inclusion in log
address oldPendingAdmin = pendingAdmin;
// Store pendingAdmin with value newPendingAdmin
pendingAdmin = newPendingAdmin;
// Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin)
emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptAdmin() external returns (uint) {
// Check caller is pendingAdmin
if (msg.sender != pendingAdmin) {
return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK);
}
// Save current values for inclusion in log
address oldAdmin = admin;
address oldPendingAdmin = pendingAdmin;
// Store admin with value pendingAdmin
admin = pendingAdmin;
// Clear the pending value
pendingAdmin = address(0);
emit NewAdmin(oldAdmin, admin);
emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets a new comptroller for the market
* @dev Admin function to set a new comptroller
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setComptroller(ComptrollerInterface newComptroller) public returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_COMPTROLLER_OWNER_CHECK);
}
ComptrollerInterface oldComptroller = comptroller;
// Ensure invoke comptroller.isComptroller() returns true
require(newComptroller.isComptroller(), "marker method returned false");
// Set market's comptroller to newComptroller
comptroller = newComptroller;
// Emit NewComptroller(oldComptroller, newComptroller)
emit NewComptroller(oldComptroller, newComptroller);
return uint(Error.NO_ERROR);
}
/**
* @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh
* @dev Admin function to accrue interest and set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveFactor(uint newReserveFactorMantissa) external nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reserve factor change failed.
return fail(Error(error), FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED);
}
// _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to.
return _setReserveFactorFresh(newReserveFactorMantissa);
}
/**
* @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual)
* @dev Admin function to set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveFactorFresh(uint newReserveFactorMantissa) internal returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK);
}
// Verify market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK);
}
// Check newReserveFactor ≤ maxReserveFactor
if (newReserveFactorMantissa > reserveFactorMaxMantissa) {
return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK);
}
uint oldReserveFactorMantissa = reserveFactorMantissa;
reserveFactorMantissa = newReserveFactorMantissa;
emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Accrues interest and adds reserves by transferring from msg.sender
* @param addAmount Amount of addition to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _addReservesInternal(uint addAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.
return fail(Error(error), FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED);
}
// _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to.
(error, ) = _addReservesFresh(addAmount);
return error;
}
/**
* @notice Add reserves by transferring from caller
* @dev Requires fresh interest accrual
* @param addAmount Amount of addition to reserves
* @return (uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees
*/
function _addReservesFresh(uint addAmount) internal returns (uint, uint) {
// totalReserves + actualAddAmount
uint totalReservesNew;
uint actualAddAmount;
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK), actualAddAmount);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call doTransferIn for the caller and the addAmount
* Note: The cToken must handle variations between BEP-20 and MTR underlying.
* On success, the cToken holds an additional addAmount of cash.
* doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
* it returns the amount actually transferred, in case of a fee.
*/
actualAddAmount = doTransferIn(msg.sender, addAmount);
totalReservesNew = totalReserves + actualAddAmount;
/* Revert on overflow */
require(totalReservesNew >= totalReserves, "add reserves unexpected overflow");
// Store reserves[n+1] = reserves[n] + actualAddAmount
totalReserves = totalReservesNew;
/* Emit NewReserves(admin, actualAddAmount, reserves[n+1]) */
emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew);
/* Return (NO_ERROR, actualAddAmount) */
return (uint(Error.NO_ERROR), actualAddAmount);
}
/**
* @notice Accrues interest and reduces reserves by transferring to admin
* @param reduceAmount Amount of reduction to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _reduceReserves(uint reduceAmount) external nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.
return fail(Error(error), FailureInfo.REDUCE_RESERVES_ACCRUE_INTEREST_FAILED);
}
// _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to.
return _reduceReservesFresh(reduceAmount);
}
/**
* @notice Reduces reserves by transferring to admin
* @dev Requires fresh interest accrual
* @param reduceAmount Amount of reduction to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _reduceReservesFresh(uint reduceAmount) internal returns (uint) {
// totalReserves - reduceAmount
uint totalReservesNew;
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK);
}
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK);
}
// Fail gracefully if protocol has insufficient underlying cash
if (getCashPrior() < reduceAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_ACAILABLE);
}
// Check reduceAmount ≤ reserves[n] (totalReserves)
if (reduceAmount > totalReserves) {
return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
totalReservesNew = totalReserves - reduceAmount;
// Store reserves[n+1] = reserves[n] - reduceAmount
totalReserves = totalReservesNew;
// doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
doTransferOut(admin, reduceAmount);
emit ReservesReduced(admin, reduceAmount, totalReservesNew);
return uint(Error.NO_ERROR);
}
/**
* @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh
* @dev Admin function to accrue interest and update the interest rate model
* @param newInterestRateModel the new interest rate model to use
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of interest rate model failed
return fail(Error(error), FailureInfo.SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED);
}
// _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to.
return _setInterestRateModelFresh(newInterestRateModel);
}
/**
* @notice updates the interest rate model (*requires fresh interest accrual)
* @dev Admin function to update the interest rate model
* @param newInterestRateModel the new interest rate model to use
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setInterestRateModelFresh(InterestRateModel newInterestRateModel) internal returns (uint) {
// Used to store old model for use in the event that is emitted on success
InterestRateModel oldInterestRateModel;
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK);
}
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK);
}
// Track the market's current interest rate model
oldInterestRateModel = interestRateModel;
// Ensure invoke newInterestRateModel.isInterestRateModel() returns true
require(newInterestRateModel.isInterestRateModel(), "marker method returned false");
// Set the interest rate model to newInterestRateModel
interestRateModel = newInterestRateModel;
// Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel)
emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel);
return uint(Error.NO_ERROR);
}
/*** Safe Token ***/
/**
* @notice Gets balance of this contract in terms of the underlying
* @dev This excludes the value of the current message, if any
* @return The quantity of underlying owned by this contract
*/
function getCashPrior() internal view returns (uint);
/**
* @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee.
* This may revert due to insufficient balance or insufficient allowance.
*/
function doTransferIn(address from, uint amount) internal returns (uint);
/**
* @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting.
* If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract.
* If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions.
*/
function doTransferOut(address payable to, uint amount) internal;
/*** Reentrancy Guard ***/
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
*/
modifier nonReentrant() {
require(_notEntered, "re-entered");
_notEntered = false;
_;
_notEntered = true; // get a gas-refund post-Istanbul
}
}
| 30,778 |
27 | // require(recipient != address(0), "BEP20: transfer to the zero address"); | require(amount <= _balances[sender] );
_balances[sender] = _balances[sender].sub(amount);
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
| require(amount <= _balances[sender] );
_balances[sender] = _balances[sender].sub(amount);
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
| 14,511 |
35 | // A contract attempts to get the coins / | function transferFrom(address _from, address _to, uint256 _value) lockAffected returns (bool success) {
require(_to != 0x0 && _to != address(this));
balances[_from] = balances[_from].sub(_value); // Deduct senders balance
balances[_to] = balances[_to].add(_value); // Add recipient blaance
allowances[_from][msg.sender] = allowances[_from][msg.sender].sub(_value); // Deduct allowance for this address
Transfer(_from, _to, _value); // Raise Transfer event
return true;
}
| function transferFrom(address _from, address _to, uint256 _value) lockAffected returns (bool success) {
require(_to != 0x0 && _to != address(this));
balances[_from] = balances[_from].sub(_value); // Deduct senders balance
balances[_to] = balances[_to].add(_value); // Add recipient blaance
allowances[_from][msg.sender] = allowances[_from][msg.sender].sub(_value); // Deduct allowance for this address
Transfer(_from, _to, _value); // Raise Transfer event
return true;
}
| 8,978 |
197 | // if token == BUSD return 1 if token == NXDT calc from pancakeswap | if (_token == BUSD_BSC) {
return rateDenominator;
}
| if (_token == BUSD_BSC) {
return rateDenominator;
}
| 2,575 |
9 | // Solidity中msg.sender代表合约调用者地址。一个智能合约既可以被合约创建者调用,也可以被其它人调用。 | administrator = msg.sender;
| administrator = msg.sender;
| 38,695 |
24 | // calculate fees | uint fee = getFourPercent(weiAmount);
uint krakintFee = fee.div(2);
uint investorFee = fee.sub(krakintFee);
uint afterFees = weiAmount.sub(fee);
| uint fee = getFourPercent(weiAmount);
uint krakintFee = fee.div(2);
uint investorFee = fee.sub(krakintFee);
uint afterFees = weiAmount.sub(fee);
| 36,754 |
109 | // External view function to check whether the caller is the currentrole holder. role The role to check for.return A boolean indicating if the caller has the specified role. / | function isRole(Role role) external view returns (bool hasRole) {
hasRole = _isRole(role);
}
| function isRole(Role role) external view returns (bool hasRole) {
hasRole = _isRole(role);
}
| 29,238 |
168 | // A harvest window longer than the harvest delay doesn't make sense. | require(newHarvestWindow <= harvestDelay, "WINDOW_TOO_LONG");
| require(newHarvestWindow <= harvestDelay, "WINDOW_TOO_LONG");
| 55,409 |
7 | // : Removes top item from the stack. returns: The data stored at the top of the stack./ | function pop()
public
hasContents
returns(uint256 _data)
| function pop()
public
hasContents
returns(uint256 _data)
| 18,933 |
155 | // _owner The owner whose ships tokens we are interested in.This method MUST NEVER be called by smart contract code. First, it's fairlyexpensive (it walks the entire Collectibles owners array looking for NFT belonging to owner)/ | function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
// Return an empty array
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 totalItems = balanceOf(_owner);
uint256 resultIndex = 0;
// We count on the fact that all Collectible have IDs starting at 0 and increasing
// sequentially up to the total count.
uint256 _assetId;
for (_assetId = 0; _assetId < totalItems; _assetId++) {
result[resultIndex] = tokenOfOwnerByIndex(_owner,_assetId);
resultIndex++;
}
return result;
}
}
| function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
// Return an empty array
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 totalItems = balanceOf(_owner);
uint256 resultIndex = 0;
// We count on the fact that all Collectible have IDs starting at 0 and increasing
// sequentially up to the total count.
uint256 _assetId;
for (_assetId = 0; _assetId < totalItems; _assetId++) {
result[resultIndex] = tokenOfOwnerByIndex(_owner,_assetId);
resultIndex++;
}
return result;
}
}
| 30,970 |
57 | // set contractionBondRedeemPenaltyPercent = 0 to disable the redeem bond during contraction | function setContractionBondRedeemPenaltyPercent(uint256 _contractionBondRedeemPenaltyPercent) external onlyOperator {
require(_contractionBondRedeemPenaltyPercent <= 5000, "out range"); // <= 50%
contractionBondRedeemPenaltyPercent = _contractionBondRedeemPenaltyPercent;
}
| function setContractionBondRedeemPenaltyPercent(uint256 _contractionBondRedeemPenaltyPercent) external onlyOperator {
require(_contractionBondRedeemPenaltyPercent <= 5000, "out range"); // <= 50%
contractionBondRedeemPenaltyPercent = _contractionBondRedeemPenaltyPercent;
}
| 38,112 |
6 | // The floor is the minimum number that can be voted on in the current range poll. This value is set by a whitelisted address at the start of each poll. | uint256 _floor;
| uint256 _floor;
| 36,211 |
11 | // Arbitrum sets `msg.sender` on calls coming from L1 to be the aliased form of the address that sent the message so we need to check that aliased address here. In our case, that is the L2 alias of our caller, ArbitrumL1Messenger. | IArbSys arbsys = IArbSys(address(100));
return
courier ==
arbsys.mapL1SenderContractAddressToL2Alias(caller, address(0));
| IArbSys arbsys = IArbSys(address(100));
return
courier ==
arbsys.mapL1SenderContractAddressToL2Alias(caller, address(0));
| 12,391 |
46 | // Burn up to `maxPoolAmountIn` for exactly `tokenAmountOut` of `tokenOut`.Returns the number of pool tokens burned. The pool implicitly burns the tokens for all underlying tokens and swaps themto the desired output token. A swap fee is charged against the output tokens.tokenOut Token to receive tokenAmountOut Exact amount of `tokenOut` to receive maxPoolAmountIn Maximum amount of pool tokens to burnreturn poolAmountIn - Amount of pool tokens burned / | function exitswapExternAmountOut(
address tokenOut,
uint256 tokenAmountOut,
uint256 maxPoolAmountIn
)
external
override
_lock_
returns (uint256/* poolAmountIn */)
| function exitswapExternAmountOut(
address tokenOut,
uint256 tokenAmountOut,
uint256 maxPoolAmountIn
)
external
override
_lock_
returns (uint256/* poolAmountIn */)
| 15,626 |
331 | // NOTE: Solidity stores the free memory pointer at address 0x40. Read it before and after calling `processOrder` to ensure that there are no memory allocations. solhint-disable-next-line no-inline-assembly | assembly {
mem := mload(0x40)
}
| assembly {
mem := mload(0x40)
}
| 75,433 |
10 | // Tracks start token id each edition, edition indexed / | uint256[] public editionStartId;
| uint256[] public editionStartId;
| 40,443 |
134 | // Write the character to the pointer. 48 is the ASCII index of '0'. | mstore8(ptr, add(48, mod(temp, 10)))
temp := div(temp, 10)
| mstore8(ptr, add(48, mod(temp, 10)))
temp := div(temp, 10)
| 8,064 |
47 | // for request id | address addr;
int reqTime;
| address addr;
int reqTime;
| 36,506 |
191 | // SetToken must be in a pending state and module must be in pending state / | function _validateOnlyValidAndPendingSet(ISetToken _setToken) internal view {
require(controller.isSet(address(_setToken)), "Must be controller-enabled SetToken");
require(isSetPendingInitialization(_setToken), "Must be pending initialization");
}
| function _validateOnlyValidAndPendingSet(ISetToken _setToken) internal view {
require(controller.isSet(address(_setToken)), "Must be controller-enabled SetToken");
require(isSetPendingInitialization(_setToken), "Must be pending initialization");
}
| 79,565 |
16 | // Transfers the role of drawee to another address. Can be called/ only by the contract owner. | function setDrawee(address newDrawee) public onlyOwner {
require(newDrawee != address(0), "New drawee can not be zero address");
emit DraweeRoleTransferred(drawee, newDrawee);
drawee = newDrawee;
}
| function setDrawee(address newDrawee) public onlyOwner {
require(newDrawee != address(0), "New drawee can not be zero address");
emit DraweeRoleTransferred(drawee, newDrawee);
drawee = newDrawee;
}
| 15,217 |
68 | // These definitions are taken from across multiple dydx contracts, and are limited to just the bare minimum necessary to make flash loans work. | library Types {
enum AssetDenomination { Wei, Par }
enum AssetReference { Delta, Target }
struct AssetAmount {
bool sign;
AssetDenomination denomination;
AssetReference ref;
uint256 value;
}
}
| library Types {
enum AssetDenomination { Wei, Par }
enum AssetReference { Delta, Target }
struct AssetAmount {
bool sign;
AssetDenomination denomination;
AssetReference ref;
uint256 value;
}
}
| 21,322 |
23 | // Increase the amount of tokens that an owner allowed to a spender.approve should be called when allowed_[_spender] == 0. To incrementallowed value is better to use this function to avoid 2 calls (and wait untilthe first transaction is mined)From MonolithDAO Token.sol spender The address which will spend the funds. addedValue The amount of tokens to increase the allowance by. / | function increaseAllowance(
address spender,
uint256 addedValue
)
public
returns (bool)
| function increaseAllowance(
address spender,
uint256 addedValue
)
public
returns (bool)
| 29,789 |
56 | // transfers minter role from msg.sender to newMinter / | function transferMinterRole(address newMinter) public {
addMinter(newMinter);
renounceMinter();
}
| function transferMinterRole(address newMinter) public {
addMinter(newMinter);
renounceMinter();
}
| 13,419 |
113 | // Hash(current element of the proof + current computed hash) | computedHash = _efficientHash(proofElement, computedHash);
| computedHash = _efficientHash(proofElement, computedHash);
| 10,552 |
54 | // Cannot overflow, as that would require more tokens to be burned/transferred out than the owner initially received through minting and transferring in. | _balances[owner] -= 1;
| _balances[owner] -= 1;
| 13,267 |
167 | // Adds collateral addresses supported, such as tether and busd, must be ERC20 | function addPool(address pool_address) public onlyByOwnerOrGovernance {
require(frax_pools[pool_address] == false, "address already exists");
frax_pools[pool_address] = true;
frax_pools_array.push(pool_address);
}
| function addPool(address pool_address) public onlyByOwnerOrGovernance {
require(frax_pools[pool_address] == false, "address already exists");
frax_pools[pool_address] = true;
frax_pools_array.push(pool_address);
}
| 21,941 |
98 | // convert Bento balance to underlying `asset` for Maker | IERC20 asset = IERC20(kashiPair.asset());
bentoBox.withdraw(asset, address(this), address(this), 0, bentoBox.balanceOf(asset, address(this)));
uint256 assetBalance = asset.balanceOf(address(this));
| IERC20 asset = IERC20(kashiPair.asset());
bentoBox.withdraw(asset, address(this), address(this), 0, bentoBox.balanceOf(asset, address(this)));
uint256 assetBalance = asset.balanceOf(address(this));
| 7,308 |
11 | // Address of liquidator | address public override liquidator;
| address public override liquidator;
| 16,493 |
1 | // Initial state variables on creation | constructor(uint256 _feeBasisPoints, address _feeRecipient) {
require(_feeBasisPoints <= 10000, "Fee can't be more than 100%");
feeBasisPoints = _feeBasisPoints;
feeRecipient = _feeRecipient;
}
| constructor(uint256 _feeBasisPoints, address _feeRecipient) {
require(_feeBasisPoints <= 10000, "Fee can't be more than 100%");
feeBasisPoints = _feeBasisPoints;
feeRecipient = _feeRecipient;
}
| 2,126 |
66 | // ====== VARIABLES ====== // ====== STRUCTS ====== / | struct Info {
uint rate; // in ten-thousandths ( 5000 = 0.5% )
address recipient;
}
| struct Info {
uint rate; // in ten-thousandths ( 5000 = 0.5% )
address recipient;
}
| 10,079 |
21 | // Event emitted when the funds recipient is changed/newAddress new address for the funds recipient/changedBy address that the recipient is changed by | event FundsRecipientChanged(
address indexed newAddress,
address indexed changedBy
);
| event FundsRecipientChanged(
address indexed newAddress,
address indexed changedBy
);
| 3,333 |
37 | // 1018 to remove extra decimals from oracle price | } else if (tbnTokenDecimals > paymentTokenDecimals && !isNative) {
| } else if (tbnTokenDecimals > paymentTokenDecimals && !isNative) {
| 79,618 |
1 | // Reverts if proxy delegatecalls to unexistent method. | fallback() external payable {
revert("WitnetRequestBoardUpgradableBase: not implemented");
}
| fallback() external payable {
revert("WitnetRequestBoardUpgradableBase: not implemented");
}
| 23,894 |
3 | // Types of subscribers | enum SubscriberType {
/// Relay Backer
RELAY,
/// Fan
FAN
}
| enum SubscriberType {
/// Relay Backer
RELAY,
/// Fan
FAN
}
| 4,426 |
52 | // staked amount at initial block | uint256 stakedAmount;
| uint256 stakedAmount;
| 49,308 |
149 | // TODO: currenlty only adjusted to kyber, but should be genric interfaces for more dec. exchanges | interface ExchangeInterface {
function swapEtherToToken(uint256 _ethAmount, address _tokenAddress, uint256 _maxAmount)
external
payable
returns (uint256, uint256);
function swapTokenToEther(address _tokenAddress, uint256 _amount, uint256 _maxAmount)
external
returns (uint256);
function swapTokenToToken(address _src, address _dest, uint256 _amount)
external
payable
returns (uint256);
function getExpectedRate(address src, address dest, uint256 srcQty)
external
view
returns (uint256 expectedRate);
}
| interface ExchangeInterface {
function swapEtherToToken(uint256 _ethAmount, address _tokenAddress, uint256 _maxAmount)
external
payable
returns (uint256, uint256);
function swapTokenToEther(address _tokenAddress, uint256 _amount, uint256 _maxAmount)
external
returns (uint256);
function swapTokenToToken(address _src, address _dest, uint256 _amount)
external
payable
returns (uint256);
function getExpectedRate(address src, address dest, uint256 srcQty)
external
view
returns (uint256 expectedRate);
}
| 40,436 |
51 | // Used to Round Up the auction price interval small restrictions | function ceil(uint a, uint m) pure private returns (uint) {
return ((a + m - 1) / m) * m;
}
| function ceil(uint a, uint m) pure private returns (uint) {
return ((a + m - 1) / m) * m;
}
| 29,074 |
93 | // maximum and minimum eth needed for a purchase / | uint256 private constant _ETHMIN = 1 * 10**18;
| uint256 private constant _ETHMIN = 1 * 10**18;
| 84,960 |
0 | // Gucci |
bytes32 internal constant KEY = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
|
bytes32 internal constant KEY = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
| 17,172 |
4 | // Absorb specified token into position. If airdropFee defined, send portion to feeRecipient and portion toprotocol feeRecipient address. Callable only by manager unless manager has set anyoneAbsorb to true._setToken Address of SetToken _tokenAddress of token to absorb / | function absorb(ISetToken _setToken, address _token)
external
nonReentrant
onlyValidCaller(_setToken)
onlyValidAndInitializedSet(_setToken)
| function absorb(ISetToken _setToken, address _token)
external
nonReentrant
onlyValidCaller(_setToken)
onlyValidAndInitializedSet(_setToken)
| 3,482 |
12 | // Keep track of selected recipients for each round | mapping(uint256 => Recipient) private _recipients;
| mapping(uint256 => Recipient) private _recipients;
| 7,562 |
39 | // Send multiple types of Tokens from the _from address to the _to address (with safety call) _from Source addresses _to Target addresses _idsIDs of each token type _amountsTransfer amounts per token type _data Additional data with no specified format, sent in call to `_to` / | function safeBatchTransferFrom(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data)
public
| function safeBatchTransferFrom(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data)
public
| 10,996 |
138 | // need pay price, next price99.99%n | amountERC20=geteditprice();
| amountERC20=geteditprice();
| 24,125 |
13 | // Defines a balance action for batchAction | struct BalanceAction {
// Deposit action to take (if any)
DepositActionType actionType;
uint16 currencyId;
// Deposit action amount must correspond to the depositActionType, see documentation above.
uint256 depositActionAmount;
// Withdraw an amount of asset cash specified in Notional internal 8 decimal precision
uint256 withdrawAmountInternalPrecision;
// If set to true, will withdraw entire cash balance. Useful if there may be an unknown amount of asset cash
// residual left from trading.
bool withdrawEntireCashBalance;
// If set to true, will redeem asset cash to the underlying token on withdraw.
bool redeemToUnderlying;
}
| struct BalanceAction {
// Deposit action to take (if any)
DepositActionType actionType;
uint16 currencyId;
// Deposit action amount must correspond to the depositActionType, see documentation above.
uint256 depositActionAmount;
// Withdraw an amount of asset cash specified in Notional internal 8 decimal precision
uint256 withdrawAmountInternalPrecision;
// If set to true, will withdraw entire cash balance. Useful if there may be an unknown amount of asset cash
// residual left from trading.
bool withdrawEntireCashBalance;
// If set to true, will redeem asset cash to the underlying token on withdraw.
bool redeemToUnderlying;
}
| 12,163 |
241 | // IPriceOracleGetter interfaceInterface for the Aave price oracle./ | interface IPriceOracleGetter {
/**
* @dev returns the asset price in ETH
* @param _asset the address of the asset
* @return the ETH price of the asset
**/
function getAssetPrice(address _asset) external view returns (uint256);
}
| interface IPriceOracleGetter {
/**
* @dev returns the asset price in ETH
* @param _asset the address of the asset
* @return the ETH price of the asset
**/
function getAssetPrice(address _asset) external view returns (uint256);
}
| 16,165 |
299 | // Returns the pool address for a given pair of tokens and a fee, or address 0 if it does not exist/tokenA and tokenB may be passed in either token0/token1 or token1/token0 order/tokenA The contract address of either token0 or token1/tokenB The contract address of the other token/fee The fee collected upon every swap in the pool, denominated in hundredths of a bip/ return pool The pool address | function getPool(
address tokenA,
address tokenB,
uint24 fee
) external view returns (address pool);
| function getPool(
address tokenA,
address tokenB,
uint24 fee
) external view returns (address pool);
| 3,562 |
108 | // SushiswapPool12Goblin is specific for SUSHI-ETH pool in Sushiswap. In this case, fToken = SUSHI and pid = 12. | contract PicklePool0Goblin is Ownable, ReentrancyGuard, Goblin {
/// @notice Libraries
using SafeToken for address;
using SafeMath for uint256;
/// @notice Events
event Reinvest(address indexed caller, uint256 reward, uint256 bounty);
event AddShare(uint256 indexed id, uint256 share);
event RemoveShare(uint256 indexed id, uint256 share);
event Liquidate(uint256 indexed id, uint256 wad);
/// @notice Immutable variables
IMasterChef public masterChef;
IUniswapV2Factory public factory;
IUniswapV2Router02 public router;
IUniswapV2Pair public lpToken;
address public weth;
address public sushi;
address public operator;
uint256 public constant pid = 12;
/// @notice Mutable state variables
mapping(uint256 => uint256) public shares;
mapping(address => bool) public okStrats;
uint256 public totalShare;
Strategy public addStrat;
Strategy public liqStrat;
uint256 public reinvestBountyBps;
constructor(
address _operator,
IMasterChef _masterChef,
IUniswapV2Router02 _router,
Strategy _addStrat,
Strategy _liqStrat,
uint256 _reinvestBountyBps
) public {
operator = _operator;
weth = _router.WETH();
masterChef = _masterChef;
router = _router;
factory = IUniswapV2Factory(_router.factory());
(IERC20 _lpToken, , , ) = masterChef.poolInfo(pid);
lpToken = IUniswapV2Pair(address(_lpToken));
sushi = address(masterChef.pickle());
addStrat = _addStrat;
liqStrat = _liqStrat;
okStrats[address(addStrat)] = true;
okStrats[address(liqStrat)] = true;
reinvestBountyBps = _reinvestBountyBps;
lpToken.approve(address(_masterChef), uint256(-1)); // 100% trust in the staking pool
lpToken.approve(address(router), uint256(-1)); // 100% trust in the router
sushi.safeApprove(address(router), uint256(-1)); // 100% trust in the router
}
/// @dev Require that the caller must be an EOA account to avoid flash loans.
modifier onlyEOA() {
require(msg.sender == tx.origin, "not eoa");
_;
}
/// @dev Require that the caller must be the operator (the bank).
modifier onlyOperator() {
require(msg.sender == operator, "not operator");
_;
}
/// @dev Return the entitied LP token balance for the given shares.
/// @param share The number of shares to be converted to LP balance.
function shareToBalance(uint256 share) public view returns (uint256) {
if (totalShare == 0) return share; // When there's no share, 1 share = 1 balance.
(uint256 totalBalance, ) = masterChef.userInfo(pid, address(this));
return share.mul(totalBalance).div(totalShare);
}
/// @dev Return the number of shares to receive if staking the given LP tokens.
/// @param balance the number of LP tokens to be converted to shares.
function balanceToShare(uint256 balance) public view returns (uint256) {
if (totalShare == 0) return balance; // When there's no share, 1 share = 1 balance.
(uint256 totalBalance, ) = masterChef.userInfo(pid, address(this));
return balance.mul(totalShare).div(totalBalance);
}
/// @dev Re-invest whatever this worker has earned back to staked LP tokens.
function reinvest() public onlyEOA nonReentrant {
// 1. Withdraw all the rewards.
masterChef.withdraw(pid, 0);
uint256 reward = sushi.balanceOf(address(this));
if (reward == 0) return;
// 2. Send the reward bounty to the caller.
uint256 bounty = reward.mul(reinvestBountyBps) / 10000;
sushi.safeTransfer(msg.sender, bounty);
// 3. Use add Two-side optimal strategy to convert sushi to ETH and add
// liquidity to get LP tokens.
sushi.safeTransfer(address(addStrat), reward.sub(bounty));
addStrat.execute(address(this), 0, abi.encode(sushi, 0, 0));
// 4. Mint more LP tokens and stake them for more rewards.
masterChef.deposit(pid, lpToken.balanceOf(address(this)));
emit Reinvest(msg.sender, reward, bounty);
}
/// @dev Work on the given position. Must be called by the operator.
/// @param id The position ID to work on.
/// @param user The original user that is interacting with the operator.
/// @param debt The amount of user debt to help the strategy make decisions.
/// @param data The encoded data, consisting of strategy address and calldata.
function work(uint256 id, address user, uint256 debt, bytes calldata data)
external payable
onlyOperator nonReentrant
{
// 1. Convert this position back to LP tokens.
_removeShare(id);
// 2. Perform the worker strategy; sending LP tokens + ETH; expecting LP tokens + ETH.
(address strat, bytes memory ext) = abi.decode(data, (address, bytes));
require(okStrats[strat], "unapproved work strategy");
lpToken.transfer(strat, lpToken.balanceOf(address(this)));
Strategy(strat).execute.value(msg.value)(user, debt, ext);
// 3. Add LP tokens back to the farming pool.
_addShare(id);
// 4. Return any remaining ETH back to the operator.
SafeToken.safeTransferETH(msg.sender, address(this).balance);
}
/// @dev Return maximum output given the input amount and the status of Uniswap reserves.
/// @param aIn The amount of asset to market sell.
/// @param rIn the amount of asset in reserve for input.
/// @param rOut The amount of asset in reserve for output.
function getMktSellAmount(uint256 aIn, uint256 rIn, uint256 rOut) public pure returns (uint256) {
if (aIn == 0) return 0;
require(rIn > 0 && rOut > 0, "bad reserve values");
uint256 aInWithFee = aIn.mul(997);
uint256 numerator = aInWithFee.mul(rOut);
uint256 denominator = rIn.mul(1000).add(aInWithFee);
return numerator / denominator;
}
/// @dev Return the amount of ETH to receive if we are to liquidate the given position.
/// @param id The position ID to perform health check.
function health(uint256 id) external view returns (uint256) {
// 1. Get the position's LP balance and LP total supply.
uint256 lpBalance = shareToBalance(shares[id]);
uint256 lpSupply = lpToken.totalSupply(); // Ignore pending mintFee as it is insignificant
// 2. Get the pool's total supply of WETH and farming token.
(uint256 r0, uint256 r1,) = lpToken.getReserves();
(uint256 totalWETH, uint256 totalSushi) = lpToken.token0() == weth ? (r0, r1) : (r1, r0);
// 3. Convert the position's LP tokens to the underlying assets.
uint256 userWETH = lpBalance.mul(totalWETH).div(lpSupply);
uint256 userSushi = lpBalance.mul(totalSushi).div(lpSupply);
// 4. Convert all farming tokens to ETH and return total ETH.
return getMktSellAmount(
userSushi, totalSushi.sub(userSushi), totalWETH.sub(userWETH)
).add(userWETH);
}
/// @dev Liquidate the given position by converting it to ETH and return back to caller.
/// @param id The position ID to perform liquidation
function liquidate(uint256 id) external onlyOperator nonReentrant {
// 1. Convert the position back to LP tokens and use liquidate strategy.
_removeShare(id);
lpToken.transfer(address(liqStrat), lpToken.balanceOf(address(this)));
liqStrat.execute(address(0), 0, abi.encode(sushi, 0));
// 2. Return all available ETH back to the operator.
uint256 wad = address(this).balance;
SafeToken.safeTransferETH(msg.sender, wad);
emit Liquidate(id, wad);
}
/// @dev Internal function to stake all outstanding LP tokens to the given position ID.
function _addShare(uint256 id) internal {
uint256 balance = lpToken.balanceOf(address(this));
if (balance > 0) {
uint256 share = balanceToShare(balance);
masterChef.deposit(pid, balance);
shares[id] = shares[id].add(share);
totalShare = totalShare.add(share);
emit AddShare(id, share);
}
}
/// @dev Internal function to remove shares of the ID and convert to outstanding LP tokens.
function _removeShare(uint256 id) internal {
uint256 share = shares[id];
if (share > 0) {
uint256 balance = shareToBalance(share);
masterChef.withdraw(pid, balance);
totalShare = totalShare.sub(share);
shares[id] = 0;
emit RemoveShare(id, share);
}
}
/// @dev Recover ERC20 tokens that were accidentally sent to this smart contract.
/// @param token The token contract. Can be anything. This contract should not hold ERC20 tokens.
/// @param to The address to send the tokens to.
/// @param value The number of tokens to transfer to `to`.
function recover(address token, address to, uint256 value) external onlyOwner nonReentrant {
token.safeTransfer(to, value);
}
/// @dev Set the reward bounty for calling reinvest operations.
/// @param _reinvestBountyBps The bounty value to update.
function setReinvestBountyBps(uint256 _reinvestBountyBps) external onlyOwner {
reinvestBountyBps = _reinvestBountyBps;
}
/// @dev Set the given strategies' approval status.
/// @param strats The strategy addresses.
/// @param isOk Whether to approve or unapprove the given strategies.
function setStrategyOk(address[] calldata strats, bool isOk) external onlyOwner {
uint256 len = strats.length;
for (uint256 idx = 0; idx < len; idx++) {
okStrats[strats[idx]] = isOk;
}
}
/// @dev Update critical strategy smart contracts. EMERGENCY ONLY. Bad strategies can steal funds.
/// @param _addStrat The new add strategy contract.
/// @param _liqStrat The new liquidate strategy contract.
function setCriticalStrategies(Strategy _addStrat, Strategy _liqStrat) external onlyOwner {
addStrat = _addStrat;
liqStrat = _liqStrat;
}
function() external payable {}
} | contract PicklePool0Goblin is Ownable, ReentrancyGuard, Goblin {
/// @notice Libraries
using SafeToken for address;
using SafeMath for uint256;
/// @notice Events
event Reinvest(address indexed caller, uint256 reward, uint256 bounty);
event AddShare(uint256 indexed id, uint256 share);
event RemoveShare(uint256 indexed id, uint256 share);
event Liquidate(uint256 indexed id, uint256 wad);
/// @notice Immutable variables
IMasterChef public masterChef;
IUniswapV2Factory public factory;
IUniswapV2Router02 public router;
IUniswapV2Pair public lpToken;
address public weth;
address public sushi;
address public operator;
uint256 public constant pid = 12;
/// @notice Mutable state variables
mapping(uint256 => uint256) public shares;
mapping(address => bool) public okStrats;
uint256 public totalShare;
Strategy public addStrat;
Strategy public liqStrat;
uint256 public reinvestBountyBps;
constructor(
address _operator,
IMasterChef _masterChef,
IUniswapV2Router02 _router,
Strategy _addStrat,
Strategy _liqStrat,
uint256 _reinvestBountyBps
) public {
operator = _operator;
weth = _router.WETH();
masterChef = _masterChef;
router = _router;
factory = IUniswapV2Factory(_router.factory());
(IERC20 _lpToken, , , ) = masterChef.poolInfo(pid);
lpToken = IUniswapV2Pair(address(_lpToken));
sushi = address(masterChef.pickle());
addStrat = _addStrat;
liqStrat = _liqStrat;
okStrats[address(addStrat)] = true;
okStrats[address(liqStrat)] = true;
reinvestBountyBps = _reinvestBountyBps;
lpToken.approve(address(_masterChef), uint256(-1)); // 100% trust in the staking pool
lpToken.approve(address(router), uint256(-1)); // 100% trust in the router
sushi.safeApprove(address(router), uint256(-1)); // 100% trust in the router
}
/// @dev Require that the caller must be an EOA account to avoid flash loans.
modifier onlyEOA() {
require(msg.sender == tx.origin, "not eoa");
_;
}
/// @dev Require that the caller must be the operator (the bank).
modifier onlyOperator() {
require(msg.sender == operator, "not operator");
_;
}
/// @dev Return the entitied LP token balance for the given shares.
/// @param share The number of shares to be converted to LP balance.
function shareToBalance(uint256 share) public view returns (uint256) {
if (totalShare == 0) return share; // When there's no share, 1 share = 1 balance.
(uint256 totalBalance, ) = masterChef.userInfo(pid, address(this));
return share.mul(totalBalance).div(totalShare);
}
/// @dev Return the number of shares to receive if staking the given LP tokens.
/// @param balance the number of LP tokens to be converted to shares.
function balanceToShare(uint256 balance) public view returns (uint256) {
if (totalShare == 0) return balance; // When there's no share, 1 share = 1 balance.
(uint256 totalBalance, ) = masterChef.userInfo(pid, address(this));
return balance.mul(totalShare).div(totalBalance);
}
/// @dev Re-invest whatever this worker has earned back to staked LP tokens.
function reinvest() public onlyEOA nonReentrant {
// 1. Withdraw all the rewards.
masterChef.withdraw(pid, 0);
uint256 reward = sushi.balanceOf(address(this));
if (reward == 0) return;
// 2. Send the reward bounty to the caller.
uint256 bounty = reward.mul(reinvestBountyBps) / 10000;
sushi.safeTransfer(msg.sender, bounty);
// 3. Use add Two-side optimal strategy to convert sushi to ETH and add
// liquidity to get LP tokens.
sushi.safeTransfer(address(addStrat), reward.sub(bounty));
addStrat.execute(address(this), 0, abi.encode(sushi, 0, 0));
// 4. Mint more LP tokens and stake them for more rewards.
masterChef.deposit(pid, lpToken.balanceOf(address(this)));
emit Reinvest(msg.sender, reward, bounty);
}
/// @dev Work on the given position. Must be called by the operator.
/// @param id The position ID to work on.
/// @param user The original user that is interacting with the operator.
/// @param debt The amount of user debt to help the strategy make decisions.
/// @param data The encoded data, consisting of strategy address and calldata.
function work(uint256 id, address user, uint256 debt, bytes calldata data)
external payable
onlyOperator nonReentrant
{
// 1. Convert this position back to LP tokens.
_removeShare(id);
// 2. Perform the worker strategy; sending LP tokens + ETH; expecting LP tokens + ETH.
(address strat, bytes memory ext) = abi.decode(data, (address, bytes));
require(okStrats[strat], "unapproved work strategy");
lpToken.transfer(strat, lpToken.balanceOf(address(this)));
Strategy(strat).execute.value(msg.value)(user, debt, ext);
// 3. Add LP tokens back to the farming pool.
_addShare(id);
// 4. Return any remaining ETH back to the operator.
SafeToken.safeTransferETH(msg.sender, address(this).balance);
}
/// @dev Return maximum output given the input amount and the status of Uniswap reserves.
/// @param aIn The amount of asset to market sell.
/// @param rIn the amount of asset in reserve for input.
/// @param rOut The amount of asset in reserve for output.
function getMktSellAmount(uint256 aIn, uint256 rIn, uint256 rOut) public pure returns (uint256) {
if (aIn == 0) return 0;
require(rIn > 0 && rOut > 0, "bad reserve values");
uint256 aInWithFee = aIn.mul(997);
uint256 numerator = aInWithFee.mul(rOut);
uint256 denominator = rIn.mul(1000).add(aInWithFee);
return numerator / denominator;
}
/// @dev Return the amount of ETH to receive if we are to liquidate the given position.
/// @param id The position ID to perform health check.
function health(uint256 id) external view returns (uint256) {
// 1. Get the position's LP balance and LP total supply.
uint256 lpBalance = shareToBalance(shares[id]);
uint256 lpSupply = lpToken.totalSupply(); // Ignore pending mintFee as it is insignificant
// 2. Get the pool's total supply of WETH and farming token.
(uint256 r0, uint256 r1,) = lpToken.getReserves();
(uint256 totalWETH, uint256 totalSushi) = lpToken.token0() == weth ? (r0, r1) : (r1, r0);
// 3. Convert the position's LP tokens to the underlying assets.
uint256 userWETH = lpBalance.mul(totalWETH).div(lpSupply);
uint256 userSushi = lpBalance.mul(totalSushi).div(lpSupply);
// 4. Convert all farming tokens to ETH and return total ETH.
return getMktSellAmount(
userSushi, totalSushi.sub(userSushi), totalWETH.sub(userWETH)
).add(userWETH);
}
/// @dev Liquidate the given position by converting it to ETH and return back to caller.
/// @param id The position ID to perform liquidation
function liquidate(uint256 id) external onlyOperator nonReentrant {
// 1. Convert the position back to LP tokens and use liquidate strategy.
_removeShare(id);
lpToken.transfer(address(liqStrat), lpToken.balanceOf(address(this)));
liqStrat.execute(address(0), 0, abi.encode(sushi, 0));
// 2. Return all available ETH back to the operator.
uint256 wad = address(this).balance;
SafeToken.safeTransferETH(msg.sender, wad);
emit Liquidate(id, wad);
}
/// @dev Internal function to stake all outstanding LP tokens to the given position ID.
function _addShare(uint256 id) internal {
uint256 balance = lpToken.balanceOf(address(this));
if (balance > 0) {
uint256 share = balanceToShare(balance);
masterChef.deposit(pid, balance);
shares[id] = shares[id].add(share);
totalShare = totalShare.add(share);
emit AddShare(id, share);
}
}
/// @dev Internal function to remove shares of the ID and convert to outstanding LP tokens.
function _removeShare(uint256 id) internal {
uint256 share = shares[id];
if (share > 0) {
uint256 balance = shareToBalance(share);
masterChef.withdraw(pid, balance);
totalShare = totalShare.sub(share);
shares[id] = 0;
emit RemoveShare(id, share);
}
}
/// @dev Recover ERC20 tokens that were accidentally sent to this smart contract.
/// @param token The token contract. Can be anything. This contract should not hold ERC20 tokens.
/// @param to The address to send the tokens to.
/// @param value The number of tokens to transfer to `to`.
function recover(address token, address to, uint256 value) external onlyOwner nonReentrant {
token.safeTransfer(to, value);
}
/// @dev Set the reward bounty for calling reinvest operations.
/// @param _reinvestBountyBps The bounty value to update.
function setReinvestBountyBps(uint256 _reinvestBountyBps) external onlyOwner {
reinvestBountyBps = _reinvestBountyBps;
}
/// @dev Set the given strategies' approval status.
/// @param strats The strategy addresses.
/// @param isOk Whether to approve or unapprove the given strategies.
function setStrategyOk(address[] calldata strats, bool isOk) external onlyOwner {
uint256 len = strats.length;
for (uint256 idx = 0; idx < len; idx++) {
okStrats[strats[idx]] = isOk;
}
}
/// @dev Update critical strategy smart contracts. EMERGENCY ONLY. Bad strategies can steal funds.
/// @param _addStrat The new add strategy contract.
/// @param _liqStrat The new liquidate strategy contract.
function setCriticalStrategies(Strategy _addStrat, Strategy _liqStrat) external onlyOwner {
addStrat = _addStrat;
liqStrat = _liqStrat;
}
function() external payable {}
} | 43,250 |
13 | // Meow - I no longer exist / | contract MeowINoLongerExist is Ownable, ERC721BurnRedeem, ICreatorExtensionTokenURI {
using Strings for uint256;
string constant private _EDITION_TAG = '<EDITION>';
string[] private _uriParts;
bool private _active;
constructor(address creator) ERC721BurnRedeem(creator, 1, 99) {
_uriParts.push('data:application/json;utf8,{"name":"I no longer exist. #');
_uriParts.push('<EDITION>');
_uriParts.push('/99", "created_by":"Mad Dog Jones", ');
_uriParts.push('"description":"Meow.\\n\\nMichah Dowbak aka Mad Dog Jones (b. 1985)\\n\\nI no longer exist., 2021", ');
_uriParts.push('"image":"https://arweave.net/MCLOrh3_oSdj5Xjnsb9b6FypsgbD3YASp98i2UM2KYo","image_url":"https://arweave.net/MCLOrh3_oSdj5Xjnsb9b6FypsgbD3YASp98i2UM2KYo","image_details":{"sha256":"1aae4785c05f9a242799fa2636098d1390210bc6267498acd39900d8d3678568","bytes":14244289,"width":4800,"height":6000,"format":"PNG"},');
_uriParts.push('"animation":"https://arweave.net/_IhFnLdnnnzpp0p-Is8rBwGW2RWEaE7Wl32S1WszCGc","animation_url":"https://arweave.net/_IhFnLdnnnzpp0p-Is8rBwGW2RWEaE7Wl32S1WszCGc","animation_details":{"sha256":"ff41ea91186aef63edcdce6add5f34c0d12d4166e145e7fdf088f6eeeffa8c28","bytes":27294968,"width":4800,"height":6000,"duration":21,"format":"MP4","codecs":["H.264","AAC"]},');
_uriParts.push('"attributes":[{"trait_type":"Artist","value":"Mad Dog Jones"},{"trait_type":"Collection","value":"Meow"},{"trait_type":"Edition","value":"A"},{"display_type":"number","trait_type":"Edition","value":');
_uriParts.push('<EDITION>');
_uriParts.push(',"max_value":99}]}');
}
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721BurnRedeem, IERC165) returns (bool) {
return interfaceId == type(ICreatorExtensionTokenURI).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Activate the contract and mint the first token
*/
function activate() public onlyOwner {
// Mint the first one to the owner
require(!_active, "Already active");
_active = true;
_mintRedemption(owner());
}
/**
* @dev update the URI data
*/
function updateURIParts(string[] memory uriParts) public onlyOwner {
_uriParts = uriParts;
}
/**
* @dev Generate uri
*/
function _generateURI(uint256 tokenId) private view returns(string memory) {
bytes memory byteString;
for (uint i = 0; i < _uriParts.length; i++) {
if (_checkTag(_uriParts[i], _EDITION_TAG)) {
byteString = abi.encodePacked(byteString, (100-_mintNumbers[tokenId]).toString());
} else {
byteString = abi.encodePacked(byteString, _uriParts[i]);
}
}
return string(byteString);
}
function _checkTag(string storage a, string memory b) private pure returns (bool) {
return (keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((b))));
}
/**
* @dev See {IERC721RedeemBase-mintNumber}.
* Override for reverse numbering
*/
function mintNumber(uint256 tokenId) external view override returns(uint256) {
require(_mintNumbers[tokenId] != 0, "Invalid token");
return 100-_mintNumbers[tokenId];
}
/**
* @dev See {IRedeemBase-redeemable}.
*/
function redeemable(address contract_, uint256 tokenId) public view virtual override returns(bool) {
require(_active, "Inactive");
return super.redeemable(contract_, tokenId);
}
/**
* @dev See {ICreatorExtensionTokenURI-tokenURI}.
*/
function tokenURI(address creator, uint256 tokenId) external view override returns (string memory) {
require(creator == _creator && _mintNumbers[tokenId] != 0, "Invalid token");
return _generateURI(tokenId);
}
}
| contract MeowINoLongerExist is Ownable, ERC721BurnRedeem, ICreatorExtensionTokenURI {
using Strings for uint256;
string constant private _EDITION_TAG = '<EDITION>';
string[] private _uriParts;
bool private _active;
constructor(address creator) ERC721BurnRedeem(creator, 1, 99) {
_uriParts.push('data:application/json;utf8,{"name":"I no longer exist. #');
_uriParts.push('<EDITION>');
_uriParts.push('/99", "created_by":"Mad Dog Jones", ');
_uriParts.push('"description":"Meow.\\n\\nMichah Dowbak aka Mad Dog Jones (b. 1985)\\n\\nI no longer exist., 2021", ');
_uriParts.push('"image":"https://arweave.net/MCLOrh3_oSdj5Xjnsb9b6FypsgbD3YASp98i2UM2KYo","image_url":"https://arweave.net/MCLOrh3_oSdj5Xjnsb9b6FypsgbD3YASp98i2UM2KYo","image_details":{"sha256":"1aae4785c05f9a242799fa2636098d1390210bc6267498acd39900d8d3678568","bytes":14244289,"width":4800,"height":6000,"format":"PNG"},');
_uriParts.push('"animation":"https://arweave.net/_IhFnLdnnnzpp0p-Is8rBwGW2RWEaE7Wl32S1WszCGc","animation_url":"https://arweave.net/_IhFnLdnnnzpp0p-Is8rBwGW2RWEaE7Wl32S1WszCGc","animation_details":{"sha256":"ff41ea91186aef63edcdce6add5f34c0d12d4166e145e7fdf088f6eeeffa8c28","bytes":27294968,"width":4800,"height":6000,"duration":21,"format":"MP4","codecs":["H.264","AAC"]},');
_uriParts.push('"attributes":[{"trait_type":"Artist","value":"Mad Dog Jones"},{"trait_type":"Collection","value":"Meow"},{"trait_type":"Edition","value":"A"},{"display_type":"number","trait_type":"Edition","value":');
_uriParts.push('<EDITION>');
_uriParts.push(',"max_value":99}]}');
}
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721BurnRedeem, IERC165) returns (bool) {
return interfaceId == type(ICreatorExtensionTokenURI).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Activate the contract and mint the first token
*/
function activate() public onlyOwner {
// Mint the first one to the owner
require(!_active, "Already active");
_active = true;
_mintRedemption(owner());
}
/**
* @dev update the URI data
*/
function updateURIParts(string[] memory uriParts) public onlyOwner {
_uriParts = uriParts;
}
/**
* @dev Generate uri
*/
function _generateURI(uint256 tokenId) private view returns(string memory) {
bytes memory byteString;
for (uint i = 0; i < _uriParts.length; i++) {
if (_checkTag(_uriParts[i], _EDITION_TAG)) {
byteString = abi.encodePacked(byteString, (100-_mintNumbers[tokenId]).toString());
} else {
byteString = abi.encodePacked(byteString, _uriParts[i]);
}
}
return string(byteString);
}
function _checkTag(string storage a, string memory b) private pure returns (bool) {
return (keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((b))));
}
/**
* @dev See {IERC721RedeemBase-mintNumber}.
* Override for reverse numbering
*/
function mintNumber(uint256 tokenId) external view override returns(uint256) {
require(_mintNumbers[tokenId] != 0, "Invalid token");
return 100-_mintNumbers[tokenId];
}
/**
* @dev See {IRedeemBase-redeemable}.
*/
function redeemable(address contract_, uint256 tokenId) public view virtual override returns(bool) {
require(_active, "Inactive");
return super.redeemable(contract_, tokenId);
}
/**
* @dev See {ICreatorExtensionTokenURI-tokenURI}.
*/
function tokenURI(address creator, uint256 tokenId) external view override returns (string memory) {
require(creator == _creator && _mintNumbers[tokenId] != 0, "Invalid token");
return _generateURI(tokenId);
}
}
| 1,808 |
35 | // Aprrove the transfer of token. A user must own the token to approve it | function approve( address _to, uint256 _tokenId) public {
// Caller must own token.
require(_owns(msg.sender, _tokenId));
require(_addressNotNull(_to));
countryIndexToApproved[_tokenId] = _to;
emit Approval(msg.sender, _to, _tokenId);
}
| function approve( address _to, uint256 _tokenId) public {
// Caller must own token.
require(_owns(msg.sender, _tokenId));
require(_addressNotNull(_to));
countryIndexToApproved[_tokenId] = _to;
emit Approval(msg.sender, _to, _tokenId);
}
| 2,944 |
0 | // SPDX-License-Identifier: MIT / | abstract contract AdminStorage {
/**
* @notice The address of the administrator account or contract.
*/
address public admin;
}
| abstract contract AdminStorage {
/**
* @notice The address of the administrator account or contract.
*/
address public admin;
}
| 21,900 |
12 | // Harvest profits while preventing a sandwich attack exploit./maxBalance The maximum balance of the underlying token that is allowed to be in BentoBox./rebalance Whether BentoBox should rebalance the strategy assets to acheive it's target allocation./maxChangeAmount When rebalancing - the maximum amount that will be deposited to or withdrawn from a strategy to BentoBox./harvestRewards If we want to claim any accrued reward tokens/maxBalance can be set to 0 to keep the previous value./maxChangeAmount can be set to 0 to allow for full rebalancing. | function safeHarvest(uint256 maxBalance, bool rebalance, uint256 maxChangeAmount, bool harvestRewards) external onlyExecutor {
if (harvestRewards) {
_harvestRewards();
}
if (maxBalance > 0) {
maxBentoBoxBalance = maxBalance;
}
IBentoBoxV1(bentoBox).harvest(strategyToken, rebalance, maxChangeAmount);
}
| function safeHarvest(uint256 maxBalance, bool rebalance, uint256 maxChangeAmount, bool harvestRewards) external onlyExecutor {
if (harvestRewards) {
_harvestRewards();
}
if (maxBalance > 0) {
maxBentoBoxBalance = maxBalance;
}
IBentoBoxV1(bentoBox).harvest(strategyToken, rebalance, maxChangeAmount);
}
| 12,766 |
212 | // Token used as the trade in for the weaponSmith | IERC20 public token;
| IERC20 public token;
| 20,583 |
80 | // Start off with z at 1. | z := 1
| z := 1
| 14,289 |
337 | // No-Op | if(tokenBalanceBefore == tokenBalanceAfter) {
return;
}
| if(tokenBalanceBefore == tokenBalanceAfter) {
return;
}
| 47,229 |
30 | // Writes up to 32 bytes to the buffer. Resizes if doing so wouldexceed the capacity of the buffer.buf The buffer to append to.off The offset to write at.data The data to append.len The number of bytes to write (left-aligned). return The original buffer, for chaining./ | function write(
buffer memory buf,
uint off,
bytes32 data,
uint len
)
private
pure
returns(
buffer memory
| function write(
buffer memory buf,
uint off,
bytes32 data,
uint len
)
private
pure
returns(
buffer memory
| 4,461 |
146 | // Used for changing the `settlementFeeRecipient`contract address for distributing the settlement fees(staking rewards) among the staking participants. recipient New staking contract address / | {
require(address(recipient) != address(0));
settlementFeeRecipient = recipient;
}
| {
require(address(recipient) != address(0));
settlementFeeRecipient = recipient;
}
| 47,744 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.