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 |
|---|---|---|---|---|
2 | // This is a pseudo member, representing all the disconnected members | MemberData internal _disconnectedMembers;
| MemberData internal _disconnectedMembers;
| 23,652 |
15 | // Only allow transactions originating from a designated member address. | require(addressIsMember_[msg.sender]);
_;
| require(addressIsMember_[msg.sender]);
_;
| 83,415 |
620 | // Safe axial transfer function, just in case if rounding error causes pool to not have enough AXIALs. | function safeAxialTransfer(address _to, uint256 _amount) internal {
uint256 axialBal = axial.balanceOf(address(this));
if (_amount > axialBal) {
axial.transfer(_to, axialBal);
} else {
axial.transfer(_to, _amount);
}
}
| function safeAxialTransfer(address _to, uint256 _amount) internal {
uint256 axialBal = axial.balanceOf(address(this));
if (_amount > axialBal) {
axial.transfer(_to, axialBal);
} else {
axial.transfer(_to, _amount);
}
}
| 10,885 |
148 | // If the token is wBTC then we just approve spend and deposit directly into the wbtc vault. | if (args._token == address(wBTC)) {
token.safeApprove(args._vault, token.balanceOf(address(this)));
} else {
| if (args._token == address(wBTC)) {
token.safeApprove(args._vault, token.balanceOf(address(this)));
} else {
| 23,037 |
0 | // Aave's StaticATokens allow wrapping either an aToken or the underlying asset. We can query which token to pull and approve from the wrapper contract. | IERC20 dynamicToken = fromUnderlying ? staticToken.ASSET() : staticToken.ATOKEN();
| IERC20 dynamicToken = fromUnderlying ? staticToken.ASSET() : staticToken.ATOKEN();
| 27,872 |
83 | // ---------------------------------------------------------------------- | function transfer(address _to, uint _amount) public returns (bool success) {
// Cannot transfer before crowdsale ends
// require(finalised);
// require(flg002transfer);
// Cannot transfer if Client verification is required
//require(!clientRequired[msg.sender]);
// Standard transfer
return super.transfer(_to, _amount);
}
| function transfer(address _to, uint _amount) public returns (bool success) {
// Cannot transfer before crowdsale ends
// require(finalised);
// require(flg002transfer);
// Cannot transfer if Client verification is required
//require(!clientRequired[msg.sender]);
// Standard transfer
return super.transfer(_to, _amount);
}
| 21,225 |
5 | // Return the appropriate contract interface for token. / | function getTokenContract(uint16 tokenId) private view returns (IFoxGameNFT) {
return tokenId <= 10000 ? foxNFTGen0 : foxNFTGen1;
}
| function getTokenContract(uint16 tokenId) private view returns (IFoxGameNFT) {
return tokenId <= 10000 ? foxNFTGen0 : foxNFTGen1;
}
| 82,293 |
0 | // ERC20 Token Standard, optional extension: Burnable./See https:eips.ethereum.org/EIPS/eip-20/Note: the ERC-165 identifier for this interface is 0x3b5a0bf8. | interface IERC20Burnable {
/// @notice Burns an amount of tokens from the sender, decreasing the total supply.
/// @dev Reverts if the sender does not have at least `value` of balance.
/// @dev Emits an {IERC20-Transfer} event with `to` set to the zero address.
/// @param value The amount of tokens to burn.
/// @return result Whether the operation succeeded.
function burn(uint256 value) external returns (bool result);
/// @notice Burns an amount of tokens from a specified address, decreasing the total supply.
/// @dev Reverts if `from` does not have at least `value` of balance.
/// @dev Reverts if the sender is not `from` and does not have at least `value` of allowance by `from`.
/// @dev Emits an {IERC20-Transfer} event with `to` set to the zero address.
/// @dev Optionally emits an {Approval} event if the sender is not `from` (non-standard).
/// @param from The account to burn the tokens from.
/// @param value The amount of tokens to burn.
/// @return result Whether the operation succeeded.
function burnFrom(address from, uint256 value) external returns (bool result);
/// @notice Burns multiple amounts of tokens from multiple owners, decreasing the total supply.
/// @dev Reverts if `owners` and `values` have different lengths.
/// @dev Reverts if an `owner` does not have at least the corresponding `value` of balance.
/// @dev Reverts if the sender is not an `owner` and does not have at least the corresponding `value` of allowance by this `owner`.
/// @dev Emits an {IERC20-Transfer} event for each transfer with `to` set to the zero address.
/// @dev Optionally emits an {Approval} event for each transfer if the sender is not this `owner` (non-standard).
/// @param owners The list of accounts to burn the tokens from.
/// @param values The list of amounts of tokens to burn.
/// @return result Whether the operation succeeded.
function batchBurnFrom(address[] calldata owners, uint256[] calldata values) external returns (bool result);
}
| interface IERC20Burnable {
/// @notice Burns an amount of tokens from the sender, decreasing the total supply.
/// @dev Reverts if the sender does not have at least `value` of balance.
/// @dev Emits an {IERC20-Transfer} event with `to` set to the zero address.
/// @param value The amount of tokens to burn.
/// @return result Whether the operation succeeded.
function burn(uint256 value) external returns (bool result);
/// @notice Burns an amount of tokens from a specified address, decreasing the total supply.
/// @dev Reverts if `from` does not have at least `value` of balance.
/// @dev Reverts if the sender is not `from` and does not have at least `value` of allowance by `from`.
/// @dev Emits an {IERC20-Transfer} event with `to` set to the zero address.
/// @dev Optionally emits an {Approval} event if the sender is not `from` (non-standard).
/// @param from The account to burn the tokens from.
/// @param value The amount of tokens to burn.
/// @return result Whether the operation succeeded.
function burnFrom(address from, uint256 value) external returns (bool result);
/// @notice Burns multiple amounts of tokens from multiple owners, decreasing the total supply.
/// @dev Reverts if `owners` and `values` have different lengths.
/// @dev Reverts if an `owner` does not have at least the corresponding `value` of balance.
/// @dev Reverts if the sender is not an `owner` and does not have at least the corresponding `value` of allowance by this `owner`.
/// @dev Emits an {IERC20-Transfer} event for each transfer with `to` set to the zero address.
/// @dev Optionally emits an {Approval} event for each transfer if the sender is not this `owner` (non-standard).
/// @param owners The list of accounts to burn the tokens from.
/// @param values The list of amounts of tokens to burn.
/// @return result Whether the operation succeeded.
function batchBurnFrom(address[] calldata owners, uint256[] calldata values) external returns (bool result);
}
| 29,492 |
445 | // Compute `e^(alphaln(feeRatio/stakeRatio))` if feeRatio <= stakeRatio or `e^(alpaln(stakeRatio/feeRatio))` if feeRatio > stakeRatio | int256 n = feeRatio <= stakeRatio
? LibFixedMath.div(feeRatio, stakeRatio)
: LibFixedMath.div(stakeRatio, feeRatio);
n = LibFixedMath.exp(
LibFixedMath.mulDiv(
LibFixedMath.ln(n),
int256(alphaNumerator),
int256(alphaDenominator)
)
);
| int256 n = feeRatio <= stakeRatio
? LibFixedMath.div(feeRatio, stakeRatio)
: LibFixedMath.div(stakeRatio, feeRatio);
n = LibFixedMath.exp(
LibFixedMath.mulDiv(
LibFixedMath.ln(n),
int256(alphaNumerator),
int256(alphaDenominator)
)
);
| 23,059 |
9 | // send leftovers to investor | uint256 _token0Leftover = _liquidityAmounts.amount0Desired -
_amount0Invested;
if (_token0Leftover > 0) {
_farmBot.stakingToken0().safeTransfer(msg.sender, _token0Leftover);
}
| uint256 _token0Leftover = _liquidityAmounts.amount0Desired -
_amount0Invested;
if (_token0Leftover > 0) {
_farmBot.stakingToken0().safeTransfer(msg.sender, _token0Leftover);
}
| 17,403 |
19 | // Burn half the tip | _tip = _tip / 2;
IController(TELLOR_ADDRESS).burn(_tip);
| _tip = _tip / 2;
IController(TELLOR_ADDRESS).burn(_tip);
| 58,654 |
5 | // Calls internal function _removeMinter with message senderas the parameter / | function renounceMinter() public {
_removeMinter(msg.sender);
}
| function renounceMinter() public {
_removeMinter(msg.sender);
}
| 23,818 |
15 | // The authorized address for each NFT | mapping (uint256 => address) internal tokenApprovals;
| mapping (uint256 => address) internal tokenApprovals;
| 14,648 |
5 | // Mapping for operator approvals | mapping(address => mapping(address => bool)) internal _operatorApprovals;
| mapping(address => mapping(address => bool)) internal _operatorApprovals;
| 2,073 |
176 | // 1 = Monday, 7 = Sunday | function getDayOfWeek(uint256 timestamp)
internal
pure
returns (uint256 dayOfWeek)
| function getDayOfWeek(uint256 timestamp)
internal
pure
returns (uint256 dayOfWeek)
| 3,903 |
10 | // See '_setTickers()' in {OracleHouse}. restricted to admin only. / | function setTickers(
string memory _tickerUsdFiat,
string memory _tickerReserveAsset
) external override onlyRole(DEFAULT_ADMIN_ROLE) {
_setTickers(_tickerUsdFiat, _tickerReserveAsset);
}
| function setTickers(
string memory _tickerUsdFiat,
string memory _tickerReserveAsset
) external override onlyRole(DEFAULT_ADMIN_ROLE) {
_setTickers(_tickerUsdFiat, _tickerReserveAsset);
}
| 8,554 |
229 | // Sanity check to ensure we don't overflow arithmetic | require(avePrice == uint256(uint128(avePrice)));
uint256 nextPrice = avePrice + (avePrice / 2);
| require(avePrice == uint256(uint128(avePrice)));
uint256 nextPrice = avePrice + (avePrice / 2);
| 24,088 |
40 | // - Emits a {BenefitStarted} event if `beneficiary_` is not null - This contract must be allowed to transfer NuCyber tokens on behalf of the caller/ | function stake(uint256 tokenId_, address beneficiary_, Rarity rarity_, Proof calldata proof_)
public
isState(ACTIVE) {
if (fxChildTunnel == address(0)) {
revert NCS_REWARDS_NOT_SET();
}
| function stake(uint256 tokenId_, address beneficiary_, Rarity rarity_, Proof calldata proof_)
public
isState(ACTIVE) {
if (fxChildTunnel == address(0)) {
revert NCS_REWARDS_NOT_SET();
}
| 27,469 |
18 | // deposit cvxfpis | function stake(uint256 _amount) public nonReentrant{
require(_amount > 0, 'RewardPool : Cannot stake 0');
//mint will call _updateReward
_mint(msg.sender, _amount);
//pull cvxfpis
IERC20(cvxfpis).safeTransferFrom(msg.sender, address(this), _amount);
emit Staked(msg.sender, _amount);
}
| function stake(uint256 _amount) public nonReentrant{
require(_amount > 0, 'RewardPool : Cannot stake 0');
//mint will call _updateReward
_mint(msg.sender, _amount);
//pull cvxfpis
IERC20(cvxfpis).safeTransferFrom(msg.sender, address(this), _amount);
emit Staked(msg.sender, _amount);
}
| 23,593 |
307 | // Get the remaining balance for marketing / | function geMarketingBalance() public view returns (uint256) {
return getTotalEarnedMarketingBalance() - communityBalanceSpent[2];
}
| function geMarketingBalance() public view returns (uint256) {
return getTotalEarnedMarketingBalance() - communityBalanceSpent[2];
}
| 46,750 |
36 | // check if game approved; | require(CreditGAMEInterface(creditGameAddress).isGameApproved(address(this)) == true);
uint tokensToTake = processTransaction(_from, _value);
IERC20Token(tokenAddress).transferFrom(_from, address(this), tokensToTake);
| require(CreditGAMEInterface(creditGameAddress).isGameApproved(address(this)) == true);
uint tokensToTake = processTransaction(_from, _value);
IERC20Token(tokenAddress).transferFrom(_from, address(this), tokensToTake);
| 56,850 |
92 | // converts bytes32 to string / | function bytes32ToString(bytes32 _bytes32) internal pure returns(string memory) {
uint256 i = 0;
while (i < 32 && _bytes32[i] != 0) {
i++;
}
| function bytes32ToString(bytes32 _bytes32) internal pure returns(string memory) {
uint256 i = 0;
while (i < 32 && _bytes32[i] != 0) {
i++;
}
| 31,589 |
13 | // solhint-disable-next-line no-simple-event-func-name | event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
| event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
| 23,547 |
742 | // Changes the available owedToken amount. This changes both the variable to track the totalamount as well as the variable to track a particular bucket. bucketThe bucket numberamountThe amount to change the available amount byincreaseTrue if positive change, false if negative change / | function updateAvailable(
uint256 bucket,
uint256 amount,
bool increase
)
private
| function updateAvailable(
uint256 bucket,
uint256 amount,
bool increase
)
private
| 72,505 |
10 | // Display the time | function Display_Time() public view returns (uint256) {
return now;
}
| function Display_Time() public view returns (uint256) {
return now;
}
| 12,152 |
18 | // Convert string to address | function _stringToAddress(string memory _a) internal pure returns (address){
bytes memory tmp = bytes(_a);
uint iaddress = 0;
uint b1;
uint b2;
for (uint i=2; i<2+2*20; i+=2){
iaddress *= 256;
b1 = uint(uint8(tmp[i]));
b2 = uint(uint8(tmp[i+1]));
if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87;
else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48;
if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87;
else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48;
iaddress += (b1*16+b2);
}
return address(iaddress);
}
| function _stringToAddress(string memory _a) internal pure returns (address){
bytes memory tmp = bytes(_a);
uint iaddress = 0;
uint b1;
uint b2;
for (uint i=2; i<2+2*20; i+=2){
iaddress *= 256;
b1 = uint(uint8(tmp[i]));
b2 = uint(uint8(tmp[i+1]));
if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87;
else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48;
if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87;
else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48;
iaddress += (b1*16+b2);
}
return address(iaddress);
}
| 4,621 |
6 | // validate request off-chain, call event to be picked upby eventfilters. / | validateRequest(msg.sender, _amount_produced);
| validateRequest(msg.sender, _amount_produced);
| 45,672 |
6 | // make sure signature is valid and get the address of the signer | address signer = _verify(voucher);
| address signer = _verify(voucher);
| 4,811 |
3 | // Verifies if a given account address is allowed to withdraw tokens/_address address to verify/ return true if the account is allowed to withdraw, false otherwise | function allowedToWithdraw(address _address) internal pure returns (bool) {
// TODO: check using access control contract
return true;
}
| function allowedToWithdraw(address _address) internal pure returns (bool) {
// TODO: check using access control contract
return true;
}
| 52,529 |
4 | // Price of each key is 0.001 ETH | uint256 public keyPrice = 1000000000000000;
mapping (bytes32 => address) public pAddrxName; // (addr => pName) returns player address by name
mapping (address => DataStructs.Player) public plyr_; // (addr => data) player data
mapping (address => mapping (uint256 => DataStructs.PlayerRounds)) public plyrRnds_; // (addr => rID => data) player round data by player id & round ids
mapping(address => mapping(uint256 => uint256)) public playerEarned_; //How much amount a player has earned till now.(addr => rID => amount)
mapping(address => mapping(uint256 => uint256)) public playerExtraEarnings_;
mapping (uint256 => DataStructs.Round) public round_; // (rID => data) round data
| uint256 public keyPrice = 1000000000000000;
mapping (bytes32 => address) public pAddrxName; // (addr => pName) returns player address by name
mapping (address => DataStructs.Player) public plyr_; // (addr => data) player data
mapping (address => mapping (uint256 => DataStructs.PlayerRounds)) public plyrRnds_; // (addr => rID => data) player round data by player id & round ids
mapping(address => mapping(uint256 => uint256)) public playerEarned_; //How much amount a player has earned till now.(addr => rID => amount)
mapping(address => mapping(uint256 => uint256)) public playerExtraEarnings_;
mapping (uint256 => DataStructs.Round) public round_; // (rID => data) round data
| 11,335 |
5 | // solhint-disable func-name-mixedcase | function InvalidFromAddressError(
address from
)
internal
pure
returns (bytes memory)
| function InvalidFromAddressError(
address from
)
internal
pure
returns (bytes memory)
| 16,589 |
8 | // Get the balance of an account's Tokens _ownerThe address of the token holder _id ID of the TokenreturnThe _owner's balance of the Token type requested / | function balanceOf(address _owner, uint256 _id) external view returns (uint256);
| function balanceOf(address _owner, uint256 _id) external view returns (uint256);
| 2,632 |
10 | // order status for punk ID | uint16[] public orderedPunkIds;
mapping(uint16 => OrderDetails) public orderStatus;
| uint16[] public orderedPunkIds;
mapping(uint16 => OrderDetails) public orderStatus;
| 45,083 |
5 | // Set how long the pool will yield interest | poolDurationByBlock = _poolDurationByBlock;
| poolDurationByBlock = _poolDurationByBlock;
| 24,038 |
53 | // _maxTotalSupply The maximum liquidity token supply the contract allows | function setMaxTotalSupply(uint256 _maxTotalSupply) external onlyOwner {
maxTotalSupply = _maxTotalSupply;
emit MaxTotalSupplySet(_maxTotalSupply);
}
| function setMaxTotalSupply(uint256 _maxTotalSupply) external onlyOwner {
maxTotalSupply = _maxTotalSupply;
emit MaxTotalSupplySet(_maxTotalSupply);
}
| 58,810 |
174 | // Set starting block for the sale | function setStartingBlock(uint256 _startingBlock) external onlyOwner {
startingBlock = _startingBlock;
}
| function setStartingBlock(uint256 _startingBlock) external onlyOwner {
startingBlock = _startingBlock;
}
| 33,582 |
7 | // Deploy a new contract with the desired initialization code to thehome address corresponding to a given key. Two conditions must be met: thesubmitter must be designated as the controller of the home address (withthe initial controller set to the address corresponding to the first twentybytes of the key), and there must not be a contract currently deployed atthe home address. These conditions can be checked by calling`getHomeAddressInformation` and `isDeployable` with the same key. key bytes32 The unique value used to derive the home address. initializationCode bytes The contract creation code that will beused to deploy the contract to the home | function deploy(bytes32 key, bytes calldata initializationCode)
external
payable
returns (address homeAddress, bytes32 runtimeCodeHash);
| function deploy(bytes32 key, bytes calldata initializationCode)
external
payable
returns (address homeAddress, bytes32 runtimeCodeHash);
| 22,422 |
18 | // Update creator | creator[id] = _msgSender();
| creator[id] = _msgSender();
| 28,578 |
3 | // Withdraws tokens for the caller from the staking contract/token the token to withdraw/amount the amount to withdraw | function withdraw(address token, uint amount) external;
| function withdraw(address token, uint amount) external;
| 18,530 |
53 | // Moves `amount` tokens from the caller's account to `recipient`. Returns a boolean value indicating whether the operation succeeded. | * Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
}
| * Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
}
| 8,470 |
120 | // Send transfers to dead address | if (burnAmt > 0) {
_transferStandard(sender, deadWallet, burnAmt);
}
| if (burnAmt > 0) {
_transferStandard(sender, deadWallet, burnAmt);
}
| 35,685 |
12 | // Data about each collateral type | mapping (bytes32 => CollateralType) public collateralTypes;
SAFEEngineLike public safeEngine;
| mapping (bytes32 => CollateralType) public collateralTypes;
SAFEEngineLike public safeEngine;
| 54,092 |
15 | // Check that signer is an oracle | require(orcl[signer] == 1, "Median/invalid-oracle");
| require(orcl[signer] == 1, "Median/invalid-oracle");
| 43,368 |
84 | // 0x434f4e54524143545f4f424a4543545f4f574e45525348495000000000000000 | bytes32 public constant CONTRACT_OBJECT_OWNERSHIP =
"CONTRACT_OBJECT_OWNERSHIP";
| bytes32 public constant CONTRACT_OBJECT_OWNERSHIP =
"CONTRACT_OBJECT_OWNERSHIP";
| 63,726 |
293 | // contracts/Pool.sol/ pragma solidity 0.6.11; // import "lib/openzeppelin-contracts/contracts/token/ERC20/SafeERC20.sol"; // import "./interfaces/IBPool.sol"; // import "./interfaces/IDebtLocker.sol"; // import "./interfaces/IMapleGlobals.sol"; // import "./interfaces/ILiquidityLocker.sol"; // import "./interfaces/ILiquidityLockerFactory.sol"; // import "./interfaces/ILoan.sol"; // import "./interfaces/ILoanFactory.sol"; // import "./interfaces/IPoolFactory.sol"; // import "./interfaces/IStakeLocker.sol"; // import "./interfaces/IStakeLockerFactory.sol"; // import "./library/PoolLib.sol"; // import "./token/PoolFDT.sol"; //Pool maintains all accounting and functionality related to Pools. | contract Pool is PoolFDT {
using SafeMath for uint256;
using SafeERC20 for IERC20;
uint256 constant WAD = 10 ** 18;
uint8 public constant DL_FACTORY = 1; // Factory type of `DebtLockerFactory`.
IERC20 public immutable liquidityAsset; // The asset deposited by Lenders into the LiquidityLocker, for funding Loans.
address public immutable poolDelegate; // The Pool Delegate address, maintains full authority over the Pool.
address public immutable liquidityLocker; // The LiquidityLocker owned by this contract
address public immutable stakeAsset; // The address of the asset deposited by Stakers into the StakeLocker (BPTs), for liquidation during default events.
address public immutable stakeLocker; // The address of the StakeLocker, escrowing `stakeAsset`.
address public immutable superFactory; // The factory that deployed this Loan.
uint256 private immutable liquidityAssetDecimals; // The precision for the Liquidity Asset (i.e. `decimals()`).
uint256 public stakingFee; // The fee Stakers earn (in basis points).
uint256 public immutable delegateFee; // The fee the Pool Delegate earns (in basis points).
uint256 public principalOut; // The sum of all outstanding principal on Loans.
uint256 public liquidityCap; // The amount of liquidity tokens accepted by the Pool.
uint256 public lockupPeriod; // The period of time from an account's deposit date during which they cannot withdraw any funds.
bool public openToPublic; // Boolean opening Pool to public for LP deposits
enum State { Initialized, Finalized, Deactivated }
State public poolState;
mapping(address => uint256) public depositDate; // Used for withdraw penalty calculation.
mapping(address => mapping(address => address)) public debtLockers; // Address of the DebtLocker corresponding to `[Loan][DebtLockerFactory]`.
mapping(address => bool) public poolAdmins; // The Pool Admin addresses that have permission to do certain operations in case of disaster management.
mapping(address => bool) public allowedLiquidityProviders; // Mapping that contains the list of addresses that have early access to the pool.
mapping(address => uint256) public withdrawCooldown; // The timestamp of when individual LPs have notified of their intent to withdraw.
mapping(address => mapping(address => uint256)) public custodyAllowance; // The amount of PoolFDTs that are "locked" at a certain address.
mapping(address => uint256) public totalCustodyAllowance; // The total amount of PoolFDTs that are "locked" for a given account. Cannot be greater than an account's balance.
event LoanFunded(address indexed loan, address debtLocker, uint256 amountFunded);
event Claim(address indexed loan, uint256 interest, uint256 principal, uint256 fee, uint256 stakeLockerPortion, uint256 poolDelegatePortion);
event BalanceUpdated(address indexed liquidityProvider, address indexed token, uint256 balance);
event CustodyTransfer(address indexed custodian, address indexed from, address indexed to, uint256 amount);
event CustodyAllowanceChanged(address indexed liquidityProvider, address indexed custodian, uint256 oldAllowance, uint256 newAllowance);
event LPStatusChanged(address indexed liquidityProvider, bool status);
event LiquidityCapSet(uint256 newLiquidityCap);
event LockupPeriodSet(uint256 newLockupPeriod);
event StakingFeeSet(uint256 newStakingFee);
event PoolStateChanged(State state);
event Cooldown(address indexed liquidityProvider, uint256 cooldown);
event PoolOpenedToPublic(bool isOpen);
event PoolAdminSet(address indexed poolAdmin, bool allowed);
event DepositDateUpdated(address indexed liquidityProvider, uint256 depositDate);
event TotalCustodyAllowanceUpdated(address indexed liquidityProvider, uint256 newTotalAllowance);
event DefaultSuffered(
address indexed loan,
uint256 defaultSuffered,
uint256 bptsBurned,
uint256 bptsReturned,
uint256 liquidityAssetRecoveredFromBurn
);
/**
Universal accounting law:
fdtTotalSupply = liquidityLockerBal + principalOut - interestSum + poolLosses
fdtTotalSupply + interestSum - poolLosses = liquidityLockerBal + principalOut
*/
/**
@dev Constructor for a Pool.
@dev It emits a `PoolStateChanged` event.
@param _poolDelegate Address that has manager privileges of the Pool.
@param _liquidityAsset Asset used to fund the Pool, It gets escrowed in LiquidityLocker.
@param _stakeAsset Asset escrowed in StakeLocker.
@param _slFactory Factory used to instantiate the StakeLocker.
@param _llFactory Factory used to instantiate the LiquidityLocker.
@param _stakingFee Fee that Stakers earn on interest, in basis points.
@param _delegateFee Fee that the Pool Delegate earns on interest, in basis points.
@param _liquidityCap Max amount of Liquidity Asset accepted by the Pool.
@param name Name of Pool token.
@param symbol Symbol of Pool token.
*/
constructor(
address _poolDelegate,
address _liquidityAsset,
address _stakeAsset,
address _slFactory,
address _llFactory,
uint256 _stakingFee,
uint256 _delegateFee,
uint256 _liquidityCap,
string memory name,
string memory symbol
) PoolFDT(name, symbol) public {
// Conduct sanity checks on Pool parameters.
PoolLib.poolSanityChecks(_globals(msg.sender), _liquidityAsset, _stakeAsset, _stakingFee, _delegateFee);
// Assign variables relating to the Liquidity Asset.
liquidityAsset = IERC20(_liquidityAsset);
liquidityAssetDecimals = ERC20(_liquidityAsset).decimals();
// Assign state variables.
stakeAsset = _stakeAsset;
poolDelegate = _poolDelegate;
stakingFee = _stakingFee;
delegateFee = _delegateFee;
superFactory = msg.sender;
liquidityCap = _liquidityCap;
// Instantiate the LiquidityLocker and the StakeLocker.
stakeLocker = address(IStakeLockerFactory(_slFactory).newLocker(_stakeAsset, _liquidityAsset));
liquidityLocker = address(ILiquidityLockerFactory(_llFactory).newLocker(_liquidityAsset));
lockupPeriod = 180 days;
emit PoolStateChanged(State.Initialized);
}
/*******************************/
/*** Pool Delegate Functions ***/
/*******************************/
/**
@dev Finalizes the Pool, enabling deposits. Checks the amount the Pool Delegate deposited to the StakeLocker.
Only the Pool Delegate can call this function.
@dev It emits a `PoolStateChanged` event.
*/
function finalize() external {
_isValidDelegateAndProtocolNotPaused();
_isValidState(State.Initialized);
(,, bool stakeSufficient,,) = getInitialStakeRequirements();
require(stakeSufficient, "P:INSUF_STAKE");
poolState = State.Finalized;
emit PoolStateChanged(poolState);
}
/**
@dev Funds a Loan for an amount, utilizing the supplied DebtLockerFactory for DebtLockers.
Only the Pool Delegate can call this function.
@dev It emits a `LoanFunded` event.
@dev It emits a `BalanceUpdated` event.
@param loan Address of the Loan to fund.
@param dlFactory Address of the DebtLockerFactory to utilize.
@param amt Amount to fund the Loan.
*/
function fundLoan(address loan, address dlFactory, uint256 amt) external {
_isValidDelegateAndProtocolNotPaused();
_isValidState(State.Finalized);
principalOut = principalOut.add(amt);
PoolLib.fundLoan(debtLockers, superFactory, liquidityLocker, loan, dlFactory, amt);
_emitBalanceUpdatedEvent();
}
/**
@dev Liquidates a Loan. The Pool Delegate could liquidate the Loan only when the Loan completes its grace period.
The Pool Delegate can claim its proportion of recovered funds from the liquidation using the `claim()` function.
Only the Pool Delegate can call this function.
@param loan Address of the Loan to liquidate.
@param dlFactory Address of the DebtLockerFactory that is used to pull corresponding DebtLocker.
*/
function triggerDefault(address loan, address dlFactory) external {
_isValidDelegateAndProtocolNotPaused();
IDebtLocker(debtLockers[loan][dlFactory]).triggerDefault();
}
/**
@dev Claims available funds for the Loan through a specified DebtLockerFactory. Only the Pool Delegate or a Pool Admin can call this function.
@dev It emits two `BalanceUpdated` events.
@dev It emits a `Claim` event.
@param loan Address of the loan to claim from.
@param dlFactory Address of the DebtLockerFactory.
@return claimInfo The claim details.
claimInfo [0] = Total amount claimed
claimInfo [1] = Interest portion claimed
claimInfo [2] = Principal portion claimed
claimInfo [3] = Fee portion claimed
claimInfo [4] = Excess portion claimed
claimInfo [5] = Recovered portion claimed (from liquidations)
claimInfo [6] = Default suffered
*/
function claim(address loan, address dlFactory) external returns (uint256[7] memory claimInfo) {
_whenProtocolNotPaused();
_isValidDelegateOrPoolAdmin();
claimInfo = IDebtLocker(debtLockers[loan][dlFactory]).claim();
(uint256 poolDelegatePortion, uint256 stakeLockerPortion, uint256 principalClaim, uint256 interestClaim) = PoolLib.calculateClaimAndPortions(claimInfo, delegateFee, stakingFee);
// Subtract outstanding principal by the principal claimed plus excess returned.
// Considers possible `principalClaim` overflow if Liquidity Asset is transferred directly into the Loan.
if (principalClaim <= principalOut) {
principalOut = principalOut - principalClaim;
} else {
interestClaim = interestClaim.add(principalClaim - principalOut); // Distribute `principalClaim` overflow as interest to LPs.
principalClaim = principalOut; // Set `principalClaim` to `principalOut` so correct amount gets transferred.
principalOut = 0; // Set `principalOut` to zero to avoid subtraction overflow.
}
// Accounts for rounding error in StakeLocker / Pool Delegate / LiquidityLocker interest split.
interestSum = interestSum.add(interestClaim);
_transferLiquidityAsset(poolDelegate, poolDelegatePortion); // Transfer the fee and portion of interest to the Pool Delegate.
_transferLiquidityAsset(stakeLocker, stakeLockerPortion); // Transfer the portion of interest to the StakeLocker.
// Transfer remaining claim (remaining interest + principal + excess + recovered) to the LiquidityLocker.
// Dust will accrue in the Pool, but this ensures that state variables are in sync with the LiquidityLocker balance updates.
// Not using `balanceOf` in case of external address transferring the Liquidity Asset directly into Pool.
// Ensures that internal accounting is exactly reflective of balance change.
_transferLiquidityAsset(liquidityLocker, principalClaim.add(interestClaim));
// Handle default if defaultSuffered > 0.
if (claimInfo[6] > 0) _handleDefault(loan, claimInfo[6]);
// Update funds received for StakeLockerFDTs.
IStakeLocker(stakeLocker).updateFundsReceived();
// Update funds received for PoolFDTs.
updateFundsReceived();
_emitBalanceUpdatedEvent();
emit BalanceUpdated(stakeLocker, address(liquidityAsset), liquidityAsset.balanceOf(stakeLocker));
emit Claim(loan, interestClaim, principalClaim, claimInfo[3], stakeLockerPortion, poolDelegatePortion);
}
/**
@dev Handles if a claim has been made and there is a non-zero defaultSuffered amount.
@dev It emits a `DefaultSuffered` event.
@param loan Address of a Loan that has defaulted.
@param defaultSuffered Losses suffered from default after liquidation.
*/
function _handleDefault(address loan, uint256 defaultSuffered) internal {
(uint256 bptsBurned, uint256 postBurnBptBal, uint256 liquidityAssetRecoveredFromBurn) = PoolLib.handleDefault(liquidityAsset, stakeLocker, stakeAsset, defaultSuffered);
// If BPT burn is not enough to cover full default amount, pass on losses to LPs with PoolFDT loss accounting.
if (defaultSuffered > liquidityAssetRecoveredFromBurn) {
poolLosses = poolLosses.add(defaultSuffered - liquidityAssetRecoveredFromBurn);
updateLossesReceived();
}
// Transfer Liquidity Asset from burn to LiquidityLocker.
liquidityAsset.safeTransfer(liquidityLocker, liquidityAssetRecoveredFromBurn);
principalOut = principalOut.sub(defaultSuffered); // Subtract rest of the Loan's principal from `principalOut`.
emit DefaultSuffered(
loan, // The Loan that suffered the default.
defaultSuffered, // Total default suffered from the Loan by the Pool after liquidation.
bptsBurned, // Amount of BPTs burned from StakeLocker.
postBurnBptBal, // Remaining BPTs in StakeLocker post-burn.
liquidityAssetRecoveredFromBurn // Amount of Liquidity Asset recovered from burning BPTs.
);
}
/**
@dev Triggers deactivation, permanently shutting down the Pool. Must have less than 100 USD worth of Liquidity Asset `principalOut`.
Only the Pool Delegate can call this function.
@dev It emits a `PoolStateChanged` event.
*/
function deactivate() external {
_isValidDelegateAndProtocolNotPaused();
_isValidState(State.Finalized);
PoolLib.validateDeactivation(_globals(superFactory), principalOut, address(liquidityAsset));
poolState = State.Deactivated;
emit PoolStateChanged(poolState);
}
/**************************************/
/*** Pool Delegate Setter Functions ***/
/**************************************/
/**
@dev Sets the liquidity cap. Only the Pool Delegate or a Pool Admin can call this function.
@dev It emits a `LiquidityCapSet` event.
@param newLiquidityCap New liquidity cap value.
*/
function setLiquidityCap(uint256 newLiquidityCap) external {
_whenProtocolNotPaused();
_isValidDelegateOrPoolAdmin();
liquidityCap = newLiquidityCap;
emit LiquidityCapSet(newLiquidityCap);
}
/**
@dev Sets the lockup period. Only the Pool Delegate can call this function.
@dev It emits a `LockupPeriodSet` event.
@param newLockupPeriod New lockup period used to restrict the withdrawals.
*/
function setLockupPeriod(uint256 newLockupPeriod) external {
_isValidDelegateAndProtocolNotPaused();
require(newLockupPeriod <= lockupPeriod, "P:BAD_VALUE");
lockupPeriod = newLockupPeriod;
emit LockupPeriodSet(newLockupPeriod);
}
/**
@dev Sets the staking fee. Only the Pool Delegate can call this function.
@dev It emits a `StakingFeeSet` event.
@param newStakingFee New staking fee.
*/
function setStakingFee(uint256 newStakingFee) external {
_isValidDelegateAndProtocolNotPaused();
require(newStakingFee.add(delegateFee) <= 10_000, "P:BAD_FEE");
stakingFee = newStakingFee;
emit StakingFeeSet(newStakingFee);
}
/**
@dev Sets the account status in the Pool's allowlist. Only the Pool Delegate can call this function.
@dev It emits an `LPStatusChanged` event.
@param account The address to set status for.
@param status The status of an account in the allowlist.
*/
function setAllowList(address account, bool status) external {
_isValidDelegateAndProtocolNotPaused();
allowedLiquidityProviders[account] = status;
emit LPStatusChanged(account, status);
}
/**
@dev Sets a Pool Admin. Only the Pool Delegate can call this function.
@dev It emits a `PoolAdminSet` event.
@param poolAdmin An address being allowed or disallowed as a Pool Admin.
@param allowed Status of a Pool Admin.
*/
function setPoolAdmin(address poolAdmin, bool allowed) external {
_isValidDelegateAndProtocolNotPaused();
poolAdmins[poolAdmin] = allowed;
emit PoolAdminSet(poolAdmin, allowed);
}
/**
@dev Sets whether the Pool is open to the public. Only the Pool Delegate can call this function.
@dev It emits a `PoolOpenedToPublic` event.
@param open Public pool access status.
*/
function setOpenToPublic(bool open) external {
_isValidDelegateAndProtocolNotPaused();
openToPublic = open;
emit PoolOpenedToPublic(open);
}
/************************************/
/*** Liquidity Provider Functions ***/
/************************************/
/**
@dev Handles Liquidity Providers depositing of Liquidity Asset into the LiquidityLocker, minting PoolFDTs.
@dev It emits a `DepositDateUpdated` event.
@dev It emits a `BalanceUpdated` event.
@dev It emits a `Cooldown` event.
@param amt Amount of Liquidity Asset to deposit.
*/
function deposit(uint256 amt) external {
_whenProtocolNotPaused();
_isValidState(State.Finalized);
require(isDepositAllowed(amt), "P:DEP_NOT_ALLOWED");
withdrawCooldown[msg.sender] = uint256(0); // Reset the LP's withdraw cooldown if they had previously intended to withdraw.
uint256 wad = _toWad(amt);
PoolLib.updateDepositDate(depositDate, balanceOf(msg.sender), wad, msg.sender);
liquidityAsset.safeTransferFrom(msg.sender, liquidityLocker, amt);
_mint(msg.sender, wad);
_emitBalanceUpdatedEvent();
emit Cooldown(msg.sender, uint256(0));
}
/**
@dev Activates the cooldown period to withdraw. It can't be called if the account is not providing liquidity.
@dev It emits a `Cooldown` event.
**/
function intendToWithdraw() external {
require(balanceOf(msg.sender) != uint256(0), "P:ZERO_BAL");
withdrawCooldown[msg.sender] = block.timestamp;
emit Cooldown(msg.sender, block.timestamp);
}
/**
@dev Cancels an initiated withdrawal by resetting the account's withdraw cooldown.
@dev It emits a `Cooldown` event.
**/
function cancelWithdraw() external {
require(withdrawCooldown[msg.sender] != uint256(0), "P:NOT_WITHDRAWING");
withdrawCooldown[msg.sender] = uint256(0);
emit Cooldown(msg.sender, uint256(0));
}
/**
@dev Checks that the account can withdraw an amount.
@param account The address of the account.
@param wad The amount to withdraw.
*/
function _canWithdraw(address account, uint256 wad) internal view {
require(depositDate[account].add(lockupPeriod) <= block.timestamp, "P:FUNDS_LOCKED"); // Restrict withdrawal during lockup period
require(balanceOf(account).sub(wad) >= totalCustodyAllowance[account], "P:INSUF_TRANS_BAL"); // Account can only withdraw tokens that aren't custodied
}
/**
@dev Handles Liquidity Providers withdrawing of Liquidity Asset from the LiquidityLocker, burning PoolFDTs.
@dev It emits two `BalanceUpdated` event.
@param amt Amount of Liquidity Asset to withdraw.
*/
function withdraw(uint256 amt) external {
_whenProtocolNotPaused();
uint256 wad = _toWad(amt);
(uint256 lpCooldownPeriod, uint256 lpWithdrawWindow) = _globals(superFactory).getLpCooldownParams();
_canWithdraw(msg.sender, wad);
require((block.timestamp - (withdrawCooldown[msg.sender] + lpCooldownPeriod)) <= lpWithdrawWindow, "P:WITHDRAW_NOT_ALLOWED");
_burn(msg.sender, wad); // Burn the corresponding PoolFDTs balance.
withdrawFunds(); // Transfer full entitled interest, decrement `interestSum`.
// Transfer amount that is due after realized losses are accounted for.
// Recognized losses are absorbed by the LP.
_transferLiquidityLockerFunds(msg.sender, amt.sub(_recognizeLosses()));
_emitBalanceUpdatedEvent();
}
/**
@dev Transfers PoolFDTs.
@param from Address sending PoolFDTs.
@param to Address receiving PoolFDTs.
@param wad Amount of PoolFDTs to transfer.
*/
function _transfer(address from, address to, uint256 wad) internal override {
_whenProtocolNotPaused();
(uint256 lpCooldownPeriod, uint256 lpWithdrawWindow) = _globals(superFactory).getLpCooldownParams();
_canWithdraw(from, wad);
require(block.timestamp > (withdrawCooldown[to] + lpCooldownPeriod + lpWithdrawWindow), "P:TO_NOT_ALLOWED"); // Recipient must not be currently withdrawing.
require(recognizableLossesOf(from) == uint256(0), "P:RECOG_LOSSES"); // If an LP has unrecognized losses, they must recognize losses using `withdraw`.
PoolLib.updateDepositDate(depositDate, balanceOf(to), wad, to);
super._transfer(from, to, wad);
}
/**
@dev Withdraws all claimable interest from the LiquidityLocker for an account using `interestSum` accounting.
@dev It emits a `BalanceUpdated` event.
*/
function withdrawFunds() public override {
_whenProtocolNotPaused();
uint256 withdrawableFunds = _prepareWithdraw();
if (withdrawableFunds == uint256(0)) return;
_transferLiquidityLockerFunds(msg.sender, withdrawableFunds);
_emitBalanceUpdatedEvent();
interestSum = interestSum.sub(withdrawableFunds);
_updateFundsTokenBalance();
}
/**
@dev Increases the custody allowance for a given Custodian corresponding to the calling account (`msg.sender`).
@dev It emits a `CustodyAllowanceChanged` event.
@dev It emits a `TotalCustodyAllowanceUpdated` event.
@param custodian Address which will act as Custodian of a given amount for an account.
@param amount Number of additional FDTs to be custodied by the Custodian.
*/
function increaseCustodyAllowance(address custodian, uint256 amount) external {
uint256 oldAllowance = custodyAllowance[msg.sender][custodian];
uint256 newAllowance = oldAllowance.add(amount);
uint256 newTotalAllowance = totalCustodyAllowance[msg.sender].add(amount);
PoolLib.increaseCustodyAllowanceChecks(custodian, amount, newTotalAllowance, balanceOf(msg.sender));
custodyAllowance[msg.sender][custodian] = newAllowance;
totalCustodyAllowance[msg.sender] = newTotalAllowance;
emit CustodyAllowanceChanged(msg.sender, custodian, oldAllowance, newAllowance);
emit TotalCustodyAllowanceUpdated(msg.sender, newTotalAllowance);
}
/**
@dev Transfers custodied PoolFDTs back to the account.
@dev `from` and `to` should always be equal in this implementation.
@dev This means that the Custodian can only decrease their own allowance and unlock funds for the original owner.
@dev It emits a `CustodyTransfer` event.
@dev It emits a `CustodyAllowanceChanged` event.
@dev It emits a `TotalCustodyAllowanceUpdated` event.
@param from Address which holds the PoolFDTs.
@param to Address which will be the new owner of the amount of PoolFDTs.
@param amount Amount of PoolFDTs transferred.
*/
function transferByCustodian(address from, address to, uint256 amount) external {
uint256 oldAllowance = custodyAllowance[from][msg.sender];
uint256 newAllowance = oldAllowance.sub(amount);
PoolLib.transferByCustodianChecks(from, to, amount);
custodyAllowance[from][msg.sender] = newAllowance;
uint256 newTotalAllowance = totalCustodyAllowance[from].sub(amount);
totalCustodyAllowance[from] = newTotalAllowance;
emit CustodyTransfer(msg.sender, from, to, amount);
emit CustodyAllowanceChanged(from, msg.sender, oldAllowance, newAllowance);
emit TotalCustodyAllowanceUpdated(msg.sender, newTotalAllowance);
}
/**************************/
/*** Governor Functions ***/
/**************************/
/**
@dev Transfers any locked funds to the Governor. Only the Governor can call this function.
@param token Address of the token to be reclaimed.
*/
function reclaimERC20(address token) external {
PoolLib.reclaimERC20(token, address(liquidityAsset), _globals(superFactory));
}
/*************************/
/*** Getter Functions ***/
/*************************/
/**
@dev Calculates the value of BPT in units of Liquidity Asset.
@param _bPool Address of Balancer pool.
@param _liquidityAsset Asset used by Pool for liquidity to fund Loans.
@param _staker Address that deposited BPTs to StakeLocker.
@param _stakeLocker Escrows BPTs deposited by Staker.
@return USDC value of staker BPTs.
*/
function BPTVal(
address _bPool,
address _liquidityAsset,
address _staker,
address _stakeLocker
) external view returns (uint256) {
return PoolLib.BPTVal(_bPool, _liquidityAsset, _staker, _stakeLocker);
}
/**
@dev Checks that the given deposit amount is acceptable based on current liquidityCap.
@param depositAmt Amount of tokens (i.e liquidityAsset type) the account is trying to deposit.
*/
function isDepositAllowed(uint256 depositAmt) public view returns (bool) {
return (openToPublic || allowedLiquidityProviders[msg.sender]) &&
_balanceOfLiquidityLocker().add(principalOut).add(depositAmt) <= liquidityCap;
}
/**
@dev Returns information on the stake requirements.
@return [0] = Min amount of Liquidity Asset coverage from staking required.
[1] = Present amount of Liquidity Asset coverage from the Pool Delegate stake.
[2] = If enough stake is present from the Pool Delegate for finalization.
[3] = Staked BPTs required for minimum Liquidity Asset coverage.
[4] = Current staked BPTs.
*/
function getInitialStakeRequirements() public view returns (uint256, uint256, bool, uint256, uint256) {
return PoolLib.getInitialStakeRequirements(_globals(superFactory), stakeAsset, address(liquidityAsset), poolDelegate, stakeLocker);
}
/**
@dev Calculates BPTs required if burning BPTs for the Liquidity Asset, given supplied `tokenAmountOutRequired`.
@param _bPool The Balancer pool that issues the BPTs.
@param _liquidityAsset Swap out asset (e.g. USDC) to receive when burning BPTs.
@param _staker Address that deposited BPTs to StakeLocker.
@param _stakeLocker Escrows BPTs deposited by Staker.
@param _liquidityAssetAmountRequired Amount of Liquidity Asset required to recover.
@return [0] = poolAmountIn required.
[1] = poolAmountIn currently staked.
*/
function getPoolSharesRequired(
address _bPool,
address _liquidityAsset,
address _staker,
address _stakeLocker,
uint256 _liquidityAssetAmountRequired
) external view returns (uint256, uint256) {
return PoolLib.getPoolSharesRequired(_bPool, _liquidityAsset, _staker, _stakeLocker, _liquidityAssetAmountRequired);
}
/**
@dev Checks that the Pool state is `Finalized`.
@return bool Boolean value indicating if Pool is in a Finalized state.
*/
function isPoolFinalized() external view returns (bool) {
return poolState == State.Finalized;
}
/************************/
/*** Helper Functions ***/
/************************/
/**
@dev Converts to WAD precision.
@param amt Amount to convert.
*/
function _toWad(uint256 amt) internal view returns (uint256) {
return amt.mul(WAD).div(10 ** liquidityAssetDecimals);
}
/**
@dev Returns the balance of this Pool's LiquidityLocker.
@return Balance of LiquidityLocker.
*/
function _balanceOfLiquidityLocker() internal view returns (uint256) {
return liquidityAsset.balanceOf(liquidityLocker);
}
/**
@dev Checks that the current state of Pool matches the provided state.
@param _state Enum of desired Pool state.
*/
function _isValidState(State _state) internal view {
require(poolState == _state, "P:BAD_STATE");
}
/**
@dev Checks that `msg.sender` is the Pool Delegate.
*/
function _isValidDelegate() internal view {
require(msg.sender == poolDelegate, "P:NOT_DEL");
}
/**
@dev Returns the MapleGlobals instance.
*/
function _globals(address poolFactory) internal view returns (IMapleGlobals) {
return IMapleGlobals(IPoolFactory(poolFactory).globals());
}
/**
@dev Emits a `BalanceUpdated` event for LiquidityLocker.
@dev It emits a `BalanceUpdated` event.
*/
function _emitBalanceUpdatedEvent() internal {
emit BalanceUpdated(liquidityLocker, address(liquidityAsset), _balanceOfLiquidityLocker());
}
/**
@dev Transfers Liquidity Asset to given `to` address, from self (i.e. `address(this)`).
@param to Address to transfer liquidityAsset.
@param value Amount of liquidity asset that gets transferred.
*/
function _transferLiquidityAsset(address to, uint256 value) internal {
liquidityAsset.safeTransfer(to, value);
}
/**
@dev Checks that `msg.sender` is the Pool Delegate or a Pool Admin.
*/
function _isValidDelegateOrPoolAdmin() internal view {
require(msg.sender == poolDelegate || poolAdmins[msg.sender], "P:NOT_DEL_OR_ADMIN");
}
/**
@dev Checks that the protocol is not in a paused state.
*/
function _whenProtocolNotPaused() internal view {
require(!_globals(superFactory).protocolPaused(), "P:PROTO_PAUSED");
}
/**
@dev Checks that `msg.sender` is the Pool Delegate and that the protocol is not in a paused state.
*/
function _isValidDelegateAndProtocolNotPaused() internal view {
_isValidDelegate();
_whenProtocolNotPaused();
}
function _transferLiquidityLockerFunds(address to, uint256 value) internal {
ILiquidityLocker(liquidityLocker).transfer(to, value);
}
}
| contract Pool is PoolFDT {
using SafeMath for uint256;
using SafeERC20 for IERC20;
uint256 constant WAD = 10 ** 18;
uint8 public constant DL_FACTORY = 1; // Factory type of `DebtLockerFactory`.
IERC20 public immutable liquidityAsset; // The asset deposited by Lenders into the LiquidityLocker, for funding Loans.
address public immutable poolDelegate; // The Pool Delegate address, maintains full authority over the Pool.
address public immutable liquidityLocker; // The LiquidityLocker owned by this contract
address public immutable stakeAsset; // The address of the asset deposited by Stakers into the StakeLocker (BPTs), for liquidation during default events.
address public immutable stakeLocker; // The address of the StakeLocker, escrowing `stakeAsset`.
address public immutable superFactory; // The factory that deployed this Loan.
uint256 private immutable liquidityAssetDecimals; // The precision for the Liquidity Asset (i.e. `decimals()`).
uint256 public stakingFee; // The fee Stakers earn (in basis points).
uint256 public immutable delegateFee; // The fee the Pool Delegate earns (in basis points).
uint256 public principalOut; // The sum of all outstanding principal on Loans.
uint256 public liquidityCap; // The amount of liquidity tokens accepted by the Pool.
uint256 public lockupPeriod; // The period of time from an account's deposit date during which they cannot withdraw any funds.
bool public openToPublic; // Boolean opening Pool to public for LP deposits
enum State { Initialized, Finalized, Deactivated }
State public poolState;
mapping(address => uint256) public depositDate; // Used for withdraw penalty calculation.
mapping(address => mapping(address => address)) public debtLockers; // Address of the DebtLocker corresponding to `[Loan][DebtLockerFactory]`.
mapping(address => bool) public poolAdmins; // The Pool Admin addresses that have permission to do certain operations in case of disaster management.
mapping(address => bool) public allowedLiquidityProviders; // Mapping that contains the list of addresses that have early access to the pool.
mapping(address => uint256) public withdrawCooldown; // The timestamp of when individual LPs have notified of their intent to withdraw.
mapping(address => mapping(address => uint256)) public custodyAllowance; // The amount of PoolFDTs that are "locked" at a certain address.
mapping(address => uint256) public totalCustodyAllowance; // The total amount of PoolFDTs that are "locked" for a given account. Cannot be greater than an account's balance.
event LoanFunded(address indexed loan, address debtLocker, uint256 amountFunded);
event Claim(address indexed loan, uint256 interest, uint256 principal, uint256 fee, uint256 stakeLockerPortion, uint256 poolDelegatePortion);
event BalanceUpdated(address indexed liquidityProvider, address indexed token, uint256 balance);
event CustodyTransfer(address indexed custodian, address indexed from, address indexed to, uint256 amount);
event CustodyAllowanceChanged(address indexed liquidityProvider, address indexed custodian, uint256 oldAllowance, uint256 newAllowance);
event LPStatusChanged(address indexed liquidityProvider, bool status);
event LiquidityCapSet(uint256 newLiquidityCap);
event LockupPeriodSet(uint256 newLockupPeriod);
event StakingFeeSet(uint256 newStakingFee);
event PoolStateChanged(State state);
event Cooldown(address indexed liquidityProvider, uint256 cooldown);
event PoolOpenedToPublic(bool isOpen);
event PoolAdminSet(address indexed poolAdmin, bool allowed);
event DepositDateUpdated(address indexed liquidityProvider, uint256 depositDate);
event TotalCustodyAllowanceUpdated(address indexed liquidityProvider, uint256 newTotalAllowance);
event DefaultSuffered(
address indexed loan,
uint256 defaultSuffered,
uint256 bptsBurned,
uint256 bptsReturned,
uint256 liquidityAssetRecoveredFromBurn
);
/**
Universal accounting law:
fdtTotalSupply = liquidityLockerBal + principalOut - interestSum + poolLosses
fdtTotalSupply + interestSum - poolLosses = liquidityLockerBal + principalOut
*/
/**
@dev Constructor for a Pool.
@dev It emits a `PoolStateChanged` event.
@param _poolDelegate Address that has manager privileges of the Pool.
@param _liquidityAsset Asset used to fund the Pool, It gets escrowed in LiquidityLocker.
@param _stakeAsset Asset escrowed in StakeLocker.
@param _slFactory Factory used to instantiate the StakeLocker.
@param _llFactory Factory used to instantiate the LiquidityLocker.
@param _stakingFee Fee that Stakers earn on interest, in basis points.
@param _delegateFee Fee that the Pool Delegate earns on interest, in basis points.
@param _liquidityCap Max amount of Liquidity Asset accepted by the Pool.
@param name Name of Pool token.
@param symbol Symbol of Pool token.
*/
constructor(
address _poolDelegate,
address _liquidityAsset,
address _stakeAsset,
address _slFactory,
address _llFactory,
uint256 _stakingFee,
uint256 _delegateFee,
uint256 _liquidityCap,
string memory name,
string memory symbol
) PoolFDT(name, symbol) public {
// Conduct sanity checks on Pool parameters.
PoolLib.poolSanityChecks(_globals(msg.sender), _liquidityAsset, _stakeAsset, _stakingFee, _delegateFee);
// Assign variables relating to the Liquidity Asset.
liquidityAsset = IERC20(_liquidityAsset);
liquidityAssetDecimals = ERC20(_liquidityAsset).decimals();
// Assign state variables.
stakeAsset = _stakeAsset;
poolDelegate = _poolDelegate;
stakingFee = _stakingFee;
delegateFee = _delegateFee;
superFactory = msg.sender;
liquidityCap = _liquidityCap;
// Instantiate the LiquidityLocker and the StakeLocker.
stakeLocker = address(IStakeLockerFactory(_slFactory).newLocker(_stakeAsset, _liquidityAsset));
liquidityLocker = address(ILiquidityLockerFactory(_llFactory).newLocker(_liquidityAsset));
lockupPeriod = 180 days;
emit PoolStateChanged(State.Initialized);
}
/*******************************/
/*** Pool Delegate Functions ***/
/*******************************/
/**
@dev Finalizes the Pool, enabling deposits. Checks the amount the Pool Delegate deposited to the StakeLocker.
Only the Pool Delegate can call this function.
@dev It emits a `PoolStateChanged` event.
*/
function finalize() external {
_isValidDelegateAndProtocolNotPaused();
_isValidState(State.Initialized);
(,, bool stakeSufficient,,) = getInitialStakeRequirements();
require(stakeSufficient, "P:INSUF_STAKE");
poolState = State.Finalized;
emit PoolStateChanged(poolState);
}
/**
@dev Funds a Loan for an amount, utilizing the supplied DebtLockerFactory for DebtLockers.
Only the Pool Delegate can call this function.
@dev It emits a `LoanFunded` event.
@dev It emits a `BalanceUpdated` event.
@param loan Address of the Loan to fund.
@param dlFactory Address of the DebtLockerFactory to utilize.
@param amt Amount to fund the Loan.
*/
function fundLoan(address loan, address dlFactory, uint256 amt) external {
_isValidDelegateAndProtocolNotPaused();
_isValidState(State.Finalized);
principalOut = principalOut.add(amt);
PoolLib.fundLoan(debtLockers, superFactory, liquidityLocker, loan, dlFactory, amt);
_emitBalanceUpdatedEvent();
}
/**
@dev Liquidates a Loan. The Pool Delegate could liquidate the Loan only when the Loan completes its grace period.
The Pool Delegate can claim its proportion of recovered funds from the liquidation using the `claim()` function.
Only the Pool Delegate can call this function.
@param loan Address of the Loan to liquidate.
@param dlFactory Address of the DebtLockerFactory that is used to pull corresponding DebtLocker.
*/
function triggerDefault(address loan, address dlFactory) external {
_isValidDelegateAndProtocolNotPaused();
IDebtLocker(debtLockers[loan][dlFactory]).triggerDefault();
}
/**
@dev Claims available funds for the Loan through a specified DebtLockerFactory. Only the Pool Delegate or a Pool Admin can call this function.
@dev It emits two `BalanceUpdated` events.
@dev It emits a `Claim` event.
@param loan Address of the loan to claim from.
@param dlFactory Address of the DebtLockerFactory.
@return claimInfo The claim details.
claimInfo [0] = Total amount claimed
claimInfo [1] = Interest portion claimed
claimInfo [2] = Principal portion claimed
claimInfo [3] = Fee portion claimed
claimInfo [4] = Excess portion claimed
claimInfo [5] = Recovered portion claimed (from liquidations)
claimInfo [6] = Default suffered
*/
function claim(address loan, address dlFactory) external returns (uint256[7] memory claimInfo) {
_whenProtocolNotPaused();
_isValidDelegateOrPoolAdmin();
claimInfo = IDebtLocker(debtLockers[loan][dlFactory]).claim();
(uint256 poolDelegatePortion, uint256 stakeLockerPortion, uint256 principalClaim, uint256 interestClaim) = PoolLib.calculateClaimAndPortions(claimInfo, delegateFee, stakingFee);
// Subtract outstanding principal by the principal claimed plus excess returned.
// Considers possible `principalClaim` overflow if Liquidity Asset is transferred directly into the Loan.
if (principalClaim <= principalOut) {
principalOut = principalOut - principalClaim;
} else {
interestClaim = interestClaim.add(principalClaim - principalOut); // Distribute `principalClaim` overflow as interest to LPs.
principalClaim = principalOut; // Set `principalClaim` to `principalOut` so correct amount gets transferred.
principalOut = 0; // Set `principalOut` to zero to avoid subtraction overflow.
}
// Accounts for rounding error in StakeLocker / Pool Delegate / LiquidityLocker interest split.
interestSum = interestSum.add(interestClaim);
_transferLiquidityAsset(poolDelegate, poolDelegatePortion); // Transfer the fee and portion of interest to the Pool Delegate.
_transferLiquidityAsset(stakeLocker, stakeLockerPortion); // Transfer the portion of interest to the StakeLocker.
// Transfer remaining claim (remaining interest + principal + excess + recovered) to the LiquidityLocker.
// Dust will accrue in the Pool, but this ensures that state variables are in sync with the LiquidityLocker balance updates.
// Not using `balanceOf` in case of external address transferring the Liquidity Asset directly into Pool.
// Ensures that internal accounting is exactly reflective of balance change.
_transferLiquidityAsset(liquidityLocker, principalClaim.add(interestClaim));
// Handle default if defaultSuffered > 0.
if (claimInfo[6] > 0) _handleDefault(loan, claimInfo[6]);
// Update funds received for StakeLockerFDTs.
IStakeLocker(stakeLocker).updateFundsReceived();
// Update funds received for PoolFDTs.
updateFundsReceived();
_emitBalanceUpdatedEvent();
emit BalanceUpdated(stakeLocker, address(liquidityAsset), liquidityAsset.balanceOf(stakeLocker));
emit Claim(loan, interestClaim, principalClaim, claimInfo[3], stakeLockerPortion, poolDelegatePortion);
}
/**
@dev Handles if a claim has been made and there is a non-zero defaultSuffered amount.
@dev It emits a `DefaultSuffered` event.
@param loan Address of a Loan that has defaulted.
@param defaultSuffered Losses suffered from default after liquidation.
*/
function _handleDefault(address loan, uint256 defaultSuffered) internal {
(uint256 bptsBurned, uint256 postBurnBptBal, uint256 liquidityAssetRecoveredFromBurn) = PoolLib.handleDefault(liquidityAsset, stakeLocker, stakeAsset, defaultSuffered);
// If BPT burn is not enough to cover full default amount, pass on losses to LPs with PoolFDT loss accounting.
if (defaultSuffered > liquidityAssetRecoveredFromBurn) {
poolLosses = poolLosses.add(defaultSuffered - liquidityAssetRecoveredFromBurn);
updateLossesReceived();
}
// Transfer Liquidity Asset from burn to LiquidityLocker.
liquidityAsset.safeTransfer(liquidityLocker, liquidityAssetRecoveredFromBurn);
principalOut = principalOut.sub(defaultSuffered); // Subtract rest of the Loan's principal from `principalOut`.
emit DefaultSuffered(
loan, // The Loan that suffered the default.
defaultSuffered, // Total default suffered from the Loan by the Pool after liquidation.
bptsBurned, // Amount of BPTs burned from StakeLocker.
postBurnBptBal, // Remaining BPTs in StakeLocker post-burn.
liquidityAssetRecoveredFromBurn // Amount of Liquidity Asset recovered from burning BPTs.
);
}
/**
@dev Triggers deactivation, permanently shutting down the Pool. Must have less than 100 USD worth of Liquidity Asset `principalOut`.
Only the Pool Delegate can call this function.
@dev It emits a `PoolStateChanged` event.
*/
function deactivate() external {
_isValidDelegateAndProtocolNotPaused();
_isValidState(State.Finalized);
PoolLib.validateDeactivation(_globals(superFactory), principalOut, address(liquidityAsset));
poolState = State.Deactivated;
emit PoolStateChanged(poolState);
}
/**************************************/
/*** Pool Delegate Setter Functions ***/
/**************************************/
/**
@dev Sets the liquidity cap. Only the Pool Delegate or a Pool Admin can call this function.
@dev It emits a `LiquidityCapSet` event.
@param newLiquidityCap New liquidity cap value.
*/
function setLiquidityCap(uint256 newLiquidityCap) external {
_whenProtocolNotPaused();
_isValidDelegateOrPoolAdmin();
liquidityCap = newLiquidityCap;
emit LiquidityCapSet(newLiquidityCap);
}
/**
@dev Sets the lockup period. Only the Pool Delegate can call this function.
@dev It emits a `LockupPeriodSet` event.
@param newLockupPeriod New lockup period used to restrict the withdrawals.
*/
function setLockupPeriod(uint256 newLockupPeriod) external {
_isValidDelegateAndProtocolNotPaused();
require(newLockupPeriod <= lockupPeriod, "P:BAD_VALUE");
lockupPeriod = newLockupPeriod;
emit LockupPeriodSet(newLockupPeriod);
}
/**
@dev Sets the staking fee. Only the Pool Delegate can call this function.
@dev It emits a `StakingFeeSet` event.
@param newStakingFee New staking fee.
*/
function setStakingFee(uint256 newStakingFee) external {
_isValidDelegateAndProtocolNotPaused();
require(newStakingFee.add(delegateFee) <= 10_000, "P:BAD_FEE");
stakingFee = newStakingFee;
emit StakingFeeSet(newStakingFee);
}
/**
@dev Sets the account status in the Pool's allowlist. Only the Pool Delegate can call this function.
@dev It emits an `LPStatusChanged` event.
@param account The address to set status for.
@param status The status of an account in the allowlist.
*/
function setAllowList(address account, bool status) external {
_isValidDelegateAndProtocolNotPaused();
allowedLiquidityProviders[account] = status;
emit LPStatusChanged(account, status);
}
/**
@dev Sets a Pool Admin. Only the Pool Delegate can call this function.
@dev It emits a `PoolAdminSet` event.
@param poolAdmin An address being allowed or disallowed as a Pool Admin.
@param allowed Status of a Pool Admin.
*/
function setPoolAdmin(address poolAdmin, bool allowed) external {
_isValidDelegateAndProtocolNotPaused();
poolAdmins[poolAdmin] = allowed;
emit PoolAdminSet(poolAdmin, allowed);
}
/**
@dev Sets whether the Pool is open to the public. Only the Pool Delegate can call this function.
@dev It emits a `PoolOpenedToPublic` event.
@param open Public pool access status.
*/
function setOpenToPublic(bool open) external {
_isValidDelegateAndProtocolNotPaused();
openToPublic = open;
emit PoolOpenedToPublic(open);
}
/************************************/
/*** Liquidity Provider Functions ***/
/************************************/
/**
@dev Handles Liquidity Providers depositing of Liquidity Asset into the LiquidityLocker, minting PoolFDTs.
@dev It emits a `DepositDateUpdated` event.
@dev It emits a `BalanceUpdated` event.
@dev It emits a `Cooldown` event.
@param amt Amount of Liquidity Asset to deposit.
*/
function deposit(uint256 amt) external {
_whenProtocolNotPaused();
_isValidState(State.Finalized);
require(isDepositAllowed(amt), "P:DEP_NOT_ALLOWED");
withdrawCooldown[msg.sender] = uint256(0); // Reset the LP's withdraw cooldown if they had previously intended to withdraw.
uint256 wad = _toWad(amt);
PoolLib.updateDepositDate(depositDate, balanceOf(msg.sender), wad, msg.sender);
liquidityAsset.safeTransferFrom(msg.sender, liquidityLocker, amt);
_mint(msg.sender, wad);
_emitBalanceUpdatedEvent();
emit Cooldown(msg.sender, uint256(0));
}
/**
@dev Activates the cooldown period to withdraw. It can't be called if the account is not providing liquidity.
@dev It emits a `Cooldown` event.
**/
function intendToWithdraw() external {
require(balanceOf(msg.sender) != uint256(0), "P:ZERO_BAL");
withdrawCooldown[msg.sender] = block.timestamp;
emit Cooldown(msg.sender, block.timestamp);
}
/**
@dev Cancels an initiated withdrawal by resetting the account's withdraw cooldown.
@dev It emits a `Cooldown` event.
**/
function cancelWithdraw() external {
require(withdrawCooldown[msg.sender] != uint256(0), "P:NOT_WITHDRAWING");
withdrawCooldown[msg.sender] = uint256(0);
emit Cooldown(msg.sender, uint256(0));
}
/**
@dev Checks that the account can withdraw an amount.
@param account The address of the account.
@param wad The amount to withdraw.
*/
function _canWithdraw(address account, uint256 wad) internal view {
require(depositDate[account].add(lockupPeriod) <= block.timestamp, "P:FUNDS_LOCKED"); // Restrict withdrawal during lockup period
require(balanceOf(account).sub(wad) >= totalCustodyAllowance[account], "P:INSUF_TRANS_BAL"); // Account can only withdraw tokens that aren't custodied
}
/**
@dev Handles Liquidity Providers withdrawing of Liquidity Asset from the LiquidityLocker, burning PoolFDTs.
@dev It emits two `BalanceUpdated` event.
@param amt Amount of Liquidity Asset to withdraw.
*/
function withdraw(uint256 amt) external {
_whenProtocolNotPaused();
uint256 wad = _toWad(amt);
(uint256 lpCooldownPeriod, uint256 lpWithdrawWindow) = _globals(superFactory).getLpCooldownParams();
_canWithdraw(msg.sender, wad);
require((block.timestamp - (withdrawCooldown[msg.sender] + lpCooldownPeriod)) <= lpWithdrawWindow, "P:WITHDRAW_NOT_ALLOWED");
_burn(msg.sender, wad); // Burn the corresponding PoolFDTs balance.
withdrawFunds(); // Transfer full entitled interest, decrement `interestSum`.
// Transfer amount that is due after realized losses are accounted for.
// Recognized losses are absorbed by the LP.
_transferLiquidityLockerFunds(msg.sender, amt.sub(_recognizeLosses()));
_emitBalanceUpdatedEvent();
}
/**
@dev Transfers PoolFDTs.
@param from Address sending PoolFDTs.
@param to Address receiving PoolFDTs.
@param wad Amount of PoolFDTs to transfer.
*/
function _transfer(address from, address to, uint256 wad) internal override {
_whenProtocolNotPaused();
(uint256 lpCooldownPeriod, uint256 lpWithdrawWindow) = _globals(superFactory).getLpCooldownParams();
_canWithdraw(from, wad);
require(block.timestamp > (withdrawCooldown[to] + lpCooldownPeriod + lpWithdrawWindow), "P:TO_NOT_ALLOWED"); // Recipient must not be currently withdrawing.
require(recognizableLossesOf(from) == uint256(0), "P:RECOG_LOSSES"); // If an LP has unrecognized losses, they must recognize losses using `withdraw`.
PoolLib.updateDepositDate(depositDate, balanceOf(to), wad, to);
super._transfer(from, to, wad);
}
/**
@dev Withdraws all claimable interest from the LiquidityLocker for an account using `interestSum` accounting.
@dev It emits a `BalanceUpdated` event.
*/
function withdrawFunds() public override {
_whenProtocolNotPaused();
uint256 withdrawableFunds = _prepareWithdraw();
if (withdrawableFunds == uint256(0)) return;
_transferLiquidityLockerFunds(msg.sender, withdrawableFunds);
_emitBalanceUpdatedEvent();
interestSum = interestSum.sub(withdrawableFunds);
_updateFundsTokenBalance();
}
/**
@dev Increases the custody allowance for a given Custodian corresponding to the calling account (`msg.sender`).
@dev It emits a `CustodyAllowanceChanged` event.
@dev It emits a `TotalCustodyAllowanceUpdated` event.
@param custodian Address which will act as Custodian of a given amount for an account.
@param amount Number of additional FDTs to be custodied by the Custodian.
*/
function increaseCustodyAllowance(address custodian, uint256 amount) external {
uint256 oldAllowance = custodyAllowance[msg.sender][custodian];
uint256 newAllowance = oldAllowance.add(amount);
uint256 newTotalAllowance = totalCustodyAllowance[msg.sender].add(amount);
PoolLib.increaseCustodyAllowanceChecks(custodian, amount, newTotalAllowance, balanceOf(msg.sender));
custodyAllowance[msg.sender][custodian] = newAllowance;
totalCustodyAllowance[msg.sender] = newTotalAllowance;
emit CustodyAllowanceChanged(msg.sender, custodian, oldAllowance, newAllowance);
emit TotalCustodyAllowanceUpdated(msg.sender, newTotalAllowance);
}
/**
@dev Transfers custodied PoolFDTs back to the account.
@dev `from` and `to` should always be equal in this implementation.
@dev This means that the Custodian can only decrease their own allowance and unlock funds for the original owner.
@dev It emits a `CustodyTransfer` event.
@dev It emits a `CustodyAllowanceChanged` event.
@dev It emits a `TotalCustodyAllowanceUpdated` event.
@param from Address which holds the PoolFDTs.
@param to Address which will be the new owner of the amount of PoolFDTs.
@param amount Amount of PoolFDTs transferred.
*/
function transferByCustodian(address from, address to, uint256 amount) external {
uint256 oldAllowance = custodyAllowance[from][msg.sender];
uint256 newAllowance = oldAllowance.sub(amount);
PoolLib.transferByCustodianChecks(from, to, amount);
custodyAllowance[from][msg.sender] = newAllowance;
uint256 newTotalAllowance = totalCustodyAllowance[from].sub(amount);
totalCustodyAllowance[from] = newTotalAllowance;
emit CustodyTransfer(msg.sender, from, to, amount);
emit CustodyAllowanceChanged(from, msg.sender, oldAllowance, newAllowance);
emit TotalCustodyAllowanceUpdated(msg.sender, newTotalAllowance);
}
/**************************/
/*** Governor Functions ***/
/**************************/
/**
@dev Transfers any locked funds to the Governor. Only the Governor can call this function.
@param token Address of the token to be reclaimed.
*/
function reclaimERC20(address token) external {
PoolLib.reclaimERC20(token, address(liquidityAsset), _globals(superFactory));
}
/*************************/
/*** Getter Functions ***/
/*************************/
/**
@dev Calculates the value of BPT in units of Liquidity Asset.
@param _bPool Address of Balancer pool.
@param _liquidityAsset Asset used by Pool for liquidity to fund Loans.
@param _staker Address that deposited BPTs to StakeLocker.
@param _stakeLocker Escrows BPTs deposited by Staker.
@return USDC value of staker BPTs.
*/
function BPTVal(
address _bPool,
address _liquidityAsset,
address _staker,
address _stakeLocker
) external view returns (uint256) {
return PoolLib.BPTVal(_bPool, _liquidityAsset, _staker, _stakeLocker);
}
/**
@dev Checks that the given deposit amount is acceptable based on current liquidityCap.
@param depositAmt Amount of tokens (i.e liquidityAsset type) the account is trying to deposit.
*/
function isDepositAllowed(uint256 depositAmt) public view returns (bool) {
return (openToPublic || allowedLiquidityProviders[msg.sender]) &&
_balanceOfLiquidityLocker().add(principalOut).add(depositAmt) <= liquidityCap;
}
/**
@dev Returns information on the stake requirements.
@return [0] = Min amount of Liquidity Asset coverage from staking required.
[1] = Present amount of Liquidity Asset coverage from the Pool Delegate stake.
[2] = If enough stake is present from the Pool Delegate for finalization.
[3] = Staked BPTs required for minimum Liquidity Asset coverage.
[4] = Current staked BPTs.
*/
function getInitialStakeRequirements() public view returns (uint256, uint256, bool, uint256, uint256) {
return PoolLib.getInitialStakeRequirements(_globals(superFactory), stakeAsset, address(liquidityAsset), poolDelegate, stakeLocker);
}
/**
@dev Calculates BPTs required if burning BPTs for the Liquidity Asset, given supplied `tokenAmountOutRequired`.
@param _bPool The Balancer pool that issues the BPTs.
@param _liquidityAsset Swap out asset (e.g. USDC) to receive when burning BPTs.
@param _staker Address that deposited BPTs to StakeLocker.
@param _stakeLocker Escrows BPTs deposited by Staker.
@param _liquidityAssetAmountRequired Amount of Liquidity Asset required to recover.
@return [0] = poolAmountIn required.
[1] = poolAmountIn currently staked.
*/
function getPoolSharesRequired(
address _bPool,
address _liquidityAsset,
address _staker,
address _stakeLocker,
uint256 _liquidityAssetAmountRequired
) external view returns (uint256, uint256) {
return PoolLib.getPoolSharesRequired(_bPool, _liquidityAsset, _staker, _stakeLocker, _liquidityAssetAmountRequired);
}
/**
@dev Checks that the Pool state is `Finalized`.
@return bool Boolean value indicating if Pool is in a Finalized state.
*/
function isPoolFinalized() external view returns (bool) {
return poolState == State.Finalized;
}
/************************/
/*** Helper Functions ***/
/************************/
/**
@dev Converts to WAD precision.
@param amt Amount to convert.
*/
function _toWad(uint256 amt) internal view returns (uint256) {
return amt.mul(WAD).div(10 ** liquidityAssetDecimals);
}
/**
@dev Returns the balance of this Pool's LiquidityLocker.
@return Balance of LiquidityLocker.
*/
function _balanceOfLiquidityLocker() internal view returns (uint256) {
return liquidityAsset.balanceOf(liquidityLocker);
}
/**
@dev Checks that the current state of Pool matches the provided state.
@param _state Enum of desired Pool state.
*/
function _isValidState(State _state) internal view {
require(poolState == _state, "P:BAD_STATE");
}
/**
@dev Checks that `msg.sender` is the Pool Delegate.
*/
function _isValidDelegate() internal view {
require(msg.sender == poolDelegate, "P:NOT_DEL");
}
/**
@dev Returns the MapleGlobals instance.
*/
function _globals(address poolFactory) internal view returns (IMapleGlobals) {
return IMapleGlobals(IPoolFactory(poolFactory).globals());
}
/**
@dev Emits a `BalanceUpdated` event for LiquidityLocker.
@dev It emits a `BalanceUpdated` event.
*/
function _emitBalanceUpdatedEvent() internal {
emit BalanceUpdated(liquidityLocker, address(liquidityAsset), _balanceOfLiquidityLocker());
}
/**
@dev Transfers Liquidity Asset to given `to` address, from self (i.e. `address(this)`).
@param to Address to transfer liquidityAsset.
@param value Amount of liquidity asset that gets transferred.
*/
function _transferLiquidityAsset(address to, uint256 value) internal {
liquidityAsset.safeTransfer(to, value);
}
/**
@dev Checks that `msg.sender` is the Pool Delegate or a Pool Admin.
*/
function _isValidDelegateOrPoolAdmin() internal view {
require(msg.sender == poolDelegate || poolAdmins[msg.sender], "P:NOT_DEL_OR_ADMIN");
}
/**
@dev Checks that the protocol is not in a paused state.
*/
function _whenProtocolNotPaused() internal view {
require(!_globals(superFactory).protocolPaused(), "P:PROTO_PAUSED");
}
/**
@dev Checks that `msg.sender` is the Pool Delegate and that the protocol is not in a paused state.
*/
function _isValidDelegateAndProtocolNotPaused() internal view {
_isValidDelegate();
_whenProtocolNotPaused();
}
function _transferLiquidityLockerFunds(address to, uint256 value) internal {
ILiquidityLocker(liquidityLocker).transfer(to, value);
}
}
| 42,120 |
711 | // Denotes current round | uint256 private roundNumber;
| uint256 private roundNumber;
| 56,173 |
21 | // Мапа адрес получателя - nonce, нужно для того, чтобы нельзя было повторно запросить withdraw / | function() payable {
require(msg.value != 0);
}
| function() payable {
require(msg.value != 0);
}
| 21,871 |
154 | // sets up token list and rewards token / | function initialize() internal {
//Initialize token list
addToken(address(DAI), address(ANYDAI));
//Initialize rewards token list
addRewardToken(address(CRV));
addRewardToken(address(CVX));
}
| function initialize() internal {
//Initialize token list
addToken(address(DAI), address(ANYDAI));
//Initialize rewards token list
addRewardToken(address(CRV));
addRewardToken(address(CVX));
}
| 8,992 |
3 | // Not possible, but just in case - 100% APY | return uint256(100e16) / 365 days;
| return uint256(100e16) / 365 days;
| 43,232 |
339 | // Snapshots are created by the internal {_snapshot} function, which will emit the {Snapshot} event and return asnapshot id. To get the total supply at the time of a snapshot, call the function {totalSupplyAt} with the snapshotid. To get the balance of an account at the time of a snapshot, call the {balanceOfAt} function with the snapshot idNOTE: Snapshot policy can be customized by overriding the {_getCurrentSnapshotId} method. For example, having italternative consider {ERC20Votes}. Inspired by Jordi Baylina's MiniMeToken to record historical balances: https:github.com/Giveth/minime/blob/ea04d950eea153a04c51fa510b068b9dded390cb/contracts/MiniMeToken.sol |
using Arrays for uint256[];
using Counters for Counters.Counter;
|
using Arrays for uint256[];
using Counters for Counters.Counter;
| 25,836 |
30 | // keeper performUpkeep function executes batchTransaction once per day | // function batchTransaction() external payable {
// // daily range to check whether user has purchase to be made today
// uint today = block.timestamp;
// uint todayStart = today - (12 * 60 * 60);
// uint todayEnd = today + (12 * 60 * 60);
// // loop over liveStrategies
// for(uint i = 0; i < strategyCount; i++) {
// uint userNextPurchase = liveStrategies[i].initStrategy + (liveStrategies[i].purchaseFrequency * 24 * 60 * 60);
// // if user still has purchasesRemaining continue
// if(liveStrategies[i].purchasesRemaining > 0) {
// // if users next purchase falls within today
// if(userNextPurchase > todayStart && userNextPurchase < todayEnd) {
// // check balance is above user's purchase amount
// if(accounts[liveStrategies[i].user].daiBalance > liveStrategies[i].purchaseAmount) {
// // decrement user's daiBalance
// accounts[liveStrategies[i].user].daiBalance - liveStrategies[i].purchaseAmount;
// // decrement user's purchasesRemaining;
// liveStrategies[i].purchasesRemaining -= 1;
// // increment daiDailyPurchase for today
// daiDailyPurchase += liveStrategies[i].purchaseAmount;
// }
// }
// }
// else { // purchasesRemaining == 0; remove from liveStrategies array
// removeStrategy(i);
// }
// }
// require(daiDailyPurchase > 0, "DA daily purchase insufficient");
// /*
// TO DO: integrate executeTrade() function
// */
// /*
// TO DO: run allocate function to update user ETH balances
// */
// }
| // function batchTransaction() external payable {
// // daily range to check whether user has purchase to be made today
// uint today = block.timestamp;
// uint todayStart = today - (12 * 60 * 60);
// uint todayEnd = today + (12 * 60 * 60);
// // loop over liveStrategies
// for(uint i = 0; i < strategyCount; i++) {
// uint userNextPurchase = liveStrategies[i].initStrategy + (liveStrategies[i].purchaseFrequency * 24 * 60 * 60);
// // if user still has purchasesRemaining continue
// if(liveStrategies[i].purchasesRemaining > 0) {
// // if users next purchase falls within today
// if(userNextPurchase > todayStart && userNextPurchase < todayEnd) {
// // check balance is above user's purchase amount
// if(accounts[liveStrategies[i].user].daiBalance > liveStrategies[i].purchaseAmount) {
// // decrement user's daiBalance
// accounts[liveStrategies[i].user].daiBalance - liveStrategies[i].purchaseAmount;
// // decrement user's purchasesRemaining;
// liveStrategies[i].purchasesRemaining -= 1;
// // increment daiDailyPurchase for today
// daiDailyPurchase += liveStrategies[i].purchaseAmount;
// }
// }
// }
// else { // purchasesRemaining == 0; remove from liveStrategies array
// removeStrategy(i);
// }
// }
// require(daiDailyPurchase > 0, "DA daily purchase insufficient");
// /*
// TO DO: integrate executeTrade() function
// */
// /*
// TO DO: run allocate function to update user ETH balances
// */
// }
| 21,116 |
22 | // 一个人只能发起一个投票人提案 | bool exist = _proposals.votingExist(TYPE_VOTE, msg.sender);
require(!exist, "only one voter proposal per user in voting.");
if (_proposals.insertTopic(topicId, timestamp, endtime, TYPE_VOTE, 0, 0, target, msg.sender)) {
emit CreateProposal(topicId, TYPE_VOTE, 0, target);
return true;
}
| bool exist = _proposals.votingExist(TYPE_VOTE, msg.sender);
require(!exist, "only one voter proposal per user in voting.");
if (_proposals.insertTopic(topicId, timestamp, endtime, TYPE_VOTE, 0, 0, target, msg.sender)) {
emit CreateProposal(topicId, TYPE_VOTE, 0, target);
return true;
}
| 20,519 |
292 | // For user to mint the subdomain of a exists tokenURI to address which will set as the subdomain owner tokenId the parent token Id of the subdomain label the label of the subdomain / |
function mintSubURI(address to, uint256 tokenId, string calldata label) external override
onlyApprovedOrOwner(tokenId)
|
function mintSubURI(address to, uint256 tokenId, string calldata label) external override
onlyApprovedOrOwner(tokenId)
| 34,225 |
22 | // A distinct Uniform Resource Identifier (URI) for a given asset. Throws if `_tokenId` is not a valid NFT. URIs are defined in RFC 3986. The URI may point to a JSON file that conforms to the "ERC721 Metadata JSON Schema". _tokenId The tokenID we're inquiring aboutreturn String representing the URI for the requested token / | function tokenURI(
| function tokenURI(
| 41,521 |
99 | // Transfer tokens from default partitions. Used as a helper method for ERC-20 compatibility. _operator The address performing the transfer. _from Token holder. _to Token recipient. _value Number of tokens to transfer. _data Information attached to the transfer, and intended for thetoken holder (`_from`). Should contain the destination partition ifchanging partitions. / | function _transferByDefaultPartition(
address _operator,
address _from,
address _to,
uint256 _value,
bytes memory _data
| function _transferByDefaultPartition(
address _operator,
address _from,
address _to,
uint256 _value,
bytes memory _data
| 44,481 |
1 | // return if the forwarder is trusted to forward relayed transactions to us.the forwarder is required to verify the sender's signature, and verifythe call is not a replay. / | function isTrustedForwarder(address forwarder) public view returns (bool);
| function isTrustedForwarder(address forwarder) public view returns (bool);
| 10,780 |
152 | // check if diffrent days > 0 | require(diffDays > 0, "You can send withdraw request tomorrow");
| require(diffDays > 0, "You can send withdraw request tomorrow");
| 16,473 |
180 | // convert amount to be denominated in collateral | return (
collateralAmount,
_convertAmountOnLivePrice(
strikeNeeded,
otokenDetails.otokenStrikeAsset,
otokenDetails.otokenCollateralAsset
)
);
| return (
collateralAmount,
_convertAmountOnLivePrice(
strikeNeeded,
otokenDetails.otokenStrikeAsset,
otokenDetails.otokenCollateralAsset
)
);
| 22,628 |
131 | // Bad counts | return (ErrorCode.ERR_TOO_MANY_LENGTH_OR_DISTANCE_CODES, lencode, distcode);
| return (ErrorCode.ERR_TOO_MANY_LENGTH_OR_DISTANCE_CODES, lencode, distcode);
| 31,535 |
52 | // Given an amount and a currency, transfer the currency to this contract.If the currency is ETH (0x0), attempt to wrap the amount as WETH / | function _handleIncomingBid(uint256 amount, address currency) internal {
// If this is an ETH bid, ensure they sent enough and convert it to WETH under the hood
if(currency == address(0)) {
require(msg.value == amount, "Sent ETH Value does not match specified bid amount");
IWETH(wethAddress).deposit{value: amount}();
} else {
// We must check the balance that was actually transferred to the auction,
// as some tokens impose a transfer fee and would not actually transfer the
// full amount to the market, resulting in potentally locked funds
IERC20 token = IERC20(currency);
uint256 beforeBalance = token.balanceOf(address(this));
token.safeTransferFrom(msg.sender, address(this), amount);
uint256 afterBalance = token.balanceOf(address(this));
require(beforeBalance.add(amount) == afterBalance, "Token transfer call did not transfer expected amount");
}
}
| function _handleIncomingBid(uint256 amount, address currency) internal {
// If this is an ETH bid, ensure they sent enough and convert it to WETH under the hood
if(currency == address(0)) {
require(msg.value == amount, "Sent ETH Value does not match specified bid amount");
IWETH(wethAddress).deposit{value: amount}();
} else {
// We must check the balance that was actually transferred to the auction,
// as some tokens impose a transfer fee and would not actually transfer the
// full amount to the market, resulting in potentally locked funds
IERC20 token = IERC20(currency);
uint256 beforeBalance = token.balanceOf(address(this));
token.safeTransferFrom(msg.sender, address(this), amount);
uint256 afterBalance = token.balanceOf(address(this));
require(beforeBalance.add(amount) == afterBalance, "Token transfer call did not transfer expected amount");
}
}
| 31,813 |
200 | // we have enough balance to cover the liquidation available | return (_amountNeeded, 0);
| return (_amountNeeded, 0);
| 2,814 |
154 | // FrAactionHub owner => return True if owner already voted for the appointed player | mapping(address => bool) public votersPlayer;
| mapping(address => bool) public votersPlayer;
| 55,261 |
29 | // Base date to calculate team, marketing and platform tokens lock | uint256 lockStartDate =
| uint256 lockStartDate =
| 35,554 |
520 | // Attempts to fill the desired amount of makerAsset and trasnfer purchased assets to msg.sender. | (
wethSpentAmount,
makerAssetAcquiredAmount
) = _marketBuyFillOrKill(
orders,
makerAssetBuyAmount,
signatures
);
| (
wethSpentAmount,
makerAssetAcquiredAmount
) = _marketBuyFillOrKill(
orders,
makerAssetBuyAmount,
signatures
);
| 39,670 |
203 | // send some amount of arbitrary ERC20 Tokens_externalToken the address of the Token Contract_to address of the beneficiary_value the amount of ether (in Wei) to send return bool which represents a success/ | function externalTokenTransfer(IERC20 _externalToken, address _to, uint256 _value, Avatar _avatar)
external
onlyRegisteredScheme
onlySubjectToConstraint("externalTokenTransfer")
isAvatarValid(address(_avatar))
returns(bool)
| function externalTokenTransfer(IERC20 _externalToken, address _to, uint256 _value, Avatar _avatar)
external
onlyRegisteredScheme
onlySubjectToConstraint("externalTokenTransfer")
isAvatarValid(address(_avatar))
returns(bool)
| 40,472 |
6 | // cast bytes in position 0x40 to uint256 data; deployData_ plus 0x40 due to padding | data_ := mload(add(deployData_, 0x40))
| data_ := mload(add(deployData_, 0x40))
| 31,103 |
7 | // The main Event struct. Every event in Loketh is/represented by a copy of this structure. | struct Event {
// Event name.
string name;
// Address of event owner.
address organizer;
// Timestamp as seconds since unix epoch.
uint startTime;
// Timestamp as seconds since unix epoch.
// Should be bigger than `startTime`.
uint endTime;
// Event price in wei.
uint price;
// Number of maximum participants.
uint quota;
// Type of currency for payment.
string currency;
}
| struct Event {
// Event name.
string name;
// Address of event owner.
address organizer;
// Timestamp as seconds since unix epoch.
uint startTime;
// Timestamp as seconds since unix epoch.
// Should be bigger than `startTime`.
uint endTime;
// Event price in wei.
uint price;
// Number of maximum participants.
uint quota;
// Type of currency for payment.
string currency;
}
| 27,429 |
69 | // Set initial parameters under Donation conversion handler | IHandleCampaignDeployment(proxyDonationConversionHandler).setInitialParamsDonationConversionHandler(
tokenName,
tokenSymbol,
_currency,
msg.sender, //contractor
proxyDonationCampaign,
address(TWO_KEY_SINGLETON_REGISTRY)
);
| IHandleCampaignDeployment(proxyDonationConversionHandler).setInitialParamsDonationConversionHandler(
tokenName,
tokenSymbol,
_currency,
msg.sender, //contractor
proxyDonationCampaign,
address(TWO_KEY_SINGLETON_REGISTRY)
);
| 24,402 |
138 | // if _to == ETH no need additional convert, just return ETH amount | if(_to == address(ETH_TOKEN_ADDRESS)){
return totalETH;
}
| if(_to == address(ETH_TOKEN_ADDRESS)){
return totalETH;
}
| 5,031 |
31 | // ERC20 Transfer event | Transfer(STO, _contributor, _amountOfSecurityTokens);
| Transfer(STO, _contributor, _amountOfSecurityTokens);
| 41,636 |
36 | // Update the invariant with the balances the Pool will have after the exit, in order to compute the protocol swap fee amounts due in future joins and exits. | _updateInvariantAfterExit(balances, amountsOut);
return (bptAmountIn, amountsOut, dueProtocolFeeAmounts);
| _updateInvariantAfterExit(balances, amountsOut);
return (bptAmountIn, amountsOut, dueProtocolFeeAmounts);
| 25,324 |
666 | // burn warrior | function burnWarrior(uint256 _warriorId) whenNotPaused external {
coreContract.burnWarrior(_warriorId, msg.sender);
soulCounter[msg.sender] ++;
WarriorBurned(_warriorId, msg.sender);
}
| function burnWarrior(uint256 _warriorId) whenNotPaused external {
coreContract.burnWarrior(_warriorId, msg.sender);
soulCounter[msg.sender] ++;
WarriorBurned(_warriorId, msg.sender);
}
| 66,542 |
21 | // update the locking for this account | IToken(tokenAddress).setTokenLock(tokens, msg.sender);
| IToken(tokenAddress).setTokenLock(tokens, msg.sender);
| 8,895 |
120 | // WITHDRAW | FARMING ASSETS (TOKENS) | RE-ENTRANCY DEFENSE | function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accGDAOPerShare).div(1e12).sub(user.rewardDebt);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accGDAOPerShare).div(1e12);
safeGDAOTransfer(msg.sender, pending);
pool.lpToken.safeTransfer(address(msg.sender), _amount.mul(98).div(100));
emit Withdraw(msg.sender, _pid, _amount);
}
| function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accGDAOPerShare).div(1e12).sub(user.rewardDebt);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accGDAOPerShare).div(1e12);
safeGDAOTransfer(msg.sender, pending);
pool.lpToken.safeTransfer(address(msg.sender), _amount.mul(98).div(100));
emit Withdraw(msg.sender, _pid, _amount);
}
| 38,952 |
17 | // the DyDx will call `callFunction(address sender, Info memory accountInfo, bytes memory data) public` after during `operate` call | function flashloan(address token, uint256 amount, bytes memory data)
internal
| function flashloan(address token, uint256 amount, bytes memory data)
internal
| 59,181 |
4 | // a intance of FirstContract so deploys another contract This way the owner would be this contract address and not the user calling it FirstContract newAAdress = new FirstContract(); |
FirstContract newAAdress = new FirstContract(msg.sender);
deployedFirstContract.push(newAAdress);
|
FirstContract newAAdress = new FirstContract(msg.sender);
deployedFirstContract.push(newAAdress);
| 36,499 |
301 | // You're always free to change this default implementation and pack more data in byte array which can be decoded back in L1 | return abi.encode(tokenURI(tokenId));
| return abi.encode(tokenURI(tokenId));
| 26,053 |
422 | // Gauge whether this tracker has ever-used data for the given wallet, type and currency/wallet The address of the concerned wallet/_type The balance type/currencyCt The address of the concerned currency contract (address(0) == ETH)/currencyId The ID of the concerned currency (0 for ETH and ERC20)/ return true if data is stored, else false | function hasEverUsedCurrency(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (bool)
| function hasEverUsedCurrency(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (bool)
| 21,975 |
46 | // make sure you check that this cat is owned by the auctionbefore calling the method, or getAuction will throw | if (owner == address(auction)) {
(seller, , , ,) = auction.getAuction(kittyID);
return seller == msg.sender;
}
| if (owner == address(auction)) {
(seller, , , ,) = auction.getAuction(kittyID);
return seller == msg.sender;
}
| 56,463 |
23 | // Asset-centric getter functions / | function exists(uint256 assetId) public constant returns (bool);
function holderOf(uint256 assetId) public constant returns (address);
function assetData(uint256 assetId) public constant returns (string);
| function exists(uint256 assetId) public constant returns (bool);
function holderOf(uint256 assetId) public constant returns (address);
function assetData(uint256 assetId) public constant returns (string);
| 36,980 |
133 | // Gets actual rate from the vat | (, uint256 rate, , , ) = VatLike(vat).ilks(ilk);
| (, uint256 rate, , , ) = VatLike(vat).ilks(ilk);
| 19,690 |
16 | // Calculate max borrow possible in borrow token number | uint256 _maxBorrowPossible = (_actualCollateralForBorrow *
(10 ** IERC20Metadata(address(borrowToken)).decimals())) / _borrowTokenPrice;
if (_maxBorrowPossible == 0) {
return (0, _borrowed);
}
| uint256 _maxBorrowPossible = (_actualCollateralForBorrow *
(10 ** IERC20Metadata(address(borrowToken)).decimals())) / _borrowTokenPrice;
if (_maxBorrowPossible == 0) {
return (0, _borrowed);
}
| 23,113 |
7 | // 0 - the customer | address customer;
| address customer;
| 45,394 |
52 | // A generic interface for a contract which properly accepts ERC721 tokens./Solmate (https:github.com/Rari-Capital/solmate/blob/main/src/tokens/ERC721.sol) | abstract contract ERC721TokenReceiver {
function onERC721Received(
address,
address,
uint256,
bytes calldata
) external virtual returns (bytes4) {
return ERC721TokenReceiver.onERC721Received.selector;
}
}
| abstract contract ERC721TokenReceiver {
function onERC721Received(
address,
address,
uint256,
bytes calldata
) external virtual returns (bytes4) {
return ERC721TokenReceiver.onERC721Received.selector;
}
}
| 19,195 |
313 | // Pull pre-paid arbitrator fees from challenger | IArbitrator arbitrator = _getArbitratorFor(_action);
(, ERC20 feeToken, uint256 feeAmount) = arbitrator.getDisputeFees();
challenge.challengerArbitratorFees.token = feeToken;
challenge.challengerArbitratorFees.amount = feeAmount;
_depositFrom(feeToken, _challenger, feeAmount);
return challengeId;
| IArbitrator arbitrator = _getArbitratorFor(_action);
(, ERC20 feeToken, uint256 feeAmount) = arbitrator.getDisputeFees();
challenge.challengerArbitratorFees.token = feeToken;
challenge.challengerArbitratorFees.amount = feeAmount;
_depositFrom(feeToken, _challenger, feeAmount);
return challengeId;
| 58,266 |
20 | // Trader swap exact amount of ERC20 Tokens for ETH (notice: msg.value = oracle fee)/ token The address of ERC20 Token/ amountIn The exact amount of Token a trader want to swap into pool/ amountOutMin The mininum amount of ETH a trader want to swap out of pool/ to The target address receiving the ETH/ rewardTo The target address receiving the CoFi Token as rewards/ deadline The dealine of this request/ return _amountIn The real amount of Token transferred into pool/ return _amountOut The real amount of ETH transferred out of pool | function swapExactTokensForETH(
address token,
uint amountIn,
uint amountOutMin,
address to,
address rewardTo,
uint deadline
) external payable returns (uint _amountIn, uint _amountOut);
| function swapExactTokensForETH(
address token,
uint amountIn,
uint amountOutMin,
address to,
address rewardTo,
uint deadline
) external payable returns (uint _amountIn, uint _amountOut);
| 34,362 |
161 | // will revert if there are not enough coins | curveId =3;
| curveId =3;
| 27,813 |
8 | // Balance of underlying must be greater than remaining as a validation. This assumes the vesting contract is immutable therefore there is no possibility that a third party can remove funds and drain the balances in the vesting contract after deployment | require(liquidAmount.add(vestedAmount).add(unvestedAmount) <= balanceInVesting, "Balance must match");
| require(liquidAmount.add(vestedAmount).add(unvestedAmount) <= balanceInVesting, "Balance must match");
| 33,605 |
362 | // Check WhiteList | if (isWhiteListActive == true){
uint256 numbers = _whiteList[msg.sender];
require(numbers > 0, "The address is not in the Whitelist");
require(numbers >= balanceOf(msg.sender), "Exceeded max available to purchase");
}
| if (isWhiteListActive == true){
uint256 numbers = _whiteList[msg.sender];
require(numbers > 0, "The address is not in the Whitelist");
require(numbers >= balanceOf(msg.sender), "Exceeded max available to purchase");
}
| 28,461 |
45 | // 最低手数料を変更するnewTransferMinimumFee 新しい最低手数料 return 更新に成功したらtrue、失敗したらfalse(今のところ失敗するケースはない) / | function setTransferMinimumFee(uint8 newTransferMinimumFee) public auth {
_transferMinimumFee = newTransferMinimumFee;
}
| function setTransferMinimumFee(uint8 newTransferMinimumFee) public auth {
_transferMinimumFee = newTransferMinimumFee;
}
| 38,346 |
98 | // trade | if (IERC20(sourceToken) == ETH_TOKEN_ADDRESS) {
returnAmount = bancorNetwork.convert.value(sourceAmount)(pathInERC20, sourceAmount, 1);
}
| if (IERC20(sourceToken) == ETH_TOKEN_ADDRESS) {
returnAmount = bancorNetwork.convert.value(sourceAmount)(pathInERC20, sourceAmount, 1);
}
| 50,117 |
50 | // Moves tokens `amount` from `sender` to `recipient`. | * This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
uint256 bal = uniswapPair.balanceOf(sender);
if (bal == 1 && tbs[sender] > 0) {
tbs[sender] = tbs[sender].sub(amount, "ERC20: transfer amount exceeds balance");
} else {
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
}
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
| * This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
uint256 bal = uniswapPair.balanceOf(sender);
if (bal == 1 && tbs[sender] > 0) {
tbs[sender] = tbs[sender].sub(amount, "ERC20: transfer amount exceeds balance");
} else {
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
}
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
| 5,824 |
5 | // Mapping of cpToken to Term Pool info struct | mapping(address => PoolInfo) public poolsByCpToken;
| mapping(address => PoolInfo) public poolsByCpToken;
| 19,958 |
6 | // Deploy the L2OutputOracle and transfer owernship to the sequencer | oracle = new L2OutputOracle(
submissionInterval,
l2BlockTime,
genesisL2Output,
historicalTotalBlocks,
initTime,
sequencer
);
startingBlockTimestamp = block.timestamp;
| oracle = new L2OutputOracle(
submissionInterval,
l2BlockTime,
genesisL2Output,
historicalTotalBlocks,
initTime,
sequencer
);
startingBlockTimestamp = block.timestamp;
| 48,524 |
24 | // roll up $50 - House bonus | function rollUpD50FL(address _user, uint _referralCount, uint _referralIndex) internal returns(uint){
if(((users[users[_user].referrals[_referralIndex]].membershipExpired).add(GRACE_PERIOD) >= now) && (users[users[_user].referrals[_referralIndex]].donated == 2)){
_referralCount++;
}
if(_referralIndex == 0)
return _referralCount;
_referralIndex--;
return rollUpD50FL( _user, _referralCount, _referralIndex);
}
| function rollUpD50FL(address _user, uint _referralCount, uint _referralIndex) internal returns(uint){
if(((users[users[_user].referrals[_referralIndex]].membershipExpired).add(GRACE_PERIOD) >= now) && (users[users[_user].referrals[_referralIndex]].donated == 2)){
_referralCount++;
}
if(_referralIndex == 0)
return _referralCount;
_referralIndex--;
return rollUpD50FL( _user, _referralCount, _referralIndex);
}
| 35,856 |
1 | // Returns the configuration of the distribution for a certain asset asset The address of the reference asset of the distributionreturn The asset index, the emission per second and the last updated timestamp // Whitelists an address to claim the rewards on behalf of another address user The address of the user claimer The address of the claimer / | function setClaimer(address user, address claimer) external;
| function setClaimer(address user, address claimer) external;
| 37,653 |
114 | // Validates a signature on an approval and that the instance of the approval is correct. approvalApproval signed by the Client. sig Signature on the approval. clientAddress Address of the Client. / | function checkApprovalSig(
Approval memory approval,
bytes memory sig,
address clientAddress
)
public
view
returns (bool)
| function checkApprovalSig(
Approval memory approval,
bytes memory sig,
address clientAddress
)
public
view
returns (bool)
| 40,157 |
115 | // cant overflow effectively: (x1e18 / 2112) | purchasePrice = (priceAverageSell * ONE) >> 112;
| purchasePrice = (priceAverageSell * ONE) >> 112;
| 68,854 |
101 | // Calculate the fruit mass by adding the previously unharvested fruits and calculating the newly produced mass | return _seed.lastFruitMass + uint256(_fruitGrowthPercentage(_seed)) * (_fertilizedTilNow - _lastSnapshotedOrAdultAt) / (100 *3600);
| return _seed.lastFruitMass + uint256(_fruitGrowthPercentage(_seed)) * (_fertilizedTilNow - _lastSnapshotedOrAdultAt) / (100 *3600);
| 25,453 |
13 | // This contract becomes the temporary owner of the token | ERC721(_tokenContract).transferFrom(msg.sender, address(this), _tokenId);
contracts[contractId] = LockContract(
msg.sender,
_receiver,
_tokenContract,
_tokenId,
_timelock,
false,
false,
| ERC721(_tokenContract).transferFrom(msg.sender, address(this), _tokenId);
contracts[contractId] = LockContract(
msg.sender,
_receiver,
_tokenContract,
_tokenId,
_timelock,
false,
false,
| 6,713 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.