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 |
|---|---|---|---|---|
126 | // Calculate now if inflation has begun | if(_inflationLastCalcTime > 0) {
return (block.timestamp).sub(_inflationLastCalcTime).div(inflationInterval);
}else{
| if(_inflationLastCalcTime > 0) {
return (block.timestamp).sub(_inflationLastCalcTime).div(inflationInterval);
}else{
| 16,388 |
38 | // Public: signs up the caller as a soulliber/ | function individualSoulliberSignUp(address referee) public whenNotPaused isNotSoulliber(_msgSender()) returns (bool) {
if (referee == zero()) {
referee = router;
}
//Perform check
profs[_msgSender()].referee = referee;
profs[_msgSender()].status[Share.SOULLIBER] = true;
_complete(Categ.INDIV, _msgSender(), zero(), Share(1));
return true;
}
| function individualSoulliberSignUp(address referee) public whenNotPaused isNotSoulliber(_msgSender()) returns (bool) {
if (referee == zero()) {
referee = router;
}
//Perform check
profs[_msgSender()].referee = referee;
profs[_msgSender()].status[Share.SOULLIBER] = true;
_complete(Categ.INDIV, _msgSender(), zero(), Share(1));
return true;
}
| 45,386 |
1 | // Getters | constructor(
address _want,
uint256 _poolId,
address _pairRouter,
address _governance,
address _strategist,
address _controller,
address _timelock
)
public
| constructor(
address _want,
uint256 _poolId,
address _pairRouter,
address _governance,
address _strategist,
address _controller,
address _timelock
)
public
| 26,037 |
15 | // |
function PPBC_API() { // Constructor: ToDo: obfuscate
|
function PPBC_API() { // Constructor: ToDo: obfuscate
| 11,338 |
94 | // See {IERC721Enumerable-tokenOfOwnerByIndex}.This read function is O(collectionSize). If calling from a separate contract, be sure to test gas first.It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. / | function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
override
returns (uint256)
{
require(index < balanceOf(owner), "ERC721B: owner index out of bounds");
uint256 numMintedSoFar = totalSupply();
uint256 tokenIdsIdx = 0;
address currOwnershipAddr = address(0);
| function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
override
returns (uint256)
{
require(index < balanceOf(owner), "ERC721B: owner index out of bounds");
uint256 numMintedSoFar = totalSupply();
uint256 tokenIdsIdx = 0;
address currOwnershipAddr = address(0);
| 48,176 |
2 | // send eth to the depositFunds() function | etherStore.depositFunds{value: 1 ether}();
| etherStore.depositFunds{value: 1 ether}();
| 23,711 |
163 | // ็จๆทๅฉไฝๆชๆๅBDK,TRXๅ็บข | users[user].bSurplus += users[user].dayMine;
users[user].tSurplus += users[user].dayFund;
| users[user].bSurplus += users[user].dayMine;
users[user].tSurplus += users[user].dayFund;
| 15,100 |
32 | // Allows the upgradeability owner to upgrade the current version of the proxy and call the new implementation to initialize whatever is needed through a low level call._newVersion representing the version name of the new implementation to be set._newImplementation representing the address of the new implementation to be set._data represents the msg.data to bet sent in the low level call. This parameter may include the function signature of the implementation to be called with the needed payload/ | function upgradeToAndCall(string calldata _newVersion, address _newImplementation, bytes calldata _data) external payable ifOwner {
_upgradeToAndCall(_newVersion, _newImplementation, _data);
}
| function upgradeToAndCall(string calldata _newVersion, address _newImplementation, bytes calldata _data) external payable ifOwner {
_upgradeToAndCall(_newVersion, _newImplementation, _data);
}
| 46,718 |
11 | // Balances for each account | mapping (address => uint256) balances;
| mapping (address => uint256) balances;
| 6,805 |
113 | // Set start time and end time for Ico. _startTimeIco The Ico start time. _endTimeIco The Ico end time. / | function setStartTimeIco(uint256 _startTimeIco, uint256 _endTimeIco) onlyOwner public {
require(_startTimeIco >= now && _endTimeIco > _startTimeIco && _startTimeIco > preIcoFinishTime);
icoStartTime = _startTimeIco;
icoFinishTime = _endTimeIco;
icoInstalled = true;
}
| function setStartTimeIco(uint256 _startTimeIco, uint256 _endTimeIco) onlyOwner public {
require(_startTimeIco >= now && _endTimeIco > _startTimeIco && _startTimeIco > preIcoFinishTime);
icoStartTime = _startTimeIco;
icoFinishTime = _endTimeIco;
icoInstalled = true;
}
| 2,822 |
41 | // Peterson's Law Protection | event logTokenTransfer(address token, address to, uint amount);
| event logTokenTransfer(address token, address to, uint amount);
| 44,455 |
11 | // ONLY OWNER: Updates redemption fee on IssuanceModule._setToken Instance of the SetToken to update redeem fee for _newFee New redeem fee percentage in precise units (1% = 1e16, 100% = 1e18) / | function updateRedeemFee(ISetToken _setToken, uint256 _newFee)
external
onlyOwner(_setToken)
| function updateRedeemFee(ISetToken _setToken, uint256 _newFee)
external
onlyOwner(_setToken)
| 12,784 |
72 | // Begins iterating over resource records.self The byte string to read from.offset The offset to start reading at. return An iterator object./ | function iterateRRs(bytes memory self, uint offset) internal pure returns (RRIterator memory ret) {
ret.data = self;
ret.nextOffset = offset;
next(ret);
}
| function iterateRRs(bytes memory self, uint offset) internal pure returns (RRIterator memory ret) {
ret.data = self;
ret.nextOffset = offset;
next(ret);
}
| 26,942 |
222 | // ScaleFactor (10e18) - fee | uint256 b = CommonMath.scaleFactor().sub(_feePercentage);
return a.div(b);
| uint256 b = CommonMath.scaleFactor().sub(_feePercentage);
return a.div(b);
| 33,703 |
12 | // Governance may withdraw any amount to any address. _to Address to send funds to. _amount Amount of funds (in Ether) to send. / | function withdraw(address payable _to, uint256 _amount) external onlyGov {
_to.transfer(_amount);
}
| function withdraw(address payable _to, uint256 _amount) external onlyGov {
_to.transfer(_amount);
}
| 67,451 |
0 | // Initializes the contract setting the deployer as the initial registryRegistryAdmin. / | constructor () internal {
address msgSender = _msgSender();
_registryAdmin = msgSender;
emit RegistryManagementTransferred(address(0), msgSender);
}
| constructor () internal {
address msgSender = _msgSender();
_registryAdmin = msgSender;
emit RegistryManagementTransferred(address(0), msgSender);
}
| 14,297 |
6 | // See `UniswapV2Library.sol` | function getReserves(
address pair,
address tokenA,
address tokenB
| function getReserves(
address pair,
address tokenA,
address tokenB
| 16,617 |
209 | // Calculate the shares to mint, new price per share, and currentShareSupply is the total supply of shares currentBalance is the total balance of the vault vaultParams is the struct with vault general data vaultState is the struct with vault accounting statereturn newLockedAmount is the amount of funds to allocate for the new roundreturn queuedWithdrawAmount is the amount of funds set aside for withdrawalreturn newPricePerShare is the price per share of the new roundreturn mintShares is the amount of shares to mint from deposits / | function rollover(
uint256 currentShareSupply,
uint256 currentBalance,
Vault.VaultParams calldata vaultParams,
Vault.VaultState calldata vaultState
)
external
pure
returns (
uint256 newLockedAmount,
| function rollover(
uint256 currentShareSupply,
uint256 currentBalance,
Vault.VaultParams calldata vaultParams,
Vault.VaultState calldata vaultState
)
external
pure
returns (
uint256 newLockedAmount,
| 71,147 |
17 | // empty fallback payable to allow ETH deposits to the contract | function() public payable{
}
| function() public payable{
}
| 9,632 |
5 | // Allocate space for the buffer data | buf.capacity = capacity;
assembly {
let ptr := mload(0x40)
mstore(buf, ptr)
mstore(0x40, add(ptr, capacity))
}
| buf.capacity = capacity;
assembly {
let ptr := mload(0x40)
mstore(buf, ptr)
mstore(0x40, add(ptr, capacity))
}
| 13,067 |
58 | // disable ico phase in case if that was not disabled yet | icoPhase = false;
regularPhase = true;
| icoPhase = false;
regularPhase = true;
| 16,547 |
9 | // Deploy a new conduit using a supplied conduit key and assigningan initial owner for the deployed conduit. Note that the firsttwenty bytes of the supplied conduit key must match the callerand that a new conduit cannot be created if one has already beendeployed using the same conduit key.conduitKey The conduit key used to deploy the conduit. Note thatthe first twenty bytes of the conduit key must matchthe caller of this contract. initialOwner The initial owner to set for the new conduit. return conduit The address of the newly deployed conduit. / | function createConduit(bytes32 conduitKey, address initialOwner)
external
override
returns (address conduit)
| function createConduit(bytes32 conduitKey, address initialOwner)
external
override
returns (address conduit)
| 15,894 |
154 | // Sets the `debtAuction` parameter on Aer after the `delay` has passed./Can only be called by the guardian. After `delay` has passed it can be `execute`'d./debtAuction See. Aer | function setDebtAuction(address debtAuction) external isDelayed {
aer.setParam("debtAuction", debtAuction);
}
| function setDebtAuction(address debtAuction) external isDelayed {
aer.setParam("debtAuction", debtAuction);
}
| 58,164 |
27 | // Fallback function allows to buy ether. | function()
public
| function()
public
| 7,611 |
7 | // The SIX_DAY_EARLY for paying the subscription fee - 6 days in unix timestamp | uint public constant SIX_DAY_EARLY = 518400;
| uint public constant SIX_DAY_EARLY = 518400;
| 1,279 |
72 | // / | uint chance = uint(keccak256(abi.encodePacked(blockhash(block.number - 1), now)));
if(chance % 200 == 0) {// once in 200 times
uint prize = rnd.airdropPot / 2;// win half of the pot, regardless of how much you paid
rnd.airdropPot = rnd.airdropPot / 2;
vaults[msg.sender].totalReturns = vaults[msg.sender].totalReturns.add(prize);
unclaimedReturns = unclaimedReturns.add(prize);
totalJackpotsWon += prize;
emit AirdropWon(msg.sender, prize, now);
}
| uint chance = uint(keccak256(abi.encodePacked(blockhash(block.number - 1), now)));
if(chance % 200 == 0) {// once in 200 times
uint prize = rnd.airdropPot / 2;// win half of the pot, regardless of how much you paid
rnd.airdropPot = rnd.airdropPot / 2;
vaults[msg.sender].totalReturns = vaults[msg.sender].totalReturns.add(prize);
unclaimedReturns = unclaimedReturns.add(prize);
totalJackpotsWon += prize;
emit AirdropWon(msg.sender, prize, now);
}
| 46,591 |
67 | // Any wallet owed value that's recorded under `addressToFailedOldOwnerTransferAmount`/ can use this function to withdraw that value. | function withdrawFailedOldOwnerTransferAmount() external whenNotPaused {
uint256 failedTransferAmount = addressToFailedOldOwnerTransferAmount[msg.sender];
require(failedTransferAmount > 0);
addressToFailedOldOwnerTransferAmount[msg.sender] = 0;
totalFailedOldOwnerTransferAmounts -= failedTransferAmount;
msg.sender.transfer(failedTransferAmount);
}
| function withdrawFailedOldOwnerTransferAmount() external whenNotPaused {
uint256 failedTransferAmount = addressToFailedOldOwnerTransferAmount[msg.sender];
require(failedTransferAmount > 0);
addressToFailedOldOwnerTransferAmount[msg.sender] = 0;
totalFailedOldOwnerTransferAmounts -= failedTransferAmount;
msg.sender.transfer(failedTransferAmount);
}
| 4,887 |
13 | // return {[type]} [description] / | function getCurrentMilestone() private constant returns (Milestone) {
uint i;
uint price;
for(i=0; i<milestones.length; i++) {
if(now < milestones[i].time) {
return milestones[i-1];
}
| function getCurrentMilestone() private constant returns (Milestone) {
uint i;
uint price;
for(i=0; i<milestones.length; i++) {
if(now < milestones[i].time) {
return milestones[i-1];
}
| 4,754 |
379 | // Returns number of stages. / | function getNumberStages() external view override returns (uint256) {
return _mintStages.length;
}
| function getNumberStages() external view override returns (uint256) {
return _mintStages.length;
}
| 36,492 |
0 | // Creates a new FCNVault that is owned by the FCNProduct _asset is the address of the underlying asset _tokenName is the name of the token _tokenSymbol is the name of the token symbol / | constructor(address _asset, string memory _tokenName, string memory _tokenSymbol) ERC20(_tokenName, _tokenSymbol) {
asset = _asset;
fcnProduct = FCNProduct(owner());
}
| constructor(address _asset, string memory _tokenName, string memory _tokenSymbol) ERC20(_tokenName, _tokenSymbol) {
asset = _asset;
fcnProduct = FCNProduct(owner());
}
| 42,384 |
21 | // because we want to know how much was received, reentrancy-events is low-risk slither-disable-next-line reentrancy-events | emit Deposited(
asset,
msg.sender,
amount,
amountReceived,
block.timestamp,
initialPenaltyPercent,
commitPeriod,
tokenId
);
| emit Deposited(
asset,
msg.sender,
amount,
amountReceived,
block.timestamp,
initialPenaltyPercent,
commitPeriod,
tokenId
);
| 24,318 |
362 | // Calculates how much token1 is entitled for a particular user | function _fee1Earned(address account, uint256 fee1PerShare_) internal view returns (uint256) {
UserInfo memory user = userInfo[account];
return
balanceOf(account)
.mul(fee1PerShare_.sub(user.token1PerSharePaid))
.unsafeDiv(1e18)
.add(user.token1Rewards);
}
| function _fee1Earned(address account, uint256 fee1PerShare_) internal view returns (uint256) {
UserInfo memory user = userInfo[account];
return
balanceOf(account)
.mul(fee1PerShare_.sub(user.token1PerSharePaid))
.unsafeDiv(1e18)
.add(user.token1Rewards);
}
| 21,670 |
5 | // add owner to whitelist | _addToWhitelist(msg.sender);
| _addToWhitelist(msg.sender);
| 21,333 |
1 | // Event fired whenever a wallet address is added or removed from the list of KYCED wallet | event KYCed(address indexed _user, bool indexed _isValid);
| event KYCed(address indexed _user, bool indexed _isValid);
| 24,587 |
19 | // 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
virtual
{
require(
sender != address(0x0)
| function _transfer(
address sender,
address recipient,
uint256 amount
)
internal
virtual
{
require(
sender != address(0x0)
| 7,876 |
354 | // Aphra Vault (avToken)/Transmissions11 and JetJadeja/Flexible, minimalist, and gas-optimized yield/ aggregator for earning interest on any ERC20 token./changes from original are to rename Rari -> Aphra tokens and any usage of rvToken => avToken | contract Vault is ERC20, Auth {
using SafeCastLib for uint256;
using SafeTransferLib for ERC20;
using FixedPointMathLib for uint256;
/* //////////////////////////////////////////////////////////////
CONSTANTS
///////////////////////////////////////////////////////////// */
/// @notice The maximum number of elements allowed on the withdrawal stack.
/// @dev Needed to prevent denial of service attacks by queue operators.
uint256 internal constant MAX_WITHDRAWAL_STACK_SIZE = 32;
/* //////////////////////////////////////////////////////////////
IMMUTABLES
///////////////////////////////////////////////////////////// */
/// @notice The underlying token the Vault accepts.
ERC20 public immutable UNDERLYING;
/// @notice The base unit of the underlying token and hence avToken.
/// @dev Equal to 10 ** decimals. Used for fixed point arithmetic.
uint256 internal immutable BASE_UNIT;
/// @notice Creates a new Vault that accepts a specific underlying token.
/// @param _UNDERLYING The ERC20 compliant token the Vault should accept.
constructor(ERC20 _UNDERLYING)
ERC20(
// ex:Aphra Vader Vault
string(abi.encodePacked("Aphra ", _UNDERLYING.name(), " Vault")),
// ex: avVader
string(abi.encodePacked("av", _UNDERLYING.symbol())),
// ex: 18
_UNDERLYING.decimals()
)
Auth(Auth(msg.sender).owner(), Auth(msg.sender).authority())
{
UNDERLYING = _UNDERLYING;
BASE_UNIT = 10**decimals;
// Prevent minting of avTokens until
// the initialize function is called.
totalSupply = type(uint256).max;
}
/* //////////////////////////////////////////////////////////////
FEE CONFIGURATION
///////////////////////////////////////////////////////////// */
/// @notice The percentage of profit recognized each harvest to reserve as fees.
/// @dev A fixed point number where 1e18 represents 100% and 0 represents 0%.
uint256 public feePercent;
/// @notice Emitted when the fee percentage is updated.
/// @param user The authorized user who triggered the update.
/// @param newFeePercent The new fee percentage.
event FeePercentUpdated(address indexed user, uint256 newFeePercent);
/// @notice Sets a new fee percentage.
/// @param newFeePercent The new fee percentage.
function setFeePercent(uint256 newFeePercent) external requiresAuth {
// A fee percentage over 100% doesn't make sense.
require(newFeePercent <= 1e18, "FEE_TOO_HIGH");
// Update the fee percentage.
feePercent = newFeePercent;
emit FeePercentUpdated(msg.sender, newFeePercent);
}
/* //////////////////////////////////////////////////////////////
HARVEST CONFIGURATION
///////////////////////////////////////////////////////////// */
/// @notice Emitted when the harvest window is updated.
/// @param user The authorized user who triggered the update.
/// @param newHarvestWindow The new harvest window.
event HarvestWindowUpdated(address indexed user, uint128 newHarvestWindow);
/// @notice Emitted when the harvest delay is updated.
/// @param user The authorized user who triggered the update.
/// @param newHarvestDelay The new harvest delay.
event HarvestDelayUpdated(address indexed user, uint64 newHarvestDelay);
/// @notice Emitted when the harvest delay is scheduled to be updated next harvest.
/// @param user The authorized user who triggered the update.
/// @param newHarvestDelay The scheduled updated harvest delay.
event HarvestDelayUpdateScheduled(address indexed user, uint64 newHarvestDelay);
/// @notice The period in seconds during which multiple harvests can occur
/// regardless if they are taking place before the harvest delay has elapsed.
/// @dev Long harvest windows open the Vault up to profit distribution slowdown attacks.
uint128 public harvestWindow;
/// @notice The period in seconds over which locked profit is unlocked.
/// @dev Cannot be 0 as it opens harvests up to sandwich attacks.
uint64 public harvestDelay;
/// @notice The value that will replace harvestDelay next harvest.
/// @dev In the case that the next delay is 0, no update will be applied.
uint64 public nextHarvestDelay;
/// @notice Sets a new harvest window.
/// @param newHarvestWindow The new harvest window.
/// @dev The Vault's harvestDelay must already be set before calling.
function setHarvestWindow(uint128 newHarvestWindow) external requiresAuth {
// A harvest window longer than the harvest delay doesn't make sense.
require(newHarvestWindow <= harvestDelay, "WINDOW_TOO_LONG");
// Update the harvest window.
harvestWindow = newHarvestWindow;
emit HarvestWindowUpdated(msg.sender, newHarvestWindow);
}
/// @notice Sets a new harvest delay.
/// @param newHarvestDelay The new harvest delay to set.
/// @dev If the current harvest delay is 0, meaning it has not
/// been set before, it will be updated immediately, otherwise
/// it will be scheduled to take effect after the next harvest.
function setHarvestDelay(uint64 newHarvestDelay) external requiresAuth {
// A harvest delay of 0 makes harvests vulnerable to sandwich attacks.
require(newHarvestDelay != 0, "DELAY_CANNOT_BE_ZERO");
// A harvest delay longer than 1 year doesn't make sense.
require(newHarvestDelay <= 365 days, "DELAY_TOO_LONG");
// If the harvest delay is 0, meaning it has not been set before:
if (harvestDelay == 0) {
// We'll apply the update immediately.
harvestDelay = newHarvestDelay;
emit HarvestDelayUpdated(msg.sender, newHarvestDelay);
} else {
// We'll apply the update next harvest.
nextHarvestDelay = newHarvestDelay;
emit HarvestDelayUpdateScheduled(msg.sender, newHarvestDelay);
}
}
/* //////////////////////////////////////////////////////////////
TARGET FLOAT CONFIGURATION
///////////////////////////////////////////////////////////// */
/// @notice The desired percentage of the Vault's holdings to keep as float.
/// @dev A fixed point number where 1e18 represents 100% and 0 represents 0%.
uint256 public targetFloatPercent;
/// @notice Emitted when the target float percentage is updated.
/// @param user The authorized user who triggered the update.
/// @param newTargetFloatPercent The new target float percentage.
event TargetFloatPercentUpdated(address indexed user, uint256 newTargetFloatPercent);
/// @notice Set a new target float percentage.
/// @param newTargetFloatPercent The new target float percentage.
function setTargetFloatPercent(uint256 newTargetFloatPercent) external requiresAuth {
// A target float percentage over 100% doesn't make sense.
require(newTargetFloatPercent <= 1e18, "TARGET_TOO_HIGH");
// Update the target float percentage.
targetFloatPercent = newTargetFloatPercent;
emit TargetFloatPercentUpdated(msg.sender, newTargetFloatPercent);
}
/* //////////////////////////////////////////////////////////////
UNDERLYING IS WETH CONFIGURATION
///////////////////////////////////////////////////////////// */
/// @notice Whether the Vault should treat the underlying token as WETH compatible.
/// @dev If enabled the Vault will allow trusting strategies that accept Ether.
bool public underlyingIsWETH;
/// @notice Emitted when whether the Vault should treat the underlying as WETH is updated.
/// @param user The authorized user who triggered the update.
/// @param newUnderlyingIsWETH Whether the Vault nows treats the underlying as WETH.
event UnderlyingIsWETHUpdated(address indexed user, bool newUnderlyingIsWETH);
/// @notice Sets whether the Vault treats the underlying as WETH.
/// @param newUnderlyingIsWETH Whether the Vault should treat the underlying as WETH.
/// @dev The underlying token must have 18 decimals, to match Ether's decimal scheme.
function setUnderlyingIsWETH(bool newUnderlyingIsWETH) external requiresAuth {
// Ensure the underlying token's decimals match ETH if is WETH being set to true.
require(!newUnderlyingIsWETH || UNDERLYING.decimals() == 18, "WRONG_DECIMALS");
// Update whether the Vault treats the underlying as WETH.
underlyingIsWETH = newUnderlyingIsWETH;
emit UnderlyingIsWETHUpdated(msg.sender, newUnderlyingIsWETH);
}
/* //////////////////////////////////////////////////////////////
STRATEGY STORAGE
///////////////////////////////////////////////////////////// */
/// @notice The total amount of underlying tokens held in strategies at the time of the last harvest.
/// @dev Includes maxLockedProfit, must be correctly subtracted to compute available/free holdings.
uint256 public totalStrategyHoldings;
/// @dev Packed struct of strategy data.
/// @param trusted Whether the strategy is trusted.
/// @param balance The amount of underlying tokens held in the strategy.
struct StrategyData {
// Used to determine if the Vault will operate on a strategy.
bool trusted;
// Used to determine profit and loss during harvests of the strategy.
uint248 balance;
}
/// @notice Maps strategies to data the Vault holds on them.
mapping(Strategy => StrategyData) public getStrategyData;
/* //////////////////////////////////////////////////////////////
HARVEST STORAGE
///////////////////////////////////////////////////////////// */
/// @notice A timestamp representing when the first harvest in the most recent harvest window occurred.
/// @dev May be equal to lastHarvest if there was/has only been one harvest in the most last/current window.
uint64 public lastHarvestWindowStart;
/// @notice A timestamp representing when the most recent harvest occurred.
uint64 public lastHarvest;
/// @notice The amount of locked profit at the end of the last harvest.
uint128 public maxLockedProfit;
/* //////////////////////////////////////////////////////////////
WITHDRAWAL STACK STORAGE
///////////////////////////////////////////////////////////// */
/// @notice An ordered array of strategies representing the withdrawal stack.
/// @dev The stack is processed in descending order, meaning the last index will be withdrawn from first.
/// @dev Strategies that are untrusted, duplicated, or have no balance are filtered out when encountered at
/// withdrawal time, not validated upfront, meaning the stack may not reflect the "true" set used for withdrawals.
Strategy[] public withdrawalStack;
/// @notice Gets the full withdrawal stack.
/// @return An ordered array of strategies representing the withdrawal stack.
/// @dev This is provided because Solidity converts public arrays into index getters,
/// but we need a way to allow external contracts and users to access the whole array.
function getWithdrawalStack() external view returns (Strategy[] memory) {
return withdrawalStack;
}
/* //////////////////////////////////////////////////////////////
DEPOSIT/WITHDRAWAL LOGIC
///////////////////////////////////////////////////////////// */
/// @notice Emitted after a successful deposit.
/// @param user The address that deposited into the Vault.
/// @param underlyingAmount The amount of underlying tokens that were deposited.
event Deposit(address indexed user, uint256 underlyingAmount);
/// @notice Emitted after a successful withdrawal.
/// @param user The address that withdrew from the Vault.
/// @param underlyingAmount The amount of underlying tokens that were withdrawn.
event Withdraw(address indexed user, uint256 underlyingAmount);
/// @notice Deposit a specific amount of underlying tokens.
/// @param underlyingAmount The amount of the underlying token to deposit.
function deposit(uint256 underlyingAmount) external {
// Determine the equivalent amount of avTokens and mint them.
_mint(msg.sender, underlyingAmount.fdiv(exchangeRate(), BASE_UNIT));
emit Deposit(msg.sender, underlyingAmount);
// Transfer in underlying tokens from the user.
// This will revert if the user does not have the amount specified.
UNDERLYING.safeTransferFrom(msg.sender, address(this), underlyingAmount);
}
/// @notice Withdraw a specific amount of underlying tokens.
/// @param underlyingAmount The amount of underlying tokens to withdraw.
function withdraw(uint256 underlyingAmount) external {
// Determine the equivalent amount of avTokens and burn them.
// This will revert if the user does not have enough avTokens.
_burn(msg.sender, underlyingAmount.fdiv(exchangeRate(), BASE_UNIT));
emit Withdraw(msg.sender, underlyingAmount);
// Withdraw from strategies if needed and transfer.
transferUnderlyingTo(msg.sender, underlyingAmount);
}
/// @notice Redeem a specific amount of avTokens for underlying tokens.
/// @param avTokenAmount The amount of avTokens to redeem for underlying tokens.
function redeem(uint256 avTokenAmount) external {
// Determine the equivalent amount of underlying tokens.
uint256 underlyingAmount = avTokenAmount.fmul(exchangeRate(), BASE_UNIT);
// Burn the provided amount of avTokens.
// This will revert if the user does not have enough avTokens.
_burn(msg.sender, avTokenAmount);
emit Withdraw(msg.sender, underlyingAmount);
// Withdraw from strategies if needed and transfer.
transferUnderlyingTo(msg.sender, underlyingAmount);
}
/// @dev Transfers a specific amount of underlying tokens held in strategies and/or float to a recipient.
/// @dev Only withdraws from strategies if needed and maintains the target float percentage if possible.
/// @param recipient The user to transfer the underlying tokens to.
/// @param underlyingAmount The amount of underlying tokens to transfer.
function transferUnderlyingTo(address recipient, uint256 underlyingAmount) internal {
// Get the Vault's floating balance.
uint256 float = totalFloat();
// If the amount is greater than the float, withdraw from strategies.
if (underlyingAmount > float) {
// Compute the amount needed to reach our target float percentage.
uint256 floatMissingForTarget = (totalHoldings() - underlyingAmount).fmul(targetFloatPercent, 1e18);
// Compute the bare minimum amount we need for this withdrawal.
uint256 floatMissingForWithdrawal = underlyingAmount - float;
// Pull enough to cover the withdrawal and reach our target float percentage.
pullFromWithdrawalStack(floatMissingForWithdrawal + floatMissingForTarget);
}
// Transfer the provided amount of underlying tokens.
UNDERLYING.safeTransfer(recipient, underlyingAmount);
}
/* //////////////////////////////////////////////////////////////
VAULT ACCOUNTING LOGIC
///////////////////////////////////////////////////////////// */
/// @notice Returns a user's Vault balance in underlying tokens.
/// @param user The user to get the underlying balance of.
/// @return The user's Vault balance in underlying tokens.
function balanceOfUnderlying(address user) external view returns (uint256) {
return balanceOf[user].fmul(exchangeRate(), BASE_UNIT);
}
/// @notice Returns the amount of underlying tokens an avToken can be redeemed for.
/// @return The amount of underlying tokens an avToken can be redeemed for.
function exchangeRate() public view returns (uint256) {
// Get the total supply of avTokens.
uint256 avTokenSupply = totalSupply;
// If there are no avTokens in circulation, return an exchange rate of 1:1.
if (avTokenSupply == 0) return BASE_UNIT;
// Calculate the exchange rate by dividing the total holdings by the avToken supply.
return totalHoldings().fdiv(avTokenSupply, BASE_UNIT);
}
/// @notice Calculates the total amount of underlying tokens the Vault holds.
/// @return totalUnderlyingHeld The total amount of underlying tokens the Vault holds.
function totalHoldings() public view returns (uint256 totalUnderlyingHeld) {
unchecked {
// Cannot underflow as locked profit can't exceed total strategy holdings.
totalUnderlyingHeld = totalStrategyHoldings - lockedProfit();
}
// Include our floating balance in the total.
totalUnderlyingHeld += totalFloat();
}
/// @notice Calculates the current amount of locked profit.
/// @return The current amount of locked profit.
function lockedProfit() public view returns (uint256) {
// Get the last harvest and harvest delay.
uint256 previousHarvest = lastHarvest;
uint256 harvestInterval = harvestDelay;
unchecked {
// If the harvest delay has passed, there is no locked profit.
// Cannot overflow on human timescales since harvestInterval is capped.
if (block.timestamp >= previousHarvest + harvestInterval) return 0;
// Get the maximum amount we could return.
uint256 maximumLockedProfit = maxLockedProfit;
// Compute how much profit remains locked based on the last harvest and harvest delay.
// It's impossible for the previous harvest to be in the future, so this will never underflow.
return maximumLockedProfit - (maximumLockedProfit * (block.timestamp - previousHarvest)) / harvestInterval;
}
}
/// @notice Returns the amount of underlying tokens that idly sit in the Vault.
/// @return The amount of underlying tokens that sit idly in the Vault.
function totalFloat() public view returns (uint256) {
return UNDERLYING.balanceOf(address(this));
}
/* //////////////////////////////////////////////////////////////
HARVEST LOGIC
///////////////////////////////////////////////////////////// */
/// @notice Emitted after a successful harvest.
/// @param user The authorized user who triggered the harvest.
/// @param strategies The trusted strategies that were harvested.
event Harvest(address indexed user, Strategy[] strategies);
/// @notice Harvest a set of trusted strategies.
/// @param strategies The trusted strategies to harvest.
/// @dev Will always revert if called outside of an active
/// harvest window or before the harvest delay has passed.
function harvest(Strategy[] calldata strategies) external requiresAuth {
// If this is the first harvest after the last window:
if (block.timestamp >= lastHarvest + harvestDelay) {
// Set the harvest window's start timestamp.
// Cannot overflow 64 bits on human timescales.
lastHarvestWindowStart = uint64(block.timestamp);
} else {
// We know this harvest is not the first in the window so we need to ensure it's within it.
require(block.timestamp <= lastHarvestWindowStart + harvestWindow, "BAD_HARVEST_TIME");
}
// Get the Vault's current total strategy holdings.
uint256 oldTotalStrategyHoldings = totalStrategyHoldings;
// Used to store the total profit accrued by the strategies.
uint256 totalProfitAccrued;
// Used to store the new total strategy holdings after harvesting.
uint256 newTotalStrategyHoldings = oldTotalStrategyHoldings;
// Will revert if any of the specified strategies are untrusted.
for (uint256 i = 0; i < strategies.length; i++) {
// Get the strategy at the current index.
Strategy strategy = strategies[i];
// If an untrusted strategy could be harvested a malicious user could use
// a fake strategy that over-reports holdings to manipulate the exchange rate.
require(getStrategyData[strategy].trusted, "UNTRUSTED_STRATEGY");
// Get the strategy's previous and current balance.
uint256 balanceLastHarvest = getStrategyData[strategy].balance;
uint256 balanceThisHarvest = strategy.balanceOfUnderlying(address(this));
// Update the strategy's stored balance. Cast overflow is unrealistic.
getStrategyData[strategy].balance = balanceThisHarvest.safeCastTo248();
// Increase/decrease newTotalStrategyHoldings based on the profit/loss registered.
// We cannot wrap the subtraction in parenthesis as it would underflow if the strategy had a loss.
newTotalStrategyHoldings = newTotalStrategyHoldings + balanceThisHarvest - balanceLastHarvest;
unchecked {
// Update the total profit accrued while counting losses as zero profit.
// Cannot overflow as we already increased total holdings without reverting.
totalProfitAccrued += balanceThisHarvest > balanceLastHarvest
? balanceThisHarvest - balanceLastHarvest // Profits since last harvest.
: 0; // If the strategy registered a net loss we don't have any new profit.
}
}
// Compute fees as the fee percent multiplied by the profit.
uint256 feesAccrued = totalProfitAccrued.fmul(feePercent, 1e18);
// If we accrued any fees, mint an equivalent amount of avTokens.
// Authorized users can claim the newly minted avTokens via claimFees.
_mint(address(this), feesAccrued.fdiv(exchangeRate(), BASE_UNIT));
// Update max unlocked profit based on any remaining locked profit plus new profit.
maxLockedProfit = (lockedProfit() + totalProfitAccrued - feesAccrued).safeCastTo128();
// Set strategy holdings to our new total.
totalStrategyHoldings = newTotalStrategyHoldings;
// Update the last harvest timestamp.
// Cannot overflow on human timescales.
lastHarvest = uint64(block.timestamp);
emit Harvest(msg.sender, strategies);
// Get the next harvest delay.
uint64 newHarvestDelay = nextHarvestDelay;
// If the next harvest delay is not 0:
if (newHarvestDelay != 0) {
// Update the harvest delay.
harvestDelay = newHarvestDelay;
// Reset the next harvest delay.
nextHarvestDelay = 0;
emit HarvestDelayUpdated(msg.sender, newHarvestDelay);
}
}
/* //////////////////////////////////////////////////////////////
STRATEGY DEPOSIT/WITHDRAWAL LOGIC
///////////////////////////////////////////////////////////// */
/// @notice Emitted after the Vault deposits into a strategy contract.
/// @param user The authorized user who triggered the deposit.
/// @param strategy The strategy that was deposited into.
/// @param underlyingAmount The amount of underlying tokens that were deposited.
event StrategyDeposit(address indexed user, Strategy indexed strategy, uint256 underlyingAmount);
/// @notice Emitted after the Vault withdraws funds from a strategy contract.
/// @param user The authorized user who triggered the withdrawal.
/// @param strategy The strategy that was withdrawn from.
/// @param underlyingAmount The amount of underlying tokens that were withdrawn.
event StrategyWithdrawal(address indexed user, Strategy indexed strategy, uint256 underlyingAmount);
/// @notice Deposit a specific amount of float into a trusted strategy.
/// @param strategy The trusted strategy to deposit into.
/// @param underlyingAmount The amount of underlying tokens in float to deposit.
function depositIntoStrategy(Strategy strategy, uint256 underlyingAmount) external requiresAuth {
// A strategy must be trusted before it can be deposited into.
require(getStrategyData[strategy].trusted, "UNTRUSTED_STRATEGY");
// Increase totalStrategyHoldings to account for the deposit.
totalStrategyHoldings += underlyingAmount;
unchecked {
// Without this the next harvest would count the deposit as profit.
// Cannot overflow as the balance of one strategy can't exceed the sum of all.
getStrategyData[strategy].balance += underlyingAmount.safeCastTo248();
}
emit StrategyDeposit(msg.sender, strategy, underlyingAmount);
// We need to deposit differently if the strategy takes ETH.
if (strategy.isCEther()) {
// Unwrap the right amount of WETH.
WETH(payable(address(UNDERLYING))).withdraw(underlyingAmount);
// Deposit into the strategy and assume it will revert on error.
ETHStrategy(address(strategy)).mint{value: underlyingAmount}();
} else {
// Approve underlyingAmount to the strategy so we can deposit.
UNDERLYING.safeApprove(address(strategy), underlyingAmount);
// Deposit into the strategy and revert if it returns an error code.
require(ERC20Strategy(address(strategy)).mint(underlyingAmount) == 0, "MINT_FAILED");
}
}
/// @notice Withdraw a specific amount of underlying tokens from a strategy.
/// @param strategy The strategy to withdraw from.
/// @param underlyingAmount The amount of underlying tokens to withdraw.
/// @dev Withdrawing from a strategy will not remove it from the withdrawal stack.
function withdrawFromStrategy(Strategy strategy, uint256 underlyingAmount) external requiresAuth {
// A strategy must be trusted before it can be withdrawn from.
require(getStrategyData[strategy].trusted, "UNTRUSTED_STRATEGY");
// Without this the next harvest would count the withdrawal as a loss.
getStrategyData[strategy].balance -= underlyingAmount.safeCastTo248();
unchecked {
// Decrease totalStrategyHoldings to account for the withdrawal.
// Cannot underflow as the balance of one strategy will never exceed the sum of all.
totalStrategyHoldings -= underlyingAmount;
}
emit StrategyWithdrawal(msg.sender, strategy, underlyingAmount);
// Withdraw from the strategy and revert if it returns an error code.
require(strategy.redeemUnderlying(underlyingAmount) == 0, "REDEEM_FAILED");
// Wrap the withdrawn Ether into WETH if necessary.
if (strategy.isCEther()) WETH(payable(address(UNDERLYING))).deposit{value: underlyingAmount}();
}
/* //////////////////////////////////////////////////////////////
STRATEGY TRUST/DISTRUST LOGIC
///////////////////////////////////////////////////////////// */
/// @notice Emitted when a strategy is set to trusted.
/// @param user The authorized user who trusted the strategy.
/// @param strategy The strategy that became trusted.
event StrategyTrusted(address indexed user, Strategy indexed strategy);
/// @notice Emitted when a strategy is set to untrusted.
/// @param user The authorized user who untrusted the strategy.
/// @param strategy The strategy that became untrusted.
event StrategyDistrusted(address indexed user, Strategy indexed strategy);
/// @notice Stores a strategy as trusted, enabling it to be harvested.
/// @param strategy The strategy to make trusted.
function trustStrategy(Strategy strategy) external requiresAuth {
// Ensure the strategy accepts the correct underlying token.
// If the strategy accepts ETH the Vault should accept WETH, it'll handle wrapping when necessary.
require(
strategy.isCEther() ? underlyingIsWETH : ERC20Strategy(address(strategy)).underlying() == UNDERLYING,
"WRONG_UNDERLYING"
);
// Store the strategy as trusted.
getStrategyData[strategy].trusted = true;
emit StrategyTrusted(msg.sender, strategy);
}
/// @notice Stores a strategy as untrusted, disabling it from being harvested.
/// @param strategy The strategy to make untrusted.
function distrustStrategy(Strategy strategy) external requiresAuth {
// Store the strategy as untrusted.
getStrategyData[strategy].trusted = false;
emit StrategyDistrusted(msg.sender, strategy);
}
/* //////////////////////////////////////////////////////////////
WITHDRAWAL STACK LOGIC
///////////////////////////////////////////////////////////// */
/// @notice Emitted when a strategy is pushed to the withdrawal stack.
/// @param user The authorized user who triggered the push.
/// @param pushedStrategy The strategy pushed to the withdrawal stack.
event WithdrawalStackPushed(address indexed user, Strategy indexed pushedStrategy);
/// @notice Emitted when a strategy is popped from the withdrawal stack.
/// @param user The authorized user who triggered the pop.
/// @param poppedStrategy The strategy popped from the withdrawal stack.
event WithdrawalStackPopped(address indexed user, Strategy indexed poppedStrategy);
/// @notice Emitted when the withdrawal stack is updated.
/// @param user The authorized user who triggered the set.
/// @param replacedWithdrawalStack The new withdrawal stack.
event WithdrawalStackSet(address indexed user, Strategy[] replacedWithdrawalStack);
/// @notice Emitted when an index in the withdrawal stack is replaced.
/// @param user The authorized user who triggered the replacement.
/// @param index The index of the replaced strategy in the withdrawal stack.
/// @param replacedStrategy The strategy in the withdrawal stack that was replaced.
/// @param replacementStrategy The strategy that overrode the replaced strategy at the index.
event WithdrawalStackIndexReplaced(
address indexed user,
uint256 index,
Strategy indexed replacedStrategy,
Strategy indexed replacementStrategy
);
/// @notice Emitted when an index in the withdrawal stack is replaced with the tip.
/// @param user The authorized user who triggered the replacement.
/// @param index The index of the replaced strategy in the withdrawal stack.
/// @param replacedStrategy The strategy in the withdrawal stack replaced by the tip.
/// @param previousTipStrategy The previous tip of the stack that replaced the strategy.
event WithdrawalStackIndexReplacedWithTip(
address indexed user,
uint256 index,
Strategy indexed replacedStrategy,
Strategy indexed previousTipStrategy
);
/// @notice Emitted when the strategies at two indexes are swapped.
/// @param user The authorized user who triggered the swap.
/// @param index1 One index involved in the swap
/// @param index2 The other index involved in the swap.
/// @param newStrategy1 The strategy (previously at index2) that replaced index1.
/// @param newStrategy2 The strategy (previously at index1) that replaced index2.
event WithdrawalStackIndexesSwapped(
address indexed user,
uint256 index1,
uint256 index2,
Strategy indexed newStrategy1,
Strategy indexed newStrategy2
);
/// @dev Withdraw a specific amount of underlying tokens from strategies in the withdrawal stack.
/// @param underlyingAmount The amount of underlying tokens to pull into float.
/// @dev Automatically removes depleted strategies from the withdrawal stack.
function pullFromWithdrawalStack(uint256 underlyingAmount) internal {
// We will update this variable as we pull from strategies.
uint256 amountLeftToPull = underlyingAmount;
// We'll start at the tip of the stack and traverse backwards.
uint256 currentIndex = withdrawalStack.length - 1;
// Iterate in reverse so we pull from the stack in a "last in, first out" manner.
// Will revert due to underflow if we empty the stack before pulling the desired amount.
for (; ; currentIndex--) {
// Get the strategy at the current stack index.
Strategy strategy = withdrawalStack[currentIndex];
// Get the balance of the strategy before we withdraw from it.
uint256 strategyBalance = getStrategyData[strategy].balance;
// If the strategy is currently untrusted or was already depleted:
if (!getStrategyData[strategy].trusted || strategyBalance == 0) {
// Remove it from the stack.
withdrawalStack.pop();
emit WithdrawalStackPopped(msg.sender, strategy);
// Move onto the next strategy.
continue;
}
// We want to pull as much as we can from the strategy, but no more than we need.
uint256 amountToPull = strategyBalance > amountLeftToPull ? amountLeftToPull : strategyBalance;
unchecked {
// Compute the balance of the strategy that will remain after we withdraw.
// Cannot underflow as we cap the amount to pull at the strategy's balance.
uint256 strategyBalanceAfterWithdrawal = strategyBalance - amountToPull;
// Without this the next harvest would count the withdrawal as a loss.
getStrategyData[strategy].balance = strategyBalanceAfterWithdrawal.safeCastTo248();
// Adjust our goal based on how much we can pull from the strategy.
// Cannot underflow as we cap the amount to pull at the amount left to pull.
amountLeftToPull -= amountToPull;
emit StrategyWithdrawal(msg.sender, strategy, amountToPull);
// Withdraw from the strategy and revert if returns an error code.
require(strategy.redeemUnderlying(amountToPull) == 0, "REDEEM_FAILED");
// If we fully depleted the strategy:
if (strategyBalanceAfterWithdrawal == 0) {
// Remove it from the stack.
withdrawalStack.pop();
emit WithdrawalStackPopped(msg.sender, strategy);
}
}
// If we've pulled all we need, exit the loop.
if (amountLeftToPull == 0) break;
}
unchecked {
// Account for the withdrawals done in the loop above.
// Cannot underflow as the balances of some strategies cannot exceed the sum of all.
totalStrategyHoldings -= underlyingAmount;
}
// Cache the Vault's balance of ETH.
uint256 ethBalance = address(this).balance;
// If the Vault's underlying token is WETH compatible and we have some ETH, wrap it into WETH.
if (ethBalance != 0 && underlyingIsWETH) WETH(payable(address(UNDERLYING))).deposit{value: ethBalance}();
}
/// @notice Pushes a single strategy to front of the withdrawal stack.
/// @param strategy The strategy to be inserted at the front of the withdrawal stack.
/// @dev Strategies that are untrusted, duplicated, or have no balance are
/// filtered out when encountered at withdrawal time, not validated upfront.
function pushToWithdrawalStack(Strategy strategy) external requiresAuth {
// Ensure pushing the strategy will not cause the stack exceed its limit.
require(withdrawalStack.length < MAX_WITHDRAWAL_STACK_SIZE, "STACK_FULL");
// Push the strategy to the front of the stack.
withdrawalStack.push(strategy);
emit WithdrawalStackPushed(msg.sender, strategy);
}
/// @notice Removes the strategy at the tip of the withdrawal stack.
/// @dev Be careful, another authorized user could push a different strategy
/// than expected to the stack while a popFromWithdrawalStack transaction is pending.
function popFromWithdrawalStack() external requiresAuth {
// Get the (soon to be) popped strategy.
Strategy poppedStrategy = withdrawalStack[withdrawalStack.length - 1];
// Pop the first strategy in the stack.
withdrawalStack.pop();
emit WithdrawalStackPopped(msg.sender, poppedStrategy);
}
/// @notice Sets a new withdrawal stack.
/// @param newStack The new withdrawal stack.
/// @dev Strategies that are untrusted, duplicated, or have no balance are
/// filtered out when encountered at withdrawal time, not validated upfront.
function setWithdrawalStack(Strategy[] calldata newStack) external requiresAuth {
// Ensure the new stack is not larger than the maximum stack size.
require(newStack.length <= MAX_WITHDRAWAL_STACK_SIZE, "STACK_TOO_BIG");
// Replace the withdrawal stack.
withdrawalStack = newStack;
emit WithdrawalStackSet(msg.sender, newStack);
}
/// @notice Replaces an index in the withdrawal stack with another strategy.
/// @param index The index in the stack to replace.
/// @param replacementStrategy The strategy to override the index with.
/// @dev Strategies that are untrusted, duplicated, or have no balance are
/// filtered out when encountered at withdrawal time, not validated upfront.
function replaceWithdrawalStackIndex(uint256 index, Strategy replacementStrategy) external requiresAuth {
// Get the (soon to be) replaced strategy.
Strategy replacedStrategy = withdrawalStack[index];
// Update the index with the replacement strategy.
withdrawalStack[index] = replacementStrategy;
emit WithdrawalStackIndexReplaced(msg.sender, index, replacedStrategy, replacementStrategy);
}
/// @notice Moves the strategy at the tip of the stack to the specified index and pop the tip off the stack.
/// @param index The index of the strategy in the withdrawal stack to replace with the tip.
function replaceWithdrawalStackIndexWithTip(uint256 index) external requiresAuth {
// Get the (soon to be) previous tip and strategy we will replace at the index.
Strategy previousTipStrategy = withdrawalStack[withdrawalStack.length - 1];
Strategy replacedStrategy = withdrawalStack[index];
// Replace the index specified with the tip of the stack.
withdrawalStack[index] = previousTipStrategy;
// Remove the now duplicated tip from the array.
withdrawalStack.pop();
emit WithdrawalStackIndexReplacedWithTip(msg.sender, index, replacedStrategy, previousTipStrategy);
}
/// @notice Swaps two indexes in the withdrawal stack.
/// @param index1 One index involved in the swap
/// @param index2 The other index involved in the swap.
function swapWithdrawalStackIndexes(uint256 index1, uint256 index2) external requiresAuth {
// Get the (soon to be) new strategies at each index.
Strategy newStrategy2 = withdrawalStack[index1];
Strategy newStrategy1 = withdrawalStack[index2];
// Swap the strategies at both indexes.
withdrawalStack[index1] = newStrategy1;
withdrawalStack[index2] = newStrategy2;
emit WithdrawalStackIndexesSwapped(msg.sender, index1, index2, newStrategy1, newStrategy2);
}
/* //////////////////////////////////////////////////////////////
SEIZE STRATEGY LOGIC
///////////////////////////////////////////////////////////// */
/// @notice Emitted after a strategy is seized.
/// @param user The authorized user who triggered the seize.
/// @param strategy The strategy that was seized.
event StrategySeized(address indexed user, Strategy indexed strategy);
/// @notice Seizes a strategy.
/// @param strategy The strategy to seize.
/// @dev Intended for use in emergencies or other extraneous situations where the
/// strategy requires interaction outside of the Vault's standard operating procedures.
function seizeStrategy(Strategy strategy) external requiresAuth {
// Get the strategy's last reported balance of underlying tokens.
uint256 strategyBalance = getStrategyData[strategy].balance;
// If the strategy's balance exceeds the Vault's current
// holdings, instantly unlock any remaining locked profit.
if (strategyBalance > totalHoldings()) maxLockedProfit = 0;
// Set the strategy's balance to 0.
getStrategyData[strategy].balance = 0;
unchecked {
// Decrease totalStrategyHoldings to account for the seize.
// Cannot underflow as the balance of one strategy will never exceed the sum of all.
totalStrategyHoldings -= strategyBalance;
}
emit StrategySeized(msg.sender, strategy);
// Transfer all of the strategy's tokens to the caller.
ERC20(strategy).safeTransfer(msg.sender, strategy.balanceOf(address(this)));
}
/* //////////////////////////////////////////////////////////////
FEE CLAIM LOGIC
///////////////////////////////////////////////////////////// */
/// @notice Emitted after fees are claimed.
/// @param user The authorized user who claimed the fees.
/// @param avTokenAmount The amount of avTokens that were claimed.
event FeesClaimed(address indexed user, uint256 avTokenAmount);
/// @notice Claims fees accrued from harvests.
/// @param avTokenAmount The amount of avTokens to claim.
/// @dev Accrued fees are measured as avTokens held by the Vault.
function claimFees(uint256 avTokenAmount) external requiresAuth {
emit FeesClaimed(msg.sender, avTokenAmount);
// Transfer the provided amount of avTokens to the caller.
ERC20(this).safeTransfer(msg.sender, avTokenAmount);
}
/* //////////////////////////////////////////////////////////////
INITIALIZATION AND DESTRUCTION LOGIC
///////////////////////////////////////////////////////////// */
/// @notice Emitted when the Vault is initialized.
/// @param user The authorized user who triggered the initialization.
event Initialized(address indexed user);
/// @notice Whether the Vault has been initialized yet.
/// @dev Can go from false to true, never from true to false.
bool public isInitialized;
/// @notice Initializes the Vault, enabling it to receive deposits.
/// @dev All critical parameters must already be set before calling.
function initialize() external requiresAuth {
// Ensure the Vault has not already been initialized.
require(!isInitialized, "ALREADY_INITIALIZED");
// Mark the Vault as initialized.
isInitialized = true;
// Open for deposits.
totalSupply = 0;
emit Initialized(msg.sender);
}
/// @notice Self destructs a Vault, enabling it to be redeployed.
/// @dev Caller will receive any ETH held as float in the Vault.
function destroy() external requiresAuth {
selfdestruct(payable(msg.sender));
}
/* //////////////////////////////////////////////////////////////
RECIEVE ETHER LOGIC
///////////////////////////////////////////////////////////// */
/// @dev Required for the Vault to receive unwrapped ETH.
receive() external payable {}
}
| contract Vault is ERC20, Auth {
using SafeCastLib for uint256;
using SafeTransferLib for ERC20;
using FixedPointMathLib for uint256;
/* //////////////////////////////////////////////////////////////
CONSTANTS
///////////////////////////////////////////////////////////// */
/// @notice The maximum number of elements allowed on the withdrawal stack.
/// @dev Needed to prevent denial of service attacks by queue operators.
uint256 internal constant MAX_WITHDRAWAL_STACK_SIZE = 32;
/* //////////////////////////////////////////////////////////////
IMMUTABLES
///////////////////////////////////////////////////////////// */
/// @notice The underlying token the Vault accepts.
ERC20 public immutable UNDERLYING;
/// @notice The base unit of the underlying token and hence avToken.
/// @dev Equal to 10 ** decimals. Used for fixed point arithmetic.
uint256 internal immutable BASE_UNIT;
/// @notice Creates a new Vault that accepts a specific underlying token.
/// @param _UNDERLYING The ERC20 compliant token the Vault should accept.
constructor(ERC20 _UNDERLYING)
ERC20(
// ex:Aphra Vader Vault
string(abi.encodePacked("Aphra ", _UNDERLYING.name(), " Vault")),
// ex: avVader
string(abi.encodePacked("av", _UNDERLYING.symbol())),
// ex: 18
_UNDERLYING.decimals()
)
Auth(Auth(msg.sender).owner(), Auth(msg.sender).authority())
{
UNDERLYING = _UNDERLYING;
BASE_UNIT = 10**decimals;
// Prevent minting of avTokens until
// the initialize function is called.
totalSupply = type(uint256).max;
}
/* //////////////////////////////////////////////////////////////
FEE CONFIGURATION
///////////////////////////////////////////////////////////// */
/// @notice The percentage of profit recognized each harvest to reserve as fees.
/// @dev A fixed point number where 1e18 represents 100% and 0 represents 0%.
uint256 public feePercent;
/// @notice Emitted when the fee percentage is updated.
/// @param user The authorized user who triggered the update.
/// @param newFeePercent The new fee percentage.
event FeePercentUpdated(address indexed user, uint256 newFeePercent);
/// @notice Sets a new fee percentage.
/// @param newFeePercent The new fee percentage.
function setFeePercent(uint256 newFeePercent) external requiresAuth {
// A fee percentage over 100% doesn't make sense.
require(newFeePercent <= 1e18, "FEE_TOO_HIGH");
// Update the fee percentage.
feePercent = newFeePercent;
emit FeePercentUpdated(msg.sender, newFeePercent);
}
/* //////////////////////////////////////////////////////////////
HARVEST CONFIGURATION
///////////////////////////////////////////////////////////// */
/// @notice Emitted when the harvest window is updated.
/// @param user The authorized user who triggered the update.
/// @param newHarvestWindow The new harvest window.
event HarvestWindowUpdated(address indexed user, uint128 newHarvestWindow);
/// @notice Emitted when the harvest delay is updated.
/// @param user The authorized user who triggered the update.
/// @param newHarvestDelay The new harvest delay.
event HarvestDelayUpdated(address indexed user, uint64 newHarvestDelay);
/// @notice Emitted when the harvest delay is scheduled to be updated next harvest.
/// @param user The authorized user who triggered the update.
/// @param newHarvestDelay The scheduled updated harvest delay.
event HarvestDelayUpdateScheduled(address indexed user, uint64 newHarvestDelay);
/// @notice The period in seconds during which multiple harvests can occur
/// regardless if they are taking place before the harvest delay has elapsed.
/// @dev Long harvest windows open the Vault up to profit distribution slowdown attacks.
uint128 public harvestWindow;
/// @notice The period in seconds over which locked profit is unlocked.
/// @dev Cannot be 0 as it opens harvests up to sandwich attacks.
uint64 public harvestDelay;
/// @notice The value that will replace harvestDelay next harvest.
/// @dev In the case that the next delay is 0, no update will be applied.
uint64 public nextHarvestDelay;
/// @notice Sets a new harvest window.
/// @param newHarvestWindow The new harvest window.
/// @dev The Vault's harvestDelay must already be set before calling.
function setHarvestWindow(uint128 newHarvestWindow) external requiresAuth {
// A harvest window longer than the harvest delay doesn't make sense.
require(newHarvestWindow <= harvestDelay, "WINDOW_TOO_LONG");
// Update the harvest window.
harvestWindow = newHarvestWindow;
emit HarvestWindowUpdated(msg.sender, newHarvestWindow);
}
/// @notice Sets a new harvest delay.
/// @param newHarvestDelay The new harvest delay to set.
/// @dev If the current harvest delay is 0, meaning it has not
/// been set before, it will be updated immediately, otherwise
/// it will be scheduled to take effect after the next harvest.
function setHarvestDelay(uint64 newHarvestDelay) external requiresAuth {
// A harvest delay of 0 makes harvests vulnerable to sandwich attacks.
require(newHarvestDelay != 0, "DELAY_CANNOT_BE_ZERO");
// A harvest delay longer than 1 year doesn't make sense.
require(newHarvestDelay <= 365 days, "DELAY_TOO_LONG");
// If the harvest delay is 0, meaning it has not been set before:
if (harvestDelay == 0) {
// We'll apply the update immediately.
harvestDelay = newHarvestDelay;
emit HarvestDelayUpdated(msg.sender, newHarvestDelay);
} else {
// We'll apply the update next harvest.
nextHarvestDelay = newHarvestDelay;
emit HarvestDelayUpdateScheduled(msg.sender, newHarvestDelay);
}
}
/* //////////////////////////////////////////////////////////////
TARGET FLOAT CONFIGURATION
///////////////////////////////////////////////////////////// */
/// @notice The desired percentage of the Vault's holdings to keep as float.
/// @dev A fixed point number where 1e18 represents 100% and 0 represents 0%.
uint256 public targetFloatPercent;
/// @notice Emitted when the target float percentage is updated.
/// @param user The authorized user who triggered the update.
/// @param newTargetFloatPercent The new target float percentage.
event TargetFloatPercentUpdated(address indexed user, uint256 newTargetFloatPercent);
/// @notice Set a new target float percentage.
/// @param newTargetFloatPercent The new target float percentage.
function setTargetFloatPercent(uint256 newTargetFloatPercent) external requiresAuth {
// A target float percentage over 100% doesn't make sense.
require(newTargetFloatPercent <= 1e18, "TARGET_TOO_HIGH");
// Update the target float percentage.
targetFloatPercent = newTargetFloatPercent;
emit TargetFloatPercentUpdated(msg.sender, newTargetFloatPercent);
}
/* //////////////////////////////////////////////////////////////
UNDERLYING IS WETH CONFIGURATION
///////////////////////////////////////////////////////////// */
/// @notice Whether the Vault should treat the underlying token as WETH compatible.
/// @dev If enabled the Vault will allow trusting strategies that accept Ether.
bool public underlyingIsWETH;
/// @notice Emitted when whether the Vault should treat the underlying as WETH is updated.
/// @param user The authorized user who triggered the update.
/// @param newUnderlyingIsWETH Whether the Vault nows treats the underlying as WETH.
event UnderlyingIsWETHUpdated(address indexed user, bool newUnderlyingIsWETH);
/// @notice Sets whether the Vault treats the underlying as WETH.
/// @param newUnderlyingIsWETH Whether the Vault should treat the underlying as WETH.
/// @dev The underlying token must have 18 decimals, to match Ether's decimal scheme.
function setUnderlyingIsWETH(bool newUnderlyingIsWETH) external requiresAuth {
// Ensure the underlying token's decimals match ETH if is WETH being set to true.
require(!newUnderlyingIsWETH || UNDERLYING.decimals() == 18, "WRONG_DECIMALS");
// Update whether the Vault treats the underlying as WETH.
underlyingIsWETH = newUnderlyingIsWETH;
emit UnderlyingIsWETHUpdated(msg.sender, newUnderlyingIsWETH);
}
/* //////////////////////////////////////////////////////////////
STRATEGY STORAGE
///////////////////////////////////////////////////////////// */
/// @notice The total amount of underlying tokens held in strategies at the time of the last harvest.
/// @dev Includes maxLockedProfit, must be correctly subtracted to compute available/free holdings.
uint256 public totalStrategyHoldings;
/// @dev Packed struct of strategy data.
/// @param trusted Whether the strategy is trusted.
/// @param balance The amount of underlying tokens held in the strategy.
struct StrategyData {
// Used to determine if the Vault will operate on a strategy.
bool trusted;
// Used to determine profit and loss during harvests of the strategy.
uint248 balance;
}
/// @notice Maps strategies to data the Vault holds on them.
mapping(Strategy => StrategyData) public getStrategyData;
/* //////////////////////////////////////////////////////////////
HARVEST STORAGE
///////////////////////////////////////////////////////////// */
/// @notice A timestamp representing when the first harvest in the most recent harvest window occurred.
/// @dev May be equal to lastHarvest if there was/has only been one harvest in the most last/current window.
uint64 public lastHarvestWindowStart;
/// @notice A timestamp representing when the most recent harvest occurred.
uint64 public lastHarvest;
/// @notice The amount of locked profit at the end of the last harvest.
uint128 public maxLockedProfit;
/* //////////////////////////////////////////////////////////////
WITHDRAWAL STACK STORAGE
///////////////////////////////////////////////////////////// */
/// @notice An ordered array of strategies representing the withdrawal stack.
/// @dev The stack is processed in descending order, meaning the last index will be withdrawn from first.
/// @dev Strategies that are untrusted, duplicated, or have no balance are filtered out when encountered at
/// withdrawal time, not validated upfront, meaning the stack may not reflect the "true" set used for withdrawals.
Strategy[] public withdrawalStack;
/// @notice Gets the full withdrawal stack.
/// @return An ordered array of strategies representing the withdrawal stack.
/// @dev This is provided because Solidity converts public arrays into index getters,
/// but we need a way to allow external contracts and users to access the whole array.
function getWithdrawalStack() external view returns (Strategy[] memory) {
return withdrawalStack;
}
/* //////////////////////////////////////////////////////////////
DEPOSIT/WITHDRAWAL LOGIC
///////////////////////////////////////////////////////////// */
/// @notice Emitted after a successful deposit.
/// @param user The address that deposited into the Vault.
/// @param underlyingAmount The amount of underlying tokens that were deposited.
event Deposit(address indexed user, uint256 underlyingAmount);
/// @notice Emitted after a successful withdrawal.
/// @param user The address that withdrew from the Vault.
/// @param underlyingAmount The amount of underlying tokens that were withdrawn.
event Withdraw(address indexed user, uint256 underlyingAmount);
/// @notice Deposit a specific amount of underlying tokens.
/// @param underlyingAmount The amount of the underlying token to deposit.
function deposit(uint256 underlyingAmount) external {
// Determine the equivalent amount of avTokens and mint them.
_mint(msg.sender, underlyingAmount.fdiv(exchangeRate(), BASE_UNIT));
emit Deposit(msg.sender, underlyingAmount);
// Transfer in underlying tokens from the user.
// This will revert if the user does not have the amount specified.
UNDERLYING.safeTransferFrom(msg.sender, address(this), underlyingAmount);
}
/// @notice Withdraw a specific amount of underlying tokens.
/// @param underlyingAmount The amount of underlying tokens to withdraw.
function withdraw(uint256 underlyingAmount) external {
// Determine the equivalent amount of avTokens and burn them.
// This will revert if the user does not have enough avTokens.
_burn(msg.sender, underlyingAmount.fdiv(exchangeRate(), BASE_UNIT));
emit Withdraw(msg.sender, underlyingAmount);
// Withdraw from strategies if needed and transfer.
transferUnderlyingTo(msg.sender, underlyingAmount);
}
/// @notice Redeem a specific amount of avTokens for underlying tokens.
/// @param avTokenAmount The amount of avTokens to redeem for underlying tokens.
function redeem(uint256 avTokenAmount) external {
// Determine the equivalent amount of underlying tokens.
uint256 underlyingAmount = avTokenAmount.fmul(exchangeRate(), BASE_UNIT);
// Burn the provided amount of avTokens.
// This will revert if the user does not have enough avTokens.
_burn(msg.sender, avTokenAmount);
emit Withdraw(msg.sender, underlyingAmount);
// Withdraw from strategies if needed and transfer.
transferUnderlyingTo(msg.sender, underlyingAmount);
}
/// @dev Transfers a specific amount of underlying tokens held in strategies and/or float to a recipient.
/// @dev Only withdraws from strategies if needed and maintains the target float percentage if possible.
/// @param recipient The user to transfer the underlying tokens to.
/// @param underlyingAmount The amount of underlying tokens to transfer.
function transferUnderlyingTo(address recipient, uint256 underlyingAmount) internal {
// Get the Vault's floating balance.
uint256 float = totalFloat();
// If the amount is greater than the float, withdraw from strategies.
if (underlyingAmount > float) {
// Compute the amount needed to reach our target float percentage.
uint256 floatMissingForTarget = (totalHoldings() - underlyingAmount).fmul(targetFloatPercent, 1e18);
// Compute the bare minimum amount we need for this withdrawal.
uint256 floatMissingForWithdrawal = underlyingAmount - float;
// Pull enough to cover the withdrawal and reach our target float percentage.
pullFromWithdrawalStack(floatMissingForWithdrawal + floatMissingForTarget);
}
// Transfer the provided amount of underlying tokens.
UNDERLYING.safeTransfer(recipient, underlyingAmount);
}
/* //////////////////////////////////////////////////////////////
VAULT ACCOUNTING LOGIC
///////////////////////////////////////////////////////////// */
/// @notice Returns a user's Vault balance in underlying tokens.
/// @param user The user to get the underlying balance of.
/// @return The user's Vault balance in underlying tokens.
function balanceOfUnderlying(address user) external view returns (uint256) {
return balanceOf[user].fmul(exchangeRate(), BASE_UNIT);
}
/// @notice Returns the amount of underlying tokens an avToken can be redeemed for.
/// @return The amount of underlying tokens an avToken can be redeemed for.
function exchangeRate() public view returns (uint256) {
// Get the total supply of avTokens.
uint256 avTokenSupply = totalSupply;
// If there are no avTokens in circulation, return an exchange rate of 1:1.
if (avTokenSupply == 0) return BASE_UNIT;
// Calculate the exchange rate by dividing the total holdings by the avToken supply.
return totalHoldings().fdiv(avTokenSupply, BASE_UNIT);
}
/// @notice Calculates the total amount of underlying tokens the Vault holds.
/// @return totalUnderlyingHeld The total amount of underlying tokens the Vault holds.
function totalHoldings() public view returns (uint256 totalUnderlyingHeld) {
unchecked {
// Cannot underflow as locked profit can't exceed total strategy holdings.
totalUnderlyingHeld = totalStrategyHoldings - lockedProfit();
}
// Include our floating balance in the total.
totalUnderlyingHeld += totalFloat();
}
/// @notice Calculates the current amount of locked profit.
/// @return The current amount of locked profit.
function lockedProfit() public view returns (uint256) {
// Get the last harvest and harvest delay.
uint256 previousHarvest = lastHarvest;
uint256 harvestInterval = harvestDelay;
unchecked {
// If the harvest delay has passed, there is no locked profit.
// Cannot overflow on human timescales since harvestInterval is capped.
if (block.timestamp >= previousHarvest + harvestInterval) return 0;
// Get the maximum amount we could return.
uint256 maximumLockedProfit = maxLockedProfit;
// Compute how much profit remains locked based on the last harvest and harvest delay.
// It's impossible for the previous harvest to be in the future, so this will never underflow.
return maximumLockedProfit - (maximumLockedProfit * (block.timestamp - previousHarvest)) / harvestInterval;
}
}
/// @notice Returns the amount of underlying tokens that idly sit in the Vault.
/// @return The amount of underlying tokens that sit idly in the Vault.
function totalFloat() public view returns (uint256) {
return UNDERLYING.balanceOf(address(this));
}
/* //////////////////////////////////////////////////////////////
HARVEST LOGIC
///////////////////////////////////////////////////////////// */
/// @notice Emitted after a successful harvest.
/// @param user The authorized user who triggered the harvest.
/// @param strategies The trusted strategies that were harvested.
event Harvest(address indexed user, Strategy[] strategies);
/// @notice Harvest a set of trusted strategies.
/// @param strategies The trusted strategies to harvest.
/// @dev Will always revert if called outside of an active
/// harvest window or before the harvest delay has passed.
function harvest(Strategy[] calldata strategies) external requiresAuth {
// If this is the first harvest after the last window:
if (block.timestamp >= lastHarvest + harvestDelay) {
// Set the harvest window's start timestamp.
// Cannot overflow 64 bits on human timescales.
lastHarvestWindowStart = uint64(block.timestamp);
} else {
// We know this harvest is not the first in the window so we need to ensure it's within it.
require(block.timestamp <= lastHarvestWindowStart + harvestWindow, "BAD_HARVEST_TIME");
}
// Get the Vault's current total strategy holdings.
uint256 oldTotalStrategyHoldings = totalStrategyHoldings;
// Used to store the total profit accrued by the strategies.
uint256 totalProfitAccrued;
// Used to store the new total strategy holdings after harvesting.
uint256 newTotalStrategyHoldings = oldTotalStrategyHoldings;
// Will revert if any of the specified strategies are untrusted.
for (uint256 i = 0; i < strategies.length; i++) {
// Get the strategy at the current index.
Strategy strategy = strategies[i];
// If an untrusted strategy could be harvested a malicious user could use
// a fake strategy that over-reports holdings to manipulate the exchange rate.
require(getStrategyData[strategy].trusted, "UNTRUSTED_STRATEGY");
// Get the strategy's previous and current balance.
uint256 balanceLastHarvest = getStrategyData[strategy].balance;
uint256 balanceThisHarvest = strategy.balanceOfUnderlying(address(this));
// Update the strategy's stored balance. Cast overflow is unrealistic.
getStrategyData[strategy].balance = balanceThisHarvest.safeCastTo248();
// Increase/decrease newTotalStrategyHoldings based on the profit/loss registered.
// We cannot wrap the subtraction in parenthesis as it would underflow if the strategy had a loss.
newTotalStrategyHoldings = newTotalStrategyHoldings + balanceThisHarvest - balanceLastHarvest;
unchecked {
// Update the total profit accrued while counting losses as zero profit.
// Cannot overflow as we already increased total holdings without reverting.
totalProfitAccrued += balanceThisHarvest > balanceLastHarvest
? balanceThisHarvest - balanceLastHarvest // Profits since last harvest.
: 0; // If the strategy registered a net loss we don't have any new profit.
}
}
// Compute fees as the fee percent multiplied by the profit.
uint256 feesAccrued = totalProfitAccrued.fmul(feePercent, 1e18);
// If we accrued any fees, mint an equivalent amount of avTokens.
// Authorized users can claim the newly minted avTokens via claimFees.
_mint(address(this), feesAccrued.fdiv(exchangeRate(), BASE_UNIT));
// Update max unlocked profit based on any remaining locked profit plus new profit.
maxLockedProfit = (lockedProfit() + totalProfitAccrued - feesAccrued).safeCastTo128();
// Set strategy holdings to our new total.
totalStrategyHoldings = newTotalStrategyHoldings;
// Update the last harvest timestamp.
// Cannot overflow on human timescales.
lastHarvest = uint64(block.timestamp);
emit Harvest(msg.sender, strategies);
// Get the next harvest delay.
uint64 newHarvestDelay = nextHarvestDelay;
// If the next harvest delay is not 0:
if (newHarvestDelay != 0) {
// Update the harvest delay.
harvestDelay = newHarvestDelay;
// Reset the next harvest delay.
nextHarvestDelay = 0;
emit HarvestDelayUpdated(msg.sender, newHarvestDelay);
}
}
/* //////////////////////////////////////////////////////////////
STRATEGY DEPOSIT/WITHDRAWAL LOGIC
///////////////////////////////////////////////////////////// */
/// @notice Emitted after the Vault deposits into a strategy contract.
/// @param user The authorized user who triggered the deposit.
/// @param strategy The strategy that was deposited into.
/// @param underlyingAmount The amount of underlying tokens that were deposited.
event StrategyDeposit(address indexed user, Strategy indexed strategy, uint256 underlyingAmount);
/// @notice Emitted after the Vault withdraws funds from a strategy contract.
/// @param user The authorized user who triggered the withdrawal.
/// @param strategy The strategy that was withdrawn from.
/// @param underlyingAmount The amount of underlying tokens that were withdrawn.
event StrategyWithdrawal(address indexed user, Strategy indexed strategy, uint256 underlyingAmount);
/// @notice Deposit a specific amount of float into a trusted strategy.
/// @param strategy The trusted strategy to deposit into.
/// @param underlyingAmount The amount of underlying tokens in float to deposit.
function depositIntoStrategy(Strategy strategy, uint256 underlyingAmount) external requiresAuth {
// A strategy must be trusted before it can be deposited into.
require(getStrategyData[strategy].trusted, "UNTRUSTED_STRATEGY");
// Increase totalStrategyHoldings to account for the deposit.
totalStrategyHoldings += underlyingAmount;
unchecked {
// Without this the next harvest would count the deposit as profit.
// Cannot overflow as the balance of one strategy can't exceed the sum of all.
getStrategyData[strategy].balance += underlyingAmount.safeCastTo248();
}
emit StrategyDeposit(msg.sender, strategy, underlyingAmount);
// We need to deposit differently if the strategy takes ETH.
if (strategy.isCEther()) {
// Unwrap the right amount of WETH.
WETH(payable(address(UNDERLYING))).withdraw(underlyingAmount);
// Deposit into the strategy and assume it will revert on error.
ETHStrategy(address(strategy)).mint{value: underlyingAmount}();
} else {
// Approve underlyingAmount to the strategy so we can deposit.
UNDERLYING.safeApprove(address(strategy), underlyingAmount);
// Deposit into the strategy and revert if it returns an error code.
require(ERC20Strategy(address(strategy)).mint(underlyingAmount) == 0, "MINT_FAILED");
}
}
/// @notice Withdraw a specific amount of underlying tokens from a strategy.
/// @param strategy The strategy to withdraw from.
/// @param underlyingAmount The amount of underlying tokens to withdraw.
/// @dev Withdrawing from a strategy will not remove it from the withdrawal stack.
function withdrawFromStrategy(Strategy strategy, uint256 underlyingAmount) external requiresAuth {
// A strategy must be trusted before it can be withdrawn from.
require(getStrategyData[strategy].trusted, "UNTRUSTED_STRATEGY");
// Without this the next harvest would count the withdrawal as a loss.
getStrategyData[strategy].balance -= underlyingAmount.safeCastTo248();
unchecked {
// Decrease totalStrategyHoldings to account for the withdrawal.
// Cannot underflow as the balance of one strategy will never exceed the sum of all.
totalStrategyHoldings -= underlyingAmount;
}
emit StrategyWithdrawal(msg.sender, strategy, underlyingAmount);
// Withdraw from the strategy and revert if it returns an error code.
require(strategy.redeemUnderlying(underlyingAmount) == 0, "REDEEM_FAILED");
// Wrap the withdrawn Ether into WETH if necessary.
if (strategy.isCEther()) WETH(payable(address(UNDERLYING))).deposit{value: underlyingAmount}();
}
/* //////////////////////////////////////////////////////////////
STRATEGY TRUST/DISTRUST LOGIC
///////////////////////////////////////////////////////////// */
/// @notice Emitted when a strategy is set to trusted.
/// @param user The authorized user who trusted the strategy.
/// @param strategy The strategy that became trusted.
event StrategyTrusted(address indexed user, Strategy indexed strategy);
/// @notice Emitted when a strategy is set to untrusted.
/// @param user The authorized user who untrusted the strategy.
/// @param strategy The strategy that became untrusted.
event StrategyDistrusted(address indexed user, Strategy indexed strategy);
/// @notice Stores a strategy as trusted, enabling it to be harvested.
/// @param strategy The strategy to make trusted.
function trustStrategy(Strategy strategy) external requiresAuth {
// Ensure the strategy accepts the correct underlying token.
// If the strategy accepts ETH the Vault should accept WETH, it'll handle wrapping when necessary.
require(
strategy.isCEther() ? underlyingIsWETH : ERC20Strategy(address(strategy)).underlying() == UNDERLYING,
"WRONG_UNDERLYING"
);
// Store the strategy as trusted.
getStrategyData[strategy].trusted = true;
emit StrategyTrusted(msg.sender, strategy);
}
/// @notice Stores a strategy as untrusted, disabling it from being harvested.
/// @param strategy The strategy to make untrusted.
function distrustStrategy(Strategy strategy) external requiresAuth {
// Store the strategy as untrusted.
getStrategyData[strategy].trusted = false;
emit StrategyDistrusted(msg.sender, strategy);
}
/* //////////////////////////////////////////////////////////////
WITHDRAWAL STACK LOGIC
///////////////////////////////////////////////////////////// */
/// @notice Emitted when a strategy is pushed to the withdrawal stack.
/// @param user The authorized user who triggered the push.
/// @param pushedStrategy The strategy pushed to the withdrawal stack.
event WithdrawalStackPushed(address indexed user, Strategy indexed pushedStrategy);
/// @notice Emitted when a strategy is popped from the withdrawal stack.
/// @param user The authorized user who triggered the pop.
/// @param poppedStrategy The strategy popped from the withdrawal stack.
event WithdrawalStackPopped(address indexed user, Strategy indexed poppedStrategy);
/// @notice Emitted when the withdrawal stack is updated.
/// @param user The authorized user who triggered the set.
/// @param replacedWithdrawalStack The new withdrawal stack.
event WithdrawalStackSet(address indexed user, Strategy[] replacedWithdrawalStack);
/// @notice Emitted when an index in the withdrawal stack is replaced.
/// @param user The authorized user who triggered the replacement.
/// @param index The index of the replaced strategy in the withdrawal stack.
/// @param replacedStrategy The strategy in the withdrawal stack that was replaced.
/// @param replacementStrategy The strategy that overrode the replaced strategy at the index.
event WithdrawalStackIndexReplaced(
address indexed user,
uint256 index,
Strategy indexed replacedStrategy,
Strategy indexed replacementStrategy
);
/// @notice Emitted when an index in the withdrawal stack is replaced with the tip.
/// @param user The authorized user who triggered the replacement.
/// @param index The index of the replaced strategy in the withdrawal stack.
/// @param replacedStrategy The strategy in the withdrawal stack replaced by the tip.
/// @param previousTipStrategy The previous tip of the stack that replaced the strategy.
event WithdrawalStackIndexReplacedWithTip(
address indexed user,
uint256 index,
Strategy indexed replacedStrategy,
Strategy indexed previousTipStrategy
);
/// @notice Emitted when the strategies at two indexes are swapped.
/// @param user The authorized user who triggered the swap.
/// @param index1 One index involved in the swap
/// @param index2 The other index involved in the swap.
/// @param newStrategy1 The strategy (previously at index2) that replaced index1.
/// @param newStrategy2 The strategy (previously at index1) that replaced index2.
event WithdrawalStackIndexesSwapped(
address indexed user,
uint256 index1,
uint256 index2,
Strategy indexed newStrategy1,
Strategy indexed newStrategy2
);
/// @dev Withdraw a specific amount of underlying tokens from strategies in the withdrawal stack.
/// @param underlyingAmount The amount of underlying tokens to pull into float.
/// @dev Automatically removes depleted strategies from the withdrawal stack.
function pullFromWithdrawalStack(uint256 underlyingAmount) internal {
// We will update this variable as we pull from strategies.
uint256 amountLeftToPull = underlyingAmount;
// We'll start at the tip of the stack and traverse backwards.
uint256 currentIndex = withdrawalStack.length - 1;
// Iterate in reverse so we pull from the stack in a "last in, first out" manner.
// Will revert due to underflow if we empty the stack before pulling the desired amount.
for (; ; currentIndex--) {
// Get the strategy at the current stack index.
Strategy strategy = withdrawalStack[currentIndex];
// Get the balance of the strategy before we withdraw from it.
uint256 strategyBalance = getStrategyData[strategy].balance;
// If the strategy is currently untrusted or was already depleted:
if (!getStrategyData[strategy].trusted || strategyBalance == 0) {
// Remove it from the stack.
withdrawalStack.pop();
emit WithdrawalStackPopped(msg.sender, strategy);
// Move onto the next strategy.
continue;
}
// We want to pull as much as we can from the strategy, but no more than we need.
uint256 amountToPull = strategyBalance > amountLeftToPull ? amountLeftToPull : strategyBalance;
unchecked {
// Compute the balance of the strategy that will remain after we withdraw.
// Cannot underflow as we cap the amount to pull at the strategy's balance.
uint256 strategyBalanceAfterWithdrawal = strategyBalance - amountToPull;
// Without this the next harvest would count the withdrawal as a loss.
getStrategyData[strategy].balance = strategyBalanceAfterWithdrawal.safeCastTo248();
// Adjust our goal based on how much we can pull from the strategy.
// Cannot underflow as we cap the amount to pull at the amount left to pull.
amountLeftToPull -= amountToPull;
emit StrategyWithdrawal(msg.sender, strategy, amountToPull);
// Withdraw from the strategy and revert if returns an error code.
require(strategy.redeemUnderlying(amountToPull) == 0, "REDEEM_FAILED");
// If we fully depleted the strategy:
if (strategyBalanceAfterWithdrawal == 0) {
// Remove it from the stack.
withdrawalStack.pop();
emit WithdrawalStackPopped(msg.sender, strategy);
}
}
// If we've pulled all we need, exit the loop.
if (amountLeftToPull == 0) break;
}
unchecked {
// Account for the withdrawals done in the loop above.
// Cannot underflow as the balances of some strategies cannot exceed the sum of all.
totalStrategyHoldings -= underlyingAmount;
}
// Cache the Vault's balance of ETH.
uint256 ethBalance = address(this).balance;
// If the Vault's underlying token is WETH compatible and we have some ETH, wrap it into WETH.
if (ethBalance != 0 && underlyingIsWETH) WETH(payable(address(UNDERLYING))).deposit{value: ethBalance}();
}
/// @notice Pushes a single strategy to front of the withdrawal stack.
/// @param strategy The strategy to be inserted at the front of the withdrawal stack.
/// @dev Strategies that are untrusted, duplicated, or have no balance are
/// filtered out when encountered at withdrawal time, not validated upfront.
function pushToWithdrawalStack(Strategy strategy) external requiresAuth {
// Ensure pushing the strategy will not cause the stack exceed its limit.
require(withdrawalStack.length < MAX_WITHDRAWAL_STACK_SIZE, "STACK_FULL");
// Push the strategy to the front of the stack.
withdrawalStack.push(strategy);
emit WithdrawalStackPushed(msg.sender, strategy);
}
/// @notice Removes the strategy at the tip of the withdrawal stack.
/// @dev Be careful, another authorized user could push a different strategy
/// than expected to the stack while a popFromWithdrawalStack transaction is pending.
function popFromWithdrawalStack() external requiresAuth {
// Get the (soon to be) popped strategy.
Strategy poppedStrategy = withdrawalStack[withdrawalStack.length - 1];
// Pop the first strategy in the stack.
withdrawalStack.pop();
emit WithdrawalStackPopped(msg.sender, poppedStrategy);
}
/// @notice Sets a new withdrawal stack.
/// @param newStack The new withdrawal stack.
/// @dev Strategies that are untrusted, duplicated, or have no balance are
/// filtered out when encountered at withdrawal time, not validated upfront.
function setWithdrawalStack(Strategy[] calldata newStack) external requiresAuth {
// Ensure the new stack is not larger than the maximum stack size.
require(newStack.length <= MAX_WITHDRAWAL_STACK_SIZE, "STACK_TOO_BIG");
// Replace the withdrawal stack.
withdrawalStack = newStack;
emit WithdrawalStackSet(msg.sender, newStack);
}
/// @notice Replaces an index in the withdrawal stack with another strategy.
/// @param index The index in the stack to replace.
/// @param replacementStrategy The strategy to override the index with.
/// @dev Strategies that are untrusted, duplicated, or have no balance are
/// filtered out when encountered at withdrawal time, not validated upfront.
function replaceWithdrawalStackIndex(uint256 index, Strategy replacementStrategy) external requiresAuth {
// Get the (soon to be) replaced strategy.
Strategy replacedStrategy = withdrawalStack[index];
// Update the index with the replacement strategy.
withdrawalStack[index] = replacementStrategy;
emit WithdrawalStackIndexReplaced(msg.sender, index, replacedStrategy, replacementStrategy);
}
/// @notice Moves the strategy at the tip of the stack to the specified index and pop the tip off the stack.
/// @param index The index of the strategy in the withdrawal stack to replace with the tip.
function replaceWithdrawalStackIndexWithTip(uint256 index) external requiresAuth {
// Get the (soon to be) previous tip and strategy we will replace at the index.
Strategy previousTipStrategy = withdrawalStack[withdrawalStack.length - 1];
Strategy replacedStrategy = withdrawalStack[index];
// Replace the index specified with the tip of the stack.
withdrawalStack[index] = previousTipStrategy;
// Remove the now duplicated tip from the array.
withdrawalStack.pop();
emit WithdrawalStackIndexReplacedWithTip(msg.sender, index, replacedStrategy, previousTipStrategy);
}
/// @notice Swaps two indexes in the withdrawal stack.
/// @param index1 One index involved in the swap
/// @param index2 The other index involved in the swap.
function swapWithdrawalStackIndexes(uint256 index1, uint256 index2) external requiresAuth {
// Get the (soon to be) new strategies at each index.
Strategy newStrategy2 = withdrawalStack[index1];
Strategy newStrategy1 = withdrawalStack[index2];
// Swap the strategies at both indexes.
withdrawalStack[index1] = newStrategy1;
withdrawalStack[index2] = newStrategy2;
emit WithdrawalStackIndexesSwapped(msg.sender, index1, index2, newStrategy1, newStrategy2);
}
/* //////////////////////////////////////////////////////////////
SEIZE STRATEGY LOGIC
///////////////////////////////////////////////////////////// */
/// @notice Emitted after a strategy is seized.
/// @param user The authorized user who triggered the seize.
/// @param strategy The strategy that was seized.
event StrategySeized(address indexed user, Strategy indexed strategy);
/// @notice Seizes a strategy.
/// @param strategy The strategy to seize.
/// @dev Intended for use in emergencies or other extraneous situations where the
/// strategy requires interaction outside of the Vault's standard operating procedures.
function seizeStrategy(Strategy strategy) external requiresAuth {
// Get the strategy's last reported balance of underlying tokens.
uint256 strategyBalance = getStrategyData[strategy].balance;
// If the strategy's balance exceeds the Vault's current
// holdings, instantly unlock any remaining locked profit.
if (strategyBalance > totalHoldings()) maxLockedProfit = 0;
// Set the strategy's balance to 0.
getStrategyData[strategy].balance = 0;
unchecked {
// Decrease totalStrategyHoldings to account for the seize.
// Cannot underflow as the balance of one strategy will never exceed the sum of all.
totalStrategyHoldings -= strategyBalance;
}
emit StrategySeized(msg.sender, strategy);
// Transfer all of the strategy's tokens to the caller.
ERC20(strategy).safeTransfer(msg.sender, strategy.balanceOf(address(this)));
}
/* //////////////////////////////////////////////////////////////
FEE CLAIM LOGIC
///////////////////////////////////////////////////////////// */
/// @notice Emitted after fees are claimed.
/// @param user The authorized user who claimed the fees.
/// @param avTokenAmount The amount of avTokens that were claimed.
event FeesClaimed(address indexed user, uint256 avTokenAmount);
/// @notice Claims fees accrued from harvests.
/// @param avTokenAmount The amount of avTokens to claim.
/// @dev Accrued fees are measured as avTokens held by the Vault.
function claimFees(uint256 avTokenAmount) external requiresAuth {
emit FeesClaimed(msg.sender, avTokenAmount);
// Transfer the provided amount of avTokens to the caller.
ERC20(this).safeTransfer(msg.sender, avTokenAmount);
}
/* //////////////////////////////////////////////////////////////
INITIALIZATION AND DESTRUCTION LOGIC
///////////////////////////////////////////////////////////// */
/// @notice Emitted when the Vault is initialized.
/// @param user The authorized user who triggered the initialization.
event Initialized(address indexed user);
/// @notice Whether the Vault has been initialized yet.
/// @dev Can go from false to true, never from true to false.
bool public isInitialized;
/// @notice Initializes the Vault, enabling it to receive deposits.
/// @dev All critical parameters must already be set before calling.
function initialize() external requiresAuth {
// Ensure the Vault has not already been initialized.
require(!isInitialized, "ALREADY_INITIALIZED");
// Mark the Vault as initialized.
isInitialized = true;
// Open for deposits.
totalSupply = 0;
emit Initialized(msg.sender);
}
/// @notice Self destructs a Vault, enabling it to be redeployed.
/// @dev Caller will receive any ETH held as float in the Vault.
function destroy() external requiresAuth {
selfdestruct(payable(msg.sender));
}
/* //////////////////////////////////////////////////////////////
RECIEVE ETHER LOGIC
///////////////////////////////////////////////////////////// */
/// @dev Required for the Vault to receive unwrapped ETH.
receive() external payable {}
}
| 26,000 |
21 | // UPDATE uGOV multiplier | function _updateUGOVMultiplier() internal {
// (1.05/(1+abs(1-TWAP_PRICE)))
uint256 currentPrice = _getTwapPrice();
bool isPriceDiffEnough = false;
// a minimum price variation is needed to update the multiplier
if (currentPrice > lastPrice) {
isPriceDiffEnough =
currentPrice - lastPrice > minPriceDiffToUpdateMultiplier;
} else {
isPriceDiffEnough =
lastPrice - currentPrice > minPriceDiffToUpdateMultiplier;
}
if (isPriceDiffEnough) {
uGOVmultiplier = IUbiquityFormulas(manager.formulasAddress())
.ugovMultiply(uGOVmultiplier, currentPrice);
lastPrice = currentPrice;
}
}
| function _updateUGOVMultiplier() internal {
// (1.05/(1+abs(1-TWAP_PRICE)))
uint256 currentPrice = _getTwapPrice();
bool isPriceDiffEnough = false;
// a minimum price variation is needed to update the multiplier
if (currentPrice > lastPrice) {
isPriceDiffEnough =
currentPrice - lastPrice > minPriceDiffToUpdateMultiplier;
} else {
isPriceDiffEnough =
lastPrice - currentPrice > minPriceDiffToUpdateMultiplier;
}
if (isPriceDiffEnough) {
uGOVmultiplier = IUbiquityFormulas(manager.formulasAddress())
.ugovMultiply(uGOVmultiplier, currentPrice);
lastPrice = currentPrice;
}
}
| 13,393 |
117 | // Test function to add shared funds and resources to a tile./ Any ether paid to this function will be added to the shared funds/ of the tile./x X coordinate of tile./y Y coordinate of tile./y Y Resources to add. | function __fundTileAt(
int32 x,
int32 y,
| function __fundTileAt(
int32 x,
int32 y,
| 15,500 |
5 | // check the collection exists | require((collection > 0 && collection <= _collectionCount.current()), "Nonexistant Collection ID");
uint256 id = _tokenIds.current();
artwork[id] = Artwork(hash, collection);
_safeMint(msg.sender, id);
_tokenIds.increment();
collections[collection].count++;
_setTokenURI(id, uri);
return id;
| require((collection > 0 && collection <= _collectionCount.current()), "Nonexistant Collection ID");
uint256 id = _tokenIds.current();
artwork[id] = Artwork(hash, collection);
_safeMint(msg.sender, id);
_tokenIds.increment();
collections[collection].count++;
_setTokenURI(id, uri);
return id;
| 6,919 |
94 | // Generates an SVG <linearGradient> element based on a points array and stop colors/id The id of the linear gradient/points The encoded points array/stop1 The first stop attribute/stop2 The second stop attribute/ return A <linearGradient> element as bytes | function linearGradient(bytes memory id, bytes memory points, bytes memory stop1, bytes memory stop2) external view returns (bytes memory);
| function linearGradient(bytes memory id, bytes memory points, bytes memory stop1, bytes memory stop2) external view returns (bytes memory);
| 32,976 |
32 | // Sort numerators | uint256 numMax = _numB;
uint256 numMin = _numA;
if (_numA > _numB) {
numMax = _numA;
numMin = _numB;
}
| uint256 numMax = _numB;
uint256 numMin = _numA;
if (_numA > _numB) {
numMax = _numA;
numMin = _numB;
}
| 15,843 |
60 | // Guarantees that _tokenId is a valid Token. _tokenId ID of the NFT to validate. / | modifier validNFToken(
uint256 _tokenId
)
| modifier validNFToken(
uint256 _tokenId
)
| 3,782 |
50 | // Create a new role identifier for the controller role | bytes32 public constant CONTROLLER_ROLE = keccak256("CONTROLLER_ROLE");
| bytes32 public constant CONTROLLER_ROLE = keccak256("CONTROLLER_ROLE");
| 3,026 |
10 | // Add the length of _postBytes to the current length of tempBytes and store it as the new length in the first 32 bytes of the tempBytes memory. | length := mload(_postBytes)
mstore(tempBytes, add(length, mload(tempBytes)))
| length := mload(_postBytes)
mstore(tempBytes, add(length, mload(tempBytes)))
| 19,875 |
33 | // `creationBlock` is the block number that the Clone Token was created | uint public creationBlock;
| uint public creationBlock;
| 19,870 |
29 | // Transfers xTokens in the event of a borrow being liquidated, in case the liquidators reclaims the xToken- Only callable by the MarginPool from The address getting liquidated, current owner of the xTokens to The recipient value The amount of tokens getting transferred / | ) external override onlyMarginPool updateReward(from) updateReward(to) {
// Being a normal transfer, the Transfer() and BalanceTransfer() are emitted
// so no need to emit a specific event here
_transfer(from, to, value, false);
emit Transfer(from, to, value);
}
| ) external override onlyMarginPool updateReward(from) updateReward(to) {
// Being a normal transfer, the Transfer() and BalanceTransfer() are emitted
// so no need to emit a specific event here
_transfer(from, to, value, false);
emit Transfer(from, to, value);
}
| 69,207 |
27 | // Removes given addresses from the active reporters control list./Can only be called from the owner address./Emits the `ReportersUnset` event. /_exReporters List of addresses to be added to the active reporters control list. | function unsetReporters(address[] memory _exReporters)
public
override
onlyOwner
| function unsetReporters(address[] memory _exReporters)
public
override
onlyOwner
| 26,416 |
151 | // Create an instance of Bekk NFT contract / | constructor(
string memory _baseURI,
address[] memory payees,
uint256[] memory shares_
| constructor(
string memory _baseURI,
address[] memory payees,
uint256[] memory shares_
| 45,103 |
3 | // closeRoundBlock to close it. |
LOCKED, // @dev Round is locked, not accepting new bids, waiting to
|
LOCKED, // @dev Round is locked, not accepting new bids, waiting to
| 20,799 |
54 | // Signal the completion of a round and the start of the next by moving RoundId forward one.As clean-up before the round change occurs, join all unclaimed player bonuses together and move themforward one round. Just-in-time initialize the next round's state once RoundId is pointing to it becausean unknown number of rounds may be played. So, it's impossible to initialize all rounds at contract creation. / | function advanceRound() private {
if (RoundId > 1) {
// Take all of the previous rounds unclaimed bonuses and roll them forward.
Round storage previousRound = Rounds[RoundId.sub(1)];
// If the active player of the previous round didn't claim their refund then they lose the ability to claim it.
// Their refund is also rolled into the bonuses for the next round.
uint remainingBonus = previousRound.totalBonus.add(INITIAL_PRICE).sub(previousRound.claimedBonus);
Rounds[RoundId].totalBonus = Rounds[RoundId].totalBonus.add(remainingBonus);
}
RoundId = RoundId.add(1);
initializeRound();
}
| function advanceRound() private {
if (RoundId > 1) {
// Take all of the previous rounds unclaimed bonuses and roll them forward.
Round storage previousRound = Rounds[RoundId.sub(1)];
// If the active player of the previous round didn't claim their refund then they lose the ability to claim it.
// Their refund is also rolled into the bonuses for the next round.
uint remainingBonus = previousRound.totalBonus.add(INITIAL_PRICE).sub(previousRound.claimedBonus);
Rounds[RoundId].totalBonus = Rounds[RoundId].totalBonus.add(remainingBonus);
}
RoundId = RoundId.add(1);
initializeRound();
}
| 13,887 |
91 | // Verify the canonical block header using the computed sha3Uncles. | assembly {
blobLength := and(calldataload(sub(offset, 30)), 0xffff)
shift := and(calldataload(sub(offset, 28)), 0xffff)
}
| assembly {
blobLength := and(calldataload(sub(offset, 30)), 0xffff)
shift := and(calldataload(sub(offset, 28)), 0xffff)
}
| 38,482 |
90 | // Submit a reference to evidence. EVENT._claimID The index of the claim._evidence A link to an evidence using its URI. / | function submitEvidence(uint256 _claimID, string memory _evidence) public {
Claim storage claim = claims[_claimID];
Transaction storage transaction = transactions[claim.transactionID];
require(claim.status < Status.Resolved, "Must not send evidence if the dispute is resolved.");
emit Evidence(transaction.arbitrator, _claimID, _msgSender(), _evidence);
}
| function submitEvidence(uint256 _claimID, string memory _evidence) public {
Claim storage claim = claims[_claimID];
Transaction storage transaction = transactions[claim.transactionID];
require(claim.status < Status.Resolved, "Must not send evidence if the dispute is resolved.");
emit Evidence(transaction.arbitrator, _claimID, _msgSender(), _evidence);
}
| 18,236 |
52 | // proof.PI_Z | mstore(mload(add(proof_ptr, 0x320)), mod(calldataload(add(data_ptr, 0x460)), q))
mstore(add(mload(add(proof_ptr, 0x320)), 0x20), mod(calldataload(add(data_ptr, 0x440)), q))
| mstore(mload(add(proof_ptr, 0x320)), mod(calldataload(add(data_ptr, 0x460)), q))
mstore(add(mload(add(proof_ptr, 0x320)), 0x20), mod(calldataload(add(data_ptr, 0x440)), q))
| 18,195 |
4 | // list of Bitcoin addresses | string[] private bitcoinAddresses;
| string[] private bitcoinAddresses;
| 45,512 |
1 | // These 3 variables below are hard coded for testing purposes only. Can be removed for generic usage. _svg = "<svg xmlns='http:www.w3.org/2000/svg' aria-label='Plex' role='img' viewBox='0 0 512 512'><rect width='512' height='512' rx='15%' fill='282a2d'/><path d='m256 70h-108l108 186-108 186h108l108-186z' fill='e5a00d'/></svg>"; tokenID = 0 ; _description = "plex.svg" ; | 3,017 | ||
96 | // add to previous rewards | return (s.rewards + userNewReward);
| return (s.rewards + userNewReward);
| 11,817 |
53 | // Returns the keccak-256 hash of the slice. self The slice to hash.return The hash of the slice. / | function keccak(slice self) internal returns (bytes32 ret) {
assembly {
ret := sha3(mload(add(self, 32)), mload(self))
}
}
| function keccak(slice self) internal returns (bytes32 ret) {
assembly {
ret := sha3(mload(add(self, 32)), mload(self))
}
}
| 3,008 |
106 | // contracts/MplRewards.sol/ pragma solidity 0.6.11; // import "lib/openzeppelin-contracts/contracts/access/Ownable.sol"; // import "lib/openzeppelin-contracts/contracts/math/Math.sol"; // import "lib/openzeppelin-contracts/contracts/math/SafeMath.sol"; // import "lib/openzeppelin-contracts/contracts/token/ERC20/SafeERC20.sol"; // import "./interfaces/IERC2258.sol"; / https:docs.synthetix.io/contracts/source/contracts/stakingrewards/MplRewards Synthetix farming contract fork for liquidity mining. | contract MplRewards is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
IERC20 public immutable rewardsToken;
IERC2258 public immutable stakingToken;
uint256 public periodFinish;
uint256 public rewardRate;
uint256 public rewardsDuration;
uint256 public lastUpdateTime;
uint256 public rewardPerTokenStored;
uint256 public lastPauseTime;
bool public paused;
mapping(address => uint256) public userRewardPerTokenPaid;
mapping(address => uint256) public rewards;
uint256 private _totalSupply;
mapping(address => uint256) private _balances;
event RewardAdded(uint256 reward);
event Staked(address indexed account, uint256 amount);
event Withdrawn(address indexed account, uint256 amount);
event RewardPaid(address indexed account, uint256 reward);
event RewardsDurationUpdated(uint256 newDuration);
event Recovered(address token, uint256 amount);
event PauseChanged(bool isPaused);
constructor(address _rewardsToken, address _stakingToken, address _owner) public {
rewardsToken = IERC20(_rewardsToken);
stakingToken = IERC2258(_stakingToken);
rewardsDuration = 7 days;
transferOwnership(_owner);
}
function _updateReward(address account) internal {
uint256 _rewardPerTokenStored = rewardPerToken();
rewardPerTokenStored = _rewardPerTokenStored;
lastUpdateTime = lastTimeRewardApplicable();
if (account != address(0)) {
rewards[account] = earned(account);
userRewardPerTokenPaid[account] = _rewardPerTokenStored;
}
}
function _notPaused() internal view {
require(!paused, "R:PAUSED");
}
function totalSupply() external view returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) external view returns (uint256) {
return _balances[account];
}
function lastTimeRewardApplicable() public view returns (uint256) {
return Math.min(block.timestamp, periodFinish);
}
function rewardPerToken() public view returns (uint256) {
return _totalSupply == 0
? rewardPerTokenStored
: rewardPerTokenStored.add(
lastTimeRewardApplicable().sub(lastUpdateTime).mul(rewardRate).mul(1e18).div(_totalSupply)
);
}
function earned(address account) public view returns (uint256) {
return _balances[account].mul(rewardPerToken().sub(userRewardPerTokenPaid[account])).div(1e18).add(rewards[account]);
}
function getRewardForDuration() external view returns (uint256) {
return rewardRate.mul(rewardsDuration);
}
/**
@dev It emits a `Staked` event.
*/
function stake(uint256 amount) external {
_notPaused();
_updateReward(msg.sender);
uint256 newBalance = _balances[msg.sender].add(amount);
require(amount > 0, "R:ZERO_STAKE");
require(stakingToken.custodyAllowance(msg.sender, address(this)) >= newBalance, "R:INSUF_CUST_ALLOWANCE");
_totalSupply = _totalSupply.add(amount);
_balances[msg.sender] = newBalance;
emit Staked(msg.sender, amount);
}
/**
@dev It emits a `Withdrawn` event.
*/
function withdraw(uint256 amount) public {
_notPaused();
_updateReward(msg.sender);
require(amount > 0, "R:ZERO_WITHDRAW");
_totalSupply = _totalSupply.sub(amount);
_balances[msg.sender] = _balances[msg.sender].sub(amount);
stakingToken.transferByCustodian(msg.sender, msg.sender, amount);
emit Withdrawn(msg.sender, amount);
}
/**
@dev It emits a `RewardPaid` event if any rewards are received.
*/
function getReward() public {
_notPaused();
_updateReward(msg.sender);
uint256 reward = rewards[msg.sender];
if (reward == uint256(0)) return;
rewards[msg.sender] = uint256(0);
rewardsToken.safeTransfer(msg.sender, reward);
emit RewardPaid(msg.sender, reward);
}
function exit() external {
withdraw(_balances[msg.sender]);
getReward();
}
/**
@dev Only the contract Owner may call this.
@dev It emits a `RewardAdded` event.
*/
function notifyRewardAmount(uint256 reward) external onlyOwner {
_updateReward(address(0));
uint256 _rewardRate = block.timestamp >= periodFinish
? reward.div(rewardsDuration)
: reward.add(
periodFinish.sub(block.timestamp).mul(rewardRate)
).div(rewardsDuration);
rewardRate = _rewardRate;
// Ensure the provided reward amount is not more than the balance in the contract.
// This keeps the reward rate in the right range, preventing overflows due to
// very high values of rewardRate in the earned and rewardsPerToken functions;
// Reward + leftover must be less than 2^256 / 10^18 to avoid overflow.
uint256 balance = rewardsToken.balanceOf(address(this));
require(_rewardRate <= balance.div(rewardsDuration), "R:REWARD_TOO_HIGH");
lastUpdateTime = block.timestamp;
periodFinish = block.timestamp.add(rewardsDuration);
emit RewardAdded(reward);
}
/**
@dev End rewards emission earlier. Only the contract Owner may call this.
*/
function updatePeriodFinish(uint256 timestamp) external onlyOwner {
_updateReward(address(0));
periodFinish = timestamp;
}
/**
@dev Added to support recovering tokens unintentionally sent to this contract.
Only the contract Owner may call this.
@dev It emits a `Recovered` event.
*/
function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyOwner {
IERC20(tokenAddress).safeTransfer(owner(), tokenAmount);
emit Recovered(tokenAddress, tokenAmount);
}
/**
@dev Only the contract Owner may call this.
@dev It emits a `RewardsDurationUpdated` event.
*/
function setRewardsDuration(uint256 _rewardsDuration) external onlyOwner {
require(block.timestamp > periodFinish, "R:PERIOD_NOT_FINISHED");
rewardsDuration = _rewardsDuration;
emit RewardsDurationUpdated(rewardsDuration);
}
/**
@dev Change the paused state of the contract. Only the contract Owner may call this.
@dev It emits a `PauseChanged` event.
*/
function setPaused(bool _paused) external onlyOwner {
// Ensure we're actually changing the state before we do anything
require(_paused != paused, "R:ALREADY_SET");
// Set our paused state.
paused = _paused;
// If applicable, set the last pause time.
if (_paused) lastPauseTime = block.timestamp;
// Let everyone know that our pause state has changed.
emit PauseChanged(paused);
}
}
| contract MplRewards is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
IERC20 public immutable rewardsToken;
IERC2258 public immutable stakingToken;
uint256 public periodFinish;
uint256 public rewardRate;
uint256 public rewardsDuration;
uint256 public lastUpdateTime;
uint256 public rewardPerTokenStored;
uint256 public lastPauseTime;
bool public paused;
mapping(address => uint256) public userRewardPerTokenPaid;
mapping(address => uint256) public rewards;
uint256 private _totalSupply;
mapping(address => uint256) private _balances;
event RewardAdded(uint256 reward);
event Staked(address indexed account, uint256 amount);
event Withdrawn(address indexed account, uint256 amount);
event RewardPaid(address indexed account, uint256 reward);
event RewardsDurationUpdated(uint256 newDuration);
event Recovered(address token, uint256 amount);
event PauseChanged(bool isPaused);
constructor(address _rewardsToken, address _stakingToken, address _owner) public {
rewardsToken = IERC20(_rewardsToken);
stakingToken = IERC2258(_stakingToken);
rewardsDuration = 7 days;
transferOwnership(_owner);
}
function _updateReward(address account) internal {
uint256 _rewardPerTokenStored = rewardPerToken();
rewardPerTokenStored = _rewardPerTokenStored;
lastUpdateTime = lastTimeRewardApplicable();
if (account != address(0)) {
rewards[account] = earned(account);
userRewardPerTokenPaid[account] = _rewardPerTokenStored;
}
}
function _notPaused() internal view {
require(!paused, "R:PAUSED");
}
function totalSupply() external view returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) external view returns (uint256) {
return _balances[account];
}
function lastTimeRewardApplicable() public view returns (uint256) {
return Math.min(block.timestamp, periodFinish);
}
function rewardPerToken() public view returns (uint256) {
return _totalSupply == 0
? rewardPerTokenStored
: rewardPerTokenStored.add(
lastTimeRewardApplicable().sub(lastUpdateTime).mul(rewardRate).mul(1e18).div(_totalSupply)
);
}
function earned(address account) public view returns (uint256) {
return _balances[account].mul(rewardPerToken().sub(userRewardPerTokenPaid[account])).div(1e18).add(rewards[account]);
}
function getRewardForDuration() external view returns (uint256) {
return rewardRate.mul(rewardsDuration);
}
/**
@dev It emits a `Staked` event.
*/
function stake(uint256 amount) external {
_notPaused();
_updateReward(msg.sender);
uint256 newBalance = _balances[msg.sender].add(amount);
require(amount > 0, "R:ZERO_STAKE");
require(stakingToken.custodyAllowance(msg.sender, address(this)) >= newBalance, "R:INSUF_CUST_ALLOWANCE");
_totalSupply = _totalSupply.add(amount);
_balances[msg.sender] = newBalance;
emit Staked(msg.sender, amount);
}
/**
@dev It emits a `Withdrawn` event.
*/
function withdraw(uint256 amount) public {
_notPaused();
_updateReward(msg.sender);
require(amount > 0, "R:ZERO_WITHDRAW");
_totalSupply = _totalSupply.sub(amount);
_balances[msg.sender] = _balances[msg.sender].sub(amount);
stakingToken.transferByCustodian(msg.sender, msg.sender, amount);
emit Withdrawn(msg.sender, amount);
}
/**
@dev It emits a `RewardPaid` event if any rewards are received.
*/
function getReward() public {
_notPaused();
_updateReward(msg.sender);
uint256 reward = rewards[msg.sender];
if (reward == uint256(0)) return;
rewards[msg.sender] = uint256(0);
rewardsToken.safeTransfer(msg.sender, reward);
emit RewardPaid(msg.sender, reward);
}
function exit() external {
withdraw(_balances[msg.sender]);
getReward();
}
/**
@dev Only the contract Owner may call this.
@dev It emits a `RewardAdded` event.
*/
function notifyRewardAmount(uint256 reward) external onlyOwner {
_updateReward(address(0));
uint256 _rewardRate = block.timestamp >= periodFinish
? reward.div(rewardsDuration)
: reward.add(
periodFinish.sub(block.timestamp).mul(rewardRate)
).div(rewardsDuration);
rewardRate = _rewardRate;
// Ensure the provided reward amount is not more than the balance in the contract.
// This keeps the reward rate in the right range, preventing overflows due to
// very high values of rewardRate in the earned and rewardsPerToken functions;
// Reward + leftover must be less than 2^256 / 10^18 to avoid overflow.
uint256 balance = rewardsToken.balanceOf(address(this));
require(_rewardRate <= balance.div(rewardsDuration), "R:REWARD_TOO_HIGH");
lastUpdateTime = block.timestamp;
periodFinish = block.timestamp.add(rewardsDuration);
emit RewardAdded(reward);
}
/**
@dev End rewards emission earlier. Only the contract Owner may call this.
*/
function updatePeriodFinish(uint256 timestamp) external onlyOwner {
_updateReward(address(0));
periodFinish = timestamp;
}
/**
@dev Added to support recovering tokens unintentionally sent to this contract.
Only the contract Owner may call this.
@dev It emits a `Recovered` event.
*/
function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyOwner {
IERC20(tokenAddress).safeTransfer(owner(), tokenAmount);
emit Recovered(tokenAddress, tokenAmount);
}
/**
@dev Only the contract Owner may call this.
@dev It emits a `RewardsDurationUpdated` event.
*/
function setRewardsDuration(uint256 _rewardsDuration) external onlyOwner {
require(block.timestamp > periodFinish, "R:PERIOD_NOT_FINISHED");
rewardsDuration = _rewardsDuration;
emit RewardsDurationUpdated(rewardsDuration);
}
/**
@dev Change the paused state of the contract. Only the contract Owner may call this.
@dev It emits a `PauseChanged` event.
*/
function setPaused(bool _paused) external onlyOwner {
// Ensure we're actually changing the state before we do anything
require(_paused != paused, "R:ALREADY_SET");
// Set our paused state.
paused = _paused;
// If applicable, set the last pause time.
if (_paused) lastPauseTime = block.timestamp;
// Let everyone know that our pause state has changed.
emit PauseChanged(paused);
}
}
| 11,569 |
169 | // Executes a set of actions and allows composability (contract calls) to other contracts./actions An array with a sequence of actions to execute (see ACTION_ declarations)./values A one-to-one mapped array to `actions`. ETH amounts to send along with the actions./ Only applicable to `ACTION_CALL`, `ACTION_BENTO_DEPOSIT`./datas A one-to-one mapped array to `actions`. Contains abi encoded data of function arguments./ return value1 May contain the first positioned return value of the last executed action (if applicable)./ return value2 May contain the second positioned return value of the last executed action which returns 2 values (if applicable). | function cook(
uint8[] calldata actions,
uint256[] calldata values,
bytes[] calldata datas
| function cook(
uint8[] calldata actions,
uint256[] calldata values,
bytes[] calldata datas
| 5,430 |
23 | // Thrown when trying to call as an unauthorized account./ return HN:Common/unauthorized-caller | string public constant UNAUTHORIZED_CALLER =
"HN:Common/unauthorized-caller";
| string public constant UNAUTHORIZED_CALLER =
"HN:Common/unauthorized-caller";
| 21,285 |
61 | // check how many tokens were received after trade execution | uint256 tradeReturn = viewBalance(to, address(this));
require(tradeReturn >= limitAmount, 'Trade returned less than the minimum amount');
| uint256 tradeReturn = viewBalance(to, address(this));
require(tradeReturn >= limitAmount, 'Trade returned less than the minimum amount');
| 2,864 |
96 | // bolean bonus switcher, only called when tokens bonus availability is exhuated terminate bonus | function setBonustoFalse() private returns (string) {
require (bidderBonus == true,"no more bonuses");
bidderBonus = false;
return "tokens exhausted";
}
| function setBonustoFalse() private returns (string) {
require (bidderBonus == true,"no more bonuses");
bidderBonus = false;
return "tokens exhausted";
}
| 11,830 |
24 | // 3Crv Metapools | address pool,
uint256[4] calldata amounts,
uint256 min_mint_amount
) external;
function add_liquidity(
| address pool,
uint256[4] calldata amounts,
uint256 min_mint_amount
) external;
function add_liquidity(
| 40,226 |
23 | // Increase the amount of tokens that an owner allowed to a spender.approve should be called when allowed_[_spender] == 0. To incrementallowed value is better to use this function to avoid 2 calls (and wait untilthe first transaction is mined)From MonolithDAO Token.solEmits an Approval event. spender The address which will spend the funds. addedValue The amount of tokens to increase the allowance by. / | function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
| function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
| 14,136 |
121 | // Accumulated DUCKs per share, times 1e18. See below. | uint public accDuckPerShare;
| uint public accDuckPerShare;
| 30,321 |
5 | // save bytecode by removing implementation of unused method | function _baseURI() internal view virtual override returns (string memory) {}
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
return IYokaiChainDescriptor(_tokenDescriptor).tokenURI(this, tokenId);
}
| function _baseURI() internal view virtual override returns (string memory) {}
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
return IYokaiChainDescriptor(_tokenDescriptor).tokenURI(this, tokenId);
}
| 51,935 |
349 | // If it's not the collateral currency, send the entire balance. | amount = balance;
| amount = balance;
| 5,447 |
33 | // Returns the amount of tokens owned by `account`. / | function balanceOf(address account) external view returns (uint256);
| function balanceOf(address account) external view returns (uint256);
| 3,019 |
55 | // Project Marketing Wallet | Updateable at a later point if necessary | marketingWallet = address(0x94E709272FA55BB86e61C1Ec829Ba04f61128578);
| marketingWallet = address(0x94E709272FA55BB86e61C1Ec829Ba04f61128578);
| 46,615 |
13 | // Cancel a listing. _listingId The ID of the listing to cancel. / | function cancelListing(uint256 _listingId) external;
| function cancelListing(uint256 _listingId) external;
| 27,236 |
123 | // !!!In updates to contracts set new variables strictly below this line!!!----------------------------------------------------------------------------------- | string public codeVersion = "ESW v1.0-137-g7fd1d69";
uint256 public constant MAXIMUM_SUPPLY = 200_000_000e18;
bool public isFirstMinter = true;
address public constant firstMinter =
0xdeb5A983AdC9b25b8A96ae43a65953Ded3939de6; // set to Oracle
address public constant secondMinter =
0x303D8Dd1878D4F38D14507B87D84c9531bd64B5A; //set to EmiVesting
uint256 public minterChangeBlock;
event MinterSwitch(address newMinter, uint256 afterBlock);
| string public codeVersion = "ESW v1.0-137-g7fd1d69";
uint256 public constant MAXIMUM_SUPPLY = 200_000_000e18;
bool public isFirstMinter = true;
address public constant firstMinter =
0xdeb5A983AdC9b25b8A96ae43a65953Ded3939de6; // set to Oracle
address public constant secondMinter =
0x303D8Dd1878D4F38D14507B87D84c9531bd64B5A; //set to EmiVesting
uint256 public minterChangeBlock;
event MinterSwitch(address newMinter, uint256 afterBlock);
| 13,681 |
15 | // mappings/ |
mapping(address => bool) private _isExcludedFromFees; // manage excluding of address from fee
mapping(address => bool) public _isExcludedFromRewardPool; // managing the excluding of user from reward pool
mapping(address => bool) public isEligible; // true if user is in list, false if not
mapping(address => uint256) public participantIndex; //index of user in list
mapping(address => bool) public marketMakerPairs; // pairs for token
|
mapping(address => bool) private _isExcludedFromFees; // manage excluding of address from fee
mapping(address => bool) public _isExcludedFromRewardPool; // managing the excluding of user from reward pool
mapping(address => bool) public isEligible; // true if user is in list, false if not
mapping(address => uint256) public participantIndex; //index of user in list
mapping(address => bool) public marketMakerPairs; // pairs for token
| 28,922 |
270 | // GrafitiCoin | address private _nctAddress;
event Purchase(uint256 ID, address purchaser);
| address private _nctAddress;
event Purchase(uint256 ID, address purchaser);
| 27,839 |
43 | // The slam-the-button escape hatch. Sells the callers tokens for Ether, then immediately invokes the withdraw() function, sending the resulting Ether to the callers address. | function getMeOutOfHere() public {
sellMyTokens();
withdraw();
}
| function getMeOutOfHere() public {
sellMyTokens();
withdraw();
}
| 10,145 |
1 | // public override | function tokenURI(uint256 tokenId) public view override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
if(block.timestamp < timeByTokenId[tokenId] + 365 days) {
return bytes(yearOneURI).length > 0 ? string(abi.encodePacked(yearOneURI, tokenId.toString())) : "";
}
| function tokenURI(uint256 tokenId) public view override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
if(block.timestamp < timeByTokenId[tokenId] + 365 days) {
return bytes(yearOneURI).length > 0 ? string(abi.encodePacked(yearOneURI, tokenId.toString())) : "";
}
| 16,592 |
135 | // burn destroys tokens after taking a fee for the `_feeRecipient`,/ allowing the associated assets to be released on their native/ chain.//_to The address to receive the un-bridged asset. The format of/this address should be of the destination chain./For example, when burning to Bitcoin, _to should be a/Bitcoin address./_amount The amount of the token being burnt, in its/smallest value. (e.g. satoshis for BTC) | function burn(bytes memory _to, uint256 _amount) public returns (uint256) {
// The recipient must not be empty. Better validation is possible,
// but would need to be customized for each destination ledger.
require(_to.length != 0, "MintGateway: to address is empty");
// Calculate fee, subtract it from amount being burnt.
uint256 fee = _amount.mul(burnFee).div(BIPS_DENOMINATOR);
uint256 amountAfterFee =
_amount.sub(fee, "MintGateway: fee exceeds amount");
// If the scaled token can represent more precision than the underlying
// token, the difference is lost. This won't exceed 1 sat, so is
// negligible compared to burning and transaction fees.
uint256 amountAfterFeeUnderlying = token.toUnderlying(amountAfterFee);
// Burn the whole amount, and then re-mint the fee.
token.burn(msg.sender, _amount);
if (fee > 0) {
token.mint(feeRecipient, fee);
}
require(
// Must be strictly greater, to that the release transaction is of
// at least one unit.
amountAfterFeeUnderlying > minimumBurnAmount,
"MintGateway: amount is less than the minimum burn amount"
);
emit LogBurn(_to, amountAfterFeeUnderlying, nextN, _to);
// Store burn so that it can be looked up instead of relying on event
// logs.
bytes memory payload;
MintGatewayStateV2.burns[nextN] = Burn({
_blocknumber: block.number,
_to: _to,
_amount: amountAfterFeeUnderlying,
_chain: "",
_payload: payload
});
nextN += 1;
return amountAfterFeeUnderlying;
}
| function burn(bytes memory _to, uint256 _amount) public returns (uint256) {
// The recipient must not be empty. Better validation is possible,
// but would need to be customized for each destination ledger.
require(_to.length != 0, "MintGateway: to address is empty");
// Calculate fee, subtract it from amount being burnt.
uint256 fee = _amount.mul(burnFee).div(BIPS_DENOMINATOR);
uint256 amountAfterFee =
_amount.sub(fee, "MintGateway: fee exceeds amount");
// If the scaled token can represent more precision than the underlying
// token, the difference is lost. This won't exceed 1 sat, so is
// negligible compared to burning and transaction fees.
uint256 amountAfterFeeUnderlying = token.toUnderlying(amountAfterFee);
// Burn the whole amount, and then re-mint the fee.
token.burn(msg.sender, _amount);
if (fee > 0) {
token.mint(feeRecipient, fee);
}
require(
// Must be strictly greater, to that the release transaction is of
// at least one unit.
amountAfterFeeUnderlying > minimumBurnAmount,
"MintGateway: amount is less than the minimum burn amount"
);
emit LogBurn(_to, amountAfterFeeUnderlying, nextN, _to);
// Store burn so that it can be looked up instead of relying on event
// logs.
bytes memory payload;
MintGatewayStateV2.burns[nextN] = Burn({
_blocknumber: block.number,
_to: _to,
_amount: amountAfterFeeUnderlying,
_chain: "",
_payload: payload
});
nextN += 1;
return amountAfterFeeUnderlying;
}
| 41,340 |
15 | // ------------------------------------------------------------------------ Claim tokens sent using signatures supplied to the other chain ------------------------------------------------------------------------ |
function verifySigData(bytes memory sigData)
private
returns (TransferData memory)
|
function verifySigData(bytes memory sigData)
private
returns (TransferData memory)
| 12,559 |
54 | // End sale / | function endSale()
external
| function endSale()
external
| 50,004 |
25 | // burn remaining tokens | token.burn(token.balanceOf(this));
FinalizeSale();
| token.burn(token.balanceOf(this));
FinalizeSale();
| 43,585 |
259 | // Calculate the fees a user will have to pay to mint tokens with their collateral collateralAmount Amount of collateral on which fees are calculatedreturn fee Amount of fee that must be paid by the user / | function calculateFee(uint256 collateralAmount)
| function calculateFee(uint256 collateralAmount)
| 51,976 |
3 | // Will return true if oracle already initialized, if oracle has successfully been initialized by this call, or if oracle does not need to be initialized | function initializeOracle(address asset, address compareTo) external returns (bool);
| function initializeOracle(address asset, address compareTo) external returns (bool);
| 42,653 |
12 | // Assert that the given domain has a xApp Router registered and return its address _domain The domain of the chain for which to get the xApp Routerreturn _remote The address of the remote xApp Router on _domain / | function _mustHaveRemote(uint32 _domain)
internal
view
returns (bytes32 _remote)
| function _mustHaveRemote(uint32 _domain)
internal
view
returns (bytes32 _remote)
| 42,574 |
20 | // ``` / | library EnumSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Set storage set, bytes32 value) internal returns (bool) {
if (!contains(set, value)) {
set.values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set.indexes[value] = set.values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Set storage set, bytes32 value) internal returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set.indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set.values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set.values[lastIndex];
// Move the last value to the index where the value to delete is
set.values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set.indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set.values.pop();
// Delete the index for the deleted slot
delete set.indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Set storage set, bytes32 value) internal view returns (bool) {
return set.indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(Set storage set) internal view returns (uint256) {
return set.values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Set storage set, uint256 index) internal view returns (bytes32) {
require(set.values.length > index, "EnumSet: index out of bounds");
return set.values[index];
}
}
| library EnumSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Set storage set, bytes32 value) internal returns (bool) {
if (!contains(set, value)) {
set.values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set.indexes[value] = set.values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Set storage set, bytes32 value) internal returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set.indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set.values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set.values[lastIndex];
// Move the last value to the index where the value to delete is
set.values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set.indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set.values.pop();
// Delete the index for the deleted slot
delete set.indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Set storage set, bytes32 value) internal view returns (bool) {
return set.indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(Set storage set) internal view returns (uint256) {
return set.values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Set storage set, uint256 index) internal view returns (bytes32) {
require(set.values.length > index, "EnumSet: index out of bounds");
return set.values[index];
}
}
| 11,975 |
76 | // credit: https:github.com/flamincome/contracts/blob/bfbee3877aa7524408363516ceb2aab0d4527352/implementations/strategy/StrategyBaselineCarbonUniswapBTC.solL57 | address weth = IUniswapV2Router02(uniswapRouterV2).WETH();
| address weth = IUniswapV2Router02(uniswapRouterV2).WETH();
| 30,187 |
87 | // Withdraws the beneficiary&39;s funds. / | function beneficiaryWithdraw() public {
require(state == State.Closed);
beneficiary.transfer(address(this).balance);
}
| function beneficiaryWithdraw() public {
require(state == State.Closed);
beneficiary.transfer(address(this).balance);
}
| 38,645 |
80 | // exclude from max transaction amount | mapping (address => bool) public isExcludedFromTxLimit;
| mapping (address => bool) public isExcludedFromTxLimit;
| 9,417 |
73 | // {IERC165} interfaces can also be queried via the registry./ Sets `newManager` as the manager for `account`. A manager of anaccount is able to set interface implementers for it. By default, each account is its own manager. Passing a value of `0x0` in`newManager` will reset the manager to this initial state. Emits a {ManagerChanged} event. Requirements: - the caller must be the current manager for `account`. / | function setManager(address account, address newManager) external;
| function setManager(address account, address newManager) external;
| 9,460 |
11 | // (8) ์ข
๋ฃ | function close() public onlyOwner {
// ํ ํฐ์ ์์ ์์๊ฒ ์ ์ก
token.transfer(owner, token.balanceOf(this));
// ๊ณ์ฝ์ ํ๊ธฐ (ํด๋น ๊ณ์ฝ์ด ๋ณด์ ํ๊ณ ์๋ Ehter๋ ์์ ์์๊ฒ ์ ์ก)
selfdestruct(owner);
}
| function close() public onlyOwner {
// ํ ํฐ์ ์์ ์์๊ฒ ์ ์ก
token.transfer(owner, token.balanceOf(this));
// ๊ณ์ฝ์ ํ๊ธฐ (ํด๋น ๊ณ์ฝ์ด ๋ณด์ ํ๊ณ ์๋ Ehter๋ ์์ ์์๊ฒ ์ ์ก)
selfdestruct(owner);
}
| 10,781 |
12 | // Informs callers that this contract supports ERC2981 | function supportsInterface(bytes4 interfaceId)
public
view
override(ERC1155Upgradeable)
returns (bool)
| function supportsInterface(bytes4 interfaceId)
public
view
override(ERC1155Upgradeable)
returns (bool)
| 49,484 |
176 | // Sets new reserve ratio. | reserveRatio = _newReserveRatio;
emit NewReserveRatio(_oldReserveRatio, _newReserveRatio);
| reserveRatio = _newReserveRatio;
emit NewReserveRatio(_oldReserveRatio, _newReserveRatio);
| 71,462 |
15 | // in case someone sends Eth to this contract, this function gets it out again | function withdrawAll() public whenNotPaused onlyOwner {
(bool success,) = _msgSender().call{ value: address(this).balance }("");
require(success, "transfer failed");
}
| function withdrawAll() public whenNotPaused onlyOwner {
(bool success,) = _msgSender().call{ value: address(this).balance }("");
require(success, "transfer failed");
}
| 30,495 |
22 | // Eccentricity can vary by up to 12.5% | node = _seed.derive("eccentricity");
uint ecc = uint(node.getNormalIntBetween(0, 125));
| node = _seed.derive("eccentricity");
uint ecc = uint(node.getNormalIntBetween(0, 125));
| 15,295 |
1 | // Initial Dex Router | IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(router);
| IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(router);
| 60,042 |
19 | // The consumer actively confirms the delivered chunks and keys are received | function received() public {
require(now < timeout_receive);
require(round == state.initiated);
inState(state.received);
}
| function received() public {
require(now < timeout_receive);
require(round == state.initiated);
inState(state.received);
}
| 10,161 |
46 | // Returns the total number of pixels currently in existence./Required for ERC-721 compliance. | function totalSupply() public view returns (uint) {
return WIDTH * HEIGHT;
}
| function totalSupply() public view returns (uint) {
return WIDTH * HEIGHT;
}
| 52,165 |
4 | // Calculate and mint the amount of xSushi the Sushi is worth. The ratio will change overtime, as xSushi is burned/minted and Sushi deposited + gained from fees / withdrawn. | else {
uint256 what = _amount.mul(totalShares).div(totalSushi);
_mint(msg.sender, what);
}
| else {
uint256 what = _amount.mul(totalShares).div(totalSushi);
_mint(msg.sender, what);
}
| 7,312 |
55 | // change the minimum amount of tokens to swap | function updateSwapTokensAmount(uint256 newAmount) external onlyOwner {
require(newAmount >= totalSupply * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply.");
require(newAmount <= totalSupply * 1 / 1000, "Swap amount cannot be higher than 0.1% total supply.");
swapTokensAtAmount = newAmount;
}
| function updateSwapTokensAmount(uint256 newAmount) external onlyOwner {
require(newAmount >= totalSupply * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply.");
require(newAmount <= totalSupply * 1 / 1000, "Swap amount cannot be higher than 0.1% total supply.");
swapTokensAtAmount = newAmount;
}
| 34,925 |
76 | // compute token qty | qty = getTokenQty(token, rate, qty);
imbalanceQty = int(qty);
totalImbalance += imbalanceQty;
| qty = getTokenQty(token, rate, qty);
imbalanceQty = int(qty);
totalImbalance += imbalanceQty;
| 17,814 |
28 | // Allow users to route calls to a contract, to be used with batch | function route(address integration, bytes calldata data)
external payable
returns (bytes memory result)
| function route(address integration, bytes calldata data)
external payable
returns (bytes memory result)
| 79,605 |
39 | // Reverts if value is 0. | modifier notZero(uint256 _value) {
require(_value != 0, "VaultHandler::notZero: value can't be 0");
_;
}
| modifier notZero(uint256 _value) {
require(_value != 0, "VaultHandler::notZero: value can't be 0");
_;
}
| 9,368 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.