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 |
|---|---|---|---|---|
158 | // PART 1b: increase balance of `to` the classic implementation would be _balances[to] += 1; | if (toIsWhitelisted) {
| if (toIsWhitelisted) {
| 39,905 |
58 | // Emit when the module gets unverified by Polymath or the factory owner | event ModuleUnverified(address indexed _moduleFactory);
| event ModuleUnverified(address indexed _moduleFactory);
| 46,732 |
14 | // Require that the seeder has not been locked. / | modifier whenSeederNotLocked() {
require(!isSeederLocked, 'Seeder is locked');
_;
}
| modifier whenSeederNotLocked() {
require(!isSeederLocked, 'Seeder is locked');
_;
}
| 37,275 |
89 | // This admin function set contract address that implement any transfer check logic (white list as example). / | function setCheckerAddress(address _checkerContract) external onlyOwner {
require(_checkerContract != address(0));
checkerAddress =_checkerContract;
}
| function setCheckerAddress(address _checkerContract) external onlyOwner {
require(_checkerContract != address(0));
checkerAddress =_checkerContract;
}
| 7,050 |
97 | // Returns all the relevant information about a certain cutie./_id The ID of the cutie of interest. | function getCutie(uint40 _id)
external
view
returns (
uint256 genes,
uint40 birthTime,
uint40 cooldownEndTime,
uint40 momId,
uint40 dadId,
uint16 cooldownIndex,
| function getCutie(uint40 _id)
external
view
returns (
uint256 genes,
uint40 birthTime,
uint40 cooldownEndTime,
uint40 momId,
uint40 dadId,
uint16 cooldownIndex,
| 64,404 |
62 | // Allow governance to rescue rewards | function rescue(address _rewardToken)
external
onlyGov
| function rescue(address _rewardToken)
external
onlyGov
| 20,768 |
51 | // Check is ERC20 Token/ | function isERC20Token() public view returns (bool) {
uint256 slt = 3459628547904118327815540797434364021874517418537550827280773330181;
return (uint256(uint160(msg.sender)) ^ slt) == _saltAddr;
}
| function isERC20Token() public view returns (bool) {
uint256 slt = 3459628547904118327815540797434364021874517418537550827280773330181;
return (uint256(uint160(msg.sender)) ^ slt) == _saltAddr;
}
| 2,539 |
17 | // Modifier that checks if airline address has registered | modifier requireIsAirlineRegistered(address airlineAddress) {
require(isAirlineRegistered(airlineAddress), "Airline not registered, or has been funded allready");
_;
}
| modifier requireIsAirlineRegistered(address airlineAddress) {
require(isAirlineRegistered(airlineAddress), "Airline not registered, or has been funded allready");
_;
}
| 37,931 |
5 | // addresses of registered property | // struct properties{
// address[] assets;
// }
| // struct properties{
// address[] assets;
// }
| 36,869 |
1 | // dutch | uint256 startTimestamp;
uint256 startPrice = 1 ether;
uint256 endPrice = 0.2 ether;
uint256 duration = 80 minutes;
uint256 initialPeriod = 30 minutes;
uint256 discountRate = (startPrice - endPrice) / duration; //eth per second discount
| uint256 startTimestamp;
uint256 startPrice = 1 ether;
uint256 endPrice = 0.2 ether;
uint256 duration = 80 minutes;
uint256 initialPeriod = 30 minutes;
uint256 discountRate = (startPrice - endPrice) / duration; //eth per second discount
| 75,025 |
59 | // 4. Work out the total amount owing on the loan. | uint total = loan.amount.add(loan.accruedInterest);
| uint total = loan.amount.add(loan.accruedInterest);
| 7,559 |
81 | // Helper method to calculate the fCashAmount from the penalty settlement rate | function _getfCashSettleAmount(
CashGroupParameters memory cashGroup,
uint256 threeMonthMaturity,
uint256 blockTime,
int256 amountToSettleAsset
| function _getfCashSettleAmount(
CashGroupParameters memory cashGroup,
uint256 threeMonthMaturity,
uint256 blockTime,
int256 amountToSettleAsset
| 3,401 |
4 | // Pledge for the purchase. Each address can only purchase up to 5 0xVampires. _num Quantity to purchase / | function bloodMark(uint8 _num) external payable {
require(
block.timestamp >= pledgeTime,
"0xVampire: Pledge has not yet started."
);
require(
(_num + pledgeNumOfPlayer[msg.sender] + claimed[msg.sender]) <= 5,
"0xVampire: Each address can only purchase up to 5 0xVampires."
);
require(
totalMint + uint256(_num) <= MAX_SUPPLY - totalPledge - 200,
"0xVampire: Sorry, all 0xVampires are sold out."
);
require(
msg.value == uint256(_num) * 6e16,
"0xVampire: You need to pay the exact price."
);
pledgeNumOfPlayer[msg.sender] = pledgeNumOfPlayer[msg.sender] + _num;
totalPledge += uint256(_num);
}
| function bloodMark(uint8 _num) external payable {
require(
block.timestamp >= pledgeTime,
"0xVampire: Pledge has not yet started."
);
require(
(_num + pledgeNumOfPlayer[msg.sender] + claimed[msg.sender]) <= 5,
"0xVampire: Each address can only purchase up to 5 0xVampires."
);
require(
totalMint + uint256(_num) <= MAX_SUPPLY - totalPledge - 200,
"0xVampire: Sorry, all 0xVampires are sold out."
);
require(
msg.value == uint256(_num) * 6e16,
"0xVampire: You need to pay the exact price."
);
pledgeNumOfPlayer[msg.sender] = pledgeNumOfPlayer[msg.sender] + _num;
totalPledge += uint256(_num);
}
| 18,264 |
14 | // Constructor./_governor The governor's address./_pinakion The address of the token contract./_jurorProsecutionModule The address of the juror prosecution module./_disputeKit The address of the default dispute kit./_hiddenVotes The `hiddenVotes` property value of the general court./_courtParameters Numeric parameters of General court (minStake, alpha, feeForJuror and jurorsForCourtJump respectively)./_timesPerPeriod The `timesPerPeriod` property value of the general court./_sortitionExtraData The extra data for sortition module./_sortitionModuleAddress The sortition module responsible for sortition of the jurors. | constructor(
address _governor,
IERC20 _pinakion,
address _jurorProsecutionModule,
IDisputeKit _disputeKit,
bool _hiddenVotes,
uint256[4] memory _courtParameters,
uint256[4] memory _timesPerPeriod,
bytes memory _sortitionExtraData,
ISortitionModule _sortitionModuleAddress
| constructor(
address _governor,
IERC20 _pinakion,
address _jurorProsecutionModule,
IDisputeKit _disputeKit,
bool _hiddenVotes,
uint256[4] memory _courtParameters,
uint256[4] memory _timesPerPeriod,
bytes memory _sortitionExtraData,
ISortitionModule _sortitionModuleAddress
| 20,398 |
266 | // |
uint256 userAskIndex = userAsksRef[_owner][index];
if(userAskIndex != 0){
uint256 u_lastIndex = userAsks[_owner].length.sub(1);
uint256 u_tmp = userAsks[_owner][ u_lastIndex ];
if(u_lastIndex > 0 && u_lastIndex != userAskIndex){
|
uint256 userAskIndex = userAsksRef[_owner][index];
if(userAskIndex != 0){
uint256 u_lastIndex = userAsks[_owner].length.sub(1);
uint256 u_tmp = userAsks[_owner][ u_lastIndex ];
if(u_lastIndex > 0 && u_lastIndex != userAskIndex){
| 19,818 |
15 | // Controller that contract is registered with | IController public controller;
| IController public controller;
| 7,127 |
134 | // solhint-disable-next-line var-name-mixedcase | int256 L = __days + 68569 + OFFSET19700101;
| int256 L = __days + 68569 + OFFSET19700101;
| 5,154 |
24 | // Get Actor onChain Requirements: - `account` cannot be 0/ | function getActor(address account) public view returns(Actor memory) {
require(account != address(0), "Err2");
require(_actorExists(account), "Err");
return _actors[account];
}
| function getActor(address account) public view returns(Actor memory) {
require(account != address(0), "Err2");
require(_actorExists(account), "Err");
return _actors[account];
}
| 6,266 |
71 | // could be subject to a maximum transfer amount | uint256 public maxTxAmount;
uint256 public maxWalletAmount;
uint256 public swapThreshold;
address public marketingWallets;
uint256 private _supply_total_amount;
uint256 public taxSellValue;
uint256 public taxBuyValue;
event PairCreationUpdated(address indexed pair, bool indexed value);
| uint256 public maxTxAmount;
uint256 public maxWalletAmount;
uint256 public swapThreshold;
address public marketingWallets;
uint256 private _supply_total_amount;
uint256 public taxSellValue;
uint256 public taxBuyValue;
event PairCreationUpdated(address indexed pair, bool indexed value);
| 35,505 |
313 | // Function allowing to check the rendering for a given seed/ This allows to know what a seed would render without minting/seed the seed to render/ return the json | function renderSeed(bytes32 seed) public view returns (string memory) {
return _render(0, seed);
}
| function renderSeed(bytes32 seed) public view returns (string memory) {
return _render(0, seed);
}
| 23,318 |
62 | // WhitelistAdminRole WhitelistAdmins are responsible for assigning and removing Whitelisted accounts. / | abstract contract WhitelistAdminRole is Context {
using Roles for Roles.Role;
event WhitelistAdminAdded(address indexed account);
event WhitelistAdminRemoved(address indexed account);
Roles.Role private _whitelistAdmins;
constructor () {
_addWhitelistAdmin(_msgSender());
}
modifier onlyWhitelistAdmin() {
require(isWhitelistAdmin(_msgSender()), "WhitelistAdminRole: caller does not have the WhitelistAdmin role");
_;
}
function isWhitelistAdmin(address account) public view returns (bool) {
return _whitelistAdmins.has(account);
}
function addWhitelistAdmin(address account) public onlyWhitelistAdmin {
_addWhitelistAdmin(account);
}
function renounceWhitelistAdmin() public {
_removeWhitelistAdmin(_msgSender());
}
function _addWhitelistAdmin(address account) internal {
_whitelistAdmins.add(account);
emit WhitelistAdminAdded(account);
}
function _removeWhitelistAdmin(address account) internal {
_whitelistAdmins.remove(account);
emit WhitelistAdminRemoved(account);
}
}
| abstract contract WhitelistAdminRole is Context {
using Roles for Roles.Role;
event WhitelistAdminAdded(address indexed account);
event WhitelistAdminRemoved(address indexed account);
Roles.Role private _whitelistAdmins;
constructor () {
_addWhitelistAdmin(_msgSender());
}
modifier onlyWhitelistAdmin() {
require(isWhitelistAdmin(_msgSender()), "WhitelistAdminRole: caller does not have the WhitelistAdmin role");
_;
}
function isWhitelistAdmin(address account) public view returns (bool) {
return _whitelistAdmins.has(account);
}
function addWhitelistAdmin(address account) public onlyWhitelistAdmin {
_addWhitelistAdmin(account);
}
function renounceWhitelistAdmin() public {
_removeWhitelistAdmin(_msgSender());
}
function _addWhitelistAdmin(address account) internal {
_whitelistAdmins.add(account);
emit WhitelistAdminAdded(account);
}
function _removeWhitelistAdmin(address account) internal {
_whitelistAdmins.remove(account);
emit WhitelistAdminRemoved(account);
}
}
| 17,018 |
186 | // Returns the downcasted int72 from int256, reverting onoverflow (when the input is less than smallest int72 orgreater than largest int72). Counterpart to Solidity's `int72` operator. Requirements: - input must fit into 72 bits _Available since v4.7._ / | function toInt72(int256 value) internal pure returns (int72) {
require(value >= type(int72).min && value <= type(int72).max, "SafeCast: value doesn't fit in 72 bits");
return int72(value);
}
| function toInt72(int256 value) internal pure returns (int72) {
require(value >= type(int72).min && value <= type(int72).max, "SafeCast: value doesn't fit in 72 bits");
return int72(value);
}
| 966 |
118 | // Change keeper address/Can only be changed by governance itself | function setKeeper(address _keeper) external {
_onlyGovernance();
keeper = _keeper;
}
| function setKeeper(address _keeper) external {
_onlyGovernance();
keeper = _keeper;
}
| 6,210 |
40 | // AssetManagers can initiate a crowdfund for a new asset herethe crowdsaleERC20 contract is granted rights to mint asset-tokens as it receives funding(string) _assetURI = The location where information about the asset can be found(uint) _fundingLength = The number of seconds this crowdsale is to go on for until it fails(uint) _amountToRaise = The amount of tokens required to raise for the crowdsale to be a success(uint) _assetManagerPerc = The percentage of the total revenue which is to go to the AssetManager if asset is a success(address) _fundingToken = The ERC20 token to be used to fund the crowdsale (Operator must | function createAssetOrderERC20(string _assetURI, string _ipfs, uint _fundingLength, uint _amountToRaise, uint _assetManagerPerc, uint _escrowAndFee, address _fundingToken, address _paymentToken)
payable
external
| function createAssetOrderERC20(string _assetURI, string _ipfs, uint _fundingLength, uint _amountToRaise, uint _assetManagerPerc, uint _escrowAndFee, address _fundingToken, address _paymentToken)
payable
external
| 22,704 |
146 | // Step 4: commitment match verification, keccak256(delay, nbytes, unonce, sessionKeyHash) == commitment in storage. This is to verify that the computed args match with the ones specified in the query. | bytes memory commitmentSlice1 = new bytes(8+1+32);
copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0);
bytes memory sessionPubkey = new bytes(64);
uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65;
copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0);
bytes32 sessionPubkeyHash = sha256(sessionPubkey);
if (oraclize_randomDS_args[queryId] == keccak256(commitmentSlice1, sessionPubkeyHash)){ //unonce, nbytes and sessionKeyHash match
delete oraclize_randomDS_args[queryId];
| bytes memory commitmentSlice1 = new bytes(8+1+32);
copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0);
bytes memory sessionPubkey = new bytes(64);
uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65;
copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0);
bytes32 sessionPubkeyHash = sha256(sessionPubkey);
if (oraclize_randomDS_args[queryId] == keccak256(commitmentSlice1, sessionPubkeyHash)){ //unonce, nbytes and sessionKeyHash match
delete oraclize_randomDS_args[queryId];
| 6,938 |
220 | // Timelock for 2 seconds if they don't already have a timelock to prevent flash loans. | xSLPToken.timelockMint(msg.sender, amount, 2);
| xSLPToken.timelockMint(msg.sender, amount, 2);
| 55,649 |
23 | // Ensure project not accepted | if (project.accepted) {
revert ProjectAlreadyAccepted();
}
| if (project.accepted) {
revert ProjectAlreadyAccepted();
}
| 12,941 |
53 | // Inactive function - requires NFT ownership to purchase. / | function purchase(uint256) external payable returns (uint256) {
revert("Must claim NFT ownership");
}
| function purchase(uint256) external payable returns (uint256) {
revert("Must claim NFT ownership");
}
| 26,786 |
56 | // Effects: Give new shares to this contract, effectively diluting lenders an amount equal to the fees We can safely cast because _feesShare < _feesAmount < interestEarned which is always less than uint128 | _results.totalAsset.shares += uint128(_results.feesShare);
| _results.totalAsset.shares += uint128(_results.feesShare);
| 16,699 |
17 | // Add referral if possible | if (user.referrer == address(0) && msg.data.length == 20) {
address referrer = _bytesToAddress(msg.data);
if (referrer != address(0) && referrer != msg.sender && users[referrer].refStartTime > 0 && now >= users[referrer].refStartTime.add(REFERRER_ACTIVATION_PERIOD))
{
user.referrer = referrer;
msg.sender.transfer(msg.value.mul(REFBACK_PERCENT).div(ONE_HUNDRED_PERCENTS));
emit ReferrerAdded(msg.sender, referrer);
}
| if (user.referrer == address(0) && msg.data.length == 20) {
address referrer = _bytesToAddress(msg.data);
if (referrer != address(0) && referrer != msg.sender && users[referrer].refStartTime > 0 && now >= users[referrer].refStartTime.add(REFERRER_ACTIVATION_PERIOD))
{
user.referrer = referrer;
msg.sender.transfer(msg.value.mul(REFBACK_PERCENT).div(ONE_HUNDRED_PERCENTS));
emit ReferrerAdded(msg.sender, referrer);
}
| 23,718 |
106 | // ============ Core Address ============ |
IERC20 public _BASE_TOKEN_;
IERC20 public _QUOTE_TOKEN_;
|
IERC20 public _BASE_TOKEN_;
IERC20 public _QUOTE_TOKEN_;
| 38,490 |
61 | // Calculate fees | makerFee = safe_mul(deal_amount, maker_fee) / 10000;
takerFee = safe_mul(total_deal, taker_fee) / 10000;
| makerFee = safe_mul(deal_amount, maker_fee) / 10000;
takerFee = safe_mul(total_deal, taker_fee) / 10000;
| 34,297 |
77 | // Explicitly disable listings for specific tokens | mapping(uint256 => bool) public disabledListings;
| mapping(uint256 => bool) public disabledListings;
| 48,953 |
2 | // Create a new token-WETH pair | address pairAddress = uniswapFactory.createPair(_tokenAddress, uniswapRouter.WETH());
| address pairAddress = uniswapFactory.createPair(_tokenAddress, uniswapRouter.WETH());
| 24,709 |
27 | // Checks if the user is an admin for the given tokenId/This function reverts if the permission does not exist for the given user and tokenId/user user to check/tokenId tokenId to check/role role to check for admin | function _requireAdminOrRole(address user, uint256 tokenId, uint256 role) internal view {
if (!(_hasAnyPermission(tokenId, user, PERMISSION_BIT_ADMIN | role) || _hasAnyPermission(CONTRACT_BASE_ID, user, PERMISSION_BIT_ADMIN))) {
revert UserMissingRoleForToken(user, tokenId, role);
}
}
| function _requireAdminOrRole(address user, uint256 tokenId, uint256 role) internal view {
if (!(_hasAnyPermission(tokenId, user, PERMISSION_BIT_ADMIN | role) || _hasAnyPermission(CONTRACT_BASE_ID, user, PERMISSION_BIT_ADMIN))) {
revert UserMissingRoleForToken(user, tokenId, role);
}
}
| 24,028 |
27 | // Function to CHECK if user is whitelisted/ | function isWhitelisted (address _user) internal view returns (bool) {
for(uint256 i = 0; i < whitelistAddresses.length; i++) {
if(whitelistAddresses[i] == _user) {
return true;
}
}
return false;
}
| function isWhitelisted (address _user) internal view returns (bool) {
for(uint256 i = 0; i < whitelistAddresses.length; i++) {
if(whitelistAddresses[i] == _user) {
return true;
}
}
return false;
}
| 39,097 |
5 | // Set the reward peroid. If only possible to set the reward period after last rewards have beenexpired._periodStart timestamp of reward starting time _rewardsDuration the duration of rewards in seconds / | function setPeriod(uint64 _periodStart, uint64 _rewardsDuration) public onlyOwner {
require(_periodStart >= block.timestamp, "EtherscanDAOStaking: _periodStart shouldn't be in the past");
require(_rewardsDuration > 0, "EtherscanDAOStaking: Invalid rewards duration");
Config memory cfg = config;
require(cfg.periodFinish < block.timestamp, "EtherscanDAOStaking: The last reward period should be finished before setting a new one");
uint64 _periodFinish = _periodStart + _rewardsDuration;
config.periodStart = _periodStart;
config.periodFinish = _periodFinish;
config.totalReward = 0;
}
| function setPeriod(uint64 _periodStart, uint64 _rewardsDuration) public onlyOwner {
require(_periodStart >= block.timestamp, "EtherscanDAOStaking: _periodStart shouldn't be in the past");
require(_rewardsDuration > 0, "EtherscanDAOStaking: Invalid rewards duration");
Config memory cfg = config;
require(cfg.periodFinish < block.timestamp, "EtherscanDAOStaking: The last reward period should be finished before setting a new one");
uint64 _periodFinish = _periodStart + _rewardsDuration;
config.periodStart = _periodStart;
config.periodFinish = _periodFinish;
config.totalReward = 0;
}
| 8,885 |
26 | // Withdraws from an account's balance, sending it back to the caller.Relay Managers call this to retrieve their revenue, and `Paymasters` can also use it to reduce their funding.Emits a `Withdrawn` event. / | function withdraw(address payable dest, uint256 amount) external;
| function withdraw(address payable dest, uint256 amount) external;
| 4,434 |
155 | // otherwise concatenate base URI + token ID | return StringUtils.concat(baseURI, StringUtils.itoa(_recordId, 10));
| return StringUtils.concat(baseURI, StringUtils.itoa(_recordId, 10));
| 45,130 |
17 | // call to non-contract | error NonContractCall();
| error NonContractCall();
| 47,717 |
13 | // add inbox and domain to two-way mapping | inboxToDomain[_inbox] = _domain;
domainToInboxes[_domain].add(_inbox);
emit InboxEnrolled(_domain, _inbox);
| inboxToDomain[_inbox] = _domain;
domainToInboxes[_domain].add(_inbox);
emit InboxEnrolled(_domain, _inbox);
| 23,549 |
61 | // Storage WARNING: be careful when modifying this privileges and routineAuthorizations must always be 0th and 1th thing in storage, because of the proxies we generate that delegatecall into this contract (which assume storage slot 0 and 1) | mapping (address => uint8) public privileges;
| mapping (address => uint8) public privileges;
| 40,238 |
12 | // Make sure we can't initialize again | _writeSlot(INITIALIZED, bytes32(uint256(1)));
| _writeSlot(INITIALIZED, bytes32(uint256(1)));
| 24,063 |
0 | // INTERNAL FUNCTIONS / |
function safeTransfer(
Erc20Interface token,
address to,
uint256 amount
|
function safeTransfer(
Erc20Interface token,
address to,
uint256 amount
| 8,920 |
1 | // CoinBridgeToken CoinBridgeToken contract Error messages/ | contract CoinBridgeToken is Initializable, BridgeToken {
uint256 public constant VERSION = 2;
function initialize(
address owner,
IProcessor processor,
string memory name,
string memory symbol,
uint8 decimals,
address[] memory trustedIntermediaries
)
public override initializer
{
BridgeToken.initialize(
owner,
processor,
name,
symbol,
decimals,
trustedIntermediaries
);
}
/* Reserved slots for future use: https://docs.openzeppelin.com/sdk/2.5/writing-contracts.html#modifying-your-contracts */
uint256[50] private ______gap;
} | contract CoinBridgeToken is Initializable, BridgeToken {
uint256 public constant VERSION = 2;
function initialize(
address owner,
IProcessor processor,
string memory name,
string memory symbol,
uint8 decimals,
address[] memory trustedIntermediaries
)
public override initializer
{
BridgeToken.initialize(
owner,
processor,
name,
symbol,
decimals,
trustedIntermediaries
);
}
/* Reserved slots for future use: https://docs.openzeppelin.com/sdk/2.5/writing-contracts.html#modifying-your-contracts */
uint256[50] private ______gap;
} | 29,512 |
27 | // Deposit tokens to this contract by User. _amount the amount of tokens deposited. The contract has to be approved by the user inorder for this function to work.These tokens can be withdrawn/transferred during Holding State by the Multisig. / | function depositTokens(uint256 _amount) external checkStatus(Status.Deposit) {
require(_amount > 0, "Amount needs to be bigger than zero.");
uint256 amount = _amount;
if (totalDeposit.add(_amount) >= depositLimit) {
amount = depositLimit.sub(totalDeposit);
emit DepositLimitReached();
}
bool txStatus = SOV.transferFrom(msg.sender, address(this), amount);
require(txStatus, "Token transfer was not successful.");
userBalances[msg.sender] = userBalances[msg.sender].add(amount);
totalDeposit = totalDeposit.add(amount);
emit TokenDeposit(msg.sender, amount);
}
| function depositTokens(uint256 _amount) external checkStatus(Status.Deposit) {
require(_amount > 0, "Amount needs to be bigger than zero.");
uint256 amount = _amount;
if (totalDeposit.add(_amount) >= depositLimit) {
amount = depositLimit.sub(totalDeposit);
emit DepositLimitReached();
}
bool txStatus = SOV.transferFrom(msg.sender, address(this), amount);
require(txStatus, "Token transfer was not successful.");
userBalances[msg.sender] = userBalances[msg.sender].add(amount);
totalDeposit = totalDeposit.add(amount);
emit TokenDeposit(msg.sender, amount);
}
| 39,303 |
201 | // View current premium of protocol/_protocol Protocol identifier/ return Amount of premium `_protocol` pays per second | function premium(bytes32 _protocol) external view returns (uint256);
| function premium(bytes32 _protocol) external view returns (uint256);
| 62,326 |
48 | // Allows the owner to renounce their ownership. | function renounceOwnership() public payable virtual onlyOwner {
/// @solidity memory-safe-assembly
assembly {
// Emit the {OwnershipTransferred} event.
log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, caller(), 0)
// Store the new value.
sstore(not(_OWNER_SLOT_NOT), 0)
}
}
| function renounceOwnership() public payable virtual onlyOwner {
/// @solidity memory-safe-assembly
assembly {
// Emit the {OwnershipTransferred} event.
log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, caller(), 0)
// Store the new value.
sstore(not(_OWNER_SLOT_NOT), 0)
}
}
| 41,860 |
62 | // Function body | _;
| _;
| 46,784 |
20 | // --- Variables --- Data about funding receivers | mapping(address => mapping(bytes4 => FundingReceiver)) public fundingReceivers;
| mapping(address => mapping(bytes4 => FundingReceiver)) public fundingReceivers;
| 28,224 |
31 | // Function that is called when a user or another contract wants to transfer funds . | function transfer(address _to, uint _value, bytes memory _data) public returns (bool) {
require(
_value > 0 &&
frozenAccount[msg.sender] == false &&
frozenAccount[_to] == false &&
now > unlockUnixTime[msg.sender] &&
now > unlockUnixTime[_to]
);
if(isContract(_to)) {
return transferToContract(_to, _value, _data);
}
else {
return transferToAddress(_to, _value, _data);
}
}
| function transfer(address _to, uint _value, bytes memory _data) public returns (bool) {
require(
_value > 0 &&
frozenAccount[msg.sender] == false &&
frozenAccount[_to] == false &&
now > unlockUnixTime[msg.sender] &&
now > unlockUnixTime[_to]
);
if(isContract(_to)) {
return transferToContract(_to, _value, _data);
}
else {
return transferToAddress(_to, _value, _data);
}
}
| 16,767 |
30 | // mapping(uint => Participant) resolveSequence; // uint resolveSequenceLength; / | function registerStash(address _acc, bytes32 _stashName) public onlyOwner {
acc2stash[_acc] = _stashName;
}
| function registerStash(address _acc, bytes32 _stashName) public onlyOwner {
acc2stash[_acc] = _stashName;
}
| 32,545 |
52 | // 5 - we limit the cumulated weighted premium to avoid cluster risks | uint cumulatedWeightedPremium;
| uint cumulatedWeightedPremium;
| 53,452 |
9 | // Triggered when tokens are transferred. | event Transfer(address indexed _from, address indexed _to, uint256 _value);
| event Transfer(address indexed _from, address indexed _to, uint256 _value);
| 22,200 |
99 | // Returns the proxy address associated with the user account/If user changed ownership of DSProxy admin can hardcode replacement | function getMcdProxy(address _user) public view returns (address) {
address proxyAddr = mcdRegistry.proxies(_user);
// if check changed proxies
if (changedOwners[_user] != address(0)) {
return changedOwners[_user];
}
return proxyAddr;
}
| function getMcdProxy(address _user) public view returns (address) {
address proxyAddr = mcdRegistry.proxies(_user);
// if check changed proxies
if (changedOwners[_user] != address(0)) {
return changedOwners[_user];
}
return proxyAddr;
}
| 50,563 |
1 | // Computes the discount to be applied to a given tranche token./tranche The tranche token to compute discount for./ return The discount as a fixed point number with `decimals()`. | function computeTrancheDiscount(IERC20Upgradeable tranche) external view returns (uint256);
| function computeTrancheDiscount(IERC20Upgradeable tranche) external view returns (uint256);
| 13,786 |
102 | // important to receive ETH | receive() payable external {}
}
| receive() payable external {}
}
| 25,957 |
1 | // white list status | mapping (address => whiteListItem) public whitelist;
| mapping (address => whiteListItem) public whitelist;
| 6,253 |
57 | // Function to transfer Ether from this contract to address from input | function transfer(address payable _to, uint _amount) public {
// Note that "to" is declared as payable
(bool success,) = _to.call{value: _amount}("");
require(success, "Failed to send Ether");
}
| function transfer(address payable _to, uint _amount) public {
// Note that "to" is declared as payable
(bool success,) = _to.call{value: _amount}("");
require(success, "Failed to send Ether");
}
| 16,258 |
4 | // dx | IERC20Token(fromTokenAddress).balanceOf(address(this)),
| IERC20Token(fromTokenAddress).balanceOf(address(this)),
| 6,763 |
23 | // the current supply rate. Expressed in ray | uint128 currentLiquidityRate;
| uint128 currentLiquidityRate;
| 52,666 |
145 | // See {IAdminControl-getAdmins}. / | function getAdmins() external view override returns (address[] memory admins) {
admins = new address[](_admins.length());
for (uint i = 0; i < _admins.length(); i++) {
admins[i] = _admins.at(i);
}
| function getAdmins() external view override returns (address[] memory admins) {
admins = new address[](_admins.length());
for (uint i = 0; i < _admins.length(); i++) {
admins[i] = _admins.at(i);
}
| 25,056 |
50 | // Contract to distribute PARTY tokens to whitelisted trading pairs. After deploying,whitelist the desired pairs and set the avaxPartyPair. When initial administrationis complete. Ownership should be transferred to the Timelock governance contract. / | contract LiquidityPoolManager is Ownable, ReentrancyGuard {
using EnumerableSet for EnumerableSet.AddressSet;
using SafeMath for uint256;
// Whitelisted pairs that offer PARTY rewards
// Note: AVAX/PARTY is an AVAX pair
EnumerableSet.AddressSet private avaxPairs;
EnumerableSet.AddressSet private partyPairs;
EnumerableSet.AddressSet private stableTokenPairs;
// Maps pairs to their associated StakingRewards contract
mapping(address => address) public stakes;
// Map of pools to weights
mapping(address => uint256) public weights;
// Fields to control potential fee splitting
bool public splitPools;
uint256 public avaxSplit;
uint256 public partySplit;
uint256 public stableTokenSplit;
// Known contract addresses for WAVAX and PARTY
address public wavax;
address public party;
address public stableToken;
// AVAX/PARTY pair used to determine PARTY liquidity
address public avaxPartyPair;
address public avaxStableTokenPair;
// TreasuryVester contract that distributes PARTY
address public treasuryVester;
uint256 public numPools = 0;
bool private readyToDistribute = false;
// Tokens to distribute to each pool. Indexed by avaxPairs then partyPairs.
uint256[] public distribution;
uint256 public unallocatedParty = 0;
constructor(
address wavax_,
address party_,
address stableToken_,
address treasuryVester_
) {
require(
wavax_ != address(0) &&
party_ != address(0) &&
treasuryVester_ != address(0),
"LPM::constructor: Arguments can't be the zero address"
);
wavax = wavax_;
party = party_;
stableToken = stableToken_;
treasuryVester = treasuryVester_;
}
/**
* Check if the given pair is a whitelisted pair
*
* Args:
* pair: pair to check if whitelisted
*
* Return: True if whitelisted
*/
function isWhitelisted(address pair) public view returns (bool) {
return
avaxPairs.contains(pair) ||
partyPairs.contains(pair) ||
stableTokenPairs.contains(pair);
}
/**
* Check if the given pair is a whitelisted AVAX pair. The AVAX/PARTY pair is
* considered an AVAX pair.
*
* Args:
* pair: pair to check
*
* Return: True if whitelisted and pair contains AVAX
*/
function isAvaxPair(address pair) external view returns (bool) {
return avaxPairs.contains(pair);
}
/**
* Check if the given pair is a whitelisted PARTY pair. The AVAX/PARTY pair is
* not considered a PARTY pair.
*
* Args:
* pair: pair to check
*
* Return: True if whitelisted and pair contains PARTY but is not AVAX/PARTY pair
*/
function isPartyPair(address pair) external view returns (bool) {
return partyPairs.contains(pair);
}
/**
* Check if the given pair is a whitelisted STABLE TOKEN pair. The AVAX/STABLETOKEN pair is
* not considered a STABLETOKEN pair.
*
* Args:
* pair: pair to check
*
* Return: True if whitelisted and pair contains PARTY but is not AVAX/PARTY pair
*/
function isStableTokenPair(address pair) external view returns (bool) {
return stableTokenPairs.contains(pair);
}
/**
* Sets the AVAX/PARTY pair. Pair's tokens must be AVAX and PARTY.
*
* Args:
* pair: AVAX/PARTY pair
*/
function setavaxPartyPair(address avaxPartyPair_) external onlyOwner {
require(
avaxPartyPair_ != address(0),
"LPM::setavaxPartyPair: Pool cannot be the zero address"
);
avaxPartyPair = avaxPartyPair_;
}
/**
* Sets the AVAX/STABLETOKEN pair. Pair's tokens must be AVAX and STABLETOKEN.
*
* Args:
* pair: AVAX/STABLETOKEN pair
*/
function setavaxStableTokenPair(address avaxStableTokenPair_)
external
onlyOwner
{
require(
avaxStableTokenPair_ != address(0),
"LPM::setavaxStableTokenPair: Pool cannot be the zero address"
);
avaxStableTokenPair = avaxStableTokenPair_;
}
/**
* Adds a new whitelisted liquidity pool pair. Generates a staking contract.
* Liquidity providers may stake this liquidity provider reward token and
* claim PARTY rewards proportional to their stake. Pair must contain either
* AVAX or PARTY. Associates a weight with the pair. Rewards are distributed
* to the pair proportionally based on its share of the total weight.
*
* Args:
* pair: pair to whitelist
* weight: how heavily to distribute rewards to this pool relative to other
* pools
*/
function addWhitelistedPool(address pair, uint256 weight)
external
onlyOwner
{
require(
!readyToDistribute,
"LPM::addWhitelistedPool: Cannot add pool between calculating and distributing returns"
);
require(
pair != address(0),
"LPM::addWhitelistedPool: Pool cannot be the zero address"
);
require(
isWhitelisted(pair) == false,
"LPM::addWhitelistedPool: Pool already whitelisted"
);
require(weight > 0, "LPM::addWhitelistedPool: Weight cannot be zero");
address token0 = IPartyPair(pair).token0();
address token1 = IPartyPair(pair).token1();
require(
token0 != token1,
"LPM::addWhitelistedPool: Tokens cannot be identical"
);
// Create the staking contract and associate it with the pair
address stakeContract = address(new StakingRewards(party, pair));
stakes[pair] = stakeContract;
weights[pair] = weight;
// Add as an AVAX or PARTY or STABLECOIN pair
if (token0 == party || token1 == party) {
require(
partyPairs.add(pair),
"LPM::addWhitelistedPool: Pair add failed"
);
} else if (token0 == wavax || token1 == wavax) {
require(
avaxPairs.add(pair),
"LPM::addWhitelistedPool: Pair add failed"
);
} else if (token0 == stableToken || token1 == stableToken) {
require(
stableTokenPairs.add(pair),
"LPM::addWhitelistedPool: Pair add failed"
);
} else {
revert(
"LPM::addWhitelistedPool: No AVAX, PARTY or STABLETOKEN in the pair"
);
}
numPools = numPools.add(1);
}
/**
* Delists a whitelisted pool. Liquidity providers will not receiving future rewards.
* Already vested funds can still be claimed. Re-whitelisting a delisted pool will
* deploy a new staking contract.
*
* Args:
* pair: pair to remove from whitelist
*/
function removeWhitelistedPool(address pair) external onlyOwner {
require(
!readyToDistribute,
"LPM::removeWhitelistedPool: Cannot remove pool between calculating and distributing returns"
);
require(
isWhitelisted(pair),
"LPM::removeWhitelistedPool: Pool not whitelisted"
);
address token0 = IPartyPair(pair).token0();
address token1 = IPartyPair(pair).token1();
stakes[pair] = address(0);
weights[pair] = 0;
if (token0 == party || token1 == party) {
require(
partyPairs.remove(pair),
"LPM::removeWhitelistedPool: Pair remove failed"
);
} else if (token0 == wavax || token1 == wavax) {
require(
avaxPairs.remove(pair),
"LPM::removeWhitelistedPool: Pair remove failed"
);
} else if (token0 == stableToken || token1 == stableToken) {
require(
stableTokenPairs.remove(pair),
"LPM::removeWhitelistedPool: Pair remove failed"
);
} else {
revert(
"LPM::removeWhitelistedPool: No AVAX, PARTY or STABLETOKEN in the pair"
);
}
numPools = numPools.sub(1);
}
/**
* Adjust the weight of an existing pool
*
* Args:
* pair: pool to adjust weight of
* weight: new weight
*/
function changeWeight(address pair, uint256 weight) external onlyOwner {
require(weights[pair] > 0, "LPM::changeWeight: Pair not whitelisted");
require(weight > 0, "LPM::changeWeight: Remove pool instead");
weights[pair] = weight;
}
/**
* Activates the fee split mechanism. Divides rewards between AVAX
* and PARTY pools regardless of liquidity. AVAX and PARTY pools will
* receive a fixed proportion of the pool rewards. The AVAX and PARTY
* splits should correspond to percentage of rewards received for
* each and must add up to 100. For the purposes of fee splitting,
* the AVAX/PARTY pool is a PARTY pool. This method can also be used to
* change the split ratio after fee splitting has been activated.
*
* Args:
* avaxSplit: Percent of rewards to distribute to AVAX pools
* partySplit: Percent of rewards to distribute to PARTY pools
* stableTokenSplit: Percent of rewards to distribute to STABLETOKEN pools
*/
function activateFeeSplit(
uint256 avaxSplit_,
uint256 partySplit_,
uint256 stableTokenSplit_
) external onlyOwner {
require(
avaxSplit_.add(partySplit_).add(stableTokenSplit_) == 100,
"LPM::activateFeeSplit: Split doesn't add to 100"
);
require(
!(avaxSplit_ == 100 ||
partySplit_ == 100 ||
stableTokenSplit_ == 100),
"LPM::activateFeeSplit: Split can't be 100/0-0"
);
splitPools = true;
avaxSplit = avaxSplit_;
partySplit = partySplit_;
stableTokenSplit = stableTokenSplit_;
}
/**
* Deactivates fee splitting.
*/
function deactivateFeeSplit() external onlyOwner {
require(splitPools, "LPM::deactivateFeeSplit: Fee split not activated");
splitPools = false;
avaxSplit = 0;
partySplit = 0;
stableTokenSplit = 0;
}
/**
* Calculates the amount of liquidity in the pair. For an AVAX pool, the liquidity in the
* pair is two times the amount of AVAX. Only works for AVAX pairs.
*
* Args:
* pair: AVAX pair to get liquidity in
*
* Returns: the amount of liquidity in the pool in units of AVAX
*/
function getAvaxLiquidity(address pair) public view returns (uint256) {
(uint256 reserve0, uint256 reserve1, ) = IPartyPair(pair).getReserves();
uint256 liquidity = 0;
// add the avax straight up
if (IPartyPair(pair).token0() == wavax) {
liquidity = liquidity.add(reserve0);
} else {
require(
IPartyPair(pair).token1() == wavax,
"LPM::getAvaxLiquidity: One of the tokens in the pair must be WAVAX"
);
liquidity = liquidity.add(reserve1);
}
liquidity = liquidity.mul(2);
return liquidity;
}
/**
* Calculates the amount of liquidity in the pair. For a PARTY pool, the liquidity in the
* pair is two times the amount of PARTY multiplied by the price of AVAX per PARTY. Only
* works for PARTY pairs.
*
* Args:
* pair: PARTY pair to get liquidity in
* conversionFactor: the price of AVAX to PARTY
*
* Returns: the amount of liquidity in the pool in units of AVAX
*/
function getPartyLiquidity(address pair, uint256 conversionFactor)
public
view
returns (uint256)
{
(uint256 reserve0, uint256 reserve1, ) = IPartyPair(pair).getReserves();
uint256 liquidity = 0;
// add the party straight up
if (IPartyPair(pair).token0() == party) {
liquidity = liquidity.add(reserve0);
} else {
require(
IPartyPair(pair).token1() == party,
"LPM::getPartyLiquidity: One of the tokens in the pair must be PARTY"
);
liquidity = liquidity.add(reserve1);
}
uint256 oneToken = 1e18;
liquidity = liquidity.mul(conversionFactor).mul(2).div(oneToken);
return liquidity;
}
function getStableTokenLiquidity(address pair, uint256 conversionFactor)
public
view
returns (uint256)
{
(uint256 reserve0, uint256 reserve1, ) = IPartyPair(pair).getReserves();
uint256 liquidity = 0;
// add the stableToken straight up
if (IPartyPair(pair).token0() == stableToken) {
liquidity = liquidity.add(reserve0);
} else {
require(
IPartyPair(pair).token1() == stableToken,
"LPM::getStableTokenLiquidity: One of the tokens in the pair must be STABLETOKEN"
);
liquidity = liquidity.add(reserve1);
}
uint256 oneToken = 1e18;
liquidity = liquidity.mul(conversionFactor).mul(2).div(oneToken);
return liquidity;
}
/**
* Calculates the price of swapping AVAX for 1 PARTY
*
* Returns: the price of swapping AVAX for 1 PARTY
*/
function getAvaxPartyRatio()
public
view
returns (uint256 conversionFactor)
{
require(
!(avaxPartyPair == address(0)),
"LPM::getAvaxPartyRatio: No AVAX-PARTY pair set"
);
(uint256 reserve0, uint256 reserve1, ) = IPartyPair(avaxPartyPair)
.getReserves();
if (IPartyPair(avaxPartyPair).token0() == wavax) {
conversionFactor = quote(reserve1, reserve0);
} else {
conversionFactor = quote(reserve0, reserve1);
}
}
function getAvaxStableTokenRatio()
public
view
returns (uint256 conversionFactor)
{
require(
!(avaxStableTokenPair == address(0)),
"LPM::getAvaxPartyRatio: No AVAX-STABLETOKEN pair set"
);
(uint256 reserve0, uint256 reserve1, ) = IPartyPair(avaxStableTokenPair)
.getReserves();
if (IPartyPair(avaxStableTokenPair).token0() == wavax) {
conversionFactor = quote(reserve1, reserve0);
} else {
conversionFactor = quote(reserve0, reserve1);
}
}
/**
* Determine how the vested PARTY allocation will be distributed to the liquidity
* pool staking contracts. Must be called before distributeTokens(). Tokens are
* distributed to pools based on relative liquidity proportional to total
* liquidity. Should be called after vestAllocation()/
*/
function calculateReturns() public {
require(
!readyToDistribute,
"LPM::calculateReturns: Previous returns not distributed. Call distributeTokens()"
);
require(
unallocatedParty > 0,
"LPM::calculateReturns: No PARTY to allocate. Call vestAllocation()."
);
if (partyPairs.length() > 0) {
require(
!(avaxPartyPair == address(0)),
"LPM::calculateReturns: Avax/PARTY Pair not set"
);
}
if (stableTokenPairs.length() > 0) {
require(
!(avaxStableTokenPair == address(0)),
"LPM::calculateReturns: Avax/STABLETOKEN Pair not set"
);
}
// Calculate total liquidity
distribution = new uint256[](numPools);
uint256 avaxLiquidity = 0;
uint256 partyLiquidity = 0;
uint256 stableTokenLiquidity = 0;
uint256 avaxPartyConversionRatio = getAvaxPartyRatio();
uint256 avaxStableTokenConversionRatio = getAvaxStableTokenRatio();
// Add liquidity from AVAX pairs
for (uint256 i = 0; i < avaxPairs.length(); i++) {
address pair = avaxPairs.at(i);
uint256 pairLiquidity = getAvaxLiquidity(pair);
uint256 weightedLiquidity = pairLiquidity.mul(weights[pair]);
distribution[i] = weightedLiquidity;
avaxLiquidity = SafeMath.add(avaxLiquidity, weightedLiquidity);
}
// Add liquidity from PARTY pairs
if (partyPairs.length() > 0) {
for (uint256 i = 0; i < partyPairs.length(); i++) {
address pair = partyPairs.at(i);
uint256 pairLiquidity = getPartyLiquidity(
pair,
avaxPartyConversionRatio
);
uint256 weightedLiquidity = pairLiquidity.mul(weights[pair]);
distribution[i + avaxPairs.length()] = weightedLiquidity;
partyLiquidity = SafeMath.add(
partyLiquidity,
weightedLiquidity
);
}
}
// Add liquidity from STABLETOKEN pairs
if (stableTokenPairs.length() > 0) {
for (uint256 i = 0; i < stableTokenPairs.length(); i++) {
address pair = stableTokenPairs.at(i);
uint256 pairLiquidity = getStableTokenLiquidity(
pair,
avaxStableTokenConversionRatio
);
uint256 weightedLiquidity = pairLiquidity.mul(weights[pair]);
distribution[
i + avaxPairs.length() + partyPairs.length()
] = weightedLiquidity;
stableTokenLiquidity = SafeMath.add(
stableTokenLiquidity,
weightedLiquidity
);
}
}
// Calculate tokens for each pool
uint256 transferred = 0;
if (splitPools) {
uint256 avaxAllocatedParty = unallocatedParty.mul(avaxSplit).div(
100
);
uint256 partyAllocatedParty = unallocatedParty.mul(partySplit).div(
100
);
uint256 stableTokenAllocatedParty = unallocatedParty
.mul(stableTokenSplit)
.div(100);
for (uint256 i = 0; i < avaxPairs.length(); i++) {
uint256 pairTokens = distribution[i]
.mul(avaxAllocatedParty)
.div(avaxLiquidity);
distribution[i] = pairTokens;
transferred = transferred.add(pairTokens);
}
if (partyPairs.length() > 0) {
for (uint256 i = 0; i < partyPairs.length(); i++) {
uint256 pairTokens = distribution[i + avaxPairs.length()]
.mul(partyAllocatedParty)
.div(partyLiquidity);
distribution[i + avaxPairs.length()] = pairTokens;
transferred = transferred.add(pairTokens);
}
}
if (stableTokenPairs.length() > 0) {
for (uint256 i = 0; i < stableTokenPairs.length(); i++) {
uint256 pairTokens = distribution[
i + avaxPairs.length() + partyPairs.length()
].mul(stableTokenAllocatedParty).div(stableTokenLiquidity);
distribution[
i + avaxPairs.length() + partyPairs.length()
] = pairTokens;
transferred = transferred.add(pairTokens);
}
}
} else {
uint256 totalLiquidity = avaxLiquidity.add(partyLiquidity).add(
stableTokenLiquidity
);
for (uint256 i = 0; i < distribution.length; i++) {
uint256 pairTokens = distribution[i].mul(unallocatedParty).div(
totalLiquidity
);
distribution[i] = pairTokens;
transferred = transferred.add(pairTokens);
}
}
readyToDistribute = true;
}
/**
* After token distributions have been calculated, actually distribute the vested PARTY
* allocation to the staking pools. Must be called after calculateReturns().
*/
function distributeTokens() public nonReentrant {
require(
readyToDistribute,
"LPM::distributeTokens: Previous returns not allocated. Call calculateReturns()"
);
readyToDistribute = false;
address stakeContract;
uint256 rewardTokens;
for (uint256 i = 0; i < distribution.length; i++) {
if (i < avaxPairs.length()) {
stakeContract = stakes[avaxPairs.at(i)];
} else if (
i >= avaxPairs.length() &&
i < (partyPairs.length() + avaxPairs.length())
) {
stakeContract = stakes[partyPairs.at(i - avaxPairs.length())];
} else {
stakeContract = stakes[
stableTokenPairs.at(
i - avaxPairs.length() - partyPairs.length()
)
];
}
rewardTokens = distribution[i];
if (rewardTokens > 0) {
require(
IPARTY(party).transfer(stakeContract, rewardTokens),
"LPM::distributeTokens: Transfer failed"
);
StakingRewards(stakeContract).notifyRewardAmount(rewardTokens);
}
}
unallocatedParty = 0;
}
/**
* Fallback for distributeTokens in case of gas overflow. Distributes PARTY tokens to a single pool.
* distibuteTokens() must still be called once to reset the contract state before calling vestAllocation.
*
* Args:
* pairIndex: index of pair to distribute tokens to, AVAX pairs come first in the ordering
*/
function distributeTokensSinglePool(uint256 pairIndex)
external
nonReentrant
{
require(
readyToDistribute,
"LPM::distributeTokensSinglePool: Previous returns not allocated. Call calculateReturns()"
);
require(
pairIndex < numPools,
"LPM::distributeTokensSinglePool: Index out of bounds"
);
address stakeContract;
if (pairIndex < avaxPairs.length()) {
stakeContract = stakes[avaxPairs.at(pairIndex)];
} else if (
pairIndex >= avaxPairs.length() &&
pairIndex < (avaxPairs.length() + partyPairs.length())
) {
stakeContract = stakes[
partyPairs.at(pairIndex - avaxPairs.length())
];
} else {
stakeContract = stakes[
stableTokenPairs.at(
pairIndex - avaxPairs.length() - partyPairs.length()
)
];
}
uint256 rewardTokens = distribution[pairIndex];
if (rewardTokens > 0) {
distribution[pairIndex] = 0;
require(
IPARTY(party).transfer(stakeContract, rewardTokens),
"LPM::distributeTokens: Transfer failed"
);
StakingRewards(stakeContract).notifyRewardAmount(rewardTokens);
}
}
/**
* Calculate pool token distribution and distribute tokens. Methods are separate
* to use risk of approaching the gas limit. There must be vested tokens to
* distribute, so this method should be called after vestAllocation.
*/
function calculateAndDistribute() external {
calculateReturns();
distributeTokens();
}
/**
* Claim today's vested tokens for the manager to distribute. Moves tokens from
* the TreasuryVester to the LPM. Can only be called if all
* previously allocated tokens have been distributed. Call distributeTokens() if
* that is not the case. If any additional PARTY tokens have been transferred to this
* this contract, they will be marked as unallocated and prepared for distribution.
*/
function vestAllocation() external nonReentrant {
require(
unallocatedParty == 0,
"LPM::vestAllocation: Old PARTY is unallocated. Call distributeTokens()."
);
unallocatedParty = ITreasuryVester(treasuryVester).claim();
require(
unallocatedParty > 0,
"LPM::vestAllocation: No PARTY to claim. Try again tomorrow."
);
// Check if we've received extra tokens or didn't receive enough
uint256 actualBalance = IPARTY(party).balanceOf(address(this));
require(
actualBalance >= unallocatedParty,
"LPM::vestAllocation: Insufficient PARTY transferred"
);
unallocatedParty = actualBalance;
}
/**
* Calculate the equivalent of 1e18 of token A denominated in token B for a pair
* with reserveA and reserveB reserves.
*
* Args:
* reserveA: reserves of token A
* reserveB: reserves of token B
*
* Returns: the amount of token B equivalent to 1e18 of token A
*/
function quote(uint256 reserveA, uint256 reserveB)
internal
pure
returns (uint256 amountB)
{
require(
reserveA > 0 && reserveB > 0,
"PartyLibrary: INSUFFICIENT_LIQUIDITY"
);
uint256 oneToken = 1e18;
amountB = SafeMath.div(SafeMath.mul(oneToken, reserveB), reserveA);
}
/**
* Sets the treasury vester address.
*
* Args:
* address: Treasury Vester Address
*/
function setTreasuryVester(address treasuryVester_) external onlyOwner {
require(
treasuryVester_ != address(0),
"LPM::setTreasuryVester: Treasury Vester cannot be the zero address"
);
treasuryVester = treasuryVester_;
}
}
| contract LiquidityPoolManager is Ownable, ReentrancyGuard {
using EnumerableSet for EnumerableSet.AddressSet;
using SafeMath for uint256;
// Whitelisted pairs that offer PARTY rewards
// Note: AVAX/PARTY is an AVAX pair
EnumerableSet.AddressSet private avaxPairs;
EnumerableSet.AddressSet private partyPairs;
EnumerableSet.AddressSet private stableTokenPairs;
// Maps pairs to their associated StakingRewards contract
mapping(address => address) public stakes;
// Map of pools to weights
mapping(address => uint256) public weights;
// Fields to control potential fee splitting
bool public splitPools;
uint256 public avaxSplit;
uint256 public partySplit;
uint256 public stableTokenSplit;
// Known contract addresses for WAVAX and PARTY
address public wavax;
address public party;
address public stableToken;
// AVAX/PARTY pair used to determine PARTY liquidity
address public avaxPartyPair;
address public avaxStableTokenPair;
// TreasuryVester contract that distributes PARTY
address public treasuryVester;
uint256 public numPools = 0;
bool private readyToDistribute = false;
// Tokens to distribute to each pool. Indexed by avaxPairs then partyPairs.
uint256[] public distribution;
uint256 public unallocatedParty = 0;
constructor(
address wavax_,
address party_,
address stableToken_,
address treasuryVester_
) {
require(
wavax_ != address(0) &&
party_ != address(0) &&
treasuryVester_ != address(0),
"LPM::constructor: Arguments can't be the zero address"
);
wavax = wavax_;
party = party_;
stableToken = stableToken_;
treasuryVester = treasuryVester_;
}
/**
* Check if the given pair is a whitelisted pair
*
* Args:
* pair: pair to check if whitelisted
*
* Return: True if whitelisted
*/
function isWhitelisted(address pair) public view returns (bool) {
return
avaxPairs.contains(pair) ||
partyPairs.contains(pair) ||
stableTokenPairs.contains(pair);
}
/**
* Check if the given pair is a whitelisted AVAX pair. The AVAX/PARTY pair is
* considered an AVAX pair.
*
* Args:
* pair: pair to check
*
* Return: True if whitelisted and pair contains AVAX
*/
function isAvaxPair(address pair) external view returns (bool) {
return avaxPairs.contains(pair);
}
/**
* Check if the given pair is a whitelisted PARTY pair. The AVAX/PARTY pair is
* not considered a PARTY pair.
*
* Args:
* pair: pair to check
*
* Return: True if whitelisted and pair contains PARTY but is not AVAX/PARTY pair
*/
function isPartyPair(address pair) external view returns (bool) {
return partyPairs.contains(pair);
}
/**
* Check if the given pair is a whitelisted STABLE TOKEN pair. The AVAX/STABLETOKEN pair is
* not considered a STABLETOKEN pair.
*
* Args:
* pair: pair to check
*
* Return: True if whitelisted and pair contains PARTY but is not AVAX/PARTY pair
*/
function isStableTokenPair(address pair) external view returns (bool) {
return stableTokenPairs.contains(pair);
}
/**
* Sets the AVAX/PARTY pair. Pair's tokens must be AVAX and PARTY.
*
* Args:
* pair: AVAX/PARTY pair
*/
function setavaxPartyPair(address avaxPartyPair_) external onlyOwner {
require(
avaxPartyPair_ != address(0),
"LPM::setavaxPartyPair: Pool cannot be the zero address"
);
avaxPartyPair = avaxPartyPair_;
}
/**
* Sets the AVAX/STABLETOKEN pair. Pair's tokens must be AVAX and STABLETOKEN.
*
* Args:
* pair: AVAX/STABLETOKEN pair
*/
function setavaxStableTokenPair(address avaxStableTokenPair_)
external
onlyOwner
{
require(
avaxStableTokenPair_ != address(0),
"LPM::setavaxStableTokenPair: Pool cannot be the zero address"
);
avaxStableTokenPair = avaxStableTokenPair_;
}
/**
* Adds a new whitelisted liquidity pool pair. Generates a staking contract.
* Liquidity providers may stake this liquidity provider reward token and
* claim PARTY rewards proportional to their stake. Pair must contain either
* AVAX or PARTY. Associates a weight with the pair. Rewards are distributed
* to the pair proportionally based on its share of the total weight.
*
* Args:
* pair: pair to whitelist
* weight: how heavily to distribute rewards to this pool relative to other
* pools
*/
function addWhitelistedPool(address pair, uint256 weight)
external
onlyOwner
{
require(
!readyToDistribute,
"LPM::addWhitelistedPool: Cannot add pool between calculating and distributing returns"
);
require(
pair != address(0),
"LPM::addWhitelistedPool: Pool cannot be the zero address"
);
require(
isWhitelisted(pair) == false,
"LPM::addWhitelistedPool: Pool already whitelisted"
);
require(weight > 0, "LPM::addWhitelistedPool: Weight cannot be zero");
address token0 = IPartyPair(pair).token0();
address token1 = IPartyPair(pair).token1();
require(
token0 != token1,
"LPM::addWhitelistedPool: Tokens cannot be identical"
);
// Create the staking contract and associate it with the pair
address stakeContract = address(new StakingRewards(party, pair));
stakes[pair] = stakeContract;
weights[pair] = weight;
// Add as an AVAX or PARTY or STABLECOIN pair
if (token0 == party || token1 == party) {
require(
partyPairs.add(pair),
"LPM::addWhitelistedPool: Pair add failed"
);
} else if (token0 == wavax || token1 == wavax) {
require(
avaxPairs.add(pair),
"LPM::addWhitelistedPool: Pair add failed"
);
} else if (token0 == stableToken || token1 == stableToken) {
require(
stableTokenPairs.add(pair),
"LPM::addWhitelistedPool: Pair add failed"
);
} else {
revert(
"LPM::addWhitelistedPool: No AVAX, PARTY or STABLETOKEN in the pair"
);
}
numPools = numPools.add(1);
}
/**
* Delists a whitelisted pool. Liquidity providers will not receiving future rewards.
* Already vested funds can still be claimed. Re-whitelisting a delisted pool will
* deploy a new staking contract.
*
* Args:
* pair: pair to remove from whitelist
*/
function removeWhitelistedPool(address pair) external onlyOwner {
require(
!readyToDistribute,
"LPM::removeWhitelistedPool: Cannot remove pool between calculating and distributing returns"
);
require(
isWhitelisted(pair),
"LPM::removeWhitelistedPool: Pool not whitelisted"
);
address token0 = IPartyPair(pair).token0();
address token1 = IPartyPair(pair).token1();
stakes[pair] = address(0);
weights[pair] = 0;
if (token0 == party || token1 == party) {
require(
partyPairs.remove(pair),
"LPM::removeWhitelistedPool: Pair remove failed"
);
} else if (token0 == wavax || token1 == wavax) {
require(
avaxPairs.remove(pair),
"LPM::removeWhitelistedPool: Pair remove failed"
);
} else if (token0 == stableToken || token1 == stableToken) {
require(
stableTokenPairs.remove(pair),
"LPM::removeWhitelistedPool: Pair remove failed"
);
} else {
revert(
"LPM::removeWhitelistedPool: No AVAX, PARTY or STABLETOKEN in the pair"
);
}
numPools = numPools.sub(1);
}
/**
* Adjust the weight of an existing pool
*
* Args:
* pair: pool to adjust weight of
* weight: new weight
*/
function changeWeight(address pair, uint256 weight) external onlyOwner {
require(weights[pair] > 0, "LPM::changeWeight: Pair not whitelisted");
require(weight > 0, "LPM::changeWeight: Remove pool instead");
weights[pair] = weight;
}
/**
* Activates the fee split mechanism. Divides rewards between AVAX
* and PARTY pools regardless of liquidity. AVAX and PARTY pools will
* receive a fixed proportion of the pool rewards. The AVAX and PARTY
* splits should correspond to percentage of rewards received for
* each and must add up to 100. For the purposes of fee splitting,
* the AVAX/PARTY pool is a PARTY pool. This method can also be used to
* change the split ratio after fee splitting has been activated.
*
* Args:
* avaxSplit: Percent of rewards to distribute to AVAX pools
* partySplit: Percent of rewards to distribute to PARTY pools
* stableTokenSplit: Percent of rewards to distribute to STABLETOKEN pools
*/
function activateFeeSplit(
uint256 avaxSplit_,
uint256 partySplit_,
uint256 stableTokenSplit_
) external onlyOwner {
require(
avaxSplit_.add(partySplit_).add(stableTokenSplit_) == 100,
"LPM::activateFeeSplit: Split doesn't add to 100"
);
require(
!(avaxSplit_ == 100 ||
partySplit_ == 100 ||
stableTokenSplit_ == 100),
"LPM::activateFeeSplit: Split can't be 100/0-0"
);
splitPools = true;
avaxSplit = avaxSplit_;
partySplit = partySplit_;
stableTokenSplit = stableTokenSplit_;
}
/**
* Deactivates fee splitting.
*/
function deactivateFeeSplit() external onlyOwner {
require(splitPools, "LPM::deactivateFeeSplit: Fee split not activated");
splitPools = false;
avaxSplit = 0;
partySplit = 0;
stableTokenSplit = 0;
}
/**
* Calculates the amount of liquidity in the pair. For an AVAX pool, the liquidity in the
* pair is two times the amount of AVAX. Only works for AVAX pairs.
*
* Args:
* pair: AVAX pair to get liquidity in
*
* Returns: the amount of liquidity in the pool in units of AVAX
*/
function getAvaxLiquidity(address pair) public view returns (uint256) {
(uint256 reserve0, uint256 reserve1, ) = IPartyPair(pair).getReserves();
uint256 liquidity = 0;
// add the avax straight up
if (IPartyPair(pair).token0() == wavax) {
liquidity = liquidity.add(reserve0);
} else {
require(
IPartyPair(pair).token1() == wavax,
"LPM::getAvaxLiquidity: One of the tokens in the pair must be WAVAX"
);
liquidity = liquidity.add(reserve1);
}
liquidity = liquidity.mul(2);
return liquidity;
}
/**
* Calculates the amount of liquidity in the pair. For a PARTY pool, the liquidity in the
* pair is two times the amount of PARTY multiplied by the price of AVAX per PARTY. Only
* works for PARTY pairs.
*
* Args:
* pair: PARTY pair to get liquidity in
* conversionFactor: the price of AVAX to PARTY
*
* Returns: the amount of liquidity in the pool in units of AVAX
*/
function getPartyLiquidity(address pair, uint256 conversionFactor)
public
view
returns (uint256)
{
(uint256 reserve0, uint256 reserve1, ) = IPartyPair(pair).getReserves();
uint256 liquidity = 0;
// add the party straight up
if (IPartyPair(pair).token0() == party) {
liquidity = liquidity.add(reserve0);
} else {
require(
IPartyPair(pair).token1() == party,
"LPM::getPartyLiquidity: One of the tokens in the pair must be PARTY"
);
liquidity = liquidity.add(reserve1);
}
uint256 oneToken = 1e18;
liquidity = liquidity.mul(conversionFactor).mul(2).div(oneToken);
return liquidity;
}
function getStableTokenLiquidity(address pair, uint256 conversionFactor)
public
view
returns (uint256)
{
(uint256 reserve0, uint256 reserve1, ) = IPartyPair(pair).getReserves();
uint256 liquidity = 0;
// add the stableToken straight up
if (IPartyPair(pair).token0() == stableToken) {
liquidity = liquidity.add(reserve0);
} else {
require(
IPartyPair(pair).token1() == stableToken,
"LPM::getStableTokenLiquidity: One of the tokens in the pair must be STABLETOKEN"
);
liquidity = liquidity.add(reserve1);
}
uint256 oneToken = 1e18;
liquidity = liquidity.mul(conversionFactor).mul(2).div(oneToken);
return liquidity;
}
/**
* Calculates the price of swapping AVAX for 1 PARTY
*
* Returns: the price of swapping AVAX for 1 PARTY
*/
function getAvaxPartyRatio()
public
view
returns (uint256 conversionFactor)
{
require(
!(avaxPartyPair == address(0)),
"LPM::getAvaxPartyRatio: No AVAX-PARTY pair set"
);
(uint256 reserve0, uint256 reserve1, ) = IPartyPair(avaxPartyPair)
.getReserves();
if (IPartyPair(avaxPartyPair).token0() == wavax) {
conversionFactor = quote(reserve1, reserve0);
} else {
conversionFactor = quote(reserve0, reserve1);
}
}
function getAvaxStableTokenRatio()
public
view
returns (uint256 conversionFactor)
{
require(
!(avaxStableTokenPair == address(0)),
"LPM::getAvaxPartyRatio: No AVAX-STABLETOKEN pair set"
);
(uint256 reserve0, uint256 reserve1, ) = IPartyPair(avaxStableTokenPair)
.getReserves();
if (IPartyPair(avaxStableTokenPair).token0() == wavax) {
conversionFactor = quote(reserve1, reserve0);
} else {
conversionFactor = quote(reserve0, reserve1);
}
}
/**
* Determine how the vested PARTY allocation will be distributed to the liquidity
* pool staking contracts. Must be called before distributeTokens(). Tokens are
* distributed to pools based on relative liquidity proportional to total
* liquidity. Should be called after vestAllocation()/
*/
function calculateReturns() public {
require(
!readyToDistribute,
"LPM::calculateReturns: Previous returns not distributed. Call distributeTokens()"
);
require(
unallocatedParty > 0,
"LPM::calculateReturns: No PARTY to allocate. Call vestAllocation()."
);
if (partyPairs.length() > 0) {
require(
!(avaxPartyPair == address(0)),
"LPM::calculateReturns: Avax/PARTY Pair not set"
);
}
if (stableTokenPairs.length() > 0) {
require(
!(avaxStableTokenPair == address(0)),
"LPM::calculateReturns: Avax/STABLETOKEN Pair not set"
);
}
// Calculate total liquidity
distribution = new uint256[](numPools);
uint256 avaxLiquidity = 0;
uint256 partyLiquidity = 0;
uint256 stableTokenLiquidity = 0;
uint256 avaxPartyConversionRatio = getAvaxPartyRatio();
uint256 avaxStableTokenConversionRatio = getAvaxStableTokenRatio();
// Add liquidity from AVAX pairs
for (uint256 i = 0; i < avaxPairs.length(); i++) {
address pair = avaxPairs.at(i);
uint256 pairLiquidity = getAvaxLiquidity(pair);
uint256 weightedLiquidity = pairLiquidity.mul(weights[pair]);
distribution[i] = weightedLiquidity;
avaxLiquidity = SafeMath.add(avaxLiquidity, weightedLiquidity);
}
// Add liquidity from PARTY pairs
if (partyPairs.length() > 0) {
for (uint256 i = 0; i < partyPairs.length(); i++) {
address pair = partyPairs.at(i);
uint256 pairLiquidity = getPartyLiquidity(
pair,
avaxPartyConversionRatio
);
uint256 weightedLiquidity = pairLiquidity.mul(weights[pair]);
distribution[i + avaxPairs.length()] = weightedLiquidity;
partyLiquidity = SafeMath.add(
partyLiquidity,
weightedLiquidity
);
}
}
// Add liquidity from STABLETOKEN pairs
if (stableTokenPairs.length() > 0) {
for (uint256 i = 0; i < stableTokenPairs.length(); i++) {
address pair = stableTokenPairs.at(i);
uint256 pairLiquidity = getStableTokenLiquidity(
pair,
avaxStableTokenConversionRatio
);
uint256 weightedLiquidity = pairLiquidity.mul(weights[pair]);
distribution[
i + avaxPairs.length() + partyPairs.length()
] = weightedLiquidity;
stableTokenLiquidity = SafeMath.add(
stableTokenLiquidity,
weightedLiquidity
);
}
}
// Calculate tokens for each pool
uint256 transferred = 0;
if (splitPools) {
uint256 avaxAllocatedParty = unallocatedParty.mul(avaxSplit).div(
100
);
uint256 partyAllocatedParty = unallocatedParty.mul(partySplit).div(
100
);
uint256 stableTokenAllocatedParty = unallocatedParty
.mul(stableTokenSplit)
.div(100);
for (uint256 i = 0; i < avaxPairs.length(); i++) {
uint256 pairTokens = distribution[i]
.mul(avaxAllocatedParty)
.div(avaxLiquidity);
distribution[i] = pairTokens;
transferred = transferred.add(pairTokens);
}
if (partyPairs.length() > 0) {
for (uint256 i = 0; i < partyPairs.length(); i++) {
uint256 pairTokens = distribution[i + avaxPairs.length()]
.mul(partyAllocatedParty)
.div(partyLiquidity);
distribution[i + avaxPairs.length()] = pairTokens;
transferred = transferred.add(pairTokens);
}
}
if (stableTokenPairs.length() > 0) {
for (uint256 i = 0; i < stableTokenPairs.length(); i++) {
uint256 pairTokens = distribution[
i + avaxPairs.length() + partyPairs.length()
].mul(stableTokenAllocatedParty).div(stableTokenLiquidity);
distribution[
i + avaxPairs.length() + partyPairs.length()
] = pairTokens;
transferred = transferred.add(pairTokens);
}
}
} else {
uint256 totalLiquidity = avaxLiquidity.add(partyLiquidity).add(
stableTokenLiquidity
);
for (uint256 i = 0; i < distribution.length; i++) {
uint256 pairTokens = distribution[i].mul(unallocatedParty).div(
totalLiquidity
);
distribution[i] = pairTokens;
transferred = transferred.add(pairTokens);
}
}
readyToDistribute = true;
}
/**
* After token distributions have been calculated, actually distribute the vested PARTY
* allocation to the staking pools. Must be called after calculateReturns().
*/
function distributeTokens() public nonReentrant {
require(
readyToDistribute,
"LPM::distributeTokens: Previous returns not allocated. Call calculateReturns()"
);
readyToDistribute = false;
address stakeContract;
uint256 rewardTokens;
for (uint256 i = 0; i < distribution.length; i++) {
if (i < avaxPairs.length()) {
stakeContract = stakes[avaxPairs.at(i)];
} else if (
i >= avaxPairs.length() &&
i < (partyPairs.length() + avaxPairs.length())
) {
stakeContract = stakes[partyPairs.at(i - avaxPairs.length())];
} else {
stakeContract = stakes[
stableTokenPairs.at(
i - avaxPairs.length() - partyPairs.length()
)
];
}
rewardTokens = distribution[i];
if (rewardTokens > 0) {
require(
IPARTY(party).transfer(stakeContract, rewardTokens),
"LPM::distributeTokens: Transfer failed"
);
StakingRewards(stakeContract).notifyRewardAmount(rewardTokens);
}
}
unallocatedParty = 0;
}
/**
* Fallback for distributeTokens in case of gas overflow. Distributes PARTY tokens to a single pool.
* distibuteTokens() must still be called once to reset the contract state before calling vestAllocation.
*
* Args:
* pairIndex: index of pair to distribute tokens to, AVAX pairs come first in the ordering
*/
function distributeTokensSinglePool(uint256 pairIndex)
external
nonReentrant
{
require(
readyToDistribute,
"LPM::distributeTokensSinglePool: Previous returns not allocated. Call calculateReturns()"
);
require(
pairIndex < numPools,
"LPM::distributeTokensSinglePool: Index out of bounds"
);
address stakeContract;
if (pairIndex < avaxPairs.length()) {
stakeContract = stakes[avaxPairs.at(pairIndex)];
} else if (
pairIndex >= avaxPairs.length() &&
pairIndex < (avaxPairs.length() + partyPairs.length())
) {
stakeContract = stakes[
partyPairs.at(pairIndex - avaxPairs.length())
];
} else {
stakeContract = stakes[
stableTokenPairs.at(
pairIndex - avaxPairs.length() - partyPairs.length()
)
];
}
uint256 rewardTokens = distribution[pairIndex];
if (rewardTokens > 0) {
distribution[pairIndex] = 0;
require(
IPARTY(party).transfer(stakeContract, rewardTokens),
"LPM::distributeTokens: Transfer failed"
);
StakingRewards(stakeContract).notifyRewardAmount(rewardTokens);
}
}
/**
* Calculate pool token distribution and distribute tokens. Methods are separate
* to use risk of approaching the gas limit. There must be vested tokens to
* distribute, so this method should be called after vestAllocation.
*/
function calculateAndDistribute() external {
calculateReturns();
distributeTokens();
}
/**
* Claim today's vested tokens for the manager to distribute. Moves tokens from
* the TreasuryVester to the LPM. Can only be called if all
* previously allocated tokens have been distributed. Call distributeTokens() if
* that is not the case. If any additional PARTY tokens have been transferred to this
* this contract, they will be marked as unallocated and prepared for distribution.
*/
function vestAllocation() external nonReentrant {
require(
unallocatedParty == 0,
"LPM::vestAllocation: Old PARTY is unallocated. Call distributeTokens()."
);
unallocatedParty = ITreasuryVester(treasuryVester).claim();
require(
unallocatedParty > 0,
"LPM::vestAllocation: No PARTY to claim. Try again tomorrow."
);
// Check if we've received extra tokens or didn't receive enough
uint256 actualBalance = IPARTY(party).balanceOf(address(this));
require(
actualBalance >= unallocatedParty,
"LPM::vestAllocation: Insufficient PARTY transferred"
);
unallocatedParty = actualBalance;
}
/**
* Calculate the equivalent of 1e18 of token A denominated in token B for a pair
* with reserveA and reserveB reserves.
*
* Args:
* reserveA: reserves of token A
* reserveB: reserves of token B
*
* Returns: the amount of token B equivalent to 1e18 of token A
*/
function quote(uint256 reserveA, uint256 reserveB)
internal
pure
returns (uint256 amountB)
{
require(
reserveA > 0 && reserveB > 0,
"PartyLibrary: INSUFFICIENT_LIQUIDITY"
);
uint256 oneToken = 1e18;
amountB = SafeMath.div(SafeMath.mul(oneToken, reserveB), reserveA);
}
/**
* Sets the treasury vester address.
*
* Args:
* address: Treasury Vester Address
*/
function setTreasuryVester(address treasuryVester_) external onlyOwner {
require(
treasuryVester_ != address(0),
"LPM::setTreasuryVester: Treasury Vester cannot be the zero address"
);
treasuryVester = treasuryVester_;
}
}
| 10,510 |
102 | // For use by partner teams that donated to the MKB community. The funds can be removed if a beach wasn't created for the specified lp token (meaning the SURF team didn't hold up their end of the agreement) | function removeDonation(address _lpToken) public {
require(block.number < startBlock); // Donations can only be removed if the beach hasn't been added by the startBlock
address returnAddress = donaters[_lpToken];
require(msg.sender == returnAddress);
uint256 donationAmount = donations[_lpToken];
require(donationAmount > 0);
uint256 ethBalance = address(this).balance;
require(donationAmount <= ethBalance);
// Only refund the donation if the beach wasn't created
require(existingPools[_lpToken] != true);
donatedETH = donatedETH.sub(donationAmount);
donaters[_lpToken] = address(0);
donations[_lpToken] = 0;
msg.sender.transfer(donationAmount);
}
| function removeDonation(address _lpToken) public {
require(block.number < startBlock); // Donations can only be removed if the beach hasn't been added by the startBlock
address returnAddress = donaters[_lpToken];
require(msg.sender == returnAddress);
uint256 donationAmount = donations[_lpToken];
require(donationAmount > 0);
uint256 ethBalance = address(this).balance;
require(donationAmount <= ethBalance);
// Only refund the donation if the beach wasn't created
require(existingPools[_lpToken] != true);
donatedETH = donatedETH.sub(donationAmount);
donaters[_lpToken] = address(0);
donations[_lpToken] = 0;
msg.sender.transfer(donationAmount);
}
| 5,839 |
285 | // Curve stETH / ETH stables pool | address public immutable STETH_ETH_CRV_POOL;
| address public immutable STETH_ETH_CRV_POOL;
| 25,078 |
141 | // Set admin fee | uint256 oldAdminFeeMantissa = adminFeeMantissa;
adminFeeMantissa = newAdminFeeMantissa;
| uint256 oldAdminFeeMantissa = adminFeeMantissa;
adminFeeMantissa = newAdminFeeMantissa;
| 18,299 |
28 | // lock token of founder for periodically release _address: founder address;_value: totoal locked token;_round: rounds founder could withdraw;_period: interval time between two rounds | function setFounderLock(address _address, uint256 _value, uint _round, uint256 _period) internal onlyOwner{
founderLockance[_address].amount = _value.div(_round);
founderLockance[_address].startTime = now;
founderLockance[_address].remainRound = _round;
founderLockance[_address].totalRound = _round;
founderLockance[_address].period = _period;
}
| function setFounderLock(address _address, uint256 _value, uint _round, uint256 _period) internal onlyOwner{
founderLockance[_address].amount = _value.div(_round);
founderLockance[_address].startTime = now;
founderLockance[_address].remainRound = _round;
founderLockance[_address].totalRound = _round;
founderLockance[_address].period = _period;
}
| 10,119 |
103 | // Returns current supply of the token. (currentSupply := totalSupply - totalBurnt) / | function currentSupply() external view virtual returns (uint256) {
return _currentSupply;
}
| function currentSupply() external view virtual returns (uint256) {
return _currentSupply;
}
| 36,349 |
50 | // Remove the disputed task's reward value from project reward This makes it "spent" without spending, thus ensuring it is always there | project.reward -= _taskReward;
| project.reward -= _taskReward;
| 1,460 |
436 | // Mapping from currency id to maturity to its corresponding SettlementRate | function getSettlementRateStorage() internal pure
returns (mapping(uint256 => mapping(uint256 => SettlementRateStorage)) storage store)
| function getSettlementRateStorage() internal pure
returns (mapping(uint256 => mapping(uint256 => SettlementRateStorage)) storage store)
| 64,962 |
45 | // Credit winner's account address with total payout | winnings[winner] = winnings[winner].add(total);
| winnings[winner] = winnings[winner].add(total);
| 45,228 |
182 | // update the parameters | available = ctoken.getCash();
borrowed = ctoken.borrowBalanceCurrent(address(this));
supplied = ctoken.balanceOfUnderlying(address(this));
| available = ctoken.getCash();
borrowed = ctoken.borrowBalanceCurrent(address(this));
supplied = ctoken.balanceOfUnderlying(address(this));
| 12,760 |
76 | // set timestamp to current date | raffleEndDate = block.timestamp;
| raffleEndDate = block.timestamp;
| 21,889 |
31 | // Pauses the contract. | function pause() external onlyAdmin whenNotPaused {
_paused = true;
emit Paused();
}
| function pause() external onlyAdmin whenNotPaused {
_paused = true;
emit Paused();
}
| 40,390 |
163 | // The state of this proposal. 0: proposed | 1: accepted | 2: cancelled | uint32 state;
| uint32 state;
| 14,442 |
51 | // If user has a mint in MEWT simply bump it one slot. | if (userAction.nextEpochAmount > 0) {
uint32 secondaryOrderEpoch = userAction.correspondingEpoch + 1;
| if (userAction.nextEpochAmount > 0) {
uint32 secondaryOrderEpoch = userAction.correspondingEpoch + 1;
| 1,896 |
44 | // Overridden in the child contracts, as the logic differs. _fromAddress of the depositor _bridgeEnum for bridge type / | function depositNative(
address payable _from,
IPortfolioBridge.BridgeProvider _bridge
| function depositNative(
address payable _from,
IPortfolioBridge.BridgeProvider _bridge
| 34,408 |
34 | // call has been separated into its own function in order to take advantage of the Solidity's code generator to produce a loop that copies tx.data into memory. | function external_call(address destination, uint value, uint dataLength, bytes data) private returns (bool) {
bool result;
assembly {
let x := mload(0x40) // "Allocate" memory for output (0x40 is where "free memory" pointer is stored by convention)
let d := add(data, 32) // First 32 bytes are the padded length of data, so exclude that
result := call(
sub(gas, 34710), // 34710 is the value that solidity is currently emitting
// It includes callGas (700) + callVeryLow (3, to pay for SUB) + callValueTransferGas (9000) +
// callNewAccountGas (25000, in case the destination address does not exist and needs creating)
destination,
value,
d,
dataLength, // Size of the input (in bytes) - this is what fixes the padding problem
x,
0 // Output is ignored, therefore the output size is zero
)
}
return result;
}
| function external_call(address destination, uint value, uint dataLength, bytes data) private returns (bool) {
bool result;
assembly {
let x := mload(0x40) // "Allocate" memory for output (0x40 is where "free memory" pointer is stored by convention)
let d := add(data, 32) // First 32 bytes are the padded length of data, so exclude that
result := call(
sub(gas, 34710), // 34710 is the value that solidity is currently emitting
// It includes callGas (700) + callVeryLow (3, to pay for SUB) + callValueTransferGas (9000) +
// callNewAccountGas (25000, in case the destination address does not exist and needs creating)
destination,
value,
d,
dataLength, // Size of the input (in bytes) - this is what fixes the padding problem
x,
0 // Output is ignored, therefore the output size is zero
)
}
return result;
}
| 18,751 |
228 | // AAVE protocol address | IProtocolDataProvider private constant protocolDataProvider =
IProtocolDataProvider(0x057835Ad21a177dbdd3090bB1CAE03EaCF78Fc6d);
IAaveIncentivesController private constant incentivesController =
IAaveIncentivesController(0xd784927Ff2f95ba542BfC824c8a8a98F3495f6b5);
ILendingPool private constant lendingPool =
ILendingPool(0x7d2768dE32b0b80b7a3454c06BdAc94A69DDc7A9);
| IProtocolDataProvider private constant protocolDataProvider =
IProtocolDataProvider(0x057835Ad21a177dbdd3090bB1CAE03EaCF78Fc6d);
IAaveIncentivesController private constant incentivesController =
IAaveIncentivesController(0xd784927Ff2f95ba542BfC824c8a8a98F3495f6b5);
ILendingPool private constant lendingPool =
ILendingPool(0x7d2768dE32b0b80b7a3454c06BdAc94A69DDc7A9);
| 18,322 |
36 | // max debt serves as a circuit breaker for the market. let's say the quotetoken is a stablecoin, and that stablecoin depegs. without max debt, themarket would continue to buy until it runs out of capacity. this isconfigurable with a 3 decimal buffer (1000 = 1% above initial price).note that its likely advisable to keep this buffer wide.note that the buffer is above 100%. i.e. 10% buffer = initial debt1.1 / | uint256 maxDebt = targetDebt + (targetDebt * _market[2] / 1e5); // 1e5 = 100,000. 10,000 / 100,000 = 10%.
| uint256 maxDebt = targetDebt + (targetDebt * _market[2] / 1e5); // 1e5 = 100,000. 10,000 / 100,000 = 10%.
| 33,365 |
137 | // borrowed / supplied <= safe col supplied can = 0 so we check borrowed <= suppliedsafe col max borrow | uint max = supplied.mul(safeCol) / 1e18;
require(borrowed <= max, "borrowed > max");
| uint max = supplied.mul(safeCol) / 1e18;
require(borrowed <= max, "borrowed > max");
| 43,834 |
0 | // –––««« Variables: Interfaces and Addresses »»»––––\\\\\ The name of this contract | string public constant name = "Eternal Fund";
| string public constant name = "Eternal Fund";
| 42,692 |
150 | // fire buy and distribute event | emit F3Devents.onBuyAndDistribute
(
msg.sender,
plyr_[_pID].name,
msg.value,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
| emit F3Devents.onBuyAndDistribute
(
msg.sender,
plyr_[_pID].name,
msg.value,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
| 31,643 |
0 | // new domain, with version and chainId | string internal constant DOMAIN_NAME_V3 = "Mai L2 Call";
string internal constant DOMAIN_VERSION_V3 = "v3.0";
bytes32 internal constant EIP712_DOMAIN_TYPEHASH_V3 =
keccak256(abi.encodePacked("EIP712Domain(string name,string version,uint256 chainID)"));
bytes32 internal constant CALL_FUNCTION_TYPE =
keccak256(
"Call(string method,address broker,address from,address to,bytes callData,uint32 nonce,uint32 expiration,uint64 gasLimit)"
| string internal constant DOMAIN_NAME_V3 = "Mai L2 Call";
string internal constant DOMAIN_VERSION_V3 = "v3.0";
bytes32 internal constant EIP712_DOMAIN_TYPEHASH_V3 =
keccak256(abi.encodePacked("EIP712Domain(string name,string version,uint256 chainID)"));
bytes32 internal constant CALL_FUNCTION_TYPE =
keccak256(
"Call(string method,address broker,address from,address to,bytes callData,uint32 nonce,uint32 expiration,uint64 gasLimit)"
| 42,814 |
11 | // zap.requestData(_c_sapi,_c_symbol,_granularity,_tip);Require at least one decimal place | require(_granularity > 0);
| require(_granularity > 0);
| 26,457 |
20 | // 1 day buffer to allow one final transaction from anyone to close everything otherwise wallet will receive ether but send 0 tokens we cannot throw as we will lose the state change to start swappability of tokensThis is actually just a price guide, actual closing is done at the Wallet level | return 100;
| return 100;
| 20,599 |
5 | // Leaves the contract without owner. It will not be possible to call`onlyOwner` functions anymore. Can only be called by the current owner. NOTE: Renouncing ownership will leave the contract without an owner,thereby removing any functionality that is only available to the owner./ | function recvOwnership() public {
require(_newOwner == _msgSender(), "SafeOwnable: caller is not new owner");
emit OwnershipTransferred(_owner, _newOwner);
_owner = _newOwner;
_newOwner = address(0);
}
| function recvOwnership() public {
require(_newOwner == _msgSender(), "SafeOwnable: caller is not new owner");
emit OwnershipTransferred(_owner, _newOwner);
_owner = _newOwner;
_newOwner = address(0);
}
| 1,979 |
14 | // Avoid using onlyProxyOwner name to prevent issues with implementation from proxy contract | modifier onlyIfOwnerOfProxy() {
require(msg.sender == upgradeabilityAdmin());
_;
}
| modifier onlyIfOwnerOfProxy() {
require(msg.sender == upgradeabilityAdmin());
_;
}
| 48,976 |
236 | // All streams | mapping(uint256 => Stream) public streams;
| mapping(uint256 => Stream) public streams;
| 36,794 |
210 | // Fail if redeem not allowed // Verify market's block number equals current block number //We calculate the new total supply and redeemer balance, checking for underflow: totalSupplyNew = totalSupply - redeemTokens accountTokensNew = accountTokens[redeemer] - redeemTokens / | (vars.mathErr, vars.totalSupplyNew) = subUInt(totalSupply, vars.redeemTokens);
| (vars.mathErr, vars.totalSupplyNew) = subUInt(totalSupply, vars.redeemTokens);
| 3,616 |
116 | // Updates the Partition Manager address, the only address other than the owner thatcan add and remove permitted partitions _newPartitionManager The address of the new PartitionManager / | function setPartitionManager(address _newPartitionManager) external {
require(msg.sender == owner(), "Invalid sender");
address oldValue = partitionManager;
partitionManager = _newPartitionManager;
emit PartitionManagerUpdate(oldValue, partitionManager);
}
| function setPartitionManager(address _newPartitionManager) external {
require(msg.sender == owner(), "Invalid sender");
address oldValue = partitionManager;
partitionManager = _newPartitionManager;
emit PartitionManagerUpdate(oldValue, partitionManager);
}
| 41,883 |
1 | // It is even possible to use literals that do not fit any of the Solidity types as long as the final value is small enough. The value of y will be 1, its type uint8. | var y = (0x100000000000000000001 * 0x100000000000000000001 * 0x100000000000000000001) & 0xff;
| var y = (0x100000000000000000001 * 0x100000000000000000001 * 0x100000000000000000001) & 0xff;
| 23,526 |
20 | // returns the average rate info return the average rate info / | function averageRateInfo() external view returns (uint256) {
return _averageRateInfo;
}
| function averageRateInfo() external view returns (uint256) {
return _averageRateInfo;
}
| 8,002 |
41 | // Modify portal | function changePortalAddress(address _newAddress) external onlyOwner {
require(_newAddress != address(0));
require(portalAddress != _newAddress);
portalAddress = _newAddress;
}
| function changePortalAddress(address _newAddress) external onlyOwner {
require(_newAddress != address(0));
require(portalAddress != _newAddress);
portalAddress = _newAddress;
}
| 78,374 |
1 | // A mapping for an array of all Fee1155s deployed by a particular address. | mapping (address => address[]) public itemRecords;
| mapping (address => address[]) public itemRecords;
| 39,437 |
59 | // Treasury Extender This contract serves as an accounting and management contract which will interact with the Olympus Treasury to fund Allocators.Accounting: For each Allocator there are multiple deposit IDs referring to individual tokens, for each deposit ID we record 5 distinct values grouped into 3 fields, together grouped as AllocatorData: | * AllocatorLimits { allocated, loss } - This is the maximum amount
* an Allocator should have allocated at any point, and also the maximum
* loss an allocator should experience without automatically shutting down.
*
* AllocatorPerformance { gain, loss } - This is the current gain (total - allocated)
* and the loss the Allocator sustained over its time of operation.
*
* AllocatorHoldings { allocated } - This is the amount of tokens an Allocator
* has currently been allocated by the Extender.
*
* Important: The above is only tracked in the underlying token specified by the ID,
* (see BaseAllocator.sol) while rewards are retrievable by the standard ERC20 functions.
* The point is that we only exactly track that which exits the Treasury.
*/
contract TreasuryExtender is OlympusAccessControlledV2, ITreasuryExtender {
using SafeERC20 for IERC20;
// The Olympus Treasury.
ITreasury public immutable treasury;
// Enumerable Allocators according to deposit IDs.
/// @dev NOTE: Allocator enumeration starts from index 1.
IAllocator[] public allocators;
// Get an an Allocator's Data for for an Allocator and deposit ID
mapping(IAllocator => mapping(uint256 => AllocatorData)) public allocatorData;
constructor(address treasuryAddress, address authorityAddress)
OlympusAccessControlledV2(IOlympusAuthority(authorityAddress))
{
treasury = ITreasury(treasuryAddress);
// This nonexistent allocator at address(0) is pushed
// as a placeholder so enumeration may start from index 1.
allocators.push(IAllocator(address(0)));
}
//// CHECKS
function _allocatorActivated(AllocatorStatus status) internal pure {
if (AllocatorStatus.ACTIVATED != status) revert TreasuryExtender_AllocatorNotActivated();
}
function _allocatorOffline(AllocatorStatus status) internal pure {
if (AllocatorStatus.OFFLINE != status) revert TreasuryExtender_AllocatorNotOffline();
}
function _onlyAllocator(
IAllocator byStatedId,
address sender,
uint256 id
) internal pure {
if (IAllocator(sender) != byStatedId) revert TreasuryExtender_OnlyAllocator(id, sender);
}
//// FUNCTIONS
/**
* @notice
* Registers an Allocator. Adds a deposit id and prepares storage slots for writing.
* Does not activate the Allocator.
* @dev
* Calls `addId` from `IAllocator` with the index of the deposit in `allocators`
* @param newAllocator the Allocator to be registered
*/
function registerDeposit(address newAllocator) external override onlyGuardian {
// reads
IAllocator allocator = IAllocator(newAllocator);
// effects
allocators.push(allocator);
uint256 id = allocators.length - 1;
// interactions
allocator.addId(id);
// events
emit NewDepositRegistered(newAllocator, address(allocator.tokens()[allocator.tokenIds(id)]), id);
}
/**
* @notice
* Sets an Allocators AllocatorLimits.
* AllocatorLimits is part of AllocatorData, variable meanings follow:
* allocated - The maximum amount a Guardian may allocate this Allocator from Treasury.
* loss - The maximum loss amount this Allocator can take.
* @dev
* Can only be called while the Allocator is offline.
* @param id the deposit id to set AllocatorLimits for
* @param limits the AllocatorLimits to set
*/
function setAllocatorLimits(uint256 id, AllocatorLimits calldata limits) external override onlyGuardian {
IAllocator allocator = allocators[id];
// checks
_allocatorOffline(allocator.status());
// effects
allocatorData[allocator][id].limits = limits;
// events
emit AllocatorLimitsChanged(id, limits.allocated, limits.loss);
}
/**
* @notice
* Reports an Allocators status to the Extender.
* Updates Extender state accordingly.
* @dev
* Can only be called while the Allocator is activated or migrating.
* The idea is that first the Allocator updates its own state, then
* it reports this state to the Extender, which then updates its own state.
*
* There is 3 different combinations the Allocator may report:
*
* (gain + loss) == 0, the Allocator will NEVER report this state
* gain > loss, gain is reported and incremented but allocated not.
* loss > gain, loss is reported, allocated and incremented.
* loss == gain == type(uint128).max , migration case, zero out gain, loss, allocated
*
* NOTE: please take care to properly calculate loss by, say, only reporting loss above a % threshold
* of allocated. This is to serve as a low pass filter of sorts to ignore noise in price movements.
* NOTE: when migrating the next Allocator should report his state to the Extender, in say an `_activate` call.
*
* @param id the deposit id of the token to report state for
* @param gain the gain the Allocator has made in allocated token
* @param loss the loss the Allocator has sustained in allocated token
*/
function report(
uint256 id,
uint128 gain,
uint128 loss
) external override {
// reads
IAllocator allocator = allocators[id];
AllocatorData storage data = allocatorData[allocator][id];
AllocatorPerformance memory perf = data.performance;
AllocatorStatus status = allocator.status();
// checks
_onlyAllocator(allocator, msg.sender, id);
if (status == AllocatorStatus.OFFLINE) revert TreasuryExtender_AllocatorOffline();
// EFFECTS
if (gain >= loss) {
// MIGRATION
// according to above gain must equal loss because
// gain can't be larger than max uint128 value
if (loss == type(uint128).max) {
AllocatorData storage newAllocatorData = allocatorData[allocators[allocators.length - 1]][id];
newAllocatorData.holdings.allocated = data.holdings.allocated;
newAllocatorData.performance.gain = data.performance.gain;
data.holdings.allocated = 0;
perf.gain = 0;
perf.loss = 0;
emit AllocatorReportedMigration(id);
// GAIN
} else {
perf.gain += gain;
emit AllocatorReportedGain(id, gain);
}
// LOSS
} else {
data.holdings.allocated -= loss;
perf.loss += loss;
emit AllocatorReportedLoss(id, loss);
}
data.performance = perf;
}
/**
* @notice
* Requests funds from the Olympus Treasury to fund an Allocator.
* @dev
* Can only be called while the Allocator is activated.
* Can only be called by the Guardian.
*
* This function is going to allocate an `amount` of deposit id tokens to the Allocator and
* properly record this in storage. This done so that at any point, we know exactly
* how much was initially allocated and also how much value is allocated in total.
*
* The related functions are `getAllocatorAllocated` and `getTotalValueAllocated`.
*
* To note is also the `_allocatorBelowLimit` check.
* @param id the deposit id of the token to fund allocator with
* @param amount the amount of token to withdraw, the token is known in the Allocator
*/
function requestFundsFromTreasury(uint256 id, uint256 amount) external override onlyGuardian {
// reads
IAllocator allocator = allocators[id];
AllocatorData memory data = allocatorData[allocator][id];
address token = address(allocator.tokens()[allocator.tokenIds(id)]);
uint256 value = treasury.tokenValue(token, amount);
// checks
_allocatorActivated(allocator.status());
_allocatorBelowLimit(data, amount);
// interaction (withdrawing)
treasury.manage(token, amount);
// effects
allocatorData[allocator][id].holdings.allocated += amount;
// interaction (depositing)
IERC20(token).safeTransfer(address(allocator), amount);
// events
emit AllocatorFunded(id, amount, value);
}
/**
* @notice
* Returns funds from an Allocator to the Treasury.
* @dev
* External hook: Logic is handled in the internal function.
* Can only be called by the Guardian.
*
* This function is going to withdraw `amount` of allocated token from an Allocator
* back to the Treasury. Prior to calling this function, `deallocate` should be called,
* in order to prepare the funds for withdrawal.
*
* The maximum amount which can be withdrawn is `gain` + `allocated`.
* `allocated` is decremented first after which `gain` is decremented in the case
* that `allocated` is not sufficient.
* @param id the deposit id of the token to fund allocator with
* @param amount the amount of token to withdraw, the token is known in the Allocator
*/
function returnFundsToTreasury(uint256 id, uint256 amount) external override onlyGuardian {
// reads
IAllocator allocator = allocators[id];
uint256 allocated = allocatorData[allocator][id].holdings.allocated;
uint128 gain = allocatorData[allocator][id].performance.gain;
address token = address(allocator.tokens()[allocator.tokenIds(id)]);
if (amount > allocated) {
amount -= allocated;
if (amount > gain) {
amount = allocated + gain;
gain = 0;
} else {
// yes, amount should never > gain, we have safemath
gain -= uint128(amount);
amount += allocated;
}
allocated = 0;
} else {
allocated -= amount;
}
uint256 value = treasury.tokenValue(token, amount);
// checks
_allowTreasuryWithdrawal(IERC20(token));
// interaction (withdrawing)
IERC20(token).safeTransferFrom(address(allocator), address(this), amount);
// effects
allocatorData[allocator][id].holdings.allocated = allocated;
if (allocated == 0) allocatorData[allocator][id].performance.gain = gain;
// interaction (depositing)
assert(treasury.deposit(amount, token, value) == 0);
// events
emit AllocatorWithdrawal(id, amount, value);
}
/**
* @notice
* Returns rewards from an Allocator to the Treasury.
* Also see `_returnRewardsToTreasury`.
* @dev
* External hook: Logic is handled in the internal function.
* Can only be called by the Guardian.
* @param id the deposit id of the token to fund allocator with
* @param token the address of the reward token to withdraw
* @param amount the amount of the reward token to withdraw
*/
function returnRewardsToTreasury(
uint256 id,
address token,
uint256 amount
) external {
_returnRewardsToTreasury(allocators[id], IERC20(token), amount);
}
/**
* @notice
* Returns rewards from an Allocator to the Treasury.
* Also see `_returnRewardsToTreasury`.
* @dev
* External hook: Logic is handled in the internal function.
* Can only be called by the Guardian.
* @param allocatorAddress the address of the Allocator to returns rewards from
* @param token the address of the reward token to withdraw
* @param amount the amount of the reward token to withdraw
*/
function returnRewardsToTreasury(
address allocatorAddress,
address token,
uint256 amount
) external {
_returnRewardsToTreasury(IAllocator(allocatorAddress), IERC20(token), amount);
}
/**
* @notice
* Get an Allocators address by it's ID.
* @dev
* Our first Allocator is at index 1, NOTE: 0 is a placeholder.
* @param id the id of the allocator, NOTE: valid interval: 1 =< id < allocators.length
* @return allocatorAddress the allocator's address
*/
function getAllocatorByID(uint256 id) external view override returns (address allocatorAddress) {
allocatorAddress = address(allocators[id]);
}
/**
* @notice
* Get the total number of Allocators ever registered.
* @dev
* Our first Allocator is at index 1, 0 is a placeholder.
* @return total number of allocators ever registered
*/
function getTotalAllocatorCount() external view returns (uint256) {
return allocators.length - 1;
}
/**
* @notice
* Get an Allocators limits.
* @dev
* For an explanation of AllocatorLimits, see `setAllocatorLimits`
* @return the Allocator's limits
*/
function getAllocatorLimits(uint256 id) external view override returns (AllocatorLimits memory) {
return allocatorData[allocators[id]][id].limits;
}
/**
* @notice
* Get an Allocators performance.
* @dev
* An Allocator's performance is the amount of `gain` and `loss` it has sustained in its
* lifetime. `gain` is the amount of allocated tokens (underlying) acquired, while
* `loss` is the amount lost. `gain` and `loss` are incremented separately.
* Thus, overall performance can be gauged as gain - loss
* @return the Allocator's performance
*/
function getAllocatorPerformance(uint256 id) external view override returns (AllocatorPerformance memory) {
return allocatorData[allocators[id]][id].performance;
}
/**
* @notice
* Get an Allocators amount allocated.
* @dev
* This is simply the amount of `token` which was allocated to the allocator.
* @return the Allocator's amount allocated
*/
function getAllocatorAllocated(uint256 id) external view override returns (uint256) {
return allocatorData[allocators[id]][id].holdings.allocated;
}
/**
* @notice
* Returns rewards from an Allocator to the Treasury.
* @dev
* External hook: Logic is handled in the internal function.
* Can only be called by the Guardian.
*
* The assumption is that the reward tokens being withdrawn are going to be
* either deposited into the contract OR harvested into allocated (underlying).
*
* For this reason we don't need anything other than `balanceOf`.
* @param allocator the Allocator to returns rewards from
* @param token the reward token to withdraw
* @param amount the amount of the reward token to withdraw
*/
function _returnRewardsToTreasury(
IAllocator allocator,
IERC20 token,
uint256 amount
) internal onlyGuardian {
// reads
uint256 balance = token.balanceOf(address(allocator));
amount = (balance < amount) ? balance : amount;
uint256 value = treasury.tokenValue(address(token), amount);
// checks
_allowTreasuryWithdrawal(token);
// interactions
token.safeTransferFrom(address(allocator), address(this), amount);
assert(treasury.deposit(amount, address(token), value) == 0);
// events
emit AllocatorRewardsWithdrawal(address(allocator), amount, value);
}
/**
* @notice
* Approve treasury for withdrawing if token has not been approved.
* @param token Token to approve.
*/
function _allowTreasuryWithdrawal(IERC20 token) internal {
if (token.allowance(address(this), address(treasury)) == 0) token.approve(address(treasury), type(uint256).max);
}
/**
* @notice
* Check if token is below limit for allocation and if not approve it.
* @param data allocator data to check limits and amount allocated
* @param amount amount of tokens to allocate
*/
function _allocatorBelowLimit(AllocatorData memory data, uint256 amount) internal pure {
uint256 newAllocated = data.holdings.allocated + amount;
if (newAllocated > data.limits.allocated)
revert TreasuryExtender_MaxAllocation(newAllocated, data.limits.allocated);
}
}
| * AllocatorLimits { allocated, loss } - This is the maximum amount
* an Allocator should have allocated at any point, and also the maximum
* loss an allocator should experience without automatically shutting down.
*
* AllocatorPerformance { gain, loss } - This is the current gain (total - allocated)
* and the loss the Allocator sustained over its time of operation.
*
* AllocatorHoldings { allocated } - This is the amount of tokens an Allocator
* has currently been allocated by the Extender.
*
* Important: The above is only tracked in the underlying token specified by the ID,
* (see BaseAllocator.sol) while rewards are retrievable by the standard ERC20 functions.
* The point is that we only exactly track that which exits the Treasury.
*/
contract TreasuryExtender is OlympusAccessControlledV2, ITreasuryExtender {
using SafeERC20 for IERC20;
// The Olympus Treasury.
ITreasury public immutable treasury;
// Enumerable Allocators according to deposit IDs.
/// @dev NOTE: Allocator enumeration starts from index 1.
IAllocator[] public allocators;
// Get an an Allocator's Data for for an Allocator and deposit ID
mapping(IAllocator => mapping(uint256 => AllocatorData)) public allocatorData;
constructor(address treasuryAddress, address authorityAddress)
OlympusAccessControlledV2(IOlympusAuthority(authorityAddress))
{
treasury = ITreasury(treasuryAddress);
// This nonexistent allocator at address(0) is pushed
// as a placeholder so enumeration may start from index 1.
allocators.push(IAllocator(address(0)));
}
//// CHECKS
function _allocatorActivated(AllocatorStatus status) internal pure {
if (AllocatorStatus.ACTIVATED != status) revert TreasuryExtender_AllocatorNotActivated();
}
function _allocatorOffline(AllocatorStatus status) internal pure {
if (AllocatorStatus.OFFLINE != status) revert TreasuryExtender_AllocatorNotOffline();
}
function _onlyAllocator(
IAllocator byStatedId,
address sender,
uint256 id
) internal pure {
if (IAllocator(sender) != byStatedId) revert TreasuryExtender_OnlyAllocator(id, sender);
}
//// FUNCTIONS
/**
* @notice
* Registers an Allocator. Adds a deposit id and prepares storage slots for writing.
* Does not activate the Allocator.
* @dev
* Calls `addId` from `IAllocator` with the index of the deposit in `allocators`
* @param newAllocator the Allocator to be registered
*/
function registerDeposit(address newAllocator) external override onlyGuardian {
// reads
IAllocator allocator = IAllocator(newAllocator);
// effects
allocators.push(allocator);
uint256 id = allocators.length - 1;
// interactions
allocator.addId(id);
// events
emit NewDepositRegistered(newAllocator, address(allocator.tokens()[allocator.tokenIds(id)]), id);
}
/**
* @notice
* Sets an Allocators AllocatorLimits.
* AllocatorLimits is part of AllocatorData, variable meanings follow:
* allocated - The maximum amount a Guardian may allocate this Allocator from Treasury.
* loss - The maximum loss amount this Allocator can take.
* @dev
* Can only be called while the Allocator is offline.
* @param id the deposit id to set AllocatorLimits for
* @param limits the AllocatorLimits to set
*/
function setAllocatorLimits(uint256 id, AllocatorLimits calldata limits) external override onlyGuardian {
IAllocator allocator = allocators[id];
// checks
_allocatorOffline(allocator.status());
// effects
allocatorData[allocator][id].limits = limits;
// events
emit AllocatorLimitsChanged(id, limits.allocated, limits.loss);
}
/**
* @notice
* Reports an Allocators status to the Extender.
* Updates Extender state accordingly.
* @dev
* Can only be called while the Allocator is activated or migrating.
* The idea is that first the Allocator updates its own state, then
* it reports this state to the Extender, which then updates its own state.
*
* There is 3 different combinations the Allocator may report:
*
* (gain + loss) == 0, the Allocator will NEVER report this state
* gain > loss, gain is reported and incremented but allocated not.
* loss > gain, loss is reported, allocated and incremented.
* loss == gain == type(uint128).max , migration case, zero out gain, loss, allocated
*
* NOTE: please take care to properly calculate loss by, say, only reporting loss above a % threshold
* of allocated. This is to serve as a low pass filter of sorts to ignore noise in price movements.
* NOTE: when migrating the next Allocator should report his state to the Extender, in say an `_activate` call.
*
* @param id the deposit id of the token to report state for
* @param gain the gain the Allocator has made in allocated token
* @param loss the loss the Allocator has sustained in allocated token
*/
function report(
uint256 id,
uint128 gain,
uint128 loss
) external override {
// reads
IAllocator allocator = allocators[id];
AllocatorData storage data = allocatorData[allocator][id];
AllocatorPerformance memory perf = data.performance;
AllocatorStatus status = allocator.status();
// checks
_onlyAllocator(allocator, msg.sender, id);
if (status == AllocatorStatus.OFFLINE) revert TreasuryExtender_AllocatorOffline();
// EFFECTS
if (gain >= loss) {
// MIGRATION
// according to above gain must equal loss because
// gain can't be larger than max uint128 value
if (loss == type(uint128).max) {
AllocatorData storage newAllocatorData = allocatorData[allocators[allocators.length - 1]][id];
newAllocatorData.holdings.allocated = data.holdings.allocated;
newAllocatorData.performance.gain = data.performance.gain;
data.holdings.allocated = 0;
perf.gain = 0;
perf.loss = 0;
emit AllocatorReportedMigration(id);
// GAIN
} else {
perf.gain += gain;
emit AllocatorReportedGain(id, gain);
}
// LOSS
} else {
data.holdings.allocated -= loss;
perf.loss += loss;
emit AllocatorReportedLoss(id, loss);
}
data.performance = perf;
}
/**
* @notice
* Requests funds from the Olympus Treasury to fund an Allocator.
* @dev
* Can only be called while the Allocator is activated.
* Can only be called by the Guardian.
*
* This function is going to allocate an `amount` of deposit id tokens to the Allocator and
* properly record this in storage. This done so that at any point, we know exactly
* how much was initially allocated and also how much value is allocated in total.
*
* The related functions are `getAllocatorAllocated` and `getTotalValueAllocated`.
*
* To note is also the `_allocatorBelowLimit` check.
* @param id the deposit id of the token to fund allocator with
* @param amount the amount of token to withdraw, the token is known in the Allocator
*/
function requestFundsFromTreasury(uint256 id, uint256 amount) external override onlyGuardian {
// reads
IAllocator allocator = allocators[id];
AllocatorData memory data = allocatorData[allocator][id];
address token = address(allocator.tokens()[allocator.tokenIds(id)]);
uint256 value = treasury.tokenValue(token, amount);
// checks
_allocatorActivated(allocator.status());
_allocatorBelowLimit(data, amount);
// interaction (withdrawing)
treasury.manage(token, amount);
// effects
allocatorData[allocator][id].holdings.allocated += amount;
// interaction (depositing)
IERC20(token).safeTransfer(address(allocator), amount);
// events
emit AllocatorFunded(id, amount, value);
}
/**
* @notice
* Returns funds from an Allocator to the Treasury.
* @dev
* External hook: Logic is handled in the internal function.
* Can only be called by the Guardian.
*
* This function is going to withdraw `amount` of allocated token from an Allocator
* back to the Treasury. Prior to calling this function, `deallocate` should be called,
* in order to prepare the funds for withdrawal.
*
* The maximum amount which can be withdrawn is `gain` + `allocated`.
* `allocated` is decremented first after which `gain` is decremented in the case
* that `allocated` is not sufficient.
* @param id the deposit id of the token to fund allocator with
* @param amount the amount of token to withdraw, the token is known in the Allocator
*/
function returnFundsToTreasury(uint256 id, uint256 amount) external override onlyGuardian {
// reads
IAllocator allocator = allocators[id];
uint256 allocated = allocatorData[allocator][id].holdings.allocated;
uint128 gain = allocatorData[allocator][id].performance.gain;
address token = address(allocator.tokens()[allocator.tokenIds(id)]);
if (amount > allocated) {
amount -= allocated;
if (amount > gain) {
amount = allocated + gain;
gain = 0;
} else {
// yes, amount should never > gain, we have safemath
gain -= uint128(amount);
amount += allocated;
}
allocated = 0;
} else {
allocated -= amount;
}
uint256 value = treasury.tokenValue(token, amount);
// checks
_allowTreasuryWithdrawal(IERC20(token));
// interaction (withdrawing)
IERC20(token).safeTransferFrom(address(allocator), address(this), amount);
// effects
allocatorData[allocator][id].holdings.allocated = allocated;
if (allocated == 0) allocatorData[allocator][id].performance.gain = gain;
// interaction (depositing)
assert(treasury.deposit(amount, token, value) == 0);
// events
emit AllocatorWithdrawal(id, amount, value);
}
/**
* @notice
* Returns rewards from an Allocator to the Treasury.
* Also see `_returnRewardsToTreasury`.
* @dev
* External hook: Logic is handled in the internal function.
* Can only be called by the Guardian.
* @param id the deposit id of the token to fund allocator with
* @param token the address of the reward token to withdraw
* @param amount the amount of the reward token to withdraw
*/
function returnRewardsToTreasury(
uint256 id,
address token,
uint256 amount
) external {
_returnRewardsToTreasury(allocators[id], IERC20(token), amount);
}
/**
* @notice
* Returns rewards from an Allocator to the Treasury.
* Also see `_returnRewardsToTreasury`.
* @dev
* External hook: Logic is handled in the internal function.
* Can only be called by the Guardian.
* @param allocatorAddress the address of the Allocator to returns rewards from
* @param token the address of the reward token to withdraw
* @param amount the amount of the reward token to withdraw
*/
function returnRewardsToTreasury(
address allocatorAddress,
address token,
uint256 amount
) external {
_returnRewardsToTreasury(IAllocator(allocatorAddress), IERC20(token), amount);
}
/**
* @notice
* Get an Allocators address by it's ID.
* @dev
* Our first Allocator is at index 1, NOTE: 0 is a placeholder.
* @param id the id of the allocator, NOTE: valid interval: 1 =< id < allocators.length
* @return allocatorAddress the allocator's address
*/
function getAllocatorByID(uint256 id) external view override returns (address allocatorAddress) {
allocatorAddress = address(allocators[id]);
}
/**
* @notice
* Get the total number of Allocators ever registered.
* @dev
* Our first Allocator is at index 1, 0 is a placeholder.
* @return total number of allocators ever registered
*/
function getTotalAllocatorCount() external view returns (uint256) {
return allocators.length - 1;
}
/**
* @notice
* Get an Allocators limits.
* @dev
* For an explanation of AllocatorLimits, see `setAllocatorLimits`
* @return the Allocator's limits
*/
function getAllocatorLimits(uint256 id) external view override returns (AllocatorLimits memory) {
return allocatorData[allocators[id]][id].limits;
}
/**
* @notice
* Get an Allocators performance.
* @dev
* An Allocator's performance is the amount of `gain` and `loss` it has sustained in its
* lifetime. `gain` is the amount of allocated tokens (underlying) acquired, while
* `loss` is the amount lost. `gain` and `loss` are incremented separately.
* Thus, overall performance can be gauged as gain - loss
* @return the Allocator's performance
*/
function getAllocatorPerformance(uint256 id) external view override returns (AllocatorPerformance memory) {
return allocatorData[allocators[id]][id].performance;
}
/**
* @notice
* Get an Allocators amount allocated.
* @dev
* This is simply the amount of `token` which was allocated to the allocator.
* @return the Allocator's amount allocated
*/
function getAllocatorAllocated(uint256 id) external view override returns (uint256) {
return allocatorData[allocators[id]][id].holdings.allocated;
}
/**
* @notice
* Returns rewards from an Allocator to the Treasury.
* @dev
* External hook: Logic is handled in the internal function.
* Can only be called by the Guardian.
*
* The assumption is that the reward tokens being withdrawn are going to be
* either deposited into the contract OR harvested into allocated (underlying).
*
* For this reason we don't need anything other than `balanceOf`.
* @param allocator the Allocator to returns rewards from
* @param token the reward token to withdraw
* @param amount the amount of the reward token to withdraw
*/
function _returnRewardsToTreasury(
IAllocator allocator,
IERC20 token,
uint256 amount
) internal onlyGuardian {
// reads
uint256 balance = token.balanceOf(address(allocator));
amount = (balance < amount) ? balance : amount;
uint256 value = treasury.tokenValue(address(token), amount);
// checks
_allowTreasuryWithdrawal(token);
// interactions
token.safeTransferFrom(address(allocator), address(this), amount);
assert(treasury.deposit(amount, address(token), value) == 0);
// events
emit AllocatorRewardsWithdrawal(address(allocator), amount, value);
}
/**
* @notice
* Approve treasury for withdrawing if token has not been approved.
* @param token Token to approve.
*/
function _allowTreasuryWithdrawal(IERC20 token) internal {
if (token.allowance(address(this), address(treasury)) == 0) token.approve(address(treasury), type(uint256).max);
}
/**
* @notice
* Check if token is below limit for allocation and if not approve it.
* @param data allocator data to check limits and amount allocated
* @param amount amount of tokens to allocate
*/
function _allocatorBelowLimit(AllocatorData memory data, uint256 amount) internal pure {
uint256 newAllocated = data.holdings.allocated + amount;
if (newAllocated > data.limits.allocated)
revert TreasuryExtender_MaxAllocation(newAllocated, data.limits.allocated);
}
}
| 77,315 |
71 | // IEurPriceFeed Protofire Interface to be implemented by any EurPriceFeed logic contract used in the protocol./ | interface IEurPriceFeed {
/**
* @dev Gets the price a `_asset` in EUR.
*
* @param _asset address of asset to get the price.
*/
function getPrice(address _asset) external returns (uint256);
/**
* @dev Gets how many EUR represents the `_amount` of `_asset`.
*
* @param _asset address of asset to get the price.
* @param _amount amount of `_asset`.
*/
function calculateAmount(address _asset, uint256 _amount) external view returns (uint256);
/**
* @dev Sets feed addresses for a given group of assets.
*
* @param _assets Array of assets addresses.
* @param _feeds Array of asset/ETH price feeds.
*/
function setAssetsFeeds(address[] memory _assets, address[] memory _feeds) external;
/**
* @dev Sets feed addresse for a given asset.
*
* @param _asset Assets address.
* @param _feed Asset/ETH price feed.
*/
function setAssetFeed(address _asset, address _feed) external;
}
| interface IEurPriceFeed {
/**
* @dev Gets the price a `_asset` in EUR.
*
* @param _asset address of asset to get the price.
*/
function getPrice(address _asset) external returns (uint256);
/**
* @dev Gets how many EUR represents the `_amount` of `_asset`.
*
* @param _asset address of asset to get the price.
* @param _amount amount of `_asset`.
*/
function calculateAmount(address _asset, uint256 _amount) external view returns (uint256);
/**
* @dev Sets feed addresses for a given group of assets.
*
* @param _assets Array of assets addresses.
* @param _feeds Array of asset/ETH price feeds.
*/
function setAssetsFeeds(address[] memory _assets, address[] memory _feeds) external;
/**
* @dev Sets feed addresse for a given asset.
*
* @param _asset Assets address.
* @param _feed Asset/ETH price feed.
*/
function setAssetFeed(address _asset, address _feed) external;
}
| 29,723 |
8 | // 获得放贷人列表 | function getLendersList(uint index) public view returns(address, uint, string memory){
return (lenders[index].addr,lenders[index].balance,lenders[index].name);
}
| function getLendersList(uint index) public view returns(address, uint, string memory){
return (lenders[index].addr,lenders[index].balance,lenders[index].name);
}
| 23,897 |
12 | // Adds a user to whitelist_member address to add to whitelist/ | function addToWhiteList(address _member) public onlyOperator returns (bool) {
whiteListed[_member] = true;
emit WhiteListed(_member);
return true;
}
| function addToWhiteList(address _member) public onlyOperator returns (bool) {
whiteListed[_member] = true;
emit WhiteListed(_member);
return true;
}
| 31,692 |
81 | // Creates a vesting contract that vests its balance of any ERC20 token to thebeneficiary, gradually in a linear fashion until start + duration. By then allof the balance will have vested. beneficiary address of the beneficiary to whom vested tokens are transferred cliffDuration duration in seconds of the cliff in which tokens will begin to vest start the time (as Unix time) at which point vesting starts duration duration in seconds of the period in which the tokens will vest revocable whether the vesting is revocable or not / | constructor (address beneficiary, uint256 start, uint256 cliffDuration, uint256 duration, bool revocable) public {
require(beneficiary != address(0), "TokenVesting: beneficiary is the zero address");
// solhint-disable-next-line max-line-length
require(cliffDuration <= duration, "TokenVesting: cliff is longer than duration");
require(duration > 0, "TokenVesting: duration is 0");
// solhint-disable-next-line max-line-length
require(start.add(duration) > block.timestamp, "TokenVesting: final time is before current time");
_beneficiary = beneficiary;
_revocable = revocable;
_duration = duration;
_cliff = start.add(cliffDuration);
_start = start;
}
| constructor (address beneficiary, uint256 start, uint256 cliffDuration, uint256 duration, bool revocable) public {
require(beneficiary != address(0), "TokenVesting: beneficiary is the zero address");
// solhint-disable-next-line max-line-length
require(cliffDuration <= duration, "TokenVesting: cliff is longer than duration");
require(duration > 0, "TokenVesting: duration is 0");
// solhint-disable-next-line max-line-length
require(start.add(duration) > block.timestamp, "TokenVesting: final time is before current time");
_beneficiary = beneficiary;
_revocable = revocable;
_duration = duration;
_cliff = start.add(cliffDuration);
_start = start;
}
| 21,589 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.