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 |
|---|---|---|---|---|
60 | // [{"constant":false,"inputs":[{"name":"_multisigVault","type":"address"}],"name":"setMultisigVault","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"authorizerIndex","type":"uint256"}],"name":"getAuthorizer","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"exchangeRate","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"altDeposits","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"recipient","type":"address"},{"name":"tokens","type":"uint256"}],"name":"authorizedCreateTokens","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[],"name":"finishMinting","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_exchangeRate","type":"address"}],"name":"setExchangeRate","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_token","type":"address"}],"name":"retrieveTokens","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"totalAltDeposits","type":"uint256"}],"name":"setAltDeposit","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"start","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"recipient","type":"address"}],"name":"createTokens","outputs":[],"payable":true,"type":"function"},{"constant":false,"inputs":[{"name":"_addr","type":"address"}],"name":"addAuthorized","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"multisigVault","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_hardcap","type":"uint256"}],"name":"setHardCap","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_start","type":"uint256"}],"name":"setStart","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"token","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"_addr","type":"address"}],"name":"isAuthorized","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"payable":true,"type":"fallback"},{"anonymous":false,"inputs":[{"indexed":false,"name":"recipient","type":"address"},{"indexed":false,"name":"ether_amount","type":"uint256"},{"indexed":false,"name":"pay_amount","type":"uint256"},{"indexed":false,"name":"exchangerate","type":"uint256"}],"name":"TokenSold","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"recipient","type":"address"},{"indexed":false,"name":"pay_amount","type":"uint256"}],"name":"AuthorizedCreate","type":"event"},{"anonymous":false,"inputs":[],"name":"MainSaleClosed","type":"event"}]/ modifier to allow token creation only when the sale IS ON / | modifier saleIsOn() {
require(now > start && now < start + 30 days);
_;
}
| modifier saleIsOn() {
require(now > start && now < start + 30 days);
_;
}
| 8,817 |
9 | // Changes the {lateQuorumVoteExtension}. This operation can only be performed by the governance executor,generally through a governance proposal. Emits a {LateQuorumVoteExtensionSet} event. / | function setLateQuorumVoteExtension(uint48 newVoteExtension) public virtual onlyGovernance {
_setLateQuorumVoteExtension(newVoteExtension);
}
| function setLateQuorumVoteExtension(uint48 newVoteExtension) public virtual onlyGovernance {
_setLateQuorumVoteExtension(newVoteExtension);
}
| 1,708 |
25 | // Send 3% to multiSigWalletAddress | _shareBalances[multiSigWalletAddress] = _shareBalances[multiSigWalletAddress].add(shareValueToBurn);
_shareBalances[msg.sender] = _shareBalances[msg.sender].sub(shareValue);
shareValue = shareValue.sub(shareValueToBurn);
_shareBalances[to] = _shareBalances[to].add(shareValue);
| _shareBalances[multiSigWalletAddress] = _shareBalances[multiSigWalletAddress].add(shareValueToBurn);
_shareBalances[msg.sender] = _shareBalances[msg.sender].sub(shareValue);
shareValue = shareValue.sub(shareValueToBurn);
_shareBalances[to] = _shareBalances[to].add(shareValue);
| 1,282 |
39 | // return Returns the address of the PancakeSwap V3 deployer | function deployer() external view returns (address);
| function deployer() external view returns (address);
| 29,752 |
207 | // configuration errors | error SupplyConfigurationMishmatch(uint256 saleSupply, uint256 supply);
error BalanceNotEqualSupply(uint256 balance, uint256 supply);
| error SupplyConfigurationMishmatch(uint256 saleSupply, uint256 supply);
error BalanceNotEqualSupply(uint256 balance, uint256 supply);
| 13,730 |
0 | // Super-interface for dummy market observer / | abstract contract IDummyMarketObserver {
enum ORDER_TYPE{NONE, TRADE, CLOSURE}
event TRADE(uint256 orderId);
event CLOSURE(uint256 orderId);
/**
* @dev Get order details.
*
* @param orderId The order id.
* @return _type trade or closure.
* @return _data passed optional data.
*/
function getOrder(uint256 orderId) external view virtual returns (ORDER_TYPE _type, bytes memory _data);
}
| abstract contract IDummyMarketObserver {
enum ORDER_TYPE{NONE, TRADE, CLOSURE}
event TRADE(uint256 orderId);
event CLOSURE(uint256 orderId);
/**
* @dev Get order details.
*
* @param orderId The order id.
* @return _type trade or closure.
* @return _data passed optional data.
*/
function getOrder(uint256 orderId) external view virtual returns (ORDER_TYPE _type, bytes memory _data);
}
| 29,516 |
89 | // event for freeze | event Freeze(address target);
event UnFreeze(address target);
| event Freeze(address target);
event UnFreeze(address target);
| 37,890 |
66 | // uint8 status codes as suggested by the ERC-1404 spec | uint8 private constant STATUS_SUCCESS = 0;
uint8 private constant STATUS_ERROR_JURISDICTION_FLOW = 1;
uint8 private constant STATUS_ERROR_LOCKUP = 2;
uint8 private constant STATUS_ERROR_USER_UNKNOWN = 3;
uint8 private constant STATUS_ERROR_JURISDICTION_HALT = 4;
uint8 private constant STATUS_ERROR_NON_LISTED_USER = 5;
event ConfigWhitelist(
uint _startDate,
uint _lockupGranularity,
| uint8 private constant STATUS_SUCCESS = 0;
uint8 private constant STATUS_ERROR_JURISDICTION_FLOW = 1;
uint8 private constant STATUS_ERROR_LOCKUP = 2;
uint8 private constant STATUS_ERROR_USER_UNKNOWN = 3;
uint8 private constant STATUS_ERROR_JURISDICTION_HALT = 4;
uint8 private constant STATUS_ERROR_NON_LISTED_USER = 5;
event ConfigWhitelist(
uint _startDate,
uint _lockupGranularity,
| 41,701 |
356 | // owner mint for free last 30 | function devLastMint(uint256 _mintAmount) external onlyOwner onlyStart {
require(_mintAmount <= maxMintPerTxn, "maxPerTx!");
require(countOGFreeLastForOwners + _mintAmount <= DEV_SUPPLY_LIMIT, "exceed countOGFreeLastMax");
yieldToken.updateRewardOnMint(msg.sender, _mintAmount, 1);
uint256 id = SEQ_GENESIS_SUPPLY + countOGFreeLastForOwners;
for (uint256 i = 1; i <= _mintAmount; i++) {
_safeMint(msg.sender, id + i);
}
countOGFreeLastForOwners += _mintAmount;
balanceOG[msg.sender] += _mintAmount;
}
| function devLastMint(uint256 _mintAmount) external onlyOwner onlyStart {
require(_mintAmount <= maxMintPerTxn, "maxPerTx!");
require(countOGFreeLastForOwners + _mintAmount <= DEV_SUPPLY_LIMIT, "exceed countOGFreeLastMax");
yieldToken.updateRewardOnMint(msg.sender, _mintAmount, 1);
uint256 id = SEQ_GENESIS_SUPPLY + countOGFreeLastForOwners;
for (uint256 i = 1; i <= _mintAmount; i++) {
_safeMint(msg.sender, id + i);
}
countOGFreeLastForOwners += _mintAmount;
balanceOG[msg.sender] += _mintAmount;
}
| 10,559 |
354 | // Warriors with MINER perc are not allowed to be berned | require(CryptoUtils.getSpecialityValue(warrior.identity) < MINER_PERK);
_burn(_owner, _warriorId);
| require(CryptoUtils.getSpecialityValue(warrior.identity) < MINER_PERK);
_burn(_owner, _warriorId);
| 24,138 |
10 | // Contract may be destroyed only when there are no active bets | function kill() external onlyOwner {
require (activeBets.length == 0, "All bets should be processed (complete or canceled) before self-destruct.");
selfdestruct(owner);
}
| function kill() external onlyOwner {
require (activeBets.length == 0, "All bets should be processed (complete or canceled) before self-destruct.");
selfdestruct(owner);
}
| 1,015 |
178 | // 0 = not allowed ... 1 = allowed however value must be zero ... 2 = allowed with msg.value either zero or non-zero | uint256 constant internal NOT_ALLOWED = 0;
uint256 constant internal ALLOWED_NO_MSG_VALUE = 1;
uint256 constant internal ALLOWED_W_MSG_VALUE = 2;
uint256 internal constant LOOP_LIMIT = 200;
uint256 public constant max = 10000;
uint256 public CRVTokenTake = 1500; // pct of max
| uint256 constant internal NOT_ALLOWED = 0;
uint256 constant internal ALLOWED_NO_MSG_VALUE = 1;
uint256 constant internal ALLOWED_W_MSG_VALUE = 2;
uint256 internal constant LOOP_LIMIT = 200;
uint256 public constant max = 10000;
uint256 public CRVTokenTake = 1500; // pct of max
| 69,612 |
278 | // Remove an `IZap` from the registry name The name of the `IZap` (see `INameIdentifier`) / | function removeZap(string calldata name) external;
| function removeZap(string calldata name) external;
| 69,152 |
14 | // if glasses, add charm | if(info.glasses == 6) {
knowledge += 10;
charm += 25;
strength += 5;
}
| if(info.glasses == 6) {
knowledge += 10;
charm += 25;
strength += 5;
}
| 67,290 |
62 | // in case of user-defined collection, sell will receive amount =bidAmount - platformPerecentage amount author will get nothing as royality not tracking for user-defined collections | emit Claim(temp.bidder, temp.nftContract, _tokenId, temp.bidAmount, temp.seller, temp.currencyType);
delete _auctionTokens[_tokenId][_contract];
| emit Claim(temp.bidder, temp.nftContract, _tokenId, temp.bidAmount, temp.seller, temp.currencyType);
delete _auctionTokens[_tokenId][_contract];
| 23,214 |
94 | // Sender needs enough presale tokens to claim at this point. | uint16 tokens = _width.mul(_height);
require(presales[msg.sender] >= tokens, "Not enough unlocked presale tokens available.");
presales[msg.sender] = presales[msg.sender].sub(tokens);
| uint16 tokens = _width.mul(_height);
require(presales[msg.sender] >= tokens, "Not enough unlocked presale tokens available.");
presales[msg.sender] = presales[msg.sender].sub(tokens);
| 26,396 |
19 | // reset approval to 0 | require(ERC20(sourceTokenAddress).approve(oracleAddress, 0), "token approval reset failed");
| require(ERC20(sourceTokenAddress).approve(oracleAddress, 0), "token approval reset failed");
| 41,113 |
69 | // See {ILocker-getAndUpdateLockedAmount}. / | function getAndUpdateLockedAmount(address wallet) external override returns (uint) {
return _getAndUpdateLockedAmount(wallet);
}
| function getAndUpdateLockedAmount(address wallet) external override returns (uint) {
return _getAndUpdateLockedAmount(wallet);
}
| 69,246 |
16 | // if the funds are still in the contract a year after deploy they can all be taken by the owner | function emergencyWithdraw() external nonReentrant onlyOwner {
require(block.timestamp > emergencyWithdrawAvailableTime, "It's not time yet");
payable(owner()).transfer(address(this).balance);
}
| function emergencyWithdraw() external nonReentrant onlyOwner {
require(block.timestamp > emergencyWithdrawAvailableTime, "It's not time yet");
payable(owner()).transfer(address(this).balance);
}
| 47,162 |
45 | // Only this address will be allowed to call functions marked with `requireAuthorizedLogicContract` | address public authorizedLogicContractAddress;
| address public authorizedLogicContractAddress;
| 62,929 |
104 | // store addresses that a automatic market maker pairs. Any transfer to these addresses | mapping(address => bool) public isUniRouterPairs;
| mapping(address => bool) public isUniRouterPairs;
| 25,048 |
30 | // Modify the contract state: subtract the amount of gold from the user and add shards | warriors[user].gold = warriors[user].gold.sub(amount);
if (sphere)
warriors[user].sphere = warriors[user].sphere.add(amount.div(1000));
else
warriors[user].shard = warriors[user].shard.add(amount.div(100));
| warriors[user].gold = warriors[user].gold.sub(amount);
if (sphere)
warriors[user].sphere = warriors[user].sphere.add(amount.div(1000));
else
warriors[user].shard = warriors[user].shard.add(amount.div(100));
| 27,867 |
89 | // wealth redistribution | referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus);
| referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus);
| 8,280 |
48 | // gets freezing count _addr Address of freeze tokens owner. / | function freezingCount(address _addr) public view returns (uint count) {
uint64 release = chains[toKey(_addr, 0)];
while (release != 0) {
count++;
release = chains[toKey(_addr, release)];
}
}
| function freezingCount(address _addr) public view returns (uint count) {
uint64 release = chains[toKey(_addr, 0)];
while (release != 0) {
count++;
release = chains[toKey(_addr, release)];
}
}
| 9,629 |
135 | // cheap gas -> we can mint instead of buying | chi.mint(votedChi.div(2));
| chi.mint(votedChi.div(2));
| 51,439 |
12 | // now approve that jawn | token.approve(msg.sender, _amount);
| token.approve(msg.sender, _amount);
| 18,464 |
334 | // Create a new DAOFactory, creating DAOs with Kernels proxied to `_baseKernel`, ACLs proxied to `_baseACL`, and new EVMScriptRegistries created from `_regFactory`._baseKernel Base Kernel_baseACL Base ACL_regFactory EVMScriptRegistry factory/ | constructor(IKernel _baseKernel, IACL _baseACL, EVMScriptRegistryFactory _regFactory) public {
// No need to init as it cannot be killed by devops199
if (address(_regFactory) != address(0)) {
regFactory = _regFactory;
}
baseKernel = _baseKernel;
baseACL = _baseACL;
}
| constructor(IKernel _baseKernel, IACL _baseACL, EVMScriptRegistryFactory _regFactory) public {
// No need to init as it cannot be killed by devops199
if (address(_regFactory) != address(0)) {
regFactory = _regFactory;
}
baseKernel = _baseKernel;
baseACL = _baseACL;
}
| 6,319 |
4 | // ------------------ LendingPoolCoreData ------------------------ | function getReserveATokenAddress(address _reserve) public virtual view returns (address);
function getReserveConfiguration(address _reserve)
external virtual
view
returns (uint256, uint256, uint256, bool);
function getUserUnderlyingAssetBalance(address _reserve, address _user)
public virtual
view
returns (uint256);
| function getReserveATokenAddress(address _reserve) public virtual view returns (address);
function getReserveConfiguration(address _reserve)
external virtual
view
returns (uint256, uint256, uint256, bool);
function getUserUnderlyingAssetBalance(address _reserve, address _user)
public virtual
view
returns (uint256);
| 15,268 |
85 | // See {IAladdinConvexVault-claim} | function claim(
uint256 _pid,
uint256 _minOut,
ClaimOption _option
) public override onlyExistPool(_pid) nonReentrant returns (uint256 claimed) {
PoolInfo storage _pool = poolInfo[_pid];
require(!_pool.pauseWithdraw, "pool paused");
_updateRewards(_pid, msg.sender);
UserInfo storage _userInfo = userInfo[_pid][msg.sender];
| function claim(
uint256 _pid,
uint256 _minOut,
ClaimOption _option
) public override onlyExistPool(_pid) nonReentrant returns (uint256 claimed) {
PoolInfo storage _pool = poolInfo[_pid];
require(!_pool.pauseWithdraw, "pool paused");
_updateRewards(_pid, msg.sender);
UserInfo storage _userInfo = userInfo[_pid][msg.sender];
| 29,097 |
86 | // Check that there are still tokens available to purchase. | require(
editions[editionId].numSold < editions[editionId].quantity,
"This edition is already sold out."
);
| require(
editions[editionId].numSold < editions[editionId].quantity,
"This edition is already sold out."
);
| 9,158 |
83 | // Equivalent to 2z. | z := shl(1, z)
| z := shl(1, z)
| 11,128 |
7 | // Permanently enables arbitrary contract deployment and deletes the owner. / | function enableArbitraryContractDeployment() external onlyOwner {
emit WhitelistDisabled(owner);
allowArbitraryDeployment = true;
}
| function enableArbitraryContractDeployment() external onlyOwner {
emit WhitelistDisabled(owner);
allowArbitraryDeployment = true;
}
| 56,821 |
218 | // the liquidity of the position | uint128 liquidity;
| uint128 liquidity;
| 30,883 |
86 | // Function to calculate actual value after Taxes | function calculateTokensReceived(uint256 _ethereumToSpend) public view returns(uint256) {
// Calculate 15% for distribution
uint256 fifteen_percentToDistribute= SafeMath.percent(_ethereumToSpend,15,100,18);
uint256 _dividends = SafeMath.sub(_ethereumToSpend, fifteen_percentToDistribute);
uint256 _amountOfTokens = ethereumToTokens_(_dividends);
return _amountOfTokens;
}
| function calculateTokensReceived(uint256 _ethereumToSpend) public view returns(uint256) {
// Calculate 15% for distribution
uint256 fifteen_percentToDistribute= SafeMath.percent(_ethereumToSpend,15,100,18);
uint256 _dividends = SafeMath.sub(_ethereumToSpend, fifteen_percentToDistribute);
uint256 _amountOfTokens = ethereumToTokens_(_dividends);
return _amountOfTokens;
}
| 46,420 |
108 | // Get whitelist wallet / | function getWhitelist(address _address)
public
view
returns (
address,
uint256,
uint256,
bool,
bool,
uint256
| function getWhitelist(address _address)
public
view
returns (
address,
uint256,
uint256,
bool,
bool,
uint256
| 36,111 |
5 | // circulating supply | uint256 cashSupply = IERC20(cash).totalSupply();
uint256 totalPoints = IMasterChef(shareMasterChef).totalAllocPoint();
uint256 lpPoints = IMasterChef(shareMasterChef).poolPoint(cashShareLpPoolPid);
uint256 cashFee = ICash(cash).fee();
uint256 FEE_ONE = 10 ** 6;
if (cashPrice >= cashPriceOne.add(cashPriceDelta)) {
if (cashFee > 0) {
uint256 subFee = FEE_ONE.mul(feeSubRate).div(100);
cashFee = cashFee > subFee ? cashFee.sub(subFee) : 0;
| uint256 cashSupply = IERC20(cash).totalSupply();
uint256 totalPoints = IMasterChef(shareMasterChef).totalAllocPoint();
uint256 lpPoints = IMasterChef(shareMasterChef).poolPoint(cashShareLpPoolPid);
uint256 cashFee = ICash(cash).fee();
uint256 FEE_ONE = 10 ** 6;
if (cashPrice >= cashPriceOne.add(cashPriceDelta)) {
if (cashFee > 0) {
uint256 subFee = FEE_ONE.mul(feeSubRate).div(100);
cashFee = cashFee > subFee ? cashFee.sub(subFee) : 0;
| 4,202 |
63 | // The unit conversion for tenths of basis points | uint256 private constant TENTH_BASIS_POINTS = 100000;
| uint256 private constant TENTH_BASIS_POINTS = 100000;
| 32,082 |
33 | // we don't need check amount[i] > 0 or destinations != 0x0 because they cannot claim anyway | uint amount = 0;
for (uint i = 0; i < amounts.length; i++) {
amount = amount.add(amounts[i]);
balances[destinations[i]] = balances[destinations[i]].add(amounts[i]);
counts[destinations[i]] += 1;
}
| uint amount = 0;
for (uint i = 0; i < amounts.length; i++) {
amount = amount.add(amounts[i]);
balances[destinations[i]] = balances[destinations[i]].add(amounts[i]);
counts[destinations[i]] += 1;
}
| 47,361 |
5 | // Returns approved max amount and recovery rate./ return amount initial and maximum allowance given to spender/ return recoveryRate recovery amount per second | function renewableAllowance(address _owner, address _spender)
external
view
returns (uint256 amount, uint256 recoveryRate);
| function renewableAllowance(address _owner, address _spender)
external
view
returns (uint256 amount, uint256 recoveryRate);
| 27,064 |
72 | // get their earnings | _eth = withdrawEarnings(_pID);
| _eth = withdrawEarnings(_pID);
| 12,004 |
7 | // 3CRV -> USDT | CRV3POOL.remove_liquidity_one_coin(crvAmount, 2, 0);
| CRV3POOL.remove_liquidity_one_coin(crvAmount, 2, 0);
| 65,936 |
0 | // events dclaration | event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
| event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
| 2,249 |
97 | // Borrow tokens from aave. Borrow tokens from aave. _tokens list of token addresses. _amounts list of amounts for respective tokens./ | function aaveBorrow(
address[] memory _tokens,
uint256[] memory _amounts
| function aaveBorrow(
address[] memory _tokens,
uint256[] memory _amounts
| 34,494 |
28 | // Emits a {CallExecuted} event. Requirements: - the caller must have the 'executor' role. / This function can reenter, but it doesn't pose a risk because _afterCall checks that the proposal is pending, thus any modifications to the operation during reentrancy should be caught. slither-disable-next-line reentrancy-eth | function execute(
address target,
uint256 value,
bytes calldata payload,
bytes32 predecessor,
bytes32 salt
) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) {
bytes32 id = hashOperation(target, value, payload, predecessor, salt);
_beforeCall(id, predecessor);
| function execute(
address target,
uint256 value,
bytes calldata payload,
bytes32 predecessor,
bytes32 salt
) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) {
bytes32 id = hashOperation(target, value, payload, predecessor, salt);
_beforeCall(id, predecessor);
| 20,986 |
19 | // Transfer given number of token from the signed defined by digital signatureto given recipient._to address to transfer token to the owner of _value number of tokens to transfer _fee number of tokens to give to message sender _nonce nonce of the transfer _v parameter V of digital signature _r parameter R of digital signature _s parameter S of digital signature / | function delegatedTransfer (
address _to, uint256 _value, uint256 _fee,
uint256 _nonce, uint8 _v, bytes32 _r, bytes32 _s)
| function delegatedTransfer (
address _to, uint256 _value, uint256 _fee,
uint256 _nonce, uint8 _v, bytes32 _r, bytes32 _s)
| 44,441 |
4 | // solhint-enable var-name-mixedcase // Initializes the domain separator and parameter caches. The meaning of `name` and `version` is specified in - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.- `version`: the current major version of the signing domain. NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smartcontract upgrade]. / | constructor(string memory name, string memory version) {
bytes32 hashedName = keccak256(bytes(name));
| constructor(string memory name, string memory version) {
bytes32 hashedName = keccak256(bytes(name));
| 18,654 |
382 | // RariFundManager This contract is the primary contract powering the Rari Yield Pool.Anyone can deposit to the fund with deposit(string currencyCode, uint256 amount).Anyone can withdraw their funds (with interest) from the fund with withdraw(string currencyCode, uint256 amount). / | contract RariFundManager is Initializable, Ownable {
using SafeMath for uint256;
using SignedSafeMath for int256;
using SafeERC20 for IERC20;
/**
* @dev Boolean that, if true, disables the primary functionality of this RariFundManager.
*/
bool public fundDisabled;
/**
* @dev Address of the RariFundController.
*/
address payable private _rariFundControllerContract;
/**
* @dev Contract of the RariFundController.
*/
RariFundController public rariFundController;
/**
* @dev Address of the RariFundToken.
*/
address private _rariFundTokenContract;
/**
* @dev Contract of the RariFundToken.
*/
RariFundToken public rariFundToken;
/**
* @dev Contract of the RariFundPriceConsumer.
*/
RariFundPriceConsumer public rariFundPriceConsumer;
/**
* @dev Address of the RariFundProxy.
*/
address private _rariFundProxyContract;
/**
* @dev Address of the rebalancer.
*/
address private _rariFundRebalancerAddress;
/**
* @dev Array of currencies supported by the fund.
*/
string[] private _supportedCurrencies;
/**
* @dev Maps `_supportedCurrencies` items to their indexes.
*/
mapping(string => uint8) private _currencyIndexes;
/**
* @dev Maps supported currency codes to their decimal precisions (number of digits after the decimal point).
*/
mapping(string => uint256) private _currencyDecimals;
/**
* @dev Maps supported currency codes to ERC20 token contract addresses.
*/
mapping(string => address) private _erc20Contracts;
/**
* @dev Maps currency codes to arrays of supported pools.
*/
mapping(string => RariFundController.LiquidityPool[]) private _poolsByCurrency;
/**
* @dev Initializer that sets supported ERC20 contract addresses and supported pools for each supported token.
*/
function initialize() public initializer {
// Initialize base contracts
Ownable.initialize(msg.sender);
// Add supported currencies
addSupportedCurrency("DAI", 0x6B175474E89094C44Da98b954EedeAC495271d0F, 18);
addPoolToCurrency("DAI", RariFundController.LiquidityPool.dYdX);
addPoolToCurrency("DAI", RariFundController.LiquidityPool.Compound);
addPoolToCurrency("DAI", RariFundController.LiquidityPool.Aave);
addPoolToCurrency("DAI", RariFundController.LiquidityPool.yVault);
addSupportedCurrency("USDC", 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48, 6);
addPoolToCurrency("USDC", RariFundController.LiquidityPool.dYdX);
addPoolToCurrency("USDC", RariFundController.LiquidityPool.Compound);
addPoolToCurrency("USDC", RariFundController.LiquidityPool.Aave);
addPoolToCurrency("USDC", RariFundController.LiquidityPool.yVault);
addSupportedCurrency("USDT", 0xdAC17F958D2ee523a2206206994597C13D831ec7, 6);
addPoolToCurrency("USDT", RariFundController.LiquidityPool.Compound);
addPoolToCurrency("USDT", RariFundController.LiquidityPool.Aave);
addPoolToCurrency("USDT", RariFundController.LiquidityPool.yVault);
addSupportedCurrency("TUSD", 0x0000000000085d4780B73119b644AE5ecd22b376, 18);
addPoolToCurrency("TUSD", RariFundController.LiquidityPool.Aave);
addPoolToCurrency("TUSD", RariFundController.LiquidityPool.yVault);
addSupportedCurrency("BUSD", 0x4Fabb145d64652a948d72533023f6E7A623C7C53, 18);
addPoolToCurrency("BUSD", RariFundController.LiquidityPool.Aave);
addSupportedCurrency("sUSD", 0x57Ab1ec28D129707052df4dF418D58a2D46d5f51, 18);
addPoolToCurrency("sUSD", RariFundController.LiquidityPool.Aave);
addSupportedCurrency("mUSD", 0xe2f2a5C287993345a840Db3B0845fbC70f5935a5, 18);
addPoolToCurrency("mUSD", RariFundController.LiquidityPool.mStable);
// Initialize raw fund balance cache (can't set initial values in field declarations with proxy storage)
_rawFundBalanceCache = -1;
}
/**
* @dev Marks a token as supported by the fund and stores its decimal precision and ERC20 contract address.
* @param currencyCode The currency code of the token.
* @param erc20Contract The ERC20 contract address of the token.
* @param decimals The decimal precision (number of digits after the decimal point) of the token.
*/
function addSupportedCurrency(string memory currencyCode, address erc20Contract, uint256 decimals) internal {
_currencyIndexes[currencyCode] = uint8(_supportedCurrencies.length);
_supportedCurrencies.push(currencyCode);
_erc20Contracts[currencyCode] = erc20Contract;
_currencyDecimals[currencyCode] = decimals;
}
/**
* @dev Adds a supported pool for a token.
* @param currencyCode The currency code of the token.
* @param pool Pool ID to be supported.
*/
function addPoolToCurrency(string memory currencyCode, RariFundController.LiquidityPool pool) internal {
_poolsByCurrency[currencyCode].push(pool);
}
/**
* @dev Emitted when RariFundManager is upgraded.
*/
event FundManagerUpgraded(address newContract);
/**
* @dev Upgrades RariFundManager.
* Sends data to the new contract and sets the new RariFundToken minter.
* @param newContract The address of the new RariFundManager contract.
*/
function upgradeFundManager(address newContract) external onlyOwner {
require(fundDisabled, "This fund manager contract must be disabled before it can be upgraded.");
// Pass data to the new contract
FundManagerData memory data;
data = FundManagerData(
_netDeposits,
_rawInterestAccruedAtLastFeeRateChange,
_interestFeesGeneratedAtLastFeeRateChange,
_interestFeesClaimed
);
RariFundManager(newContract).setFundManagerData(data);
// Update RariFundToken minter
if (_rariFundTokenContract != address(0)) {
rariFundToken.addMinter(newContract);
rariFundToken.renounceMinter();
}
emit FundManagerUpgraded(newContract);
}
/**
* @dev Old RariFundManager contract authorized to migrate its data to the new one.
*/
address private _authorizedFundManagerDataSource;
/**
* @dev Upgrades RariFundManager.
* Authorizes the source for fund manager data (i.e., the old fund manager).
* @param authorizedFundManagerDataSource Authorized source for data (i.e., the old fund manager).
*/
function authorizeFundManagerDataSource(address authorizedFundManagerDataSource) external onlyOwner {
_authorizedFundManagerDataSource = authorizedFundManagerDataSource;
}
/**
* @dev Struct for data to transfer from the old RariFundManager to the new one.
*/
struct FundManagerData {
int256 netDeposits;
int256 rawInterestAccruedAtLastFeeRateChange;
int256 interestFeesGeneratedAtLastFeeRateChange;
uint256 interestFeesClaimed;
}
/**
* @dev Upgrades RariFundManager.
* Sets data receieved from the old contract.
* @param data The data from the old contract necessary to initialize the new contract.
*/
function setFundManagerData(FundManagerData calldata data) external {
require(_authorizedFundManagerDataSource != address(0) && msg.sender == _authorizedFundManagerDataSource, "Caller is not an authorized source.");
_netDeposits = data.netDeposits;
_rawInterestAccruedAtLastFeeRateChange = data.rawInterestAccruedAtLastFeeRateChange;
_interestFeesGeneratedAtLastFeeRateChange = data.interestFeesGeneratedAtLastFeeRateChange;
_interestFeesClaimed = data.interestFeesClaimed;
_interestFeeRate = RariFundManager(_authorizedFundManagerDataSource).getInterestFeeRate();
_withdrawalFeeRate = RariFundManager(_authorizedFundManagerDataSource).getWithdrawalFeeRate();
}
/**
* @dev Emitted when the RariFundController of the RariFundManager is set or upgraded.
*/
event FundControllerSet(address newContract);
/**
* @dev Sets or upgrades the RariFundController of the RariFundManager.
* @param newContract The address of the new RariFundController contract.
*/
function setFundController(address payable newContract) external onlyOwner {
_rariFundControllerContract = newContract;
rariFundController = RariFundController(_rariFundControllerContract);
emit FundControllerSet(newContract);
}
/**
* @dev Forwards tokens lost in the fund manager (in case of accidental transfer of funds to this contract).
* @param erc20Contract The ERC20 contract address of the token to forward.
* @param to The destination address to which the funds will be forwarded.
* @return Boolean indicating success.
*/
function forwardLostFunds(address erc20Contract, address to) external onlyOwner returns (bool) {
IERC20 token = IERC20(erc20Contract);
uint256 balance = token.balanceOf(address(this));
if (balance <= 0) return false;
token.safeTransfer(to, balance);
return true;
}
/**
* @dev Emitted when the RariFundToken of the RariFundManager is set.
*/
event FundTokenSet(address newContract);
/**
* @dev Sets or upgrades the RariFundToken of the RariFundManager.
* @param newContract The address of the new RariFundToken contract.
*/
function setFundToken(address newContract) external onlyOwner {
_rariFundTokenContract = newContract;
rariFundToken = RariFundToken(_rariFundTokenContract);
emit FundTokenSet(newContract);
}
/**
* @dev Emitted when the RariFundProxy of the RariFundManager is set.
*/
event FundProxySet(address newContract);
/**
* @dev Sets or upgrades the RariFundProxy of the RariFundManager.
* @param newContract The address of the new RariFundProxy contract.
*/
function setFundProxy(address newContract) external onlyOwner {
_rariFundProxyContract = newContract;
emit FundProxySet(newContract);
}
/**
* @dev Throws if called by any account other than the RariFundProxy.
*/
modifier onlyProxy() {
require(_rariFundProxyContract == msg.sender, "Caller is not the RariFundProxy.");
_;
}
/**
* @dev Emitted when the rebalancer of the RariFundManager is set.
*/
event FundRebalancerSet(address newAddress);
/**
* @dev Sets or upgrades the rebalancer of the RariFundManager.
* @param newAddress The Ethereum address of the new rebalancer server.
*/
function setFundRebalancer(address newAddress) external onlyOwner {
_rariFundRebalancerAddress = newAddress;
emit FundRebalancerSet(newAddress);
}
/**
* @dev Throws if called by any account other than the rebalancer.
*/
modifier onlyRebalancer() {
require(_rariFundRebalancerAddress == msg.sender, "Caller is not the rebalancer.");
_;
}
/**
* @dev Emitted when the RariFundPriceConsumer of the RariFundManager is set.
*/
event FundPriceConsumerSet(address newContract);
/**
* @dev Sets or upgrades the RariFundPriceConsumer of the RariFundManager.
* @param newContract The address of the new RariFundPriceConsumer contract.
*/
function setFundPriceConsumer(address newContract) external onlyOwner {
rariFundPriceConsumer = RariFundPriceConsumer(newContract);
emit FundPriceConsumerSet(newContract);
}
/**
* @dev Emitted when the primary functionality of this RariFundManager contract has been disabled.
*/
event FundDisabled();
/**
* @dev Emitted when the primary functionality of this RariFundManager contract has been enabled.
*/
event FundEnabled();
/**
* @dev Disables/enables primary functionality of this RariFundManager so contract(s) can be upgraded.
*/
function setFundDisabled(bool disabled) external onlyOwner {
require(disabled != fundDisabled, "No change to fund enabled/disabled status.");
fundDisabled = disabled;
if (disabled) emit FundDisabled(); else emit FundEnabled();
}
/**
* @dev Throws if fund is disabled.
*/
modifier fundEnabled() {
require(!fundDisabled, "This fund manager contract is disabled. This may be due to an upgrade.");
_;
}
/**
* @dev Boolean indicating if return values of `getPoolBalance` are to be cached.
*/
bool _cachePoolBalances;
/**
* @dev Boolean indicating if dYdX balances returned by `getPoolBalance` are to be cached.
*/
bool _cacheDydxBalances;
/**
* @dev Maps to currency codes to cached pool balances to pool indexes.
*/
mapping(string => mapping(uint8 => uint256)) _poolBalanceCache;
/**
* @dev Cached array of dYdX token addresses.
*/
address[] private _dydxTokenAddressesCache;
/**
* @dev Cached array of dYdX balances.
*/
uint256[] private _dydxBalancesCache;
/**
* @dev Returns the fund controller's balance of the specified currency in the specified pool.
* @dev Ideally, we can add the `view` modifier, but Compound's `getUnderlyingBalance` function (called by `CompoundPoolController.getBalance`) potentially modifies the state.
* @param pool The index of the pool.
* @param currencyCode The currency code of the token.
*/
function getPoolBalance(RariFundController.LiquidityPool pool, string memory currencyCode) internal returns (uint256) {
if (!rariFundController.hasCurrencyInPool(pool, currencyCode)) return 0;
if (_cachePoolBalances || _cacheDydxBalances) {
if (pool == RariFundController.LiquidityPool.dYdX) {
address erc20Contract = _erc20Contracts[currencyCode];
require(erc20Contract != address(0), "Invalid currency code.");
if (_dydxBalancesCache.length == 0) (_dydxTokenAddressesCache, _dydxBalancesCache) = rariFundController.getDydxBalances();
for (uint256 i = 0; i < _dydxBalancesCache.length; i++) if (_dydxTokenAddressesCache[i] == erc20Contract) return _dydxBalancesCache[i];
revert("Failed to get dYdX balance of this currency code.");
} else if (_cachePoolBalances) {
uint8 poolAsUint8 = uint8(pool);
if (_poolBalanceCache[currencyCode][poolAsUint8] == 0) _poolBalanceCache[currencyCode][poolAsUint8] = rariFundController._getPoolBalance(pool, currencyCode);
return _poolBalanceCache[currencyCode][poolAsUint8];
}
}
return rariFundController._getPoolBalance(pool, currencyCode);
}
/**
* @dev Caches dYdX pool balances returned by `getPoolBalance` for the duration of the function.
*/
modifier cacheDydxBalances() {
bool cacheSetPreviously = _cacheDydxBalances;
_cacheDydxBalances = true;
_;
if (!cacheSetPreviously) {
_cacheDydxBalances = false;
if (!_cachePoolBalances) _dydxBalancesCache.length = 0;
}
}
/**
* @dev Caches return values of `getPoolBalance` for the duration of the function.
*/
modifier cachePoolBalances() {
bool cacheSetPreviously = _cachePoolBalances;
_cachePoolBalances = true;
_;
if (!cacheSetPreviously) {
_cachePoolBalances = false;
if (!_cacheDydxBalances) _dydxBalancesCache.length = 0;
for (uint256 i = 0; i < _supportedCurrencies.length; i++) {
string memory currencyCode = _supportedCurrencies[i];
for (uint256 j = 0; j < _poolsByCurrency[currencyCode].length; j++) _poolBalanceCache[currencyCode][uint8(_poolsByCurrency[currencyCode][j])] = 0;
}
}
}
/**
* @notice Returns the fund's raw total balance (all RFT holders' funds + all unclaimed fees) of the specified currency.
* @dev Ideally, we can add the `view` modifier, but Compound's `getUnderlyingBalance` function (called by `RariFundController.getPoolBalance`) potentially modifies the state.
* @param currencyCode The currency code of the balance to be calculated.
*/
function getRawFundBalance(string memory currencyCode) public returns (uint256) {
address erc20Contract = _erc20Contracts[currencyCode];
require(erc20Contract != address(0), "Invalid currency code.");
IERC20 token = IERC20(erc20Contract);
uint256 totalBalance = token.balanceOf(_rariFundControllerContract);
for (uint256 i = 0; i < _poolsByCurrency[currencyCode].length; i++)
totalBalance = totalBalance.add(getPoolBalance(_poolsByCurrency[currencyCode][i], currencyCode));
return totalBalance;
}
/**
* @dev Caches the fund's raw total balance (all RFT holders' funds + all unclaimed fees) of all currencies in USD (scaled by 1e18).
*/
int256 private _rawFundBalanceCache;
/**
* @notice Returns the fund's raw total balance (all RFT holders' funds + all unclaimed fees) of all currencies in USD (scaled by 1e18).
* Returns `_rawFundBalanceCache` if set to save gas.
* @dev Ideally, we can add the `view` modifier, but Compound's `getUnderlyingBalance` function (called by `getRawFundBalance`) potentially modifies the state.
*/
function getRawFundBalance() public returns (uint256) {
if (_rawFundBalanceCache >= 0) return uint256(_rawFundBalanceCache);
uint256[] memory pricesInUsd = rariFundPriceConsumer.getCurrencyPricesInUsd();
return getRawFundBalance(pricesInUsd);
}
/**
* @dev Returns the fund's raw total balance (all RFT holders' funds + all unclaimed fees) of all currencies in USD (scaled by 1e18).
* Accepts prices in USD as a parameter to avoid calculating them every time.
* Ideally, we can add the `view` modifier, but Compound's `getUnderlyingBalance` function (called by `getRawFundBalance`) potentially modifies the state.
*/
function getRawFundBalance(uint256[] memory pricesInUsd) public cacheDydxBalances returns (uint256) {
uint256 totalBalance = 0;
for (uint256 i = 0; i < _supportedCurrencies.length; i++) {
string memory currencyCode = _supportedCurrencies[i];
uint256 balance = getRawFundBalance(currencyCode);
uint256 balanceUsd = balance.mul(pricesInUsd[i]).div(10 ** _currencyDecimals[currencyCode]);
totalBalance = totalBalance.add(balanceUsd);
}
return totalBalance;
}
/**
* @dev Caches the value of `getRawFundBalance()` for the duration of the function.
*/
modifier cacheRawFundBalance() {
bool cacheSetPreviously = _rawFundBalanceCache >= 0;
if (!cacheSetPreviously) _rawFundBalanceCache = toInt256(getRawFundBalance());
_;
if (!cacheSetPreviously) _rawFundBalanceCache = -1;
}
/**
* @notice Returns the fund's total investor balance (all RFT holders' funds but not unclaimed fees) of all currencies in USD (scaled by 1e18).
* @dev Ideally, we can add the `view` modifier, but Compound's `getUnderlyingBalance` function (called by `getRawFundBalance`) potentially modifies the state.
*/
function getFundBalance() public cacheRawFundBalance returns (uint256) {
return getRawFundBalance().sub(getInterestFeesUnclaimed());
}
/**
* @notice Returns the total balance in USD (scaled by 1e18) of `account`.
* @dev Ideally, we can add the `view` modifier, but Compound's `getUnderlyingBalance` function (called by `getRawFundBalance`) potentially modifies the state.
* @param account The account whose balance we are calculating.
*/
function balanceOf(address account) external returns (uint256) {
uint256 rftTotalSupply = rariFundToken.totalSupply();
if (rftTotalSupply == 0) return 0;
uint256 rftBalance = rariFundToken.balanceOf(account);
uint256 fundBalanceUsd = getFundBalance();
uint256 accountBalanceUsd = rftBalance.mul(fundBalanceUsd).div(rftTotalSupply);
return accountBalanceUsd;
}
/**
* @dev Maps currency codes to booleans indicating if they are accepted for deposits.
*/
mapping(string => bool) private _acceptedCurrencies;
/**
* @notice Returns a boolean indicating if deposits in `currencyCode` are currently accepted.
* @param currencyCode The currency code to check.
*/
function isCurrencyAccepted(string memory currencyCode) public view returns (bool) {
return _acceptedCurrencies[currencyCode];
}
/**
* @notice Returns an array of currency codes currently accepted for deposits.
*/
function getAcceptedCurrencies() external view returns (string[] memory) {
uint256 arrayLength = 0;
for (uint256 i = 0; i < _supportedCurrencies.length; i++) if (_acceptedCurrencies[_supportedCurrencies[i]]) arrayLength++;
string[] memory acceptedCurrencies = new string[](arrayLength);
uint256 index = 0;
for (uint256 i = 0; i < _supportedCurrencies.length; i++) if (_acceptedCurrencies[_supportedCurrencies[i]]) {
acceptedCurrencies[index] = _supportedCurrencies[i];
index++;
}
return acceptedCurrencies;
}
/**
* @dev Marks `currencyCodes` as accepted or not accepted.
* @param currencyCodes The currency codes to mark as accepted or not accepted.
* @param accepted An array of booleans indicating if each of `currencyCodes` is to be accepted.
*/
function setAcceptedCurrencies(string[] calldata currencyCodes, bool[] calldata accepted) external onlyRebalancer {
require (currencyCodes.length > 0 && currencyCodes.length == accepted.length, "Lengths of arrays must be equal and both greater than 0.");
for (uint256 i = 0; i < currencyCodes.length; i++) _acceptedCurrencies[currencyCodes[i]] = accepted[i];
}
/**
* @dev Emitted when funds have been deposited to RariFund.
*/
event Deposit(string indexed currencyCode, address indexed sender, address indexed payee, uint256 amount, uint256 amountUsd, uint256 rftMinted);
/**
* @dev Emitted when funds have been withdrawn from RariFund.
*/
event Withdrawal(string indexed currencyCode, address indexed sender, address indexed payee, uint256 amount, uint256 amountUsd, uint256 rftBurned, uint256 withdrawalFeeRate, uint256 amountTransferred);
/**
* @dev Internal function to call the RGT distributor when the fund balance is updated so it can update RGT distribution speeds.
*/
function updateRgtDistributionSpeeds() internal {
IRariGovernanceTokenDistributor rariGovernanceTokenDistributor = rariFundToken.rariGovernanceTokenDistributor();
if (address(rariGovernanceTokenDistributor) != address(0) && block.number < rariGovernanceTokenDistributor.distributionEndBlock()) rariGovernanceTokenDistributor.refreshDistributionSpeeds(IRariGovernanceTokenDistributor.RariPool.Yield, getFundBalance());
}
/**
* @notice Deposits funds from `msg.sender` to the Rari Yield Pool in exchange for RFT minted to `to`.
* You may only deposit currencies accepted by the fund (see `isCurrencyAccepted(string currencyCode)`).
* Please note that you must approve RariFundManager to transfer at least `amount`.
* @param to The address that will receieve the minted RFT.
* @param currencyCode The currency code of the token to be deposited.
* @param amount The amount of tokens to be deposited.
*/
function depositTo(address to, string memory currencyCode, uint256 amount) public fundEnabled {
// Input validation
address erc20Contract = _erc20Contracts[currencyCode];
require(erc20Contract != address(0), "Invalid currency code.");
require(isCurrencyAccepted(currencyCode), "This currency is not currently accepted; please convert your funds to an accepted currency before depositing.");
require(amount > 0, "Deposit amount must be greater than 0.");
// Get currency prices
uint256[] memory pricesInUsd = rariFundPriceConsumer.getCurrencyPricesInUsd();
// Manually cache raw fund balance
bool cacheSetPreviously = _rawFundBalanceCache >= 0;
if (!cacheSetPreviously) _rawFundBalanceCache = toInt256(getRawFundBalance(pricesInUsd));
// Get deposit amount in USD
uint256 amountUsd = amount.mul(pricesInUsd[_currencyIndexes[currencyCode]]).div(10 ** _currencyDecimals[currencyCode]);
// Calculate RFT to mint
uint256 rftTotalSupply = rariFundToken.totalSupply();
uint256 fundBalanceUsd = rftTotalSupply > 0 ? getFundBalance() : 0; // Only set if used
uint256 rftAmount = 0;
if (rftTotalSupply > 0 && fundBalanceUsd > 0) rftAmount = amountUsd.mul(rftTotalSupply).div(fundBalanceUsd);
else rftAmount = amountUsd;
require(rftAmount > 0, "Deposit amount is so small that no RFT would be minted.");
// Update net deposits, transfer funds from msg.sender, mint RFT, and emit event
_netDeposits = _netDeposits.add(int256(amountUsd));
IERC20(erc20Contract).safeTransferFrom(msg.sender, _rariFundControllerContract, amount); // The user must approve the transfer of tokens beforehand
require(rariFundToken.mint(to, rftAmount), "Failed to mint output tokens.");
emit Deposit(currencyCode, msg.sender, to, amount, amountUsd, rftAmount);
// Update _rawFundBalanceCache
_rawFundBalanceCache = _rawFundBalanceCache.add(int256(amountUsd));
// Update RGT distribution speeds
updateRgtDistributionSpeeds();
// Clear _rawFundBalanceCache
if (!cacheSetPreviously) _rawFundBalanceCache = -1;
}
/**
* @notice Deposits funds to the Rari Yield Pool in exchange for RFT.
* You may only deposit currencies accepted by the fund (see `isCurrencyAccepted(string currencyCode)`).
* Please note that you must approve RariFundManager to transfer at least `amount`.
* @param currencyCode The currency code of the token to be deposited.
* @param amount The amount of tokens to be deposited.
*/
function deposit(string calldata currencyCode, uint256 amount) external {
depositTo(msg.sender, currencyCode, amount);
}
/**
* @dev Returns the amount of RFT to burn for a withdrawal (used by `_withdrawFrom`).
* @param from The address from which RFT will be burned.
* @param amountUsd The amount of the withdrawal in USD
*/
function getRftBurnAmount(address from, uint256 amountUsd) internal returns (uint256) {
uint256 rftTotalSupply = rariFundToken.totalSupply();
uint256 fundBalanceUsd = getFundBalance();
require(fundBalanceUsd > 0, "Fund balance is zero.");
uint256 rftAmount = amountUsd.mul(rftTotalSupply).div(fundBalanceUsd);
require(rftAmount <= rariFundToken.balanceOf(from), "Your RFT balance is too low for a withdrawal of this amount.");
require(rftAmount > 0, "Withdrawal amount is so small that no RFT would be burned.");
return rftAmount;
}
/**
* @dev Internal function to withdraw funds from pools if necessary for `RariFundController` to hold at least `amount` of actual tokens.
* This function was separated from `_withdrawFrom` to avoid the stack going too deep.
* @param currencyCode The currency code of the token to be withdrawn.
* @param amount The minimum amount of tokens that must be held by `RariFundController` after withdrawing.
* @return The actual amount withdrawn after potential yVault withdrawal fees.
*/
function withdrawFromPoolsIfNecessary(string memory currencyCode, uint256 amount) internal returns (uint256) {
// Check contract balance of token and withdraw from pools if necessary
address erc20Contract = _erc20Contracts[currencyCode];
IERC20 token = IERC20(erc20Contract);
uint256 contractBalance = token.balanceOf(_rariFundControllerContract);
for (uint256 i = 0; i < _poolsByCurrency[currencyCode].length; i++) {
if (contractBalance >= amount) break;
RariFundController.LiquidityPool pool = _poolsByCurrency[currencyCode][i];
uint256 poolBalance = getPoolBalance(pool, currencyCode);
if (poolBalance <= 0) continue;
uint256 amountLeft = amount.sub(contractBalance);
bool withdrawAll = amountLeft >= poolBalance;
uint256 poolAmount = withdrawAll ? poolBalance : amountLeft;
rariFundController.withdrawFromPoolOptimized(pool, currencyCode, poolAmount, withdrawAll);
if (pool == RariFundController.LiquidityPool.dYdX) {
for (uint256 j = 0; j < _dydxBalancesCache.length; j++) if (_dydxTokenAddressesCache[j] == erc20Contract) _dydxBalancesCache[j] = poolBalance.sub(poolAmount);
} else _poolBalanceCache[currencyCode][uint8(pool)] = poolBalance.sub(poolAmount);
contractBalance = contractBalance.add(poolAmount);
}
require(amount <= contractBalance, "Available balance not enough to cover amount even after withdrawing from pools.");
uint256 realContractBalance = token.balanceOf(_rariFundControllerContract);
return realContractBalance < amount ? realContractBalance : amount;
}
/**
* @dev Internal function to withdraw funds from the Rari Yield Pool to `msg.sender` in exchange for RFT burned from `from`.
* You may only withdraw currencies held by the fund (see `getRawFundBalance(string currencyCode)`).
* Please note that you must approve RariFundManager to burn of the necessary amount of RFT.
* @param from The address from which RFT will be burned.
* @param currencyCode The currency code of the token to be withdrawn.
* @param amount The amount of tokens to be withdrawn.
* @return The amount withdrawn after the fee.
*/
function _withdrawFrom(address from, string memory currencyCode, uint256 amount, uint256[] memory pricesInUsd) internal fundEnabled cachePoolBalances returns (uint256) {
// Input validation
address erc20Contract = _erc20Contracts[currencyCode];
require(erc20Contract != address(0), "Invalid currency code.");
require(amount > 0, "Withdrawal amount must be greater than 0.");
// Withdraw from pools if necessary
uint256 realAmountWithdrawn = withdrawFromPoolsIfNecessary(currencyCode, amount);
// Manually cache raw fund balance
bool cacheSetPreviously = _rawFundBalanceCache >= 0;
if (!cacheSetPreviously) _rawFundBalanceCache = toInt256(getRawFundBalance(pricesInUsd));
// Calculate withdrawal fee and amount after fee
uint256 feeAmount = amount.mul(_withdrawalFeeRate).div(1e18);
uint256 amountAfterFee = amount.sub(feeAmount);
// Get withdrawal amount in USD
uint256 amountUsd = amount.mul(pricesInUsd[_currencyIndexes[currencyCode]]).div(10 ** _currencyDecimals[currencyCode]);
// Calculate RFT to burn
uint256 rftAmount = getRftBurnAmount(from, amountUsd);
// Update net deposits, burn RFT, transfer funds to msg.sender, transfer fee to _withdrawalFeeMasterBeneficiary, and emit event
_netDeposits = _netDeposits.sub(int256(amountUsd));
rariFundToken.fundManagerBurnFrom(from, rftAmount); // The user must approve the burning of tokens beforehand
IERC20 token = IERC20(erc20Contract);
token.safeTransferFrom(_rariFundControllerContract, msg.sender, realAmountWithdrawn < amountAfterFee ? realAmountWithdrawn : amountAfterFee);
if (realAmountWithdrawn > amountAfterFee) token.safeTransferFrom(_rariFundControllerContract, _withdrawalFeeMasterBeneficiary, realAmountWithdrawn.sub(amountAfterFee) < feeAmount ? realAmountWithdrawn.sub(amountAfterFee) : feeAmount);
emit Withdrawal(currencyCode, from, msg.sender, amount, amountUsd, rftAmount, _withdrawalFeeRate, realAmountWithdrawn < amountAfterFee ? realAmountWithdrawn : amountAfterFee);
// Update _rawFundBalanceCache
_rawFundBalanceCache = _rawFundBalanceCache.sub(int256(amountUsd));
// Update RGT distribution speeds
updateRgtDistributionSpeeds();
// Clear _rawFundBalanceCache
if (!cacheSetPreviously) _rawFundBalanceCache = -1;
// Return amount after fee
return realAmountWithdrawn < amountAfterFee ? realAmountWithdrawn : amountAfterFee;
}
/**
* @notice Withdraws funds from the Rari Yield Pool in exchange for RFT.
* You may only withdraw currencies held by the fund (see `getRawFundBalance(string currencyCode)`).
* Please note that you must approve RariFundManager to burn of the necessary amount of RFT.
* @param currencyCode The currency code of the token to be withdrawn.
* @param amount The amount of tokens to be withdrawn.
* @return The amount withdrawn after the fee.
*/
function withdraw(string calldata currencyCode, uint256 amount) external returns (uint256) {
return _withdrawFrom(msg.sender, currencyCode, amount, rariFundPriceConsumer.getCurrencyPricesInUsd());
}
/**
* @dev Withdraws multiple currencies from the Rari Yield Pool to `msg.sender` (RariFundProxy) in exchange for RFT burned from `from`.
* You may only withdraw currencies held by the fund (see `getRawFundBalance(string currencyCode)`).
* Please note that you must approve RariFundManager to burn of the necessary amount of RFT.
* @param from The address from which RFT will be burned.
* @param currencyCodes The currency codes of the tokens to be withdrawn.
* @param amounts The amounts of the tokens to be withdrawn.
* @return Array of amounts withdrawn after fees.
*/
function withdrawFrom(address from, string[] calldata currencyCodes, uint256[] calldata amounts) external onlyProxy cachePoolBalances returns (uint256[] memory) {
// Input validation
require(currencyCodes.length > 0 && currencyCodes.length == amounts.length, "Lengths of currency code and amount arrays must be greater than 0 and equal.");
uint256[] memory pricesInUsd = rariFundPriceConsumer.getCurrencyPricesInUsd();
// Manually cache raw fund balance (no need to check if set previously because the function is external)
_rawFundBalanceCache = toInt256(getRawFundBalance(pricesInUsd));
// Make withdrawals
uint256[] memory amountsAfterFees = new uint256[](currencyCodes.length);
for (uint256 i = 0; i < currencyCodes.length; i++) amountsAfterFees[i] = _withdrawFrom(from, currencyCodes[i], amounts[i], pricesInUsd);
// Reset _rawFundBalanceCache
_rawFundBalanceCache = -1;
// Return amounts withdrawn after fees
return amountsAfterFees;
}
/**
* @dev Net quantity of deposits to the fund (i.e., deposits - withdrawals).
* On deposit, amount deposited is added to `_netDeposits`; on withdrawal, amount withdrawn is subtracted from `_netDeposits`.
*/
int256 private _netDeposits;
/**
* @notice Returns the raw total amount of interest accrued by the fund as a whole (including the fees paid on interest) in USD (scaled by 1e18).
* @dev Ideally, we can add the `view` modifier, but Compound's `getUnderlyingBalance` function (called by `getRawFundBalance`) potentially modifies the state.
*/
function getRawInterestAccrued() public returns (int256) {
return toInt256(getRawFundBalance()).sub(_netDeposits).add(toInt256(_interestFeesClaimed));
}
/**
* @notice Returns the total amount of interest accrued by past and current RFT holders (excluding the fees paid on interest) in USD (scaled by 1e18).
* @dev Ideally, we can add the `view` modifier, but Compound's `getUnderlyingBalance` function (called by `getRawFundBalance`) potentially modifies the state.
*/
function getInterestAccrued() public returns (int256) {
return toInt256(getFundBalance()).sub(_netDeposits);
}
/**
* @dev The proportion of interest accrued that is taken as a service fee (scaled by 1e18).
*/
uint256 private _interestFeeRate;
/**
* @dev Returns the fee rate on interest (proportion of raw interest accrued scaled by 1e18).
*/
function getInterestFeeRate() public view returns (uint256) {
return _interestFeeRate;
}
/**
* @dev Sets the fee rate on interest.
* @param rate The proportion of interest accrued to be taken as a service fee (scaled by 1e18).
*/
function setInterestFeeRate(uint256 rate) external fundEnabled onlyOwner cacheRawFundBalance {
require(rate != _interestFeeRate, "This is already the current interest fee rate.");
require(rate <= 1e18, "The interest fee rate cannot be greater than 100%.");
_depositFees();
_interestFeesGeneratedAtLastFeeRateChange = getInterestFeesGenerated(); // MUST update this first before updating _rawInterestAccruedAtLastFeeRateChange since it depends on it
_rawInterestAccruedAtLastFeeRateChange = getRawInterestAccrued();
_interestFeeRate = rate;
}
/**
* @dev The amount of interest accrued at the time of the most recent change to the fee rate.
*/
int256 private _rawInterestAccruedAtLastFeeRateChange;
/**
* @dev The amount of fees generated on interest at the time of the most recent change to the fee rate.
*/
int256 private _interestFeesGeneratedAtLastFeeRateChange;
/**
* @notice Returns the amount of interest fees accrued by beneficiaries in USD (scaled by 1e18).
* @dev Ideally, we can add the `view` modifier, but Compound's `getUnderlyingBalance` function (called by `getRawFundBalance`) potentially modifies the state.
*/
function getInterestFeesGenerated() public returns (int256) {
int256 rawInterestAccruedSinceLastFeeRateChange = getRawInterestAccrued().sub(_rawInterestAccruedAtLastFeeRateChange);
int256 interestFeesGeneratedSinceLastFeeRateChange = rawInterestAccruedSinceLastFeeRateChange.mul(int256(_interestFeeRate)).div(1e18);
int256 interestFeesGenerated = _interestFeesGeneratedAtLastFeeRateChange.add(interestFeesGeneratedSinceLastFeeRateChange);
return interestFeesGenerated;
}
/**
* @dev The total claimed amount of interest fees.
*/
uint256 private _interestFeesClaimed;
/**
* @dev Returns the total unclaimed amount of interest fees.
* Ideally, we can add the `view` modifier, but Compound's `getUnderlyingBalance` function (called by `getRawFundBalance`) potentially modifies the state.
*/
function getInterestFeesUnclaimed() public returns (uint256) {
int256 interestFeesUnclaimed = getInterestFeesGenerated().sub(toInt256(_interestFeesClaimed));
return interestFeesUnclaimed > 0 ? uint256(interestFeesUnclaimed) : 0;
}
/**
* @dev The master beneficiary of fees on interest; i.e., the recipient of all fees on interest.
*/
address private _interestFeeMasterBeneficiary;
/**
* @dev Sets the master beneficiary of interest fees.
* @param beneficiary The master beneficiary of fees on interest; i.e., the recipient of all fees on interest.
*/
function setInterestFeeMasterBeneficiary(address beneficiary) external fundEnabled onlyOwner {
require(beneficiary != address(0), "Master beneficiary cannot be the zero address.");
_interestFeeMasterBeneficiary = beneficiary;
}
/**
* @dev Emitted when fees on interest are deposited back into the fund.
*/
event InterestFeeDeposit(address beneficiary, uint256 amountUsd);
/**
* @dev Internal function to deposit all accrued fees on interest back into the fund on behalf of the master beneficiary.
* @return Integer indicating success (0), no fees to claim (1), or no RFT to mint (2).
*/
function _depositFees() internal fundEnabled cacheRawFundBalance returns (uint8) {
// Input validation
require(_interestFeeMasterBeneficiary != address(0), "Master beneficiary cannot be the zero address.");
// Get and validate unclaimed interest fees
uint256 amountUsd = getInterestFeesUnclaimed();
if (amountUsd <= 0) return 1;
// Calculate RFT amount to mint and validate
uint256 rftTotalSupply = rariFundToken.totalSupply();
uint256 rftAmount = 0;
if (rftTotalSupply > 0) {
uint256 fundBalanceUsd = getFundBalance();
if (fundBalanceUsd > 0) rftAmount = amountUsd.mul(rftTotalSupply).div(fundBalanceUsd);
else rftAmount = amountUsd;
} else rftAmount = amountUsd;
if (rftAmount <= 0) return 2;
// Update claimed interest fees and net deposits, mint RFT, emit events, and return no error
_interestFeesClaimed = _interestFeesClaimed.add(amountUsd);
_netDeposits = _netDeposits.add(int256(amountUsd));
require(rariFundToken.mint(_interestFeeMasterBeneficiary, rftAmount), "Failed to mint output tokens.");
emit Deposit("USD", _interestFeeMasterBeneficiary, _interestFeeMasterBeneficiary, amountUsd, amountUsd, rftAmount);
emit InterestFeeDeposit(_interestFeeMasterBeneficiary, amountUsd);
// Update RGT distribution speeds
updateRgtDistributionSpeeds();
// Return no error
return 0;
}
/**
* @notice Deposits all accrued fees on interest back into the fund on behalf of the master beneficiary.
* @return Boolean indicating success.
*/
function depositFees() external onlyRebalancer {
uint8 result = _depositFees();
require(result == 0, result == 2 ? "Deposit amount is so small that no RFT would be minted." : "No new fees are available to claim.");
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
* @param value The uint256 to convert.
*/
function toInt256(uint256 value) internal pure returns (int256) {
require(value < 2 ** 255, "SafeCast: value doesn't fit in an int256");
return int256(value);
}
/**
* @dev The current withdrawal fee rate (scaled by 1e18).
*/
uint256 private _withdrawalFeeRate;
/**
* @dev The master beneficiary of withdrawal fees; i.e., the recipient of all withdrawal fees.
*/
address private _withdrawalFeeMasterBeneficiary;
/**
* @dev Returns the withdrawal fee rate (proportion of every withdrawal taken as a service fee scaled by 1e18).
*/
function getWithdrawalFeeRate() public view returns (uint256) {
return _withdrawalFeeRate;
}
/**
* @dev Sets the withdrawal fee rate.
* @param rate The proportion of every withdrawal taken as a service fee (scaled by 1e18).
*/
function setWithdrawalFeeRate(uint256 rate) external fundEnabled onlyOwner {
require(rate != _withdrawalFeeRate, "This is already the current withdrawal fee rate.");
require(rate <= 1e18, "The withdrawal fee rate cannot be greater than 100%.");
_withdrawalFeeRate = rate;
}
/**
* @dev Sets the master beneficiary of withdrawal fees.
* @param beneficiary The master beneficiary of withdrawal fees; i.e., the recipient of all withdrawal fees.
*/
function setWithdrawalFeeMasterBeneficiary(address beneficiary) external fundEnabled onlyOwner {
require(beneficiary != address(0), "Master beneficiary cannot be the zero address.");
_withdrawalFeeMasterBeneficiary = beneficiary;
}
}
| contract RariFundManager is Initializable, Ownable {
using SafeMath for uint256;
using SignedSafeMath for int256;
using SafeERC20 for IERC20;
/**
* @dev Boolean that, if true, disables the primary functionality of this RariFundManager.
*/
bool public fundDisabled;
/**
* @dev Address of the RariFundController.
*/
address payable private _rariFundControllerContract;
/**
* @dev Contract of the RariFundController.
*/
RariFundController public rariFundController;
/**
* @dev Address of the RariFundToken.
*/
address private _rariFundTokenContract;
/**
* @dev Contract of the RariFundToken.
*/
RariFundToken public rariFundToken;
/**
* @dev Contract of the RariFundPriceConsumer.
*/
RariFundPriceConsumer public rariFundPriceConsumer;
/**
* @dev Address of the RariFundProxy.
*/
address private _rariFundProxyContract;
/**
* @dev Address of the rebalancer.
*/
address private _rariFundRebalancerAddress;
/**
* @dev Array of currencies supported by the fund.
*/
string[] private _supportedCurrencies;
/**
* @dev Maps `_supportedCurrencies` items to their indexes.
*/
mapping(string => uint8) private _currencyIndexes;
/**
* @dev Maps supported currency codes to their decimal precisions (number of digits after the decimal point).
*/
mapping(string => uint256) private _currencyDecimals;
/**
* @dev Maps supported currency codes to ERC20 token contract addresses.
*/
mapping(string => address) private _erc20Contracts;
/**
* @dev Maps currency codes to arrays of supported pools.
*/
mapping(string => RariFundController.LiquidityPool[]) private _poolsByCurrency;
/**
* @dev Initializer that sets supported ERC20 contract addresses and supported pools for each supported token.
*/
function initialize() public initializer {
// Initialize base contracts
Ownable.initialize(msg.sender);
// Add supported currencies
addSupportedCurrency("DAI", 0x6B175474E89094C44Da98b954EedeAC495271d0F, 18);
addPoolToCurrency("DAI", RariFundController.LiquidityPool.dYdX);
addPoolToCurrency("DAI", RariFundController.LiquidityPool.Compound);
addPoolToCurrency("DAI", RariFundController.LiquidityPool.Aave);
addPoolToCurrency("DAI", RariFundController.LiquidityPool.yVault);
addSupportedCurrency("USDC", 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48, 6);
addPoolToCurrency("USDC", RariFundController.LiquidityPool.dYdX);
addPoolToCurrency("USDC", RariFundController.LiquidityPool.Compound);
addPoolToCurrency("USDC", RariFundController.LiquidityPool.Aave);
addPoolToCurrency("USDC", RariFundController.LiquidityPool.yVault);
addSupportedCurrency("USDT", 0xdAC17F958D2ee523a2206206994597C13D831ec7, 6);
addPoolToCurrency("USDT", RariFundController.LiquidityPool.Compound);
addPoolToCurrency("USDT", RariFundController.LiquidityPool.Aave);
addPoolToCurrency("USDT", RariFundController.LiquidityPool.yVault);
addSupportedCurrency("TUSD", 0x0000000000085d4780B73119b644AE5ecd22b376, 18);
addPoolToCurrency("TUSD", RariFundController.LiquidityPool.Aave);
addPoolToCurrency("TUSD", RariFundController.LiquidityPool.yVault);
addSupportedCurrency("BUSD", 0x4Fabb145d64652a948d72533023f6E7A623C7C53, 18);
addPoolToCurrency("BUSD", RariFundController.LiquidityPool.Aave);
addSupportedCurrency("sUSD", 0x57Ab1ec28D129707052df4dF418D58a2D46d5f51, 18);
addPoolToCurrency("sUSD", RariFundController.LiquidityPool.Aave);
addSupportedCurrency("mUSD", 0xe2f2a5C287993345a840Db3B0845fbC70f5935a5, 18);
addPoolToCurrency("mUSD", RariFundController.LiquidityPool.mStable);
// Initialize raw fund balance cache (can't set initial values in field declarations with proxy storage)
_rawFundBalanceCache = -1;
}
/**
* @dev Marks a token as supported by the fund and stores its decimal precision and ERC20 contract address.
* @param currencyCode The currency code of the token.
* @param erc20Contract The ERC20 contract address of the token.
* @param decimals The decimal precision (number of digits after the decimal point) of the token.
*/
function addSupportedCurrency(string memory currencyCode, address erc20Contract, uint256 decimals) internal {
_currencyIndexes[currencyCode] = uint8(_supportedCurrencies.length);
_supportedCurrencies.push(currencyCode);
_erc20Contracts[currencyCode] = erc20Contract;
_currencyDecimals[currencyCode] = decimals;
}
/**
* @dev Adds a supported pool for a token.
* @param currencyCode The currency code of the token.
* @param pool Pool ID to be supported.
*/
function addPoolToCurrency(string memory currencyCode, RariFundController.LiquidityPool pool) internal {
_poolsByCurrency[currencyCode].push(pool);
}
/**
* @dev Emitted when RariFundManager is upgraded.
*/
event FundManagerUpgraded(address newContract);
/**
* @dev Upgrades RariFundManager.
* Sends data to the new contract and sets the new RariFundToken minter.
* @param newContract The address of the new RariFundManager contract.
*/
function upgradeFundManager(address newContract) external onlyOwner {
require(fundDisabled, "This fund manager contract must be disabled before it can be upgraded.");
// Pass data to the new contract
FundManagerData memory data;
data = FundManagerData(
_netDeposits,
_rawInterestAccruedAtLastFeeRateChange,
_interestFeesGeneratedAtLastFeeRateChange,
_interestFeesClaimed
);
RariFundManager(newContract).setFundManagerData(data);
// Update RariFundToken minter
if (_rariFundTokenContract != address(0)) {
rariFundToken.addMinter(newContract);
rariFundToken.renounceMinter();
}
emit FundManagerUpgraded(newContract);
}
/**
* @dev Old RariFundManager contract authorized to migrate its data to the new one.
*/
address private _authorizedFundManagerDataSource;
/**
* @dev Upgrades RariFundManager.
* Authorizes the source for fund manager data (i.e., the old fund manager).
* @param authorizedFundManagerDataSource Authorized source for data (i.e., the old fund manager).
*/
function authorizeFundManagerDataSource(address authorizedFundManagerDataSource) external onlyOwner {
_authorizedFundManagerDataSource = authorizedFundManagerDataSource;
}
/**
* @dev Struct for data to transfer from the old RariFundManager to the new one.
*/
struct FundManagerData {
int256 netDeposits;
int256 rawInterestAccruedAtLastFeeRateChange;
int256 interestFeesGeneratedAtLastFeeRateChange;
uint256 interestFeesClaimed;
}
/**
* @dev Upgrades RariFundManager.
* Sets data receieved from the old contract.
* @param data The data from the old contract necessary to initialize the new contract.
*/
function setFundManagerData(FundManagerData calldata data) external {
require(_authorizedFundManagerDataSource != address(0) && msg.sender == _authorizedFundManagerDataSource, "Caller is not an authorized source.");
_netDeposits = data.netDeposits;
_rawInterestAccruedAtLastFeeRateChange = data.rawInterestAccruedAtLastFeeRateChange;
_interestFeesGeneratedAtLastFeeRateChange = data.interestFeesGeneratedAtLastFeeRateChange;
_interestFeesClaimed = data.interestFeesClaimed;
_interestFeeRate = RariFundManager(_authorizedFundManagerDataSource).getInterestFeeRate();
_withdrawalFeeRate = RariFundManager(_authorizedFundManagerDataSource).getWithdrawalFeeRate();
}
/**
* @dev Emitted when the RariFundController of the RariFundManager is set or upgraded.
*/
event FundControllerSet(address newContract);
/**
* @dev Sets or upgrades the RariFundController of the RariFundManager.
* @param newContract The address of the new RariFundController contract.
*/
function setFundController(address payable newContract) external onlyOwner {
_rariFundControllerContract = newContract;
rariFundController = RariFundController(_rariFundControllerContract);
emit FundControllerSet(newContract);
}
/**
* @dev Forwards tokens lost in the fund manager (in case of accidental transfer of funds to this contract).
* @param erc20Contract The ERC20 contract address of the token to forward.
* @param to The destination address to which the funds will be forwarded.
* @return Boolean indicating success.
*/
function forwardLostFunds(address erc20Contract, address to) external onlyOwner returns (bool) {
IERC20 token = IERC20(erc20Contract);
uint256 balance = token.balanceOf(address(this));
if (balance <= 0) return false;
token.safeTransfer(to, balance);
return true;
}
/**
* @dev Emitted when the RariFundToken of the RariFundManager is set.
*/
event FundTokenSet(address newContract);
/**
* @dev Sets or upgrades the RariFundToken of the RariFundManager.
* @param newContract The address of the new RariFundToken contract.
*/
function setFundToken(address newContract) external onlyOwner {
_rariFundTokenContract = newContract;
rariFundToken = RariFundToken(_rariFundTokenContract);
emit FundTokenSet(newContract);
}
/**
* @dev Emitted when the RariFundProxy of the RariFundManager is set.
*/
event FundProxySet(address newContract);
/**
* @dev Sets or upgrades the RariFundProxy of the RariFundManager.
* @param newContract The address of the new RariFundProxy contract.
*/
function setFundProxy(address newContract) external onlyOwner {
_rariFundProxyContract = newContract;
emit FundProxySet(newContract);
}
/**
* @dev Throws if called by any account other than the RariFundProxy.
*/
modifier onlyProxy() {
require(_rariFundProxyContract == msg.sender, "Caller is not the RariFundProxy.");
_;
}
/**
* @dev Emitted when the rebalancer of the RariFundManager is set.
*/
event FundRebalancerSet(address newAddress);
/**
* @dev Sets or upgrades the rebalancer of the RariFundManager.
* @param newAddress The Ethereum address of the new rebalancer server.
*/
function setFundRebalancer(address newAddress) external onlyOwner {
_rariFundRebalancerAddress = newAddress;
emit FundRebalancerSet(newAddress);
}
/**
* @dev Throws if called by any account other than the rebalancer.
*/
modifier onlyRebalancer() {
require(_rariFundRebalancerAddress == msg.sender, "Caller is not the rebalancer.");
_;
}
/**
* @dev Emitted when the RariFundPriceConsumer of the RariFundManager is set.
*/
event FundPriceConsumerSet(address newContract);
/**
* @dev Sets or upgrades the RariFundPriceConsumer of the RariFundManager.
* @param newContract The address of the new RariFundPriceConsumer contract.
*/
function setFundPriceConsumer(address newContract) external onlyOwner {
rariFundPriceConsumer = RariFundPriceConsumer(newContract);
emit FundPriceConsumerSet(newContract);
}
/**
* @dev Emitted when the primary functionality of this RariFundManager contract has been disabled.
*/
event FundDisabled();
/**
* @dev Emitted when the primary functionality of this RariFundManager contract has been enabled.
*/
event FundEnabled();
/**
* @dev Disables/enables primary functionality of this RariFundManager so contract(s) can be upgraded.
*/
function setFundDisabled(bool disabled) external onlyOwner {
require(disabled != fundDisabled, "No change to fund enabled/disabled status.");
fundDisabled = disabled;
if (disabled) emit FundDisabled(); else emit FundEnabled();
}
/**
* @dev Throws if fund is disabled.
*/
modifier fundEnabled() {
require(!fundDisabled, "This fund manager contract is disabled. This may be due to an upgrade.");
_;
}
/**
* @dev Boolean indicating if return values of `getPoolBalance` are to be cached.
*/
bool _cachePoolBalances;
/**
* @dev Boolean indicating if dYdX balances returned by `getPoolBalance` are to be cached.
*/
bool _cacheDydxBalances;
/**
* @dev Maps to currency codes to cached pool balances to pool indexes.
*/
mapping(string => mapping(uint8 => uint256)) _poolBalanceCache;
/**
* @dev Cached array of dYdX token addresses.
*/
address[] private _dydxTokenAddressesCache;
/**
* @dev Cached array of dYdX balances.
*/
uint256[] private _dydxBalancesCache;
/**
* @dev Returns the fund controller's balance of the specified currency in the specified pool.
* @dev Ideally, we can add the `view` modifier, but Compound's `getUnderlyingBalance` function (called by `CompoundPoolController.getBalance`) potentially modifies the state.
* @param pool The index of the pool.
* @param currencyCode The currency code of the token.
*/
function getPoolBalance(RariFundController.LiquidityPool pool, string memory currencyCode) internal returns (uint256) {
if (!rariFundController.hasCurrencyInPool(pool, currencyCode)) return 0;
if (_cachePoolBalances || _cacheDydxBalances) {
if (pool == RariFundController.LiquidityPool.dYdX) {
address erc20Contract = _erc20Contracts[currencyCode];
require(erc20Contract != address(0), "Invalid currency code.");
if (_dydxBalancesCache.length == 0) (_dydxTokenAddressesCache, _dydxBalancesCache) = rariFundController.getDydxBalances();
for (uint256 i = 0; i < _dydxBalancesCache.length; i++) if (_dydxTokenAddressesCache[i] == erc20Contract) return _dydxBalancesCache[i];
revert("Failed to get dYdX balance of this currency code.");
} else if (_cachePoolBalances) {
uint8 poolAsUint8 = uint8(pool);
if (_poolBalanceCache[currencyCode][poolAsUint8] == 0) _poolBalanceCache[currencyCode][poolAsUint8] = rariFundController._getPoolBalance(pool, currencyCode);
return _poolBalanceCache[currencyCode][poolAsUint8];
}
}
return rariFundController._getPoolBalance(pool, currencyCode);
}
/**
* @dev Caches dYdX pool balances returned by `getPoolBalance` for the duration of the function.
*/
modifier cacheDydxBalances() {
bool cacheSetPreviously = _cacheDydxBalances;
_cacheDydxBalances = true;
_;
if (!cacheSetPreviously) {
_cacheDydxBalances = false;
if (!_cachePoolBalances) _dydxBalancesCache.length = 0;
}
}
/**
* @dev Caches return values of `getPoolBalance` for the duration of the function.
*/
modifier cachePoolBalances() {
bool cacheSetPreviously = _cachePoolBalances;
_cachePoolBalances = true;
_;
if (!cacheSetPreviously) {
_cachePoolBalances = false;
if (!_cacheDydxBalances) _dydxBalancesCache.length = 0;
for (uint256 i = 0; i < _supportedCurrencies.length; i++) {
string memory currencyCode = _supportedCurrencies[i];
for (uint256 j = 0; j < _poolsByCurrency[currencyCode].length; j++) _poolBalanceCache[currencyCode][uint8(_poolsByCurrency[currencyCode][j])] = 0;
}
}
}
/**
* @notice Returns the fund's raw total balance (all RFT holders' funds + all unclaimed fees) of the specified currency.
* @dev Ideally, we can add the `view` modifier, but Compound's `getUnderlyingBalance` function (called by `RariFundController.getPoolBalance`) potentially modifies the state.
* @param currencyCode The currency code of the balance to be calculated.
*/
function getRawFundBalance(string memory currencyCode) public returns (uint256) {
address erc20Contract = _erc20Contracts[currencyCode];
require(erc20Contract != address(0), "Invalid currency code.");
IERC20 token = IERC20(erc20Contract);
uint256 totalBalance = token.balanceOf(_rariFundControllerContract);
for (uint256 i = 0; i < _poolsByCurrency[currencyCode].length; i++)
totalBalance = totalBalance.add(getPoolBalance(_poolsByCurrency[currencyCode][i], currencyCode));
return totalBalance;
}
/**
* @dev Caches the fund's raw total balance (all RFT holders' funds + all unclaimed fees) of all currencies in USD (scaled by 1e18).
*/
int256 private _rawFundBalanceCache;
/**
* @notice Returns the fund's raw total balance (all RFT holders' funds + all unclaimed fees) of all currencies in USD (scaled by 1e18).
* Returns `_rawFundBalanceCache` if set to save gas.
* @dev Ideally, we can add the `view` modifier, but Compound's `getUnderlyingBalance` function (called by `getRawFundBalance`) potentially modifies the state.
*/
function getRawFundBalance() public returns (uint256) {
if (_rawFundBalanceCache >= 0) return uint256(_rawFundBalanceCache);
uint256[] memory pricesInUsd = rariFundPriceConsumer.getCurrencyPricesInUsd();
return getRawFundBalance(pricesInUsd);
}
/**
* @dev Returns the fund's raw total balance (all RFT holders' funds + all unclaimed fees) of all currencies in USD (scaled by 1e18).
* Accepts prices in USD as a parameter to avoid calculating them every time.
* Ideally, we can add the `view` modifier, but Compound's `getUnderlyingBalance` function (called by `getRawFundBalance`) potentially modifies the state.
*/
function getRawFundBalance(uint256[] memory pricesInUsd) public cacheDydxBalances returns (uint256) {
uint256 totalBalance = 0;
for (uint256 i = 0; i < _supportedCurrencies.length; i++) {
string memory currencyCode = _supportedCurrencies[i];
uint256 balance = getRawFundBalance(currencyCode);
uint256 balanceUsd = balance.mul(pricesInUsd[i]).div(10 ** _currencyDecimals[currencyCode]);
totalBalance = totalBalance.add(balanceUsd);
}
return totalBalance;
}
/**
* @dev Caches the value of `getRawFundBalance()` for the duration of the function.
*/
modifier cacheRawFundBalance() {
bool cacheSetPreviously = _rawFundBalanceCache >= 0;
if (!cacheSetPreviously) _rawFundBalanceCache = toInt256(getRawFundBalance());
_;
if (!cacheSetPreviously) _rawFundBalanceCache = -1;
}
/**
* @notice Returns the fund's total investor balance (all RFT holders' funds but not unclaimed fees) of all currencies in USD (scaled by 1e18).
* @dev Ideally, we can add the `view` modifier, but Compound's `getUnderlyingBalance` function (called by `getRawFundBalance`) potentially modifies the state.
*/
function getFundBalance() public cacheRawFundBalance returns (uint256) {
return getRawFundBalance().sub(getInterestFeesUnclaimed());
}
/**
* @notice Returns the total balance in USD (scaled by 1e18) of `account`.
* @dev Ideally, we can add the `view` modifier, but Compound's `getUnderlyingBalance` function (called by `getRawFundBalance`) potentially modifies the state.
* @param account The account whose balance we are calculating.
*/
function balanceOf(address account) external returns (uint256) {
uint256 rftTotalSupply = rariFundToken.totalSupply();
if (rftTotalSupply == 0) return 0;
uint256 rftBalance = rariFundToken.balanceOf(account);
uint256 fundBalanceUsd = getFundBalance();
uint256 accountBalanceUsd = rftBalance.mul(fundBalanceUsd).div(rftTotalSupply);
return accountBalanceUsd;
}
/**
* @dev Maps currency codes to booleans indicating if they are accepted for deposits.
*/
mapping(string => bool) private _acceptedCurrencies;
/**
* @notice Returns a boolean indicating if deposits in `currencyCode` are currently accepted.
* @param currencyCode The currency code to check.
*/
function isCurrencyAccepted(string memory currencyCode) public view returns (bool) {
return _acceptedCurrencies[currencyCode];
}
/**
* @notice Returns an array of currency codes currently accepted for deposits.
*/
function getAcceptedCurrencies() external view returns (string[] memory) {
uint256 arrayLength = 0;
for (uint256 i = 0; i < _supportedCurrencies.length; i++) if (_acceptedCurrencies[_supportedCurrencies[i]]) arrayLength++;
string[] memory acceptedCurrencies = new string[](arrayLength);
uint256 index = 0;
for (uint256 i = 0; i < _supportedCurrencies.length; i++) if (_acceptedCurrencies[_supportedCurrencies[i]]) {
acceptedCurrencies[index] = _supportedCurrencies[i];
index++;
}
return acceptedCurrencies;
}
/**
* @dev Marks `currencyCodes` as accepted or not accepted.
* @param currencyCodes The currency codes to mark as accepted or not accepted.
* @param accepted An array of booleans indicating if each of `currencyCodes` is to be accepted.
*/
function setAcceptedCurrencies(string[] calldata currencyCodes, bool[] calldata accepted) external onlyRebalancer {
require (currencyCodes.length > 0 && currencyCodes.length == accepted.length, "Lengths of arrays must be equal and both greater than 0.");
for (uint256 i = 0; i < currencyCodes.length; i++) _acceptedCurrencies[currencyCodes[i]] = accepted[i];
}
/**
* @dev Emitted when funds have been deposited to RariFund.
*/
event Deposit(string indexed currencyCode, address indexed sender, address indexed payee, uint256 amount, uint256 amountUsd, uint256 rftMinted);
/**
* @dev Emitted when funds have been withdrawn from RariFund.
*/
event Withdrawal(string indexed currencyCode, address indexed sender, address indexed payee, uint256 amount, uint256 amountUsd, uint256 rftBurned, uint256 withdrawalFeeRate, uint256 amountTransferred);
/**
* @dev Internal function to call the RGT distributor when the fund balance is updated so it can update RGT distribution speeds.
*/
function updateRgtDistributionSpeeds() internal {
IRariGovernanceTokenDistributor rariGovernanceTokenDistributor = rariFundToken.rariGovernanceTokenDistributor();
if (address(rariGovernanceTokenDistributor) != address(0) && block.number < rariGovernanceTokenDistributor.distributionEndBlock()) rariGovernanceTokenDistributor.refreshDistributionSpeeds(IRariGovernanceTokenDistributor.RariPool.Yield, getFundBalance());
}
/**
* @notice Deposits funds from `msg.sender` to the Rari Yield Pool in exchange for RFT minted to `to`.
* You may only deposit currencies accepted by the fund (see `isCurrencyAccepted(string currencyCode)`).
* Please note that you must approve RariFundManager to transfer at least `amount`.
* @param to The address that will receieve the minted RFT.
* @param currencyCode The currency code of the token to be deposited.
* @param amount The amount of tokens to be deposited.
*/
function depositTo(address to, string memory currencyCode, uint256 amount) public fundEnabled {
// Input validation
address erc20Contract = _erc20Contracts[currencyCode];
require(erc20Contract != address(0), "Invalid currency code.");
require(isCurrencyAccepted(currencyCode), "This currency is not currently accepted; please convert your funds to an accepted currency before depositing.");
require(amount > 0, "Deposit amount must be greater than 0.");
// Get currency prices
uint256[] memory pricesInUsd = rariFundPriceConsumer.getCurrencyPricesInUsd();
// Manually cache raw fund balance
bool cacheSetPreviously = _rawFundBalanceCache >= 0;
if (!cacheSetPreviously) _rawFundBalanceCache = toInt256(getRawFundBalance(pricesInUsd));
// Get deposit amount in USD
uint256 amountUsd = amount.mul(pricesInUsd[_currencyIndexes[currencyCode]]).div(10 ** _currencyDecimals[currencyCode]);
// Calculate RFT to mint
uint256 rftTotalSupply = rariFundToken.totalSupply();
uint256 fundBalanceUsd = rftTotalSupply > 0 ? getFundBalance() : 0; // Only set if used
uint256 rftAmount = 0;
if (rftTotalSupply > 0 && fundBalanceUsd > 0) rftAmount = amountUsd.mul(rftTotalSupply).div(fundBalanceUsd);
else rftAmount = amountUsd;
require(rftAmount > 0, "Deposit amount is so small that no RFT would be minted.");
// Update net deposits, transfer funds from msg.sender, mint RFT, and emit event
_netDeposits = _netDeposits.add(int256(amountUsd));
IERC20(erc20Contract).safeTransferFrom(msg.sender, _rariFundControllerContract, amount); // The user must approve the transfer of tokens beforehand
require(rariFundToken.mint(to, rftAmount), "Failed to mint output tokens.");
emit Deposit(currencyCode, msg.sender, to, amount, amountUsd, rftAmount);
// Update _rawFundBalanceCache
_rawFundBalanceCache = _rawFundBalanceCache.add(int256(amountUsd));
// Update RGT distribution speeds
updateRgtDistributionSpeeds();
// Clear _rawFundBalanceCache
if (!cacheSetPreviously) _rawFundBalanceCache = -1;
}
/**
* @notice Deposits funds to the Rari Yield Pool in exchange for RFT.
* You may only deposit currencies accepted by the fund (see `isCurrencyAccepted(string currencyCode)`).
* Please note that you must approve RariFundManager to transfer at least `amount`.
* @param currencyCode The currency code of the token to be deposited.
* @param amount The amount of tokens to be deposited.
*/
function deposit(string calldata currencyCode, uint256 amount) external {
depositTo(msg.sender, currencyCode, amount);
}
/**
* @dev Returns the amount of RFT to burn for a withdrawal (used by `_withdrawFrom`).
* @param from The address from which RFT will be burned.
* @param amountUsd The amount of the withdrawal in USD
*/
function getRftBurnAmount(address from, uint256 amountUsd) internal returns (uint256) {
uint256 rftTotalSupply = rariFundToken.totalSupply();
uint256 fundBalanceUsd = getFundBalance();
require(fundBalanceUsd > 0, "Fund balance is zero.");
uint256 rftAmount = amountUsd.mul(rftTotalSupply).div(fundBalanceUsd);
require(rftAmount <= rariFundToken.balanceOf(from), "Your RFT balance is too low for a withdrawal of this amount.");
require(rftAmount > 0, "Withdrawal amount is so small that no RFT would be burned.");
return rftAmount;
}
/**
* @dev Internal function to withdraw funds from pools if necessary for `RariFundController` to hold at least `amount` of actual tokens.
* This function was separated from `_withdrawFrom` to avoid the stack going too deep.
* @param currencyCode The currency code of the token to be withdrawn.
* @param amount The minimum amount of tokens that must be held by `RariFundController` after withdrawing.
* @return The actual amount withdrawn after potential yVault withdrawal fees.
*/
function withdrawFromPoolsIfNecessary(string memory currencyCode, uint256 amount) internal returns (uint256) {
// Check contract balance of token and withdraw from pools if necessary
address erc20Contract = _erc20Contracts[currencyCode];
IERC20 token = IERC20(erc20Contract);
uint256 contractBalance = token.balanceOf(_rariFundControllerContract);
for (uint256 i = 0; i < _poolsByCurrency[currencyCode].length; i++) {
if (contractBalance >= amount) break;
RariFundController.LiquidityPool pool = _poolsByCurrency[currencyCode][i];
uint256 poolBalance = getPoolBalance(pool, currencyCode);
if (poolBalance <= 0) continue;
uint256 amountLeft = amount.sub(contractBalance);
bool withdrawAll = amountLeft >= poolBalance;
uint256 poolAmount = withdrawAll ? poolBalance : amountLeft;
rariFundController.withdrawFromPoolOptimized(pool, currencyCode, poolAmount, withdrawAll);
if (pool == RariFundController.LiquidityPool.dYdX) {
for (uint256 j = 0; j < _dydxBalancesCache.length; j++) if (_dydxTokenAddressesCache[j] == erc20Contract) _dydxBalancesCache[j] = poolBalance.sub(poolAmount);
} else _poolBalanceCache[currencyCode][uint8(pool)] = poolBalance.sub(poolAmount);
contractBalance = contractBalance.add(poolAmount);
}
require(amount <= contractBalance, "Available balance not enough to cover amount even after withdrawing from pools.");
uint256 realContractBalance = token.balanceOf(_rariFundControllerContract);
return realContractBalance < amount ? realContractBalance : amount;
}
/**
* @dev Internal function to withdraw funds from the Rari Yield Pool to `msg.sender` in exchange for RFT burned from `from`.
* You may only withdraw currencies held by the fund (see `getRawFundBalance(string currencyCode)`).
* Please note that you must approve RariFundManager to burn of the necessary amount of RFT.
* @param from The address from which RFT will be burned.
* @param currencyCode The currency code of the token to be withdrawn.
* @param amount The amount of tokens to be withdrawn.
* @return The amount withdrawn after the fee.
*/
function _withdrawFrom(address from, string memory currencyCode, uint256 amount, uint256[] memory pricesInUsd) internal fundEnabled cachePoolBalances returns (uint256) {
// Input validation
address erc20Contract = _erc20Contracts[currencyCode];
require(erc20Contract != address(0), "Invalid currency code.");
require(amount > 0, "Withdrawal amount must be greater than 0.");
// Withdraw from pools if necessary
uint256 realAmountWithdrawn = withdrawFromPoolsIfNecessary(currencyCode, amount);
// Manually cache raw fund balance
bool cacheSetPreviously = _rawFundBalanceCache >= 0;
if (!cacheSetPreviously) _rawFundBalanceCache = toInt256(getRawFundBalance(pricesInUsd));
// Calculate withdrawal fee and amount after fee
uint256 feeAmount = amount.mul(_withdrawalFeeRate).div(1e18);
uint256 amountAfterFee = amount.sub(feeAmount);
// Get withdrawal amount in USD
uint256 amountUsd = amount.mul(pricesInUsd[_currencyIndexes[currencyCode]]).div(10 ** _currencyDecimals[currencyCode]);
// Calculate RFT to burn
uint256 rftAmount = getRftBurnAmount(from, amountUsd);
// Update net deposits, burn RFT, transfer funds to msg.sender, transfer fee to _withdrawalFeeMasterBeneficiary, and emit event
_netDeposits = _netDeposits.sub(int256(amountUsd));
rariFundToken.fundManagerBurnFrom(from, rftAmount); // The user must approve the burning of tokens beforehand
IERC20 token = IERC20(erc20Contract);
token.safeTransferFrom(_rariFundControllerContract, msg.sender, realAmountWithdrawn < amountAfterFee ? realAmountWithdrawn : amountAfterFee);
if (realAmountWithdrawn > amountAfterFee) token.safeTransferFrom(_rariFundControllerContract, _withdrawalFeeMasterBeneficiary, realAmountWithdrawn.sub(amountAfterFee) < feeAmount ? realAmountWithdrawn.sub(amountAfterFee) : feeAmount);
emit Withdrawal(currencyCode, from, msg.sender, amount, amountUsd, rftAmount, _withdrawalFeeRate, realAmountWithdrawn < amountAfterFee ? realAmountWithdrawn : amountAfterFee);
// Update _rawFundBalanceCache
_rawFundBalanceCache = _rawFundBalanceCache.sub(int256(amountUsd));
// Update RGT distribution speeds
updateRgtDistributionSpeeds();
// Clear _rawFundBalanceCache
if (!cacheSetPreviously) _rawFundBalanceCache = -1;
// Return amount after fee
return realAmountWithdrawn < amountAfterFee ? realAmountWithdrawn : amountAfterFee;
}
/**
* @notice Withdraws funds from the Rari Yield Pool in exchange for RFT.
* You may only withdraw currencies held by the fund (see `getRawFundBalance(string currencyCode)`).
* Please note that you must approve RariFundManager to burn of the necessary amount of RFT.
* @param currencyCode The currency code of the token to be withdrawn.
* @param amount The amount of tokens to be withdrawn.
* @return The amount withdrawn after the fee.
*/
function withdraw(string calldata currencyCode, uint256 amount) external returns (uint256) {
return _withdrawFrom(msg.sender, currencyCode, amount, rariFundPriceConsumer.getCurrencyPricesInUsd());
}
/**
* @dev Withdraws multiple currencies from the Rari Yield Pool to `msg.sender` (RariFundProxy) in exchange for RFT burned from `from`.
* You may only withdraw currencies held by the fund (see `getRawFundBalance(string currencyCode)`).
* Please note that you must approve RariFundManager to burn of the necessary amount of RFT.
* @param from The address from which RFT will be burned.
* @param currencyCodes The currency codes of the tokens to be withdrawn.
* @param amounts The amounts of the tokens to be withdrawn.
* @return Array of amounts withdrawn after fees.
*/
function withdrawFrom(address from, string[] calldata currencyCodes, uint256[] calldata amounts) external onlyProxy cachePoolBalances returns (uint256[] memory) {
// Input validation
require(currencyCodes.length > 0 && currencyCodes.length == amounts.length, "Lengths of currency code and amount arrays must be greater than 0 and equal.");
uint256[] memory pricesInUsd = rariFundPriceConsumer.getCurrencyPricesInUsd();
// Manually cache raw fund balance (no need to check if set previously because the function is external)
_rawFundBalanceCache = toInt256(getRawFundBalance(pricesInUsd));
// Make withdrawals
uint256[] memory amountsAfterFees = new uint256[](currencyCodes.length);
for (uint256 i = 0; i < currencyCodes.length; i++) amountsAfterFees[i] = _withdrawFrom(from, currencyCodes[i], amounts[i], pricesInUsd);
// Reset _rawFundBalanceCache
_rawFundBalanceCache = -1;
// Return amounts withdrawn after fees
return amountsAfterFees;
}
/**
* @dev Net quantity of deposits to the fund (i.e., deposits - withdrawals).
* On deposit, amount deposited is added to `_netDeposits`; on withdrawal, amount withdrawn is subtracted from `_netDeposits`.
*/
int256 private _netDeposits;
/**
* @notice Returns the raw total amount of interest accrued by the fund as a whole (including the fees paid on interest) in USD (scaled by 1e18).
* @dev Ideally, we can add the `view` modifier, but Compound's `getUnderlyingBalance` function (called by `getRawFundBalance`) potentially modifies the state.
*/
function getRawInterestAccrued() public returns (int256) {
return toInt256(getRawFundBalance()).sub(_netDeposits).add(toInt256(_interestFeesClaimed));
}
/**
* @notice Returns the total amount of interest accrued by past and current RFT holders (excluding the fees paid on interest) in USD (scaled by 1e18).
* @dev Ideally, we can add the `view` modifier, but Compound's `getUnderlyingBalance` function (called by `getRawFundBalance`) potentially modifies the state.
*/
function getInterestAccrued() public returns (int256) {
return toInt256(getFundBalance()).sub(_netDeposits);
}
/**
* @dev The proportion of interest accrued that is taken as a service fee (scaled by 1e18).
*/
uint256 private _interestFeeRate;
/**
* @dev Returns the fee rate on interest (proportion of raw interest accrued scaled by 1e18).
*/
function getInterestFeeRate() public view returns (uint256) {
return _interestFeeRate;
}
/**
* @dev Sets the fee rate on interest.
* @param rate The proportion of interest accrued to be taken as a service fee (scaled by 1e18).
*/
function setInterestFeeRate(uint256 rate) external fundEnabled onlyOwner cacheRawFundBalance {
require(rate != _interestFeeRate, "This is already the current interest fee rate.");
require(rate <= 1e18, "The interest fee rate cannot be greater than 100%.");
_depositFees();
_interestFeesGeneratedAtLastFeeRateChange = getInterestFeesGenerated(); // MUST update this first before updating _rawInterestAccruedAtLastFeeRateChange since it depends on it
_rawInterestAccruedAtLastFeeRateChange = getRawInterestAccrued();
_interestFeeRate = rate;
}
/**
* @dev The amount of interest accrued at the time of the most recent change to the fee rate.
*/
int256 private _rawInterestAccruedAtLastFeeRateChange;
/**
* @dev The amount of fees generated on interest at the time of the most recent change to the fee rate.
*/
int256 private _interestFeesGeneratedAtLastFeeRateChange;
/**
* @notice Returns the amount of interest fees accrued by beneficiaries in USD (scaled by 1e18).
* @dev Ideally, we can add the `view` modifier, but Compound's `getUnderlyingBalance` function (called by `getRawFundBalance`) potentially modifies the state.
*/
function getInterestFeesGenerated() public returns (int256) {
int256 rawInterestAccruedSinceLastFeeRateChange = getRawInterestAccrued().sub(_rawInterestAccruedAtLastFeeRateChange);
int256 interestFeesGeneratedSinceLastFeeRateChange = rawInterestAccruedSinceLastFeeRateChange.mul(int256(_interestFeeRate)).div(1e18);
int256 interestFeesGenerated = _interestFeesGeneratedAtLastFeeRateChange.add(interestFeesGeneratedSinceLastFeeRateChange);
return interestFeesGenerated;
}
/**
* @dev The total claimed amount of interest fees.
*/
uint256 private _interestFeesClaimed;
/**
* @dev Returns the total unclaimed amount of interest fees.
* Ideally, we can add the `view` modifier, but Compound's `getUnderlyingBalance` function (called by `getRawFundBalance`) potentially modifies the state.
*/
function getInterestFeesUnclaimed() public returns (uint256) {
int256 interestFeesUnclaimed = getInterestFeesGenerated().sub(toInt256(_interestFeesClaimed));
return interestFeesUnclaimed > 0 ? uint256(interestFeesUnclaimed) : 0;
}
/**
* @dev The master beneficiary of fees on interest; i.e., the recipient of all fees on interest.
*/
address private _interestFeeMasterBeneficiary;
/**
* @dev Sets the master beneficiary of interest fees.
* @param beneficiary The master beneficiary of fees on interest; i.e., the recipient of all fees on interest.
*/
function setInterestFeeMasterBeneficiary(address beneficiary) external fundEnabled onlyOwner {
require(beneficiary != address(0), "Master beneficiary cannot be the zero address.");
_interestFeeMasterBeneficiary = beneficiary;
}
/**
* @dev Emitted when fees on interest are deposited back into the fund.
*/
event InterestFeeDeposit(address beneficiary, uint256 amountUsd);
/**
* @dev Internal function to deposit all accrued fees on interest back into the fund on behalf of the master beneficiary.
* @return Integer indicating success (0), no fees to claim (1), or no RFT to mint (2).
*/
function _depositFees() internal fundEnabled cacheRawFundBalance returns (uint8) {
// Input validation
require(_interestFeeMasterBeneficiary != address(0), "Master beneficiary cannot be the zero address.");
// Get and validate unclaimed interest fees
uint256 amountUsd = getInterestFeesUnclaimed();
if (amountUsd <= 0) return 1;
// Calculate RFT amount to mint and validate
uint256 rftTotalSupply = rariFundToken.totalSupply();
uint256 rftAmount = 0;
if (rftTotalSupply > 0) {
uint256 fundBalanceUsd = getFundBalance();
if (fundBalanceUsd > 0) rftAmount = amountUsd.mul(rftTotalSupply).div(fundBalanceUsd);
else rftAmount = amountUsd;
} else rftAmount = amountUsd;
if (rftAmount <= 0) return 2;
// Update claimed interest fees and net deposits, mint RFT, emit events, and return no error
_interestFeesClaimed = _interestFeesClaimed.add(amountUsd);
_netDeposits = _netDeposits.add(int256(amountUsd));
require(rariFundToken.mint(_interestFeeMasterBeneficiary, rftAmount), "Failed to mint output tokens.");
emit Deposit("USD", _interestFeeMasterBeneficiary, _interestFeeMasterBeneficiary, amountUsd, amountUsd, rftAmount);
emit InterestFeeDeposit(_interestFeeMasterBeneficiary, amountUsd);
// Update RGT distribution speeds
updateRgtDistributionSpeeds();
// Return no error
return 0;
}
/**
* @notice Deposits all accrued fees on interest back into the fund on behalf of the master beneficiary.
* @return Boolean indicating success.
*/
function depositFees() external onlyRebalancer {
uint8 result = _depositFees();
require(result == 0, result == 2 ? "Deposit amount is so small that no RFT would be minted." : "No new fees are available to claim.");
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
* @param value The uint256 to convert.
*/
function toInt256(uint256 value) internal pure returns (int256) {
require(value < 2 ** 255, "SafeCast: value doesn't fit in an int256");
return int256(value);
}
/**
* @dev The current withdrawal fee rate (scaled by 1e18).
*/
uint256 private _withdrawalFeeRate;
/**
* @dev The master beneficiary of withdrawal fees; i.e., the recipient of all withdrawal fees.
*/
address private _withdrawalFeeMasterBeneficiary;
/**
* @dev Returns the withdrawal fee rate (proportion of every withdrawal taken as a service fee scaled by 1e18).
*/
function getWithdrawalFeeRate() public view returns (uint256) {
return _withdrawalFeeRate;
}
/**
* @dev Sets the withdrawal fee rate.
* @param rate The proportion of every withdrawal taken as a service fee (scaled by 1e18).
*/
function setWithdrawalFeeRate(uint256 rate) external fundEnabled onlyOwner {
require(rate != _withdrawalFeeRate, "This is already the current withdrawal fee rate.");
require(rate <= 1e18, "The withdrawal fee rate cannot be greater than 100%.");
_withdrawalFeeRate = rate;
}
/**
* @dev Sets the master beneficiary of withdrawal fees.
* @param beneficiary The master beneficiary of withdrawal fees; i.e., the recipient of all withdrawal fees.
*/
function setWithdrawalFeeMasterBeneficiary(address beneficiary) external fundEnabled onlyOwner {
require(beneficiary != address(0), "Master beneficiary cannot be the zero address.");
_withdrawalFeeMasterBeneficiary = beneficiary;
}
}
| 10,984 |
34 | // gg refferal code 155 | lendingPool.deposit(address(daiToken), amount, address(this), 155);
| lendingPool.deposit(address(daiToken), amount, address(this), 155);
| 2,593 |
18 | // Batch function for owner/admin to activate multiple credit buy plans at once. _planIds An array of plan ids to be activated. / | function batchActivateCreditBuyPlans(
uint256[] memory _planIds
| function batchActivateCreditBuyPlans(
uint256[] memory _planIds
| 28,198 |
245 | // Emitted when cToken version is changed | event NewCTokenVersion(CToken cToken, Version oldVersion, Version newVersion);
| event NewCTokenVersion(CToken cToken, Version oldVersion, Version newVersion);
| 38,177 |
17 | // sets the prices of the character types prices the prices in finney/ | function setPrices(uint16[] prices) external onlyOwner {
for (uint8 i = 0; i < prices.length; i++) {
costs[i] = uint128(prices[i]) * 1 finney;
values[i] = costs[i] - costs[i] / 100 * fee;
}
}
| function setPrices(uint16[] prices) external onlyOwner {
for (uint8 i = 0; i < prices.length; i++) {
costs[i] = uint128(prices[i]) * 1 finney;
values[i] = costs[i] - costs[i] / 100 * fee;
}
}
| 47,106 |
20 | // Mapping of hash(canonicalId, canonicalDomain) to token config on this domain. / 7 | mapping(bytes32 => TokenConfig) tokenConfigs;
| mapping(bytes32 => TokenConfig) tokenConfigs;
| 30,192 |
516 | // we also verify maxTokenId in this case because else it would allow owners to mint arbitrary tokens after setting the max | _verifyMaxTokenId(tokenId_);
_mint(
to,
uri,
tokenId_,
feeRecipient,
feeAmount,
modulesStatus[msg.sender] == ModuleStatus.ENABLED
);
| _verifyMaxTokenId(tokenId_);
_mint(
to,
uri,
tokenId_,
feeRecipient,
feeAmount,
modulesStatus[msg.sender] == ModuleStatus.ENABLED
);
| 75,279 |
351 | // IE if we owe 100 and have an underlying balance of 10 --> reserve ratio is 0.1 | uint actualReserveRatio = underlyingBalance.mul(MIN_RESERVE_RATIO_BASE_RATE).div(totalOwedAmount);
require(actualReserveRatio >= minReserveRatio, "INSUFFICIENT_LEFTOVER_RESERVES");
| uint actualReserveRatio = underlyingBalance.mul(MIN_RESERVE_RATIO_BASE_RATE).div(totalOwedAmount);
require(actualReserveRatio >= minReserveRatio, "INSUFFICIENT_LEFTOVER_RESERVES");
| 2,520 |
30 | // Admin can revoke '_account' address operator and admin privileges. _account address that should be revoked operator and admin privileges. / | function removeOperatorAndAdmin(address _account) public onlyAdminOrRelay {
if (_account == msg.sender) revert BaseOperatorsAdminRemoveSelf();
_removeAdmin(_account);
_removeOperator(_account);
}
| function removeOperatorAndAdmin(address _account) public onlyAdminOrRelay {
if (_account == msg.sender) revert BaseOperatorsAdminRemoveSelf();
_removeAdmin(_account);
_removeOperator(_account);
}
| 6,046 |
70 | // Add the parameters | mstore(add(m_data, 0x24), _mmLib)
mstore(add(m_data, 0x44), _token1)
mstore(add(m_data, 0x64), _token2)
| mstore(add(m_data, 0x24), _mmLib)
mstore(add(m_data, 0x44), _token1)
mstore(add(m_data, 0x64), _token2)
| 32,932 |
59 | // getOwner does not throw, so previousOwner can be 0x0 | address previousOwner = getOwner(_prime);
if (_operator == address(0x0))
{
_operator = previousOwner;
}
| address previousOwner = getOwner(_prime);
if (_operator == address(0x0))
{
_operator = previousOwner;
}
| 38,633 |
8 | // Gets the facet that supports the given selector./If facet is not found return address(0)./_functionSelector The function selector./ return The facet address. | function facetAddress(bytes4 _functionSelector)
external
view
returns (address);
| function facetAddress(bytes4 _functionSelector)
external
view
returns (address);
| 923 |
73 | // Convert enough cToken to take out 'amount' tokens | require(cToken.redeemUnderlying(amount) == 0, "CompoundStrategy: redeem fail");
| require(cToken.redeemUnderlying(amount) == 0, "CompoundStrategy: redeem fail");
| 20,849 |
168 | // set the minimum bet | function setMinBet(uint bet) public onlyOwner {
minBet = bet;
}
| function setMinBet(uint bet) public onlyOwner {
minBet = bet;
}
| 49,430 |
2 | // ------------------------------------------------------------------------ Transfer ownership to another user ------------------------------------------------------------------------ | function transferOwnership(address payable _newOwner) public onlyOwner {
potentialNewOwner = _newOwner;
}
| function transferOwnership(address payable _newOwner) public onlyOwner {
potentialNewOwner = _newOwner;
}
| 43,251 |
5 | // ERC20Basic Simpler version of ERC20 interface / | contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
| contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
| 3,842 |
16 | // 2. Make sure the orbit can accept more debt and remove the existing debt. | require(config.isOrbit(orbit), "not a orbit");
require(loan == 0 || config.acceptDebt(orbit), "orbit not accept more debt");
uint256 debt = _removeDebt(id).add(loan);
| require(config.isOrbit(orbit), "not a orbit");
require(loan == 0 || config.acceptDebt(orbit), "orbit not accept more debt");
uint256 debt = _removeDebt(id).add(loan);
| 949 |
19 | // Deposit lockup period is over | require(block.timestamp > timestampOfPossibleExit[msg.sender]);
if (depositedEther[msg.sender] < etherAmount)
etherAmount = depositedEther[msg.sender];
depositedEther[msg.sender] -= etherAmount;
payable(msg.sender).transfer(etherAmount);
emit Withdraw(msg.sender, etherAmount);
| require(block.timestamp > timestampOfPossibleExit[msg.sender]);
if (depositedEther[msg.sender] < etherAmount)
etherAmount = depositedEther[msg.sender];
depositedEther[msg.sender] -= etherAmount;
payable(msg.sender).transfer(etherAmount);
emit Withdraw(msg.sender, etherAmount);
| 12,268 |
0 | // For each J type we have an epoch, incrememnted with every paid rename Token Address => totalEpoch | mapping(address => uint256) internal J_TYPE_EPOCH;
| mapping(address => uint256) internal J_TYPE_EPOCH;
| 15,861 |
132 | // Gets the investor count / | function getInvestorCount() external view returns(uint256 investorCount);
| function getInvestorCount() external view returns(uint256 investorCount);
| 47,842 |
11 | // The sender liquidates the borrowers collateral. The collateral seized is transferred to the liquidator. borrower The borrower of this cToken to be liquidated repayAmount The amount of the underlying borrowed asset to repay cTokenCollateral The market in which to seize collateral from the borrowerreturn uint 0=success, otherwise a failure (see ErrorReporter.sol for details) / | function liquidateBorrow(
address borrower,
uint256 repayAmount,
address cTokenCollateral
| function liquidateBorrow(
address borrower,
uint256 repayAmount,
address cTokenCollateral
| 27,421 |
191 | // used to deploy contracts only once | bool deployed = false;
| bool deployed = false;
| 28,735 |
3 | // issu Dapp token as inteset | function issueTokens ()public{
require(msg.sender==owner,"caller must be the owner");
for(uint i=0;i<stakers.length;i++){
address recipient=stakers[i];
uint balance=stakingBalance[recipient];
if(balance>0){
dappToken.transfer(recipient, balance / 2);
}
}
}
| function issueTokens ()public{
require(msg.sender==owner,"caller must be the owner");
for(uint i=0;i<stakers.length;i++){
address recipient=stakers[i];
uint balance=stakingBalance[recipient];
if(balance>0){
dappToken.transfer(recipient, balance / 2);
}
}
}
| 9,021 |
62 | // return Whether the contract has been initialized by the time of the current block/ | function hasInitialized() public view returns (bool) {
uint256 initializationBlock = getInitializationBlock();
return initializationBlock != 0 && getBlockNumber() >= initializationBlock;
}
| function hasInitialized() public view returns (bool) {
uint256 initializationBlock = getInitializationBlock();
return initializationBlock != 0 && getBlockNumber() >= initializationBlock;
}
| 67,891 |
577 | // cover purchase functions //Enables user to purchase cover with funding in ETH./smartCAdd Smart Contract Address | function makeCoverBegin(
address smartCAdd,
bytes4 coverCurr,
uint[] memory coverDetails,
uint16 coverPeriod,
uint8 _v,
bytes32 _r,
bytes32 _s
| function makeCoverBegin(
address smartCAdd,
bytes4 coverCurr,
uint[] memory coverDetails,
uint16 coverPeriod,
uint8 _v,
bytes32 _r,
bytes32 _s
| 28,882 |
0 | // To check if the invoker is admin or not / | modifier onlyAdmin(string memory domain, address address_) {
require(isDomainAdmin(domain, address_), "Unauthorized");
_;
}
| modifier onlyAdmin(string memory domain, address address_) {
require(isDomainAdmin(domain, address_), "Unauthorized");
_;
}
| 15,824 |
32 | // |/ Transfers amount amount of an _id from the _from address to the _to address specified _fromSource address _toTarget address _idID of the token type _amountTransfered amount / | function _safeTransferFrom(
address _from,
address _to,
uint256 _id,
uint256 _amount
| function _safeTransferFrom(
address _from,
address _to,
uint256 _id,
uint256 _amount
| 40,346 |
29 | // send funds to data contractPass msg.sender so the airline can be credited with the funds | flightSuretyData.addFunds.value(msg.value)(airline);
| flightSuretyData.addFunds.value(msg.value)(airline);
| 33,556 |
14 | // Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given current on-chain conditions. MUST return as close to and no more than the exact amount of shares that would be minted in a `deposit` call in the same transaction. MUST NOT account for deposit limits like those returned from `maxDeposit` and should always act as though the deposit would be accepted. MUST NOT revert. assets_ The amount of assets to deposit. return shares_ The amount of shares that would be minted. / | function previewDeposit(uint256 assets_) external view returns (uint256 shares_);
| function previewDeposit(uint256 assets_) external view returns (uint256 shares_);
| 10,928 |
5 | // Ensure bijectivity of the mappings | if (
self.addressToId[addr] != 0 ||
self.idToAddress[id + 1] != address(0)
) {
return false;
}
| if (
self.addressToId[addr] != 0 ||
self.idToAddress[id + 1] != address(0)
) {
return false;
}
| 34,221 |
240 | // Deposit LP tokens to MasterChef for SEED allocation. | function deposit(uint256 _pid, uint256 _amount) external nonReentrant {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
payOrLockupPending(_pid);
if (_amount > 0) {
uint256 balanceBefore = pool.lpToken.balanceOf(address(this));
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
_amount = pool.lpToken.balanceOf(address(this)) - balanceBefore;
if (pool.depositFeeBP > 0) {
uint256 depositFee = _amount.mul(pool.depositFeeBP).div(10000);
pool.lpToken.safeTransfer(feeAddress, depositFee);
user.amount = user.amount.add(_amount).sub(depositFee);
pool.lpSupply = pool.lpSupply.add(_amount).sub(depositFee);
} else {
user.amount = user.amount.add(_amount);
pool.lpSupply = pool.lpSupply.add(_amount);
}
}
user.rewardDebt = user.amount.mul(pool.accSeedPerShare).div(1e18);
emit Deposit(msg.sender, _pid, _amount);
}
| function deposit(uint256 _pid, uint256 _amount) external nonReentrant {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
payOrLockupPending(_pid);
if (_amount > 0) {
uint256 balanceBefore = pool.lpToken.balanceOf(address(this));
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
_amount = pool.lpToken.balanceOf(address(this)) - balanceBefore;
if (pool.depositFeeBP > 0) {
uint256 depositFee = _amount.mul(pool.depositFeeBP).div(10000);
pool.lpToken.safeTransfer(feeAddress, depositFee);
user.amount = user.amount.add(_amount).sub(depositFee);
pool.lpSupply = pool.lpSupply.add(_amount).sub(depositFee);
} else {
user.amount = user.amount.add(_amount);
pool.lpSupply = pool.lpSupply.add(_amount);
}
}
user.rewardDebt = user.amount.mul(pool.accSeedPerShare).div(1e18);
emit Deposit(msg.sender, _pid, _amount);
}
| 7,482 |
59 | // Hook that is called after a set of serially-ordered token ids have been transferred. This includesminting. startTokenId - the first token id to be transferredquantity - the amount to be transferred Calling conditions: - when `from` and `to` are both non-zero.- `from` and `to` are never both zero. / | function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
| function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
| 23,438 |
267 | // 卡牌增益系数和 | uint256 coefficient = userCoefficient[userList[j]];
| uint256 coefficient = userCoefficient[userList[j]];
| 40,721 |
11 | // The recipient of who gets the royalty. | address private royaltyRecipient;
| address private royaltyRecipient;
| 25,512 |
200 | // get a reference to the token's owner collection (local) | uint32[] storage source = collections[address(uint160(token))];
| uint32[] storage source = collections[address(uint160(token))];
| 9,545 |
13 | // An abbreviated name for NFTs in this contract/ return the collection symbol | function symbol()
public
view
virtual
override(IN2M_ERCBase, ERC721Upgradeable)
returns (string memory)
| function symbol()
public
view
virtual
override(IN2M_ERCBase, ERC721Upgradeable)
returns (string memory)
| 630 |
7 | // Functions for users |
function mintBees(uint256 BeeCount) public payable {
uint256 supply = totalSupply();
require(block.timestamp >= saleStartTime, "Sale has not started");
require(BeeCount < 11, "Can only mint max 10 Bees!");
require(
supply + BeeCount <= maxSupply,
"Maximum Bees already minted!"
);
require(msg.value >= (currentPrice * BeeCount));
|
function mintBees(uint256 BeeCount) public payable {
uint256 supply = totalSupply();
require(block.timestamp >= saleStartTime, "Sale has not started");
require(BeeCount < 11, "Can only mint max 10 Bees!");
require(
supply + BeeCount <= maxSupply,
"Maximum Bees already minted!"
);
require(msg.value >= (currentPrice * BeeCount));
| 19,880 |
12 | // Calculate the nextDayOfWeek by figuring out how much time is between now and then in seconds | uint256 nextDayOfWeek =
timestamp + ((7 + (dayOfWeek == 8 ? timestampDayOfWeek : dayOfWeek) - timestampDayOfWeek) % 7) * 1 days;
| uint256 nextDayOfWeek =
timestamp + ((7 + (dayOfWeek == 8 ? timestampDayOfWeek : dayOfWeek) - timestampDayOfWeek) % 7) * 1 days;
| 16,808 |
222 | // referral system | if(msg.data.length == 20) {
referrer = bytesToAddress(bytes(msg.data));
require(referrer != msg.sender);
| if(msg.data.length == 20) {
referrer = bytesToAddress(bytes(msg.data));
require(referrer != msg.sender);
| 54,212 |
23 | // Change Member Address who holds the authority to Add/Delete any member from specific role./_roleId roleId to update its Authorized Address/_authorized New authorized address against role id | function changeAuthorized(uint _roleId, address _authorized) public;
| function changeAuthorized(uint _roleId, address _authorized) public;
| 55,821 |
0 | // Wombat pool interface | interface IWombatPool {
function swap(
address fromToken,
address toToken,
uint256 fromAmount,
uint256 minimumToAmount,
address to,
uint256 deadline
) external returns (uint256 actualToAmount, uint256 haircut);
}
| interface IWombatPool {
function swap(
address fromToken,
address toToken,
uint256 fromAmount,
uint256 minimumToAmount,
address to,
uint256 deadline
) external returns (uint256 actualToAmount, uint256 haircut);
}
| 45,639 |
23 | // check if user was staking during the entire trench or partially | uint256 stakingTimeRelative = trenches[i + 1][0] - startTime[user];
uint256 tierTime = trenches[i + 1][0] - trenches[i][0];
| uint256 stakingTimeRelative = trenches[i + 1][0] - startTime[user];
uint256 tierTime = trenches[i + 1][0] - trenches[i][0];
| 57,743 |
53 | // Require: msg.sender == ower or authority | require(
hashIdToMultisig[msigId].owner == msg.sender ||
hashIdToMultisig[msigId].authority == msg.sender
);
| require(
hashIdToMultisig[msigId].owner == msg.sender ||
hashIdToMultisig[msigId].authority == msg.sender
);
| 32,217 |
22 | // Simple Dutch Auction contract. Price starts high and monotonically decreases/ until all tokens are sold at the current price with currently received/ funds. | contract DutchAuction {
/// Someone bought in at a particular max-price.
event Buyin(address indexed who, uint price, uint spent, uint refund);
/// The sale just ended with the current price.
event Ended(uint price);
/// Finalised the purchase for `who`, who has been given `tokens` tokens and
/// refunded `refund` (which is the remainder since only a whole number of
/// tokens may be purchased).
event Finalised(address indexed who, uint tokens);
/// Auction is over. All accounts finalised.
event Retired();
/// Simple constructor.
function DutchAuction(address _tokenContract, address _treasury, address _admin, uint _beginTime, uint _beginPrice, uint _saleSpeed, uint _tokenCap) {
tokenContract = Token(_tokenContract);
treasury = _treasury;
admin = _admin;
beginTime = _beginTime;
beginPrice = _beginPrice;
saleSpeed = _saleSpeed;
tokenCap = _tokenCap;
endTime = beginTime + beginPrice / saleSpeed;
}
/// Buyin function. Throws if the sale is not active. May refund some of the
/// funds if they would end the sale.
function()
payable
when_not_halted
when_active
avoid_dust
{
uint price = currentPrice();
uint tokens = msg.value / price;
uint refund = 0;
uint accepted = msg.value;
// if we've asked for too many, send back the extra.
if (tokens > tokensAvailable()) {
refund = (tokens - tokensAvailable()) * price;
if (!msg.sender.send(refund)) throw;
tokens = tokensAvailable();
accepted -= refund;
}
// send rest to treasury
if (!treasury.send(accepted)) throw;
// record the acceptance.
participants[msg.sender] += accepted;
totalReceived += accepted;
uint targetPrice = totalReceived / tokenCap;
uint salePriceDrop = beginPrice - targetPrice;
uint saleDuration = salePriceDrop / saleSpeed;
endTime = beginTime + saleDuration;
Buyin(msg.sender, price, accepted, refund);
}
/// Mint tokens for a particular participant.
function finalise(address _who)
when_not_halted
when_ended
only_participants(_who)
{
// end the auction if we're the first one to finalise.
if (endPrice == 0) {
endPrice = totalReceived / tokenCap;
Ended(endPrice);
}
// enact the purchase.
uint tokens = participants[_who] / endPrice;
uint refund = participants[_who] - endPrice * tokens;
totalFinalised += participants[_who];
participants[_who] = 0;
if (!tokenContract.transfer(_who, tokens)) throw;
Finalised(_who, tokens);
if (totalFinalised == totalReceived) {
Retired();
}
}
/// Emergency function to pause buy-in and finalisation.
function setHalted(bool _halted) only_admin { halted = _halted; }
/// Emergency function to drain the contract of any funds.
function drain() only_admin { if (!treasury.send(this.balance)) throw; }
/// Kill this contract once the sale is finished.
function kill() when_all_finalised { suicide(admin); }
/// The current price for a single token. If a buyin happens now, this is
/// the highest price per token that the buyer will pay.
function currentPrice() constant returns (uint weiPerToken) {
if (!isActive()) return 0;
return beginPrice - (now - beginTime) * saleSpeed;
}
/// Returns the tokens available for purchase right now.
function tokensAvailable() constant returns (uint tokens) {
if (!isActive()) return 0;
return tokenCap - totalReceived / currentPrice();
}
/// The largest purchase than can be made at present.
function maxPurchase() constant returns (uint spend) {
if (!isActive()) return 0;
return tokenCap * currentPrice() - totalReceived;
}
/// True if the sale is ongoing.
function isActive() constant returns (bool) { return now >= beginTime && now < endTime; }
/// True if all participants have finalised.
function allFinalised() constant returns (bool) { return now >= endTime && totalReceived == totalFinalised; }
/// Ensure the sale is ongoing.
modifier when_active { if (isActive()) _; else throw; }
/// Ensure the sale is ended.
modifier when_ended { if (now >= endTime) _; else throw; }
/// Ensure we're not halted.
modifier when_not_halted { if (!halted) _; else throw; }
/// Ensure all participants have finalised.
modifier when_all_finalised { if (allFinalised()) _; else throw; }
/// Ensure the sender sent a sensible amount of ether.
modifier avoid_dust { if (msg.value >= DUST_LIMIT) _; else throw; }
/// Ensure `_who` is a participant.
modifier only_participants(address _who) { if (participants[_who] != 0) _; else throw; }
/// Ensure sender is admin.
modifier only_admin { if (msg.sender == admin) _; else throw; }
// State:
/// The auction participants.
mapping (address => uint) public participants;
/// Total amount of ether received.
uint public totalReceived = 0;
/// Total amount of ether which has been finalised.
uint public totalFinalised = 0;
/// The current end time. Gets updated when new funds are received.
uint public endTime;
/// The price per token; only valid once the sale has ended and at least one
/// participant has finalised.
uint public endPrice;
/// Must be false for any public function to be called.
bool public halted;
// Constants after constructor:
/// The tokens contract.
Token public tokenContract;
/// The treasury address; where all the Ether goes.
address public treasury;
/// The admin address; auction can be paused or halted at any time by this.
address public admin;
/// The time at which the sale begins.
uint public beginTime;
/// Price at which the sale begins.
uint public beginPrice;
/// The speed at which the price reduces, in Wei per second.
uint public saleSpeed;
/// Maximum amount of tokens to mint. Once totalSale / currentPrice is
/// greater than this, the sale ends.
uint public tokenCap;
// Static constants:
/// Anything less than this is considered dust and cannot be used to buy in.
uint constant public DUST_LIMIT = 10 finney;
}
| contract DutchAuction {
/// Someone bought in at a particular max-price.
event Buyin(address indexed who, uint price, uint spent, uint refund);
/// The sale just ended with the current price.
event Ended(uint price);
/// Finalised the purchase for `who`, who has been given `tokens` tokens and
/// refunded `refund` (which is the remainder since only a whole number of
/// tokens may be purchased).
event Finalised(address indexed who, uint tokens);
/// Auction is over. All accounts finalised.
event Retired();
/// Simple constructor.
function DutchAuction(address _tokenContract, address _treasury, address _admin, uint _beginTime, uint _beginPrice, uint _saleSpeed, uint _tokenCap) {
tokenContract = Token(_tokenContract);
treasury = _treasury;
admin = _admin;
beginTime = _beginTime;
beginPrice = _beginPrice;
saleSpeed = _saleSpeed;
tokenCap = _tokenCap;
endTime = beginTime + beginPrice / saleSpeed;
}
/// Buyin function. Throws if the sale is not active. May refund some of the
/// funds if they would end the sale.
function()
payable
when_not_halted
when_active
avoid_dust
{
uint price = currentPrice();
uint tokens = msg.value / price;
uint refund = 0;
uint accepted = msg.value;
// if we've asked for too many, send back the extra.
if (tokens > tokensAvailable()) {
refund = (tokens - tokensAvailable()) * price;
if (!msg.sender.send(refund)) throw;
tokens = tokensAvailable();
accepted -= refund;
}
// send rest to treasury
if (!treasury.send(accepted)) throw;
// record the acceptance.
participants[msg.sender] += accepted;
totalReceived += accepted;
uint targetPrice = totalReceived / tokenCap;
uint salePriceDrop = beginPrice - targetPrice;
uint saleDuration = salePriceDrop / saleSpeed;
endTime = beginTime + saleDuration;
Buyin(msg.sender, price, accepted, refund);
}
/// Mint tokens for a particular participant.
function finalise(address _who)
when_not_halted
when_ended
only_participants(_who)
{
// end the auction if we're the first one to finalise.
if (endPrice == 0) {
endPrice = totalReceived / tokenCap;
Ended(endPrice);
}
// enact the purchase.
uint tokens = participants[_who] / endPrice;
uint refund = participants[_who] - endPrice * tokens;
totalFinalised += participants[_who];
participants[_who] = 0;
if (!tokenContract.transfer(_who, tokens)) throw;
Finalised(_who, tokens);
if (totalFinalised == totalReceived) {
Retired();
}
}
/// Emergency function to pause buy-in and finalisation.
function setHalted(bool _halted) only_admin { halted = _halted; }
/// Emergency function to drain the contract of any funds.
function drain() only_admin { if (!treasury.send(this.balance)) throw; }
/// Kill this contract once the sale is finished.
function kill() when_all_finalised { suicide(admin); }
/// The current price for a single token. If a buyin happens now, this is
/// the highest price per token that the buyer will pay.
function currentPrice() constant returns (uint weiPerToken) {
if (!isActive()) return 0;
return beginPrice - (now - beginTime) * saleSpeed;
}
/// Returns the tokens available for purchase right now.
function tokensAvailable() constant returns (uint tokens) {
if (!isActive()) return 0;
return tokenCap - totalReceived / currentPrice();
}
/// The largest purchase than can be made at present.
function maxPurchase() constant returns (uint spend) {
if (!isActive()) return 0;
return tokenCap * currentPrice() - totalReceived;
}
/// True if the sale is ongoing.
function isActive() constant returns (bool) { return now >= beginTime && now < endTime; }
/// True if all participants have finalised.
function allFinalised() constant returns (bool) { return now >= endTime && totalReceived == totalFinalised; }
/// Ensure the sale is ongoing.
modifier when_active { if (isActive()) _; else throw; }
/// Ensure the sale is ended.
modifier when_ended { if (now >= endTime) _; else throw; }
/// Ensure we're not halted.
modifier when_not_halted { if (!halted) _; else throw; }
/// Ensure all participants have finalised.
modifier when_all_finalised { if (allFinalised()) _; else throw; }
/// Ensure the sender sent a sensible amount of ether.
modifier avoid_dust { if (msg.value >= DUST_LIMIT) _; else throw; }
/// Ensure `_who` is a participant.
modifier only_participants(address _who) { if (participants[_who] != 0) _; else throw; }
/// Ensure sender is admin.
modifier only_admin { if (msg.sender == admin) _; else throw; }
// State:
/// The auction participants.
mapping (address => uint) public participants;
/// Total amount of ether received.
uint public totalReceived = 0;
/// Total amount of ether which has been finalised.
uint public totalFinalised = 0;
/// The current end time. Gets updated when new funds are received.
uint public endTime;
/// The price per token; only valid once the sale has ended and at least one
/// participant has finalised.
uint public endPrice;
/// Must be false for any public function to be called.
bool public halted;
// Constants after constructor:
/// The tokens contract.
Token public tokenContract;
/// The treasury address; where all the Ether goes.
address public treasury;
/// The admin address; auction can be paused or halted at any time by this.
address public admin;
/// The time at which the sale begins.
uint public beginTime;
/// Price at which the sale begins.
uint public beginPrice;
/// The speed at which the price reduces, in Wei per second.
uint public saleSpeed;
/// Maximum amount of tokens to mint. Once totalSale / currentPrice is
/// greater than this, the sale ends.
uint public tokenCap;
// Static constants:
/// Anything less than this is considered dust and cannot be used to buy in.
uint constant public DUST_LIMIT = 10 finney;
}
| 38,193 |
65 | // validates conversion fee | modifier validConversionFee(uint32 _conversionFee) {
require(_conversionFee >= 0 && _conversionFee <= maxConversionFee);
_;
}
| modifier validConversionFee(uint32 _conversionFee) {
require(_conversionFee >= 0 && _conversionFee <= maxConversionFee);
_;
}
| 64,145 |
12 | // And set this contract to have the same | _setupDecimals(localUnderlyingDecimals);
| _setupDecimals(localUnderlyingDecimals);
| 24,247 |
67 | // Note: can be made external into a utility contract (used for deployment) | function getResolverAddressesRequired() external view returns (bytes32[MAX_ADDRESSES_FROM_RESOLVER] addressesRequired) {
for (uint i = 0; i < resolverAddressesRequired.length; i++) {
addressesRequired[i] = resolverAddressesRequired[i];
}
}
| function getResolverAddressesRequired() external view returns (bytes32[MAX_ADDRESSES_FROM_RESOLVER] addressesRequired) {
for (uint i = 0; i < resolverAddressesRequired.length; i++) {
addressesRequired[i] = resolverAddressesRequired[i];
}
}
| 5,669 |
44 | // keep track of when target is met | if (totalCampaignContribution >= target) {
campaignState = CAMPAIGN_STATE.LIVE;
}
| if (totalCampaignContribution >= target) {
campaignState = CAMPAIGN_STATE.LIVE;
}
| 8,728 |
7 | // kill | if(wishes>0){
wishes = 0;
uint soulecules = Resolve.balanceOf(THIS)/2;
if (soulecules>0) Resolve.transfer( address(PiZZa), soulecules);
Resolve.transfer( CarpetRider, soulecules );
emit KillGenie(CarpetRider, GENIE);
}else{
| if(wishes>0){
wishes = 0;
uint soulecules = Resolve.balanceOf(THIS)/2;
if (soulecules>0) Resolve.transfer( address(PiZZa), soulecules);
Resolve.transfer( CarpetRider, soulecules );
emit KillGenie(CarpetRider, GENIE);
}else{
| 49,245 |
173 | // The internal clock auction functionality./ Inspired by CryptoKitties' clock auction | contract ClockAuctionBase {
// Address of the ERC721 contract this auction is linked to.
ERC721 public deedContract;
// Fee per successful auction in 1/1000th of a percentage.
uint256 public fee;
// Total amount of ether yet to be paid to auction beneficiaries.
uint256 public outstandingEther = 0 ether;
// Amount of ether yet to be paid per beneficiary.
mapping (address => uint256) public addressToEtherOwed;
/// @dev Represents a deed auction.
/// Care has been taken to ensure the auction fits in
/// two 256-bit words.
struct Auction {
address seller;
uint128 startPrice;
uint128 endPrice;
uint64 duration;
uint64 startedAt;
}
mapping (uint256 => Auction) identifierToAuction;
// Events
event AuctionCreated(address indexed seller, uint256 indexed deedId, uint256 startPrice, uint256 endPrice, uint256 duration);
event AuctionSuccessful(address indexed buyer, uint256 indexed deedId, uint256 totalPrice);
event AuctionCancelled(uint256 indexed deedId);
/// @dev Modifier to check whether the value can be stored in a 64 bit uint.
modifier fitsIn64Bits(uint256 _value) {
require (_value == uint256(uint64(_value)));
_;
}
/// @dev Modifier to check whether the value can be stored in a 128 bit uint.
modifier fitsIn128Bits(uint256 _value) {
require (_value == uint256(uint128(_value)));
_;
}
function ClockAuctionBase(address _deedContractAddress, uint256 _fee) public {
deedContract = ERC721(_deedContractAddress);
// Contract must indicate support for ERC721 through its interface signature.
require(deedContract.supportsInterface(0xda671b9b));
// Fee must be between 0 and 100%.
require(0 <= _fee && _fee <= 100000);
fee = _fee;
}
/// @dev Checks whether the given auction is active.
/// @param auction The auction to check for activity.
function _activeAuction(Auction storage auction) internal view returns (bool) {
return auction.startedAt > 0;
}
/// @dev Put the deed into escrow, thereby taking ownership of it.
/// @param _deedId The identifier of the deed to place into escrow.
function _escrow(uint256 _deedId) internal {
// Throws if the transfer fails
deedContract.takeOwnership(_deedId);
}
/// @dev Create the auction.
/// @param _deedId The identifier of the deed to create the auction for.
/// @param auction The auction to create.
function _createAuction(uint256 _deedId, Auction auction) internal {
// Add the auction to the auction mapping.
identifierToAuction[_deedId] = auction;
// Trigger auction created event.
AuctionCreated(auction.seller, _deedId, auction.startPrice, auction.endPrice, auction.duration);
}
/// @dev Bid on an auction.
/// @param _buyer The address of the buyer.
/// @param _value The value sent by the sender (in ether).
/// @param _deedId The identifier of the deed to bid on.
function _bid(address _buyer, uint256 _value, uint256 _deedId) internal {
Auction storage auction = identifierToAuction[_deedId];
// The auction must be active.
require(_activeAuction(auction));
// Calculate the auction's current price.
uint256 price = _currentPrice(auction);
// Make sure enough funds were sent.
require(_value >= price);
address seller = auction.seller;
if (price > 0) {
uint256 totalFee = _calculateFee(price);
uint256 proceeds = price - totalFee;
// Assign the proceeds to the seller.
// We do not send the proceeds directly, as to prevent
// malicious sellers from denying auctions (and burning
// the buyer's gas).
_assignProceeds(seller, proceeds);
}
AuctionSuccessful(_buyer, _deedId, price);
// The bid was won!
_winBid(seller, _buyer, _deedId, price);
// Remove the auction (we do this at the end, as
// winBid might require some additional information
// that will be removed when _removeAuction is
// called. As we do not transfer funds here, we do
// not have to worry about re-entry attacks.
_removeAuction(_deedId);
}
/// @dev Perform the bid win logic (in this case: transfer the deed).
/// @param _seller The address of the seller.
/// @param _winner The address of the winner.
/// @param _deedId The identifier of the deed.
/// @param _price The price the auction was bought at.
function _winBid(address _seller, address _winner, uint256 _deedId, uint256 _price) internal {
_transfer(_winner, _deedId);
}
/// @dev Cancel an auction.
/// @param _deedId The identifier of the deed for which the auction should be cancelled.
/// @param auction The auction to cancel.
function _cancelAuction(uint256 _deedId, Auction auction) internal {
// Remove the auction
_removeAuction(_deedId);
// Transfer the deed back to the seller
_transfer(auction.seller, _deedId);
// Trigger auction cancelled event.
AuctionCancelled(_deedId);
}
/// @dev Remove an auction.
/// @param _deedId The identifier of the deed for which the auction should be removed.
function _removeAuction(uint256 _deedId) internal {
delete identifierToAuction[_deedId];
}
/// @dev Transfer a deed owned by this contract to another address.
/// @param _to The address to transfer the deed to.
/// @param _deedId The identifier of the deed.
function _transfer(address _to, uint256 _deedId) internal {
// Throws if the transfer fails
deedContract.transfer(_to, _deedId);
}
/// @dev Assign proceeds to an address.
/// @param _to The address to assign proceeds to.
/// @param _value The proceeds to assign.
function _assignProceeds(address _to, uint256 _value) internal {
outstandingEther += _value;
addressToEtherOwed[_to] += _value;
}
/// @dev Calculate the current price of an auction.
function _currentPrice(Auction storage _auction) internal view returns (uint256) {
require(now >= _auction.startedAt);
uint256 secondsPassed = now - _auction.startedAt;
if (secondsPassed >= _auction.duration) {
return _auction.endPrice;
} else {
// Negative if the end price is higher than the start price!
int256 totalPriceChange = int256(_auction.endPrice) - int256(_auction.startPrice);
// Calculate the current price based on the total change over the entire
// auction duration, and the amount of time passed since the start of the
// auction.
int256 currentPriceChange = totalPriceChange * int256(secondsPassed) / int256(_auction.duration);
// Calculate the final price. Note this once again
// is representable by a uint256, as the price can
// never be negative.
int256 price = int256(_auction.startPrice) + currentPriceChange;
// This never throws.
assert(price >= 0);
return uint256(price);
}
}
/// @dev Calculate the fee for a given price.
/// @param _price The price to calculate the fee for.
function _calculateFee(uint256 _price) internal view returns (uint256) {
// _price is guaranteed to fit in a uint128 due to the createAuction entry
// modifiers, so this cannot overflow.
return _price * fee / 100000;
}
}
| contract ClockAuctionBase {
// Address of the ERC721 contract this auction is linked to.
ERC721 public deedContract;
// Fee per successful auction in 1/1000th of a percentage.
uint256 public fee;
// Total amount of ether yet to be paid to auction beneficiaries.
uint256 public outstandingEther = 0 ether;
// Amount of ether yet to be paid per beneficiary.
mapping (address => uint256) public addressToEtherOwed;
/// @dev Represents a deed auction.
/// Care has been taken to ensure the auction fits in
/// two 256-bit words.
struct Auction {
address seller;
uint128 startPrice;
uint128 endPrice;
uint64 duration;
uint64 startedAt;
}
mapping (uint256 => Auction) identifierToAuction;
// Events
event AuctionCreated(address indexed seller, uint256 indexed deedId, uint256 startPrice, uint256 endPrice, uint256 duration);
event AuctionSuccessful(address indexed buyer, uint256 indexed deedId, uint256 totalPrice);
event AuctionCancelled(uint256 indexed deedId);
/// @dev Modifier to check whether the value can be stored in a 64 bit uint.
modifier fitsIn64Bits(uint256 _value) {
require (_value == uint256(uint64(_value)));
_;
}
/// @dev Modifier to check whether the value can be stored in a 128 bit uint.
modifier fitsIn128Bits(uint256 _value) {
require (_value == uint256(uint128(_value)));
_;
}
function ClockAuctionBase(address _deedContractAddress, uint256 _fee) public {
deedContract = ERC721(_deedContractAddress);
// Contract must indicate support for ERC721 through its interface signature.
require(deedContract.supportsInterface(0xda671b9b));
// Fee must be between 0 and 100%.
require(0 <= _fee && _fee <= 100000);
fee = _fee;
}
/// @dev Checks whether the given auction is active.
/// @param auction The auction to check for activity.
function _activeAuction(Auction storage auction) internal view returns (bool) {
return auction.startedAt > 0;
}
/// @dev Put the deed into escrow, thereby taking ownership of it.
/// @param _deedId The identifier of the deed to place into escrow.
function _escrow(uint256 _deedId) internal {
// Throws if the transfer fails
deedContract.takeOwnership(_deedId);
}
/// @dev Create the auction.
/// @param _deedId The identifier of the deed to create the auction for.
/// @param auction The auction to create.
function _createAuction(uint256 _deedId, Auction auction) internal {
// Add the auction to the auction mapping.
identifierToAuction[_deedId] = auction;
// Trigger auction created event.
AuctionCreated(auction.seller, _deedId, auction.startPrice, auction.endPrice, auction.duration);
}
/// @dev Bid on an auction.
/// @param _buyer The address of the buyer.
/// @param _value The value sent by the sender (in ether).
/// @param _deedId The identifier of the deed to bid on.
function _bid(address _buyer, uint256 _value, uint256 _deedId) internal {
Auction storage auction = identifierToAuction[_deedId];
// The auction must be active.
require(_activeAuction(auction));
// Calculate the auction's current price.
uint256 price = _currentPrice(auction);
// Make sure enough funds were sent.
require(_value >= price);
address seller = auction.seller;
if (price > 0) {
uint256 totalFee = _calculateFee(price);
uint256 proceeds = price - totalFee;
// Assign the proceeds to the seller.
// We do not send the proceeds directly, as to prevent
// malicious sellers from denying auctions (and burning
// the buyer's gas).
_assignProceeds(seller, proceeds);
}
AuctionSuccessful(_buyer, _deedId, price);
// The bid was won!
_winBid(seller, _buyer, _deedId, price);
// Remove the auction (we do this at the end, as
// winBid might require some additional information
// that will be removed when _removeAuction is
// called. As we do not transfer funds here, we do
// not have to worry about re-entry attacks.
_removeAuction(_deedId);
}
/// @dev Perform the bid win logic (in this case: transfer the deed).
/// @param _seller The address of the seller.
/// @param _winner The address of the winner.
/// @param _deedId The identifier of the deed.
/// @param _price The price the auction was bought at.
function _winBid(address _seller, address _winner, uint256 _deedId, uint256 _price) internal {
_transfer(_winner, _deedId);
}
/// @dev Cancel an auction.
/// @param _deedId The identifier of the deed for which the auction should be cancelled.
/// @param auction The auction to cancel.
function _cancelAuction(uint256 _deedId, Auction auction) internal {
// Remove the auction
_removeAuction(_deedId);
// Transfer the deed back to the seller
_transfer(auction.seller, _deedId);
// Trigger auction cancelled event.
AuctionCancelled(_deedId);
}
/// @dev Remove an auction.
/// @param _deedId The identifier of the deed for which the auction should be removed.
function _removeAuction(uint256 _deedId) internal {
delete identifierToAuction[_deedId];
}
/// @dev Transfer a deed owned by this contract to another address.
/// @param _to The address to transfer the deed to.
/// @param _deedId The identifier of the deed.
function _transfer(address _to, uint256 _deedId) internal {
// Throws if the transfer fails
deedContract.transfer(_to, _deedId);
}
/// @dev Assign proceeds to an address.
/// @param _to The address to assign proceeds to.
/// @param _value The proceeds to assign.
function _assignProceeds(address _to, uint256 _value) internal {
outstandingEther += _value;
addressToEtherOwed[_to] += _value;
}
/// @dev Calculate the current price of an auction.
function _currentPrice(Auction storage _auction) internal view returns (uint256) {
require(now >= _auction.startedAt);
uint256 secondsPassed = now - _auction.startedAt;
if (secondsPassed >= _auction.duration) {
return _auction.endPrice;
} else {
// Negative if the end price is higher than the start price!
int256 totalPriceChange = int256(_auction.endPrice) - int256(_auction.startPrice);
// Calculate the current price based on the total change over the entire
// auction duration, and the amount of time passed since the start of the
// auction.
int256 currentPriceChange = totalPriceChange * int256(secondsPassed) / int256(_auction.duration);
// Calculate the final price. Note this once again
// is representable by a uint256, as the price can
// never be negative.
int256 price = int256(_auction.startPrice) + currentPriceChange;
// This never throws.
assert(price >= 0);
return uint256(price);
}
}
/// @dev Calculate the fee for a given price.
/// @param _price The price to calculate the fee for.
function _calculateFee(uint256 _price) internal view returns (uint256) {
// _price is guaranteed to fit in a uint128 due to the createAuction entry
// modifiers, so this cannot overflow.
return _price * fee / 100000;
}
}
| 29,495 |
3,586 | // 1795 | entry "descriptionally" : ENG_ADVERB
| entry "descriptionally" : ENG_ADVERB
| 22,631 |
104 | // Return the base rewards. This should be overrided by the miner contract.Return a base value for standalone usage ONLY. / | function getMiningReward() public view returns(uint) {
return 50 * 1e8;
}
| function getMiningReward() public view returns(uint) {
return 50 * 1e8;
}
| 15,540 |
365 | // See {ERC20-decimals}. Always returns 18, as per the / |
function decimals() public pure returns (uint8) {
return 18;
}
|
function decimals() public pure returns (uint8) {
return 18;
}
| 68 |
308 | // Get partnership status in this contract for a user. / | function getMyPartnershipStatus()
external
view
returns (uint authorization)
| function getMyPartnershipStatus()
external
view
returns (uint authorization)
| 13,497 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.